@galacticcouncil/sdk 7.2.0 → 8.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var $=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var ve=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var ce="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ae="0x112b087b60C1a166130d59266363C45F8aa99db0",Ie="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ce=1000000n;var Le=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{defineChain as ot}from"viem";var Me=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Ge=["wss://rpc.hydradx.cloud","wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],qe=ot({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Me,webSocket:Ge},default:{http:Me,webSocket:Ge}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as He,createWalletClient as it,custom as at,http as lt,webSocket as ct}from"viem";var V=class{chain;constructor(e){this.chain=e||qe}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return He({chain:this.chain,transport:lt()})}getWsProvider(){return He({chain:this.chain,transport:ct()})}getSigner(e){return it({account:e,chain:this.chain,transport:at(window.ethereum)})}};var j=class{evmClient;constructor(){this.evmClient=new V}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:ve,address:Ae,args:[Ie],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:ve,address:Ae,args:[Ie,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:$,address:ce,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as me,encodeAddress as We}from"@polkadot/util-crypto";import{hexToU8a as ut,isHex as mt,u8aToHex as pt}from"@polkadot/util";import{Buffer as X}from"buffer";var zs=2090,Te=1e3,ue="1",Js=2034,U=63,Z=18,_="0",Ks=12,Q=15;var Ue=X.from("ETH\0");function dt(p){if(!p)return!1;try{let e=me(p,!0);return X.from(e.subarray(0,Ue.length)).equals(Ue)}catch{return!1}}function gt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Pt(p){try{let e=mt(p)?ut(p):me(p);return We(e),!0}catch{return!1}}var Y=class p{static prefixBytes=X.from("ETH\0");static toAccount=e=>{let t=X.from(e.slice(2),"hex");return We(new Uint8Array(X.concat([p.prefixBytes,t,X.alloc(8)])),63)};static fromAccount=e=>{let s=me(e).slice(p.prefixBytes.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let s=me(e).slice(0,20);return pt(s)};static fromAny=e=>{if(gt(e))return e;if(dt(e))return p.fromAccount(e);if(Pt(e))return p.fromSS58(e);throw new Error("Unknown address type")}};var M=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as w}from"bignumber.js";var ht=12;w.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:ht});var b=m(0),T=m(1),or=m("Infinity");function v(p,e){let t=new w(e.toString()),s=new w(10).pow(t);return p.times(s)}function m(p){return new w(p.toString())}var bt=m("1e27"),yt=m("1.01"),Ne=class{client;constructor(){this.client=new j}async loadAaveCtx(e){let t=Y.fromAny(e),[s,r,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[i]=s,[o,a]=r,[l,c,u,g,d,P]=n,h=m(P).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN),y=m(l),x=m(c),f=[];for(let O of o){let B=O.underlyingAsset.toLowerCase(),S=i.find(({underlyingAsset:nt})=>nt.toLowerCase()===B);if(!S)throw new Error("Missing pool reserve for "+B);let k=m(O.scaledATokenBalance),q=m(S.liquidityIndex),le=m(S.priceInMarketReferenceCurrency),K=k.multipliedBy(q).dividedBy(bt).decimalPlaces(0,w.ROUND_DOWN),Be=m(a===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold).div(1e4),st=S.usageAsCollateralEnabled&&O.usageAsCollateralEnabledOnUser&&m(O.scaledATokenBalance).gt(0),rt=M.toAssetId(B);f.push({aTokenBalance:K,decimals:Number(S.decimals),isCollateral:st,priceInRef:le,reserveId:rt,reserveAsset:B,reserveLiquidationThreshold:Be})}return{healthFactor:h.toNumber(),totalCollateral:y,totalDebt:x,reserves:f}}async getHealthFactor(e){let t=Y.fromAny(e),s=await this.client.getUserAccountData(t),[r,n,i,o,a,l]=s;return m(l).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,s){let{totalCollateral:r,totalDebt:n,reserves:i}=await this.loadAaveCtx(e),o=M.fromAssetId(t),a=i.find(x=>x.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:g}=a,d=v(m(s),l).decimalPlaces(0,1),P=c?d.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN):b,h=r.minus(P);return h.lte(0)?0:h.multipliedBy(g).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,s){let{totalCollateral:r,totalDebt:n,reserves:i}=await this.loadAaveCtx(e),o=M.fromAssetId(t),a=i.find(y=>y.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=a,d=v(m(s),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN),P=r.plus(d);return P.lte(0)?0:P.multipliedBy(u).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalCollateral:s,totalDebt:r,reserves:n}=await this.loadAaveCtx(e),i=M.fromAssetId(t),o=n.find(a=>a.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(o,s,r)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:s,reserves:r}=await this.loadAaveCtx(e),n={};for(let i of r){let o=this.calculateWithdrawMax(i,t,s);i.reserveId&&(n[i.reserveId]=o)}return n}calculateWithdrawMax(e,t,s){let{aTokenBalance:r,decimals:n,priceInRef:i,reserveLiquidationThreshold:o}=e,a=yt.multipliedBy(s).div(o).decimalPlaces(0,w.ROUND_UP),l=t.minus(a).decimalPlaces(0,1);if(l.lte(0))return{amount:b,decimals:n};let c=l.multipliedBy(m(10).pow(n)).dividedBy(i).decimalPlaces(0,w.ROUND_DOWN);return{amount:w.minimum(r,c),decimals:n}}};import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var D=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var ee=class extends D{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:n}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==_){let u=this.api.consts.balances.existentialDeposit;return{id:_,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:n,assetType:i,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:c,icon:l,type:i.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[n,i]=r,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(n.toString(),t,s),g=i.toNumber(),d=new Intl.DateTimeFormat("en-GB"),P=[c,"Bond",d.format(g)].join(" ");return{id:e,name:P,symbol:c+"b",decimals:u,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,s,r){let{assets:n}=r,{name:i,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=n.map(h=>h.toString()).map(h=>{let{symbol:y}=this.getToken(h,t,s);return[h,y]}),d=Object.fromEntries(g),P=Object.values(d);return{id:e,name:P.join(", "),symbol:o?.isSome?o.toHuman():i.toHuman(),decimals:18,icon:P.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let n=this.getToken(e,t,new Map,r),i=s?.find(o=>o.internalId===n.id);return i?{...n,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:n,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(n.toString()),symbol:i.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,n,i,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),l=this.normalizeMetadata(a,o),c=a.map(([{args:[u]},g])=>{let d=g.unwrap(),P=r.get(u.toString()),{assetType:h}=d;switch(h.toString()){case"Bond":let y=i.get(u.toString());return this.getBond(u.toString(),d,l,y);case"StableSwap":let x=n.get(u.toString());return this.getShares(u.toString(),d,l,x);case"External":return this.getExternal(u.toString(),d,t,P);default:return this.getToken(u.toString(),d,l,P)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var H=class extends D{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===_?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:n})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(_,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let n=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==_).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(n,i=>{let o=[];i.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=n[l][1];o.push([u,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),n=async()=>{let i=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,l])=>{i.push([a,l])}),s(i)};return await n(),this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:n}=e,i=new w(t),o=new w(s||n),a=new w(r||0n),l=o.gt(a)?o:a;return i.minus(l)}};import{fixed_from_rational as Xe}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as ft}from"@polkadot/types";import{u8aConcat as Ye}from"@polkadot/util";import{isAddress as $e}from"@polkadot/util-crypto";var Fe=class extends D{balanceClient;constructor(e){super(e),this.balanceClient=new H(e)}secondsInYear=new w(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new w(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(n.isNone)return;let[i]=n.unwrap(),o=i.price.n.toString(),a=i.price.d.toString(),l;return Number(t)<Number(s)?l=Xe(o,a):l=Xe(a,o),l}getGlobalRewardPerPeriod(e,t,s,r){let i=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return i.gte(s)?s:i}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return Ye(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",n=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new ft(e,this.padEndU8a(Ye(r,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!$e(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&$e(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new w(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new w(a.yieldPerPeriod.toString()),P=new w(a.maxRewardPerPeriod.toString()),h=a.blocksPerPeriod.toString(),y=new w(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new w(s).times(h)),f;if(u.isZero())f=d.times(y).times(x);else{let q=this.getGlobalRewardPerPeriod(u,d,P,l);f=this.getPoolYieldPerPeriod(q,y,u,l).times(x)}let O=new w(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=P.times(g),S=c?O.plus(c):B;return O.div(S).gte(.999)?b:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),b).toString():void 0}};var pe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ve=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},z=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ze=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Je=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ke=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},je=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{LRUCache as xs}from"@thi.ng/cache";import{memoize1 as ws}from"@thi.ng/memoize";var R=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(R||{}),J=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(J||{});var de=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:b,assetOutED:b}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=[];return r.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return v(T,e.decimalsOut)}spotPriceOutGivenIn(e){return v(T,e.decimalsIn)}calculateTradeFee(e,t){return b}};import{encodeAddress as xt}from"@polkadot/util-crypto";import{stringToU8a as Ot}from"@polkadot/util";import{decodeEventLog as Bt}from"viem";function Ze(p,e){let t=[];return JSON.stringify(p,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function tn(p,e,t){let s;return JSON.stringify(p,(r,n)=>(n&&n[e]===t&&(s=n),n)),s}var sn=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as St}from"@thi.ng/memoize";import{TLRUCache as wt}from"@thi.ng/cache";var C=class extends H{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new wt(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=St(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let n=this.subscribePoolChange(t);s.push(n)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);s.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);s.push(n)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,n])=>{let i=e.tokens.findIndex(o=>o.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=n.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(n=>n.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var vt=["Supply","Withdraw","Repay","Borrow"],ge=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:n})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return xt(Ot(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(i=>{let{event:o}=i,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=o.data.toHuman(),u=l.replace(/,/g,""),g=c.replace(/,/g,"");(u===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=o.data.toHuman();try{let{eventName:c,args:u}=Bt({abi:$,topics:l.topics,data:l.data});vt.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(i=>{let o=i.id===t.id?r.toString():n.toString();return{...i,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?Ze(e.location,"accountKey20").accountKey20.key:M.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as At,calculate_out_given_in as It,calculate_linear_weights as Tt,calculate_pool_trade_fee as Nt,get_spot_price as Ft}from"@galacticcouncil/math-lbp";var G=class{static getSpotPrice(e,t,s,r,n){return Ft(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n){return At(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n){return It(e,t,s,r,n)}static calculateLinearWeights(e,t,s,r,n){return Tt(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return Nt(e,t,s)}};function N(p,e){return p.shiftedBy(-1*e).toString()}function L(p){return p[0]/p[1]*100}function I(p){return p[0]/p[1]}function E(p){return[p/1e3,1e3]}var Pe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,n,i,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.fee=i,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&n.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=L(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:n}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&n.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),l=L(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(e,t){let s=G.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=G.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=G.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(T,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=G.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(T,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=G.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var he=class extends C{MAX_FINAL_WEIGHT=v(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([n,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(n.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let i=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,i)}else{let i=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:n,assets:i,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=G.calculateLinearWeights(r.toString(),n.toString(),o.toString(),a.toString(),s),[g,d]=i,P=g.toString(),h=m(u),y=d.toString(),x=this.MAX_FINAL_WEIGHT.minus(m(h)),[f,O,B]=await Promise.all([this.isRepayFeeApplied(P,l.toString(),c.toString()),this.getBalance(e,P),this.getBalance(e,y)]);return{repayFeeApply:f,tokens:[{id:P,weight:h,balance:O.toString()},{id:y,weight:x,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=m(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as Rt,calculate_lrna_in_given_out as Et,calculate_out_given_in as kt,calculate_out_given_lrna_in as _t,calculate_pool_trade_fee as Dt,calculate_spot_price as Ct,calculate_lrna_spot_price as Lt,calculate_shares as Mt,calculate_liquidity_out as Gt,calculate_liquidity_lrna_out as qt,calculate_liquidity_hub_in as Ht,is_sell_allowed as Ut,is_buy_allowed as Wt,is_add_liquidity_allowed as Xt,is_remove_liquidity_allowed as Yt,recalculate_asset_fee as $t,recalculate_protocol_fee as Vt,verify_asset_cap as zt}from"@galacticcouncil/math-omnipool";var A=class{static calculateSpotPrice(e,t,s,r){return Ct(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Lt(e,t)}static calculateInGivenOut(e,t,s,r,n,i,o,a,l){return Rt(e,t,s,r,n,i,o,a,l)}static calculateLrnaInGivenOut(e,t,s,r,n){return Et(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n,i,o,a,l){return kt(e,t,s,r,n,i,o,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,n){return _t(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return Dt(e,t,s)}static calculateShares(e,t,s,r){return Mt(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,n,i,o,a){return Gt(e,t,s,r,n,i,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,n,i,o,a){return qt(e,t,s,r,n,i,o,a)}static calculateCapDifference(e,t,s,r){let n=w(t),i=w(e),o=w(r),l=w(s).shiftedBy(-18);if(n.div(o).lt(l)){let u=l.times(o).minus(n).times(i),g=n.times(w(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return Ht(e,t,s,r)}static isSellAllowed(e){return Ut(e)}static isBuyAllowed(e){return Wt(e)}static isAddLiquidityAllowed(e){return Xt(e)}static isRemoveLiquidityAllowed(e){return Yt(e)}static recalculateAssetFee(e,t,s,r,n,i,o,a,l,c,u){return $t(e,t,s,r,n,i,o,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,n,i,o,a,l,c,u){return Vt(e,t,s,r,n,i,o,a,l,c,u)}static verifyAssetCap(e,t,s,r){return zt(e,t,s,r)}};var be=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,n,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=n.minus(r),o=r===b?b:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),o=r.minus(n).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=A.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString(),s?I(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateLrnaInGivenOut(e,t,s){let r=A.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=A.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString(),s?I(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenLrnaIn(e,t,s){let r=A.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=A.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=A.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=A.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=A.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Jt}from"@polkadot/util-crypto";import{stringToU8a as Kt}from"@polkadot/util";var ye=class extends C{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=s.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:g,cap:d,protocolShares:P}=l.unwrap(),h=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:g.bits.toNumber(),balance:h.toString(),cap:m(d.toString()),protocolShares:m(P.toString())}}),o=await Promise.all(i);return o.push({id:e,tradeable:r.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,n="omnipool",i="Short",o=B=>B===_?[_,ue]:[ue,B],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(n,o(s),i),this.api.query.emaOracle.oracles(n,o(r),i)]),[g,d,P]=this.getAssetFee(e,a.toNumber(),l,c),[h,y,x]=r===ue?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),f=g+h,O=P+x;return{assetFee:E(d),protocolFee:E(y),min:E(f),max:E(O)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,n)=>{let i=e.tokens[n];if(r.isNone)return i;let o=r.unwrap();return this.updateTokenState(i,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:n,cap:i,protocolShares:o}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(i.toString()),protocolShares:m(o.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:n,balanceOut:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:P,timestamp:h}=s.unwrap(),y=Math.max(1,t-h.toNumber()),x=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(x=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let B=E(P.toNumber()),S=A.recalculateAssetFee(x,f,O,"9",i.toString(),I(B).toString(),y.toString(),I(u).toString(),I(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(S)*1e6,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:n,balanceIn:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:P,timestamp:h}=s.unwrap(),y=Math.max(1,t-h.toNumber()),x=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(x=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let B=E(P.toNumber()),S=A.recalculateProtocolFee(x,f,O,"9",i.toString(),I(B).toString(),y.toString(),I(u).toString(),I(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(S)*1e6,a.toNumber()]}getPoolId(){return Jt(Kt("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as jt,calculate_out_given_in as Zt,calculate_pool_trade_fee as Qt,get_spot_price as es,calculate_liquidity_in as ts,calculate_shares as ss,calculate_spot_price as rs,calculate_spot_price_with_fee as ns,calculate_liquidity_out_asset_a as os,calculate_liquidity_out_asset_b as is}from"@galacticcouncil/math-xyk";var W=class{static getSpotPrice(e,t,s){return es(e,t,s)}static calculateInGivenOut(e,t,s){return jt(e,t,s)}static calculateOutGivenIn(e,t,s){return Zt(e,t,s)}static calculatePoolTradeFee(e,t,s){return Qt(e,t,s)}static calculateLiquidityIn(e,t,s){return ts(e,t,s)}static calculateSpotPrice(e,t){return rs(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return ns(e,t,s,r)}static calculateShares(e,t,s){return ss(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return os(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return is(e,t,s,r)}};var fe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=W.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=v(T,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=W.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=v(T,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=W.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var Se=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let n=s.toString(),[i,o]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(n,i.toString()),this.getBalance(n,o.toString())]);return{address:n,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as as,calculate_out_given_in as ls,calculate_amplification as cs,calculate_add_one_asset as us,calculate_liquidity_out_one_asset as ms,calculate_pool_trade_fee as ps,calculate_shares as ds,calculate_shares_for_amount as gs,calculate_spot_price_with_fee as Ps,pool_account_name as hs,recalculate_peg as bs}from"@galacticcouncil/math-stableswap";var F=class{static getPoolAddress(e){return hs(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,n){return cs(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n,i,o){return as(e,t,s,r,n,i,o)}static calculateAddOneAsset(e,t,s,r,n,i,o){return us(e,t,s,r,n,i,o)}static calculateSharesForAmount(e,t,s,r,n,i,o){return gs(e,t,s,r,n,i,o)}static calculateOutGivenIn(e,t,s,r,n,i,o){return ls(e,t,s,r,n,i,o)}static calculateLiquidityOutOneAsset(e,t,s,r,n,i,o){return ms(e,t,s,r,n,i,o)}static calculateShares(e,t,s,r,n,i){return ds(e,t,s,r,n,i)}static calculateSpotPriceWithFee(e,t,s,r,n,i,o,a){return Ps(e,t,s,r,n,i,o,a)}static calculatePoolTradeFee(e,t,s){return ps(e,t,s)}static recalculatePegs(e,t,s,r,n){let i=bs(e,t,s,r,n);return JSON.parse(i)}};var we=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,n,i,o,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.amplification=i,this.id=o,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=L(s.fee),o=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),i=L(s.fee),o=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:o}}calculateIn(e,t,s){let r=F.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateAddOneAsset(e,t,s){let r=F.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateSharesForAmount(e,t,s){let r=F.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=v(T,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=v(T,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=F.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateWithdrawOneAsset(e,t,s){let r=F.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateShares(e,t,s){let r=F.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=v(T,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=v(T,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=F.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{blake2AsHex as ys,encodeAddress as fs}from"@polkadot/util-crypto";var Ss=340282366920938463463374607431768211455n,xe=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=this.getPoolAddress(a),[c,u,g]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(l,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(l,o),{address:l,id:a,type:"Stableswap",fee:E(o.fee.toNumber()),tokens:u,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[n,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,n,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:n,initialBlock:i,finalBlock:o}=t,a=F.calculateAmplification(r.toString(),n.toString(),i.toString(),o.toString(),s),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,n=r.map(async o=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),i=await Promise.all(n);return i.push({id:t,tradeable:15,balance:Ss.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=F.defaultPegs(e.assets.length);return{pegsFee:E(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let n=r.unwrap(),i=await this.getLatestPegs(t,n,s),o=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=F.recalculatePegs(JSON.stringify(o),JSON.stringify(i),s,a.replace(/%/g,""),l.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:E(g),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(n=>n.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,n=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),i=r.map(async(o,a)=>{if(o.isOracle){let[l,c,u]=o.asOracle,g=[u.toString(),n[a]].map(f=>Number(f)).sort((f,O)=>f-O),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:P,updatedAt:h}]=d.unwrap(),y=P.n.toString(),x=P.d.toString();return u.toString()===g[0].toString()?[[y,x],h.toString()]:[[x,y],h.toString()]}else return[o.asValue.map(l=>l.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=F.getPoolAddress(t);return fs(ys(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var te=class extends D{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ws(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new ee(this.api),this.aaveClient=new ge(this.api),this.xykClient=new Se(this.api),this.omniClient=new ye(this.api),this.lbpClient=new he(this.api),this.stableClient=new xe(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new pe(t.type)}}};var Re=class extends te{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new xs(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let n=await super.getPoolFees(e,t);return this.feeCache.set(s,n),n}}async destroy(){this.log(`Destroying pool cache!
1
+ var $=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var ve=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var ce="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ae="0x112b087b60C1a166130d59266363C45F8aa99db0",Ie="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ce=1000000n;var Le=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{defineChain as ot}from"viem";var Me=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Ge=["wss://rpc.hydradx.cloud","wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],qe=ot({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:Me,webSocket:Ge},default:{http:Me,webSocket:Ge}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as He,createWalletClient as it,custom as at,http as lt,webSocket as ct}from"viem";var V=class{chain;constructor(e){this.chain=e||qe}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return He({chain:this.chain,transport:lt()})}getWsProvider(){return He({chain:this.chain,transport:ct()})}getSigner(e){return it({account:e,chain:this.chain,transport:at(window.ethereum)})}};var j=class{evmClient;constructor(){this.evmClient=new V}async getReservesData(){return await this.evmClient.getProvider().readContract({abi:ve,address:Ae,args:[Ie],functionName:"getReservesData"})}async getUserReservesData(e){return await this.evmClient.getProvider().readContract({abi:ve,address:Ae,args:[Ie,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.evmClient.getProvider().readContract({abi:$,address:ce,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as me,encodeAddress as We}from"@polkadot/util-crypto";import{hexToU8a as ut,isHex as mt,u8aToHex as pt}from"@polkadot/util";import{Buffer as X}from"buffer";var zs=2090,Te=1e3,ue="1",Js=2034,U=63,Z=18,_="0",Ks=12,Q=15;var Ue=X.from("ETH\0");function dt(p){if(!p)return!1;try{let e=me(p,!0);return X.from(e.subarray(0,Ue.length)).equals(Ue)}catch{return!1}}function gt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Pt(p){try{let e=mt(p)?ut(p):me(p);return We(e),!0}catch{return!1}}var Y=class p{static prefixBytes=X.from("ETH\0");static toAccount=e=>{let t=X.from(e.slice(2),"hex");return We(new Uint8Array(X.concat([p.prefixBytes,t,X.alloc(8)])),63)};static fromAccount=e=>{let s=me(e).slice(p.prefixBytes.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let s=me(e).slice(0,20);return pt(s)};static fromAny=e=>{if(gt(e))return e;if(dt(e))return p.fromAccount(e);if(Pt(e))return p.fromSS58(e);throw new Error("Unknown address type")}};var M=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as w}from"bignumber.js";var ht=12;w.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:ht});var b=m(0),T=m(1),or=m("Infinity");function v(p,e){let t=new w(e.toString()),s=new w(10).pow(t);return p.times(s)}function m(p){return new w(p.toString())}var bt=m("1e27"),yt=m("1.01"),Ne=class{client;constructor(){this.client=new j}async loadAaveCtx(e){let t=Y.fromAny(e),[s,r,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t)]),[i]=s,[o,a]=r,[l,c,u,g,d,P]=n,h=m(P).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN),y=m(l),x=m(c),f=[];for(let O of o){let B=O.underlyingAsset.toLowerCase(),S=i.find(({underlyingAsset:nt})=>nt.toLowerCase()===B);if(!S)throw new Error("Missing pool reserve for "+B);let k=m(O.scaledATokenBalance),q=m(S.liquidityIndex),le=m(S.priceInMarketReferenceCurrency),K=k.multipliedBy(q).dividedBy(bt).decimalPlaces(0,w.ROUND_DOWN),Be=m(a===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold).div(1e4),st=S.usageAsCollateralEnabled&&O.usageAsCollateralEnabledOnUser&&m(O.scaledATokenBalance).gt(0),rt=M.toAssetId(B);f.push({aTokenBalance:K,decimals:Number(S.decimals),isCollateral:st,priceInRef:le,reserveId:rt,reserveAsset:B,reserveLiquidationThreshold:Be})}return{healthFactor:h.toNumber(),totalCollateral:y,totalDebt:x,reserves:f}}async getHealthFactor(e){let t=Y.fromAny(e),s=await this.client.getUserAccountData(t),[r,n,i,o,a,l]=s;return m(l).dividedBy(1e18).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,s){let{totalCollateral:r,totalDebt:n,reserves:i}=await this.loadAaveCtx(e),o=M.fromAssetId(t),a=i.find(x=>x.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:g}=a,d=v(m(s),l).decimalPlaces(0,1),P=c?d.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN):b,h=r.minus(P);return h.lte(0)?0:h.multipliedBy(g).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,s){let{totalCollateral:r,totalDebt:n,reserves:i}=await this.loadAaveCtx(e),o=M.fromAssetId(t),a=i.find(y=>y.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=a,d=v(m(s),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,w.ROUND_DOWN),P=r.plus(d);return P.lte(0)?0:P.multipliedBy(u).dividedBy(n).decimalPlaces(6,w.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalCollateral:s,totalDebt:r,reserves:n}=await this.loadAaveCtx(e),i=M.fromAssetId(t),o=n.find(a=>a.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(o,s,r)}async getMaxWithdrawAll(e){let{totalCollateral:t,totalDebt:s,reserves:r}=await this.loadAaveCtx(e),n={};for(let i of r){let o=this.calculateWithdrawMax(i,t,s);i.reserveId&&(n[i.reserveId]=o)}return n}calculateWithdrawMax(e,t,s){let{aTokenBalance:r,decimals:n,priceInRef:i,reserveLiquidationThreshold:o}=e,a=yt.multipliedBy(s).div(o).decimalPlaces(0,w.ROUND_UP),l=t.minus(a).decimalPlaces(0,1);if(l.lte(0))return{amount:b,decimals:n};let c=l.multipliedBy(m(10).pow(n)).dividedBy(i).decimalPlaces(0,w.ROUND_DOWN);return{amount:w.minimum(r,c),decimals:n}}};import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var D=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var ee=class extends D{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol:n}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:n.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==_){let u=this.api.consts.balances.existentialDeposit;return{id:_,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:n,assetType:i,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:n.toHuman(),symbol:l,decimals:c,icon:l,type:i.toHuman(),isSufficient:o?o.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[n,i]=r,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(n.toString(),t,s),g=i.toNumber(),d=new Intl.DateTimeFormat("en-GB"),P=[c,"Bond",d.format(g)].join(" ");return{id:e,name:P,symbol:c+"b",decimals:u,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:n.toString(),maturity:g}}getShares(e,t,s,r){let{assets:n}=r,{name:i,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=n.map(h=>h.toString()).map(h=>{let{symbol:y}=this.getToken(h,t,s);return[h,y]}),d=Object.fromEntries(g),P=Object.values(d);return{id:e,name:P.join(", "),symbol:o?.isSome?o.toHuman():i.toHuman(),decimals:18,icon:P.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let n=this.getToken(e,t,new Map,r),i=s?.find(o=>o.internalId===n.id);return i?{...n,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:n}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:n,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(n.toString()),symbol:i.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,s])=>{if(s.isNone)return!1;let r=s.unwrap();return this.isSupportedAsset(r)})}async getOnChainAssets(e,t){let[s,r,n,i,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(s),l=this.normalizeMetadata(a,o),c=a.map(([{args:[u]},g])=>{let d=g.unwrap(),P=r.get(u.toString()),{assetType:h}=d;switch(h.toString()){case"Bond":let y=i.get(u.toString());return this.getBond(u.toString(),d,l,y);case"StableSwap":let x=n.get(u.toString());return this.getShares(u.toString(),d,l,x);case"External":return this.getExternal(u.toString(),d,t,P);default:return this.getToken(u.toString(),d,l,P)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var H=class extends D{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===_?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:n}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:n})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:n}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:0n,frozen:n})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(_,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let n=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==_).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(n,i=>{let o=[];i.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=n[l][1];o.push([u,c])}),s(o)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),n=async()=>{let i=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,l])=>{i.push([a,l])}),s(i)};return await n(),this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:n}=e,i=new w(t),o=new w(s||n),a=new w(r||0n),l=o.gt(a)?o:a;return i.minus(l)}};import{fixed_from_rational as Xe}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as ft}from"@polkadot/types";import{u8aConcat as Ye}from"@polkadot/util";import{isAddress as $e}from"@polkadot/util-crypto";var Fe=class extends D{balanceClient;constructor(e){super(e),this.balanceClient=new H(e)}secondsInYear=new w(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,n])=>{let[,i]=r.args,o=n.unwrap().toString(),a=i.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new w(1).shiftedBy(18).toString();let n=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(n.isNone)return;let[i]=n.unwrap(),o=i.price.n.toString(),a=i.price.d.toString(),l;return Number(t)<Number(s)?l=Xe(o,a):l=Xe(a,o),l}getGlobalRewardPerPeriod(e,t,s,r){let i=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return i.gte(s)?s:i}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return Ye(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",n=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new ft(e,this.padEndU8a(Ye(r,n,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!$e(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&$e(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new w(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),d=new w(a.yieldPerPeriod.toString()),P=new w(a.maxRewardPerPeriod.toString()),h=a.blocksPerPeriod.toString(),y=new w(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new w(s).times(h)),f;if(u.isZero())f=d.times(y).times(x);else{let q=this.getGlobalRewardPerPeriod(u,d,P,l);f=this.getPoolYieldPerPeriod(q,y,u,l).times(x)}let O=new w(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),B=P.times(g),S=c?O.plus(c):B;return O.div(S).gte(.999)?b:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),b).toString():void 0}};var pe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Ve=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},z=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ze=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Je=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ke=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},je=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{LRUCache as xs}from"@thi.ng/cache";import{memoize1 as ws}from"@thi.ng/memoize";var R=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n))(R||{}),J=(n=>(n.UnknownError="UnknownError",n.InsufficientTradingAmount="InsufficientTradingAmount",n.MaxInRatioExceeded="MaxInRatioExceeded",n.MaxOutRatioExceeded="MaxOutRatioExceeded",n.TradeNotAllowed="TradeNotAllowed",n))(J||{});var de=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:b,assetOutED:b}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=[];return t.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=[];return r.isGreaterThan(e.balanceOut)&&n.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:n}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return v(T,e.decimalsOut)}spotPriceOutGivenIn(e){return v(T,e.decimalsIn)}calculateTradeFee(e,t){return b}};import{encodeAddress as xt}from"@polkadot/util-crypto";import{stringToU8a as Ot}from"@polkadot/util";import{decodeEventLog as Bt}from"viem";function Ze(p,e){let t=[];return JSON.stringify(p,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function tn(p,e,t){let s;return JSON.stringify(p,(r,n)=>(n&&n[e]===t&&(s=n),n)),s}var sn=(p,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as St}from"@thi.ng/memoize";import{TLRUCache as wt}from"@thi.ng/cache";var C=class extends H{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new wt(null,{maxlen:1,ttl:1*60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=St(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let n=this.subscribePoolChange(t);s.push(n)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let n=this.subscribeSystemPoolBalance(t);s.push(n)}if(this.hasErc20Asset(t)){let n=this.subscribeErc20PoolBalance(t);s.push(n)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,n])=>{let i=e.tokens.findIndex(o=>o.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=n.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(n=>n.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var vt=["Supply","Withdraw","Repay","Borrow"],ge=class extends C{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:n})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:n.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return xt(Ot(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);return this.api.query.system.events(n=>{n.forEach(i=>{let{event:o}=i,a=`${o.section}:${o.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=o.data.toHuman(),u=l.replace(/,/g,""),g=c.replace(/,/g,"");(u===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=o.data.toHuman();try{let{eventName:c,args:u}=Bt({abi:$,topics:l.topics,data:l.data});vt.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:n}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(i=>{let o=i.id===t.id?r.toString():n.toString();return{...i,balance:o}})}getReserveH160Id(e){return e.type==="Erc20"?Ze(e.location,"accountKey20").accountKey20.key:M.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as At,calculate_out_given_in as It,calculate_linear_weights as Tt,calculate_pool_trade_fee as Nt,get_spot_price as Ft}from"@galacticcouncil/math-lbp";var G=class{static getSpotPrice(e,t,s,r,n){return Ft(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n){return At(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n){return It(e,t,s,r,n)}static calculateLinearWeights(e,t,s,r,n){return Tt(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return Nt(e,t,s)}};function N(p,e){return p.shiftedBy(-1*e).toString()}function L(p){return p[0]/p[1]*100}function I(p){return p[0]/p[1]}function E(p){return[p/1e3,1e3]}var Pe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,n,i,o){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.fee=i,this.repayFeeApply=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,weightIn:r.weight,weightOut:n.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&n.push("MaxOutRatioExceeded"),r===e.assetOut){let o=this.calculateTradeFee(t,s),a=L(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:n}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:n}}}validateAndSell(e,t,s){let r=this.tokens[0].id,n=[];t.isLessThan(this.minTradingLimit)&&n.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&n.push("MaxInRatioExceeded"),r===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:n}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,s),l=L(this.repayFeeApply?s.repayFee:s.exchangeFee),c=o.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(e,t){let s=G.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=G.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=G.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(T,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=G.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(T,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=G.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var he=class extends C{MAX_FINAL_WEIGHT=v(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([n,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=await this.getPoolDelta(a,o,s.toString());return this.poolsData.set(n.toString(),o),{address:a,type:"Lbp",fee:o.fee.toJSON(),...l,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let i=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,i)}else{let i=this.pools.findIndex(o=>o.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:n,assets:i,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=G.calculateLinearWeights(r.toString(),n.toString(),o.toString(),a.toString(),s),[g,d]=i,P=g.toString(),h=m(u),y=d.toString(),x=this.MAX_FINAL_WEIGHT.minus(m(h)),[f,O,B]=await Promise.all([this.isRepayFeeApplied(P,l.toString(),c.toString()),this.getBalance(e,P),this.getBalance(e,y)]);return{repayFeeApply:f,tokens:[{id:P,weight:h,balance:O.toString()},{id:y,weight:x,balance:B.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=m(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as Rt,calculate_lrna_in_given_out as Et,calculate_out_given_in as kt,calculate_out_given_lrna_in as _t,calculate_pool_trade_fee as Dt,calculate_spot_price as Ct,calculate_lrna_spot_price as Lt,calculate_shares as Mt,calculate_liquidity_out as Gt,calculate_liquidity_lrna_out as qt,calculate_liquidity_hub_in as Ht,is_sell_allowed as Ut,is_buy_allowed as Wt,is_add_liquidity_allowed as Xt,is_remove_liquidity_allowed as Yt,recalculate_asset_fee as $t,recalculate_protocol_fee as Vt,verify_asset_cap as zt}from"@galacticcouncil/math-omnipool";var A=class{static calculateSpotPrice(e,t,s,r){return Ct(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Lt(e,t)}static calculateInGivenOut(e,t,s,r,n,i,o,a,l){return Rt(e,t,s,r,n,i,o,a,l)}static calculateLrnaInGivenOut(e,t,s,r,n){return Et(e,t,s,r,n)}static calculateOutGivenIn(e,t,s,r,n,i,o,a,l){return kt(e,t,s,r,n,i,o,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,n){return _t(e,t,s,r,n)}static calculatePoolTradeFee(e,t,s){return Dt(e,t,s)}static calculateShares(e,t,s,r){return Mt(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,n,i,o,a){return Gt(e,t,s,r,n,i,o,a)}static calculateLiquidityLRNAOut(e,t,s,r,n,i,o,a){return qt(e,t,s,r,n,i,o,a)}static calculateCapDifference(e,t,s,r){let n=w(t),i=w(e),o=w(r),l=w(s).shiftedBy(-18);if(n.div(o).lt(l)){let u=l.times(o).minus(n).times(i),g=n.times(w(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return Ht(e,t,s,r)}static isSellAllowed(e){return Ut(e)}static isBuyAllowed(e){return Wt(e)}static isAddLiquidityAllowed(e){return Xt(e)}static isRemoveLiquidityAllowed(e){return Yt(e)}static recalculateAssetFee(e,t,s,r,n,i,o,a,l,c,u){return $t(e,t,s,r,n,i,o,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,n,i,o,a,l,c,u){return Vt(e,t,s,r,n,i,o,a,l,c,u)}static verifyAssetCap(e,t,s,r){return zt(e,t,s,r)}};var be=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,n,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.hubAssetId=i}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:n.hubReserves,sharesIn:r.shares,sharesOut:n.shares,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,tradeableIn:r.tradeable,tradeableOut:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=n.minus(r),o=r===b?b:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),o=r.minus(n).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=A.isSellAllowed(e.tradeableIn),c=A.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=A.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString(),s?I(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateLrnaInGivenOut(e,t,s){let r=A.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=A.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString(),s?I(s.protocolFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}calculateOutGivenLrnaIn(e,t,s){let r=A.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?I(s.assetFee).toString():b.toString()),n=m(r);return n.isNegative()?b:n}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=A.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=A.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=A.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=A.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Jt}from"@polkadot/util-crypto";import{stringToU8a as Kt}from"@polkadot/util";var ye=class extends C{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,n]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=s.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:g,cap:d,protocolShares:P}=l.unwrap(),h=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:g.bits.toNumber(),balance:h.toString(),cap:m(d.toString()),protocolShares:m(P.toString())}}),o=await Promise.all(i);return o.push({id:e,tradeable:r.bits.toNumber(),balance:n.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,n="omnipool",i="Short",o=B=>B===_?[_,ue]:[ue,B],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(n,o(s),i),this.api.query.emaOracle.oracles(n,o(r),i)]),[g,d,P]=this.getAssetFee(e,a.toNumber(),l,c),[h,y,x]=r===ue?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),f=g+h,O=P+x;return{assetFee:E(d),protocolFee:E(y),min:E(f),max:E(O)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,n)=>{let i=e.tokens[n];if(r.isNone)return i;let o=r.unwrap();return this.updateTokenState(i,o)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:n,cap:i,protocolShares:o}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(i.toString()),protocolShares:m(o.toString()),tradeable:n.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:n,balanceOut:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:P,timestamp:h}=s.unwrap(),y=Math.max(1,t-h.toNumber()),x=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(x=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let B=E(P.toNumber()),S=A.recalculateAssetFee(x,f,O,"9",i.toString(),I(B).toString(),y.toString(),I(u).toString(),I(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(S)*1e6,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:n,balanceIn:i}=e,{minFee:o,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=E(o.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[o.toNumber(),o.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:P,timestamp:h}=s.unwrap(),y=Math.max(1,t-h.toNumber()),x=d.volume.bIn.toString(),f=d.volume.bOut.toString(),O=d.liquidity.b.toString();n===_&&(x=d.volume.aIn.toString(),f=d.volume.aOut.toString(),O=d.liquidity.a.toString());let B=E(P.toNumber()),S=A.recalculateProtocolFee(x,f,O,"9",i.toString(),I(B).toString(),y.toString(),I(u).toString(),I(g).toString(),l.toString(),c.toString());return[o.toNumber(),Number(S)*1e6,a.toNumber()]}getPoolId(){return Jt(Kt("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as jt,calculate_out_given_in as Zt,calculate_pool_trade_fee as Qt,get_spot_price as es,calculate_liquidity_in as ts,calculate_shares as ss,calculate_spot_price as rs,calculate_spot_price_with_fee as ns,calculate_liquidity_out_asset_a as os,calculate_liquidity_out_asset_b as is}from"@galacticcouncil/math-xyk";var W=class{static getSpotPrice(e,t,s){return es(e,t,s)}static calculateInGivenOut(e,t,s){return jt(e,t,s)}static calculateOutGivenIn(e,t,s){return Zt(e,t,s)}static calculatePoolTradeFee(e,t,s){return Qt(e,t,s)}static calculateLiquidityIn(e,t,s){return ts(e,t,s)}static calculateSpotPrice(e,t){return rs(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return ns(e,t,s,r)}static calculateShares(e,t,s){return ss(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return os(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return is(e,t,s,r)}};var fe=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,n){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:n.decimals,balanceIn:i,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.plus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(r,s),i=L(s.exchangeFee),o=r.minus(n),a=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=W.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=v(T,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=W.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=v(T,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=W.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var Se=class extends C{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let n=s.toString(),[i,o]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(n,i.toString()),this.getBalance(n,o.toString())]);return{address:n,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as as,calculate_out_given_in as ls,calculate_amplification as cs,calculate_add_one_asset as us,calculate_liquidity_out_one_asset as ms,calculate_pool_trade_fee as ps,calculate_shares as ds,calculate_shares_for_amount as gs,calculate_spot_price_with_fee as Ps,pool_account_name as hs,recalculate_peg as bs}from"@galacticcouncil/math-stableswap";var F=class{static getPoolAddress(e){return hs(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,n){return cs(e,t,s,r,n)}static calculateInGivenOut(e,t,s,r,n,i,o){return as(e,t,s,r,n,i,o)}static calculateAddOneAsset(e,t,s,r,n,i,o){return us(e,t,s,r,n,i,o)}static calculateSharesForAmount(e,t,s,r,n,i,o){return gs(e,t,s,r,n,i,o)}static calculateOutGivenIn(e,t,s,r,n,i,o){return ls(e,t,s,r,n,i,o)}static calculateLiquidityOutOneAsset(e,t,s,r,n,i,o){return ms(e,t,s,r,n,i,o)}static calculateShares(e,t,s,r,n,i){return ds(e,t,s,r,n,i)}static calculateSpotPriceWithFee(e,t,s,r,n,i,o,a){return Ps(e,t,s,r,n,i,o,a)}static calculatePoolTradeFee(e,t,s){return ps(e,t,s)}static recalculatePegs(e,t,s,r,n){let i=bs(e,t,s,r,n);return JSON.parse(i)}};var we=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,n,i,o,a,l,c,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=n,this.amplification=i,this.id=o,this.fee=a,this.totalIssuance=l,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),n=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),o=m(n.balance),a=m(r.existentialDeposit),l=m(n.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:r.decimals,decimalsOut:n.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:n.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),n=this.calculateInGivenOut(e,t,s),i=L(s.fee),o=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),n=this.calculateOutGivenIn(e,t,s),i=L(s.fee),o=[],a=A.isSellAllowed(e.tradeableIn),l=A.isBuyAllowed(e.tradeableOut);return(!a||!l)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:o}}calculateIn(e,t,s){let r=F.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateAddOneAsset(e,t,s){let r=F.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateSharesForAmount(e,t,s){let r=F.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=v(T,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=v(T,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=F.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateWithdrawOneAsset(e,t,s){let r=F.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateShares(e,t,s){let r=F.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?I(s.fee).toString():b.toString(),this.getPegs()),n=m(r);return n.isNegative()?b:n}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=F.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=v(T,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=v(T,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=F.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{blake2AsHex as ys,encodeAddress as fs}from"@polkadot/util-crypto";var Ss=340282366920938463463374607431768211455n,xe=class extends C{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[n]},i])=>{let o=i.unwrap(),a=n.toString(),l=this.getPoolAddress(a),[c,u,g]=await Promise.all([this.getPoolDelta(a,o,s.toString()),this.getPoolTokens(l,a,o),this.getPoolPegs(a,o,s.toString())]);return this.stablePools.set(l,o),{address:l,id:a,type:"Stableswap",fee:E(o.fee.toNumber()),tokens:u,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[n,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,n,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:n,initialBlock:i,finalBlock:o}=t,a=F.calculateAmplification(r.toString(),n.toString(),i.toString(),o.toString(),s),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,n=r.map(async o=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),i=await Promise.all(n);return i.push({id:t,tradeable:15,balance:Ss.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=F.defaultPegs(e.assets.length);return{pegsFee:E(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let n=r.unwrap(),i=await this.getLatestPegs(t,n,s),o=this.getRecentPegs(n),a=n.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=F.recalculatePegs(JSON.stringify(o),JSON.stringify(i),s,a.replace(/%/g,""),l.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:E(g),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(n=>n.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,n=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),i=r.map(async(o,a)=>{if(o.isOracle){let[l,c,u]=o.asOracle,g=[u.toString(),n[a]].map(f=>Number(f)).sort((f,O)=>f-O),d=await this.api.query.emaOracle.oracles(l,g,c),[{price:P,updatedAt:h}]=d.unwrap(),y=P.n.toString(),x=P.d.toString();return u.toString()===g[0].toString()?[[y,x],h.toString()]:[[x,y],h.toString()]}else return[o.asValue.map(l=>l.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=F.getPoolAddress(t);return fs(ys(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var te=class extends D{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ws(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new ee(this.api),this.aaveClient=new ge(this.api),this.xykClient=new Se(this.api),this.omniClient=new ye(this.api),this.lbpClient=new he(this.api),this.stableClient=new xe(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new pe(t.type)}}};var Re=class extends te{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new xs(null),this.api.rpc.chain.subscribeNewHeads(async t=>{this.feeCache.release()}).then(t=>{this.disconnectSubscribeNewHeads=t})}async getPoolFees(e,t){let s=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(s))return this.feeCache.get(s);{let n=await super.getPoolFees(e,t);return this.feeCache.set(s,n),n}}async destroy(){this.log(`Destroying pool cache!
2
2
  Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var se=class{static get(e){switch(e.type){case"Aave":return de.fromPool(e);case"Xyk":return fe.fromPool(e);case"Omnipool":return be.fromPool(e);case"Lbp":return Pe.fromPool(e);case"Stableswap":return we.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Oe=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 Os=5,re=class{isNotVisited(e,t){let s=!0;return t.forEach(r=>{(r[0]===e[0]||r[1]===e[1])&&(s=!1)}),s}findPaths(e,t,s){let r=[],n=new Oe,i=[];for(i.push([t,""]),n.enqueue(i);n.size()>0;){let o=n.dequeue();if(o==null||o.length>Os)return r;let a=o[o.length-1];(s===null||a[0]===s)&&r.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let u=[...o];u.push(c),n.enqueue(u)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,n,i]of t){let o=parseInt(n),a=parseInt(i);s.get(o)?.push([a,r])}return s}};function Ee(p){let e={};for(let t of p){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let n=0;n<s;n++){if(r==n)continue;let i=[t.address,t.tokens[r].id,t.tokens[n].id];e[t.tokens[r].id].push(i)}}}return e}var ne=class{getProposals(e,t,s){let r=Ee(s),n=Object.keys(r),i=n.map(c=>r[c]).flat(),o=new re,a=o.buildAndPopulateGraph(n,i),l=o.findPaths(a,parseInt(e),t?parseInt(t):null);return this.parsePaths(l)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let n=0;n<s.length;n++){let i=s[n],o=s[n+1];if(o==null)break;r.push(this.toEdge(i,o))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var oe=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new ne,this.routerOptions={...this.defaultRouterOptions,...t}}async getPools(){let e=this.routerOptions.includeOnly;return await this.poolService.getPools(e)}async getAllAssets(){let e=await this.getPools();if(e.length===0)throw new Error("No pools configured");let t=await this.getAssets(e);return[...new Map(t).values()]}async getAssetPairs(e){let t=await this.getPools();if(t.length===0)throw new Error("No pools configured");let{assets:s,poolsMap:r}=await this.validateToken(e,t),i=this.getPaths(e,null,r,t).map(o=>o[o.length-1].assetOut);return this.toAssets([...new Set(i)],s)}async getAllPaths(e,t){let s=await this.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await this.validateTokenPair(e,t,s);return this.getPaths(e,t,r,s)}async getAssets(e){let t=e.map(s=>s.tokens.map(r=>({id:r.id,name:r.name,symbol:r.symbol,decimals:r.decimals,icon:r.icon,type:r.type,isSufficient:r.isSufficient,existentialDeposit:r.existentialDeposit,meta:r.meta,location:r.location,isWhiteListed:r.isWhiteListed}))).flat();return new Map(t.map(s=>[s.id,s]))}getPaths(e,t,s,r){return this.routeSuggester.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}async validateTokenPair(e,t,s){let r=await this.getAssets(s);if(r.get(e)==null)throw new Error(e+" is not supported token");if(r.get(t)==null)throw new Error(t+" is not supported token");let n=this.getPoolMap(s);return{assets:r,poolsMap:n}}async validateToken(e,t){let s=await this.getAssets(t);if(s.get(e)==null)throw new Error(e+" is not supported token");let r=this.getPoolMap(t);return{assets:s,poolsMap:r}}getPoolMap(e){return new Map(e.map(t=>[t.address,se.get(t)]))}validPath(e,t){return e.length>0&&e.map(s=>this.validEdge(s,t)).reduce((s,r)=>s&&r)}validEdge([e,t,s],r){return r.get(e)?.validatePair(t,s)||!1}toHops(e,t){return e.map(([s,r,n])=>{let i=t.get(s);return{poolAddress:s,poolId:i?.id,pool:i?.type,assetIn:r,assetOut:n}})}toAssets(e,t){return e.map(s=>t.get(s))}};var Bs=m("100");function hl(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ie(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Qe(p,e){return T.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function et(p,e){return e.div(p).minus(T).multipliedBy(100).decimalPlaces(2)}function ae(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(Bs).multipliedBy(e).decimalPlaces(0,1)}var ke=(t=>(t.Buy="Buy",t.Sell="Sell",t))(ke||{});var _e=class extends oe{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let n=s[s.length-1].amountOut,i=r[r.length-1].amountOut;return n.isGreaterThan(i)?-1:1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(s=>s.tradeFeeRange).length>0){let s=e.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,i)=>n+i),r=e.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,i)=>n+i);return[s,r]}}getPoolFeeRange(e){let t=e.min?L(e.min):void 0,s=e.max?L(e.max):void 0;if(t&&s)return[t,s]}async getBestSell(e,t,s){return this.getSell(e,t,s)}async getSell(e,t,s,r){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,n),o=super.getPaths(e,t,i,n);if(o.length===0)throw new z(e,t);let a;if(r)a=await this.toSellSwaps(s,r,i);else{let S=o.map(async q=>await this.toSellSwaps(s,q,i)),k=await Promise.all(S);a=this.findBestSellRoute(k)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),g=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetOutDecimals)).reduce((S,k)=>S.multipliedBy(k)),d=v(g,c.assetOutDecimals),P=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,i),h=c.amountOut,y=u?c.tradeFeePct:Qe(P,h).toNumber(),x=P.minus(h),f=this.getRouteFeeRange(a),O=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),B=ie(P,O);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:N(l.amountIn,l.assetInDecimals),amountOut:N(c.amountOut,c.assetOutDecimals),spotPrice:N(d,c.assetOutDecimals),tradeFee:N(x,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:f,priceImpactPct:B.toNumber(),swaps:a.map(S=>S.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n>0?l=r[n-1]:l=e;let c=o.calculateOutGivenIn(a,l);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let n=0;n<t.length;n++){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n>0?l=r[n-1].amountOut:l=v(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:u,calculatedOut:g,feePct:d,errors:P}=o.validateAndSell(a,l,c),h=this.getPoolFeeRange(c),y=o.spotPriceOutGivenIn(a),x=l.shiftedBy(-1*a.decimalsIn).multipliedBy(y),f=ie(g,x);r.push({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:g,amountOut:u,spotPrice:y,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f.toNumber(),errors:P,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:N(l,a.decimalsIn),calculatedOut:N(g,a.decimalsOut),amountOut:N(u,a.decimalsOut),spotPrice:N(y,a.decimalsOut),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f.toNumber(),errors:P}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),n=super.getPaths(e,t,r,s);if(n.length===0)throw new z(e,t);let l=s.filter(d=>d.tokens.some(P=>P.id===e&&P.id!==d.id)).map(d=>d.type==="Aave"?d.tokens:d.tokens.filter(P=>P.id===e)).map(d=>d.map(P=>m(P.balance).shiftedBy(-1*P.decimals)).reduce((P,h)=>P.plus(h))).sort((d,P)=>P.isLessThan(d)?-1:1)[0].div(100).multipliedBy(.1),c=n.map(async d=>await this.toSellSwaps(l,d,r)),u=await Promise.all(c);return this.findBestSellRoute(u).map(d=>({poolAddress:d.poolAddress,poolId:d?.poolId,pool:d.pool,assetIn:d.assetIn,assetOut:d.assetOut}))}async getBestSpotPrice(e,t){let s=await super.getPools();if(s.length===0)throw new Error("No pools configured");let{poolsMap:r}=await super.validateTokenPair(e,t,s);if(super.getPaths(e,t,r,s).length===0)return Promise.resolve(void 0);let i=await this.getMostLiquidRoute(e,t),o=await this.toSellSwaps("1",i,r),a=o.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,g)=>u.multipliedBy(g)),l=o[o.length-1].assetOutDecimals;return{amount:v(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let n=s[0].amountIn,i=r[0].amountIn;return n.isGreaterThan(i)?1:-1});return t.find(s=>s.every(r=>r.errors.length==0))||t[0]}async getBestBuy(e,t,s){return this.getBuy(e,t,s)}async getBuy(e,t,s,r){let n=await super.getPools();if(n.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,n),o=super.getPaths(e,t,i,n);if(o.length===0)throw new z(e,t);let a;if(r)a=await this.toBuySwaps(s,r,i);else{let S=o.map(async q=>await this.toBuySwaps(s,q,i)),k=await Promise.all(S);a=this.findBestBuyRoute(k)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),g=a.map(S=>S.spotPrice.shiftedBy(-1*S.assetInDecimals)).reduce((S,k)=>S.multipliedBy(k)),d=v(g,c.assetInDecimals),P=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,i),h=c.amountIn,y=u?c.tradeFeePct:et(P,h).toNumber(),x=h.minus(P),f=this.getRouteFeeRange(a),O=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),B;return P.isZero()?B=-100:B=ie(O,P).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:x,tradeFeePct:y,tradeFeeRange:f,priceImpactPct:B,swaps:a,toHuman(){return{type:"Buy",amountOut:N(l.amountOut,l.assetOutDecimals),amountIn:N(c.amountIn,c.assetInDecimals),spotPrice:N(d,c.assetInDecimals),tradeFee:N(x,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:f,priceImpactPct:B,swaps:a.map(S=>S.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let n=t.length-1;n>=0;n--){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n==t.length-1?l=e:l=r[0];let c=o.calculateInGivenOut(a,l);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let n=t.length-1;n>=0;n--){let i=t[n],o=s.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(i.assetIn,i.assetOut),l;n==t.length-1?l=v(m(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:u,calculatedIn:g,feePct:d,errors:P}=o.validateAndBuy(a,l,c),h=this.getPoolFeeRange(c),y=o.spotPriceInGivenOut(a),x=l.shiftedBy(-1*a.decimalsOut).multipliedBy(y),f;g.isZero()?f=-100:f=ie(x,g).toNumber(),r.unshift({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:g,amountIn:u,spotPrice:y,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f,errors:P,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:N(l,a.decimalsOut),calculatedIn:N(g,a.decimalsIn),amountIn:N(u,a.decimalsIn),spotPrice:N(y,a.decimalsIn),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:f,errors:P}}})}return r}};import{encodeFunctionData as vs}from"viem";var De=class extends D{balanceClient;evmClient;constructor(e){super(e),this.balanceClient=new H(e),this.evmClient=new V}buildBuyTx(e,t=1){if(e.type!=="Buy")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:n}=e,i=n[0],o=n[n.length-1],a=ae(s,t),l=i.assetIn,c=o.assetOut,u=s.plus(a),g;return this.isDirectOmnipoolTrade(n)?g=this.api.tx.omnipool.buy(c,l,r.toFixed(),u.toFixed()):g=this.api.tx.router.buy(l,c,r.toFixed(),u.toFixed(),this.buildRoute(n)),{hex:g.toHex(),name:"RouterBuy",get:()=>g,dryRun:d=>this.dryRun(d,g)}}buildSellTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:n}=e,i=n[0],o=n[n.length-1],a=ae(r,t),l=i.assetIn,c=o.assetOut,u=r.minus(a),g;return this.isDirectOmnipoolTrade(n)?g=this.api.tx.omnipool.sell(l,c,s.toFixed(),u.toFixed()):g=this.api.tx.router.sell(l,c,s.toFixed(),u.toFixed(),this.buildRoute(n)),{hex:g.toHex(),name:"RouterSell",get:()=>g,dryRun:d=>this.dryRun(d,g)}}buildSellAllTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountOut:s,swaps:r}=e,n=r[0],i=r[r.length-1],o=ae(s,t),a=n.assetIn,l=i.assetOut,c=s.minus(o),u=this.api.tx.router.sellAll(a,l,c.toFixed(),this.buildRoute(r));return{hex:u.toHex(),name:"RouterSellAll",get:()=>u,dryRun:g=>this.dryRun(g,u)}}async buildWithdrawAndSellReserveTx(e,t,s=1){let{amountIn:r,amountOut:n,swaps:i}=t,o=i[0],a=i[i.length-1];if(!o.isWithdraw())throw new Error("Not permitted");let l=o.assetIn,c=o.assetOut,[u,g]=await Promise.all([this.evmClient.getProvider().getGasPrice(),this.balanceClient.getBalance(e,l)]),d=r.isGreaterThanOrEqualTo(g.minus(5)),P=u*10n/100n,h=Y.fromAny(e),y=d?Le:BigInt(r.toFixed()),x=M.fromAssetId(c),f=vs({abi:$,functionName:"withdraw",args:[x,y,h]}),O=this.api.tx.evm.call(h,ce,f,0n,Ce,u+P,u+P,null,[]),B=ae(n,s),S=c,k=a.assetOut,q=n.minus(B),le=this.api.tx.router.sell(S,k,r.minus(5).toFixed(),q.toFixed(),this.buildRoute(i.slice(1))),K=this.api.tx.utility.batchAll([O,le]);return{hex:K.toHex(),name:"WithdrawAndRouterReserveSell",get:()=>K,dryRun:Be=>this.dryRun(Be,K)}}buildRoute(e){return e.map(({assetIn:t,assetOut:s,pool:r,poolId:n})=>r==="Stableswap"?{pool:{Stableswap:n},assetIn:t,assetOut:s}:{pool:r,assetIn:t,assetOut:s})}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};export{Ss as AMOUNT_MAX,j as AaveClient,de as AavePool,ge as AavePoolClient,Ne as AaveUtils,ee as AssetClient,ze as AssetNotFound,zs as BASILISK_PARACHAIN_ID,H as BalanceClient,w as BigNumber,Re as CachingPoolService,ht as DECIMAL_PLACES,Te as DENOMINATOR,M as ERC20,V as EvmClient,Fe as FarmClient,Y as H160,ue as HUB_ASSET_ID,Js as HYDRADX_PARACHAIN_ID,U as HYDRADX_SS58_PREFIX,or as INFINITY,G as LbpMath,Pe as LbpPool,he as LbpPoolClient,T as ONE,A as OmniMath,be as OmniPool,ye as OmniPoolClient,D as PolkadotApiClient,Ve as PoolConfigNotFound,J as PoolError,se as PoolFactory,pe as PoolNotFound,te as PoolService,R as PoolType,je as ProviderConfigNotFound,Z as RUNTIME_DECIMALS,z as RouteNotFound,oe as Router,Ks as SYSTEM_ASSET_DECIMALS,_ as SYSTEM_ASSET_ID,F as StableMath,we as StableSwap,xe as StableSwapClient,Je as StorageConfigNotFound,Ke as SubscriptionNotSupported,Q as TRADEABLE_DEFAULT,_e as TradeRouter,ke as TradeType,De as TradeUtils,W as XykMath,fe as XykPool,Se as XykPoolClient,b as ZERO,sn as bnFormatter,m as bnum,et as calculateBuyFee,hl as calculateDiffToAvg,ie as calculateDiffToRef,Qe as calculateSellFee,qe as evmMainnet,Ze as findNestedKey,tn as findNestedObj,ae as getFraction,dt as isEvmAccount,gt as isEvmAddress,Pt as isSs58Address,v as scale};