@galacticcouncil/sdk 5.6.0 → 5.7.0-pr146-35311fb

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var ke=Object.defineProperty;var at=Object.getOwnPropertyDescriptor;var lt=Object.getOwnPropertyNames;var ut=Object.prototype.hasOwnProperty;var ct=(l,e)=>{for(var t in e)ke(l,t,{get:e[t],enumerable:!0})},mt=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of lt(e))!ut.call(l,r)&&r!==t&&ke(l,r,{get:()=>e[r],enumerable:!(s=at(e,r))||s.enumerable});return l};var pt=l=>mt(ke({},"__esModule",{value:!0}),l);var At={};ct(At,{AssetClient:()=>X,AssetNotFound:()=>Ge,BASILISK_PARACHAIN_ID:()=>Pt,BalanceClient:()=>Y,BigNumber:()=>x.BigNumber,CachingPoolService:()=>Re,DECIMAL_PLACES:()=>$e,DENOMINATOR:()=>be,FarmClient:()=>Pe,HUB_ASSET_ID:()=>le,HYDRADX_OMNIPOOL_ADDRESS:()=>ue,HYDRADX_PARACHAIN_ID:()=>bt,HYDRADX_SS58_PREFIX:()=>K,INFINITY:()=>dt,LbpMath:()=>C,LbpPool:()=>ee,ONE:()=>E,OmniMath:()=>O,OmniPool:()=>te,PoolConfigNotFound:()=>qe,PoolError:()=>J,PoolFactory:()=>ie,PoolNotFound:()=>ce,PoolService:()=>Q,PoolType:()=>k,ProviderConfigNotFound:()=>We,RUNTIME_DECIMALS:()=>Z,RouteNotFound:()=>j,Router:()=>$,SYSTEM_ASSET_DECIMALS:()=>ht,SYSTEM_ASSET_ID:()=>L,StableMath:()=>_,StableSwap:()=>se,StorageConfigNotFound:()=>He,SubscriptionNotSupported:()=>ze,TRADEABLE_DEFAULT:()=>he,TradeRouter:()=>pe,TradeType:()=>Le,XykMath:()=>z,XykPool:()=>re,ZERO:()=>b,bnum:()=>m,buildRoute:()=>Oe,calculateBuyFee:()=>je,calculateDiffToAvg:()=>wt,calculateDiffToRef:()=>ne,calculateSellFee:()=>Ye,findNestedKey:()=>vt,findNestedObj:()=>It,scale:()=>v});module.exports=pt(At);var ge=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 gt=5,oe=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=[],i=new ge,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let a=i.dequeue();if(a==null||a.length>gt)return r;let o=a[a.length-1];(s===null||o[0]===s)&&r.push(a),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,a)){let p=[...a];p.push(c),i.enqueue(p)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,n]of t){let a=parseInt(i),o=parseInt(n);s.get(a)?.push([o,r])}return s}};function Me(l){let e={};for(let t of l){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let n=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(n)}}}return e}var ae=class{getProposals(e,t,s){let r=Me(s),i=Object.keys(r),n=i.map(c=>r[c]).flat(),a=new oe,o=a.buildAndPopulateGraph(i,n),u=a.findPaths(o,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let n=s[i],a=s[i+1];if(a==null)break;r.push(this.toEdge(n,a))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var de=(l,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=l(t)),s)};var x=require("bignumber.js"),$e=12;x.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:$e});var b=m(0),E=m(1),dt=m("Infinity");function v(l,e){let t=new x.BigNumber(e.toString()),s=new x.BigNumber(10).pow(t);return l.times(s)}function m(l){return new x.BigNumber(l.toString())}var k=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(k||{}),J=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(J||{}),Le=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Le||{});var G=require("@galacticcouncil/math-lbp"),C=class{static getSpotPrice(e,t,s,r,i){return(0,G.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,G.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,G.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,G.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,G.calculate_pool_trade_fee)(e,t,s)}};var Je=require("@polkadot/util-crypto"),Ze=require("@polkadot/util"),Z=18,he=15,L="0",ht=12,le="1",bt=2034,K=63,Pt=2090,be=1e3,ue=(0,Je.encodeAddress)((0,Ze.stringToU8a)("modlomnipool".padEnd(32,"\0")),K);var Zt=require("@galacticcouncil/api-augment/hydradx"),Kt=require("@galacticcouncil/api-augment/basilisk"),U=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var X=class extends U{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:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},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==L){let p=this.api.consts.balances.existentialDeposit;return{id:L,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:p.toString()}}let{name:i,assetType:n,isSufficient:a,existentialDeposit:o}=t,{symbol:u,decimals:c}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:u,decimals:c,icon:u,type:n.toHuman(),isSufficient:a?a.toHuman():!0,location:r?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,s,r){let[i,n]=r,{assetType:a,isSufficient:o,existentialDeposit:u}=t,{symbol:c,decimals:p}=this.getToken(i.toString(),t,s),h=n.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(h)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:p,icon:c,type:a.toString(),isSufficient:o.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,s,r){let{assets:i}=r,{name:n,symbol:a,assetType:o,isSufficient:u,existentialDeposit:c}=t,h=i.map(P=>P.toString()).map(P=>{let{symbol:y}=this.getToken(P,t,s);return[P,y]}),d=Object.fromEntries(h),g=Object.values(d);return{id:e,name:g.join(", "),symbol:a?.isSome?a.toHuman():n.toHuman(),decimals:18,icon:g.join("/"),type:o.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),n=s?.find(a=>a.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:n}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:n.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,i,n,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(s),u=this.normalizeMetadata(o,a),c=o.map(([{args:[p]},h])=>{let d=h.unwrap(),g=r.get(p.toString()),{assetType:P}=d;switch(P.toString()){case"Bond":let y=n.get(p.toString());return this.getBond(p.toString(),d,u,y);case"StableSwap":let S=i.get(p.toString());return this.getShares(p.toString(),d,u,S);case"External":return this.getExternal(p.toString(),d,t,g);default:return this.getToken(p.toString(),d,u,g)}});return e?c:c.filter(p=>this.isValidAsset(p))}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 Y=class extends U{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===L?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:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(L,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(n=>n.type!=="Erc20").filter(n=>n.id!==L).map(n=>[e,n.id]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,u)=>{let c=this.calculateFreeBalance(o),p=i[u][1];a.push([p,c])}),s(a)})}async subscribeErc20Balance(e,t,s){let r=t.filter(n=>n.type==="Erc20"),i=async()=>{let n=[];(await Promise.all(r.map(async o=>[o.id,await this.getErc20Balance(e,o.id)]))).forEach(([o,u])=>{n.push([o,u])}),s(n)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,n=new x.BigNumber(t),a=new x.BigNumber(s||i),o=new x.BigNumber(r||0n),u=a.gt(o)?a:o;return n.minus(u)}};var De=require("@polkadot/util-crypto"),Ce=require("@galacticcouncil/math-liquidity-mining");var Pe=class extends U{constructor(e){super(e)}secondsInYear=new x.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,a=i.unwrap().toString(),o=n.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,a)).unwrap(),p=await this.getOraclePrice(u)??u.priceAdjustment.toString();return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:p}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,a=i.unwrap().toString(),o=n.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,a)).unwrap(),p=await this.getOraclePrice(u)??u.priceAdjustment.toString();return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:p}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new x.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),a=n.price.n.toString(),o=n.price.d.toString(),u;return Number(t)<Number(s)?u=(0,Ce.fixed_from_rational)(a,o):u=(0,Ce.fixed_from_rational)(o,a),u}getGlobalRewardPerPeriod(e,t,s,r){let n=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return n.gte(s)?s:n}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,De.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,De.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:a,globalFarm:o,priceAdjustment:u})=>{let c=new x.BigNumber(o.totalSharesZ.toString()),p=o.plannedYieldingPeriods.toString(),h=new x.BigNumber(o.yieldPerPeriod.toString()),d=new x.BigNumber(o.maxRewardPerPeriod.toString()),g=o.blocksPerPeriod.toString(),P=new x.BigNumber(a.multiplier.toString()).shiftedBy(-18),y=this.secondsInYear.div(new x.BigNumber(s).times(g)),S;if(c.isZero())S=h.times(P).times(y);else{let W=this.getGlobalRewardPerPeriod(c,h,d,u);S=this.getPoolYieldPerPeriod(W,P,c,u).times(y)}let B=new x.BigNumber(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),R=d.times(p);return B.div(R).gte(.99)?b:S.times(100)}).reduce((a,o)=>a.plus(o),b).toString():void 0}};var H=class extends Y{pools=[];subs=[];assets=new Map([]);mem=0;memPools=de(e=>(console.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));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 this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return console.log(e,`pools(${this.augmentedPools.length})`,"\u2705"),console.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[this.subscribeTokensPoolBalance(t)];try{let r=this.subscribePoolChange(t);s.push(r)}catch{}if(this.hasSystemAsset(t)){let r=this.subscribeSystemPoolBalance(t);s.push(r)}if(this.hasErc20Asset(t)){let r=this.subscribeErc20PoolBalance(t);s.push(r)}if(this.hasShareAsset(t)){let r=this.subscribeSharePoolBalance(t);s.push(r)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}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("...");console.log(`${e.type} [${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))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(ue,[t],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,i])=>{let n=e.tokens.findIndex(a=>a.id==r);n>=0&&t(e,r)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var fe=class extends H{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(([i,n])=>this.isActivePool(n.unwrap(),s)).map(async([{args:[i]},n])=>{let a=n.unwrap(),o=i.toString(),u=await this.getPoolDelta(o,a,s.toString());return this.poolsData.set(i.toString(),a),{address:o,type:"Lbp",fee:a.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let n=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(a=>a.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:n,initialWeight:a,finalWeight:o,repayTarget:u,feeCollector:c}=t,p=C.calculateLinearWeights(r.toString(),i.toString(),a.toString(),o.toString(),s),[h,d]=n,g=h.toString(),P=m(p),y=d.toString(),S=this.MAX_FINAL_WEIGHT.minus(m(P)),[B,R,N]=await Promise.all([this.isRepayFeeApplied(g,u.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,y)]);return{repayFeeApply:B,tokens:[{id:g,weight:P,balance:R.toString()},{id:y,weight:S,balance:N.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}}};var Ke=require("@polkadot/util-crypto"),Qe=require("@polkadot/util");function F(l,e){return l.shiftedBy(-1*e).toString()}function T(l){return l[0]/l[1]*100}function M(l){return l[0]/l[1]}function D(l){return[l/be,be]}var f=require("@galacticcouncil/math-omnipool");var O=class{static calculateSpotPrice(e,t,s,r){return(0,f.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,f.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,n,a,o,u){return(0,f.calculate_in_given_out)(e,t,s,r,i,n,a,o,u)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,f.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,n,a,o,u){return(0,f.calculate_out_given_in)(e,t,s,r,i,n,a,o,u)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,f.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,f.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,f.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,n,a,o){return(0,f.calculate_liquidity_out)(e,t,s,r,i,n,a,o)}static calculateLiquidityLRNAOut(e,t,s,r,i,n,a,o){return(0,f.calculate_liquidity_lrna_out)(e,t,s,r,i,n,a,o)}static calculateCapDifference(e,t,s,r){let i=(0,x.BigNumber)(t),n=(0,x.BigNumber)(e),a=(0,x.BigNumber)(r),u=(0,x.BigNumber)(s).shiftedBy(-18);if(i.div(a).lt(u)){let p=u.times(a).minus(i).times(n),h=i.times((0,x.BigNumber)(1).minus(u));return p.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return(0,f.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,f.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,f.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,f.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,f.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,i,n,a,o,u,c,p){return(0,f.recalculate_asset_fee)(e,t,s,r,i,n,a,o,u,c,p)}static recalculateProtocolFee(e,t,s,r,i,n,a,o,u,c,p){return(0,f.recalculate_protocol_fee)(e,t,s,r,i,n,a,o,u,c,p)}static verifyAssetCap(e,t,s,r){return(0,f.verify_asset_cap)(e,t,s,r)}};var ye=class extends H{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=s.map(async([{args:[o]},u])=>{let{hubReserve:c,shares:p,tradable:h,cap:d,protocolShares:g}=u.unwrap(),P=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:m(c.toString()),shares:m(p.toString()),tradeable:h.bits.toNumber(),balance:P.toString(),cap:m(d.toString()),protocolShares:m(g.toString())}}),a=await Promise.all(n);return a.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:a,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,i="omnipool",n="Short",a=N=>N===L?[L,le]:[le,N],[o,u,c,p]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(i,a(s),n),this.api.query.emaOracle.oracles(i,a(r),n)]),[h,d,g]=this.getAssetFee(e,o.toNumber(),u,c),[P,y,S]=r===le?[0,0,0]:this.getProtocolFee(e,o.toNumber(),u,p),B=h+P,R=g+S;return{assetFee:D(d),protocolFee:D(y),min:D(B),max:D(R)}}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,i)=>{let n=e.tokens[i];if(r.isNone)return n;let a=r.unwrap();return this.updateTokenState(n,a)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i,cap:n,protocolShares:a}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(n.toString()),protocolShares:m(a.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:i,balanceOut:n}=e,{minFee:a,maxFee:o,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,p=D(a.toNumber()),h=D(o.toNumber());if(s.isNone||r.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[d]=r.unwrap(),{assetFee:g,timestamp:P}=s.unwrap(),y=t-P.toNumber(),S=d.volume.bIn.toString(),B=d.volume.bOut.toString(),R=d.liquidity.b.toString();i===L&&(S=d.volume.aIn.toString(),B=d.volume.aOut.toString(),R=d.liquidity.a.toString());let N=D(g.toNumber()),W=O.recalculateAssetFee(S,B,R,"9",n.toString(),T(N).toString(),y.toString(),T(p).toString(),T(h).toString(),u.toString(),c.toString());return[a.toNumber(),Number(W)*1e4,o.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:i,balanceIn:n}=e,{minFee:a,maxFee:o,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,p=D(a.toNumber()),h=D(o.toNumber());if(s.isNone||r.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[d]=r.unwrap(),{protocolFee:g,timestamp:P}=s.unwrap(),y=t-P.toNumber(),S=d.volume.bIn.toString(),B=d.volume.bOut.toString(),R=d.liquidity.b.toString();i===L&&(S=d.volume.aIn.toString(),B=d.volume.aOut.toString(),R=d.liquidity.a.toString());let N=D(g.toNumber()),W=O.recalculateProtocolFee(S,B,R,"9",n.toString(),T(N).toString(),y.toString(),T(p).toString(),T(h).toString(),u.toString(),c.toString());return[a.toNumber(),Number(W)*1e4,o.toNumber()]}getPoolId(){return(0,Ke.encodeAddress)((0,Qe.stringToU8a)("modlomnipool".padEnd(32,"\0")),K)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Se=class extends H{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[n,a]=r.unwrap(),[o,u]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,a.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:o.toString()},{id:a.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var xe=require("@polkadot/util-crypto");var I=require("@galacticcouncil/math-stableswap"),_=class{static getPoolAddress(e){return(0,I.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,I.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,n){return(0,I.calculate_in_given_out)(e,t,s,r,i,n)}static calculateAddOneAsset(e,t,s,r,i,n){return(0,I.calculate_add_one_asset)(e,t,s,r,i,n)}static calculateSharesForAmount(e,t,s,r,i,n){return(0,I.calculate_shares_for_amount)(e,t,s,r,i,n)}static calculateOutGivenIn(e,t,s,r,i,n){return(0,I.calculate_out_given_in)(e,t,s,r,i,n)}static calculateLiquidityOutOneAsset(e,t,s,r,i,n){return(0,I.calculate_liquidity_out_one_asset)(e,t,s,r,i,n)}static calculateShares(e,t,s,r,i){return(0,I.calculate_shares)(e,t,s,r,i)}static calculateSpotPriceWithFee(e,t,s,r,i,n,a){return(0,I.calculate_spot_price_with_fee)(e,t,s,r,i,n,a)}static calculatePoolTradeFee(e,t,s){return(0,I.calculate_pool_trade_fee)(e,t,s)}};var Be=class extends H{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},n])=>{let a=n.unwrap(),o=i.toString(),u=this.getPoolAddress(o),[c,p]=await Promise.all([this.getPoolDelta(o,a,s.toString()),this.getPoolTokens(u,o,a)]);return this.stablePools.set(u,a),{address:u,id:o,type:"Stableswap",fee:D(a.fee.toNumber()),tokens:p,...c,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:n,finalBlock:a}=t,o=_.calculateAmplification(r.toString(),i.toString(),n.toString(),a.toString(),s),u=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:u.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async o=>{let[u,c]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:u.bits.toNumber(),balance:c.toString()}}),n=await Promise.all(i),a=await this.api.query.omnipool.assets(t);if(a.isSome){let{tradable:o}=a.unwrap(),u=await this.getBalance(ue,t);n.push({id:t,tradeable:o.bits.toNumber(),balance:u.toString()})}return n}getPoolAddress(e){let t=Number(e),s=_.getPoolAddress(t);return(0,xe.encodeAddress)((0,xe.blake2AsHex)(s),K)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Oe(l){return l.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var ce=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},qe=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},j=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Ge=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},He=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},ze=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},We=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Q=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=de(e=>(console.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){this.api=e,this.assetClient=new X(this.api),this.xykClient=new Se(this.api),this.omniClient=new ye(this.api),this.lbpClient=new fe(this.api),this.stableClient=new Be(this.api),this.clients=[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()}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){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 ce(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let n;this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):n=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Oe(i));let a=()=>n;return{hex:n.toHex(),name:"RouterBuy",get:a}}buildSellTx(e,t,s,r,i){let n;this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):n=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Oe(i));let a=()=>n;return{hex:n.toHex(),name:"RouterSell",get:a}}};var me=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var we=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var ft=we(()=>"illegal argument(s)"),Ve=l=>{throw new ft(l)};var yt=we(()=>"index out of bounds"),Ue=l=>{throw new yt(l)},ve=(l,e,t)=>(l<e||l>=t)&&Ue(l);var et=23283064365386963e-26,Ie=class{float(e=1){return this.int()*et*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*et-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var Ae=class extends Ie{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var tt=new Ae(Math.random);var st=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var rt=Object.getPrototypeOf({}),Te="function",it="string",V=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Te)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Te)return e.equiv(l)}else return l==e;return typeof l===it||typeof e===it?!1:(t=Object.getPrototypeOf(l),(t==null||t===rt)&&(t=Object.getPrototypeOf(e),t==null||t===rt)?Ot(l,e):typeof l!==Te&&l.length!==void 0&&typeof e!==Te&&e.length!==void 0?St(l,e):l instanceof Set&&e instanceof Set?Bt(l,e):l instanceof Map&&e instanceof Map?xt(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},St=(l,e,t=V)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},Bt=(l,e,t=V)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),xt=(l,e,t=V)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Ot=(l,e,t=V)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var Xe=class{value;constructor(e){this.value=e}deref(){return this.value}};var nt=l=>l instanceof Xe;var Ne=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return ot("next",this._head)}reverseIterator(){return ot("prev",this.tail)}clear(){this.release()}compare(e,t=me){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,n=0;for(;s-- >0&&n===0;)n=t(r.value,i.value),r=r.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof l||st(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!V(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||me;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!nt(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&Ue(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*ot(l,e){for(;e;)yield e.value,e=e[l]}var Fe=class l extends Ne{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(ve(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(ve(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==r&&n.next?i(n.next):void 0}});return s?i(s):void 0}shuffle(e,t=tt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&Ve("invalid indices: ${from} / ${to}");let i=new l,n=this.nthCell(s);for(;n&&++s<=r;)i.push(n.value),n=n.next;return i}sort(e=me){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,n=0;for(let o=0;o<t&&(n++,i=i.next,!!i);o++);let a=t;for(;n>0||a>0&&i;){let o;n===0?(o=i,i=i.next,a--):!i||a===0||e(s.value,i.value)<=0?(o=s,s=s.next,n--):(o=i,i=i.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),ve(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new l;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let n of s)this.insertBefore(r,n);else for(let n of s)this.push(n);return i}};var _e=class l{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new Fe,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Re=class extends Q{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new _e(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 i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ee=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,n,a){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=a}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(o=>[o.id,o])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(r.balance),a=m(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let a=this.calculateTradeFee(t,s),o=T(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(a),c=this.calculateInGivenOut(e,u),p=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(p)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:i}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:i}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,s),u=T(this.repayFeeApply?s.repayFee:s.exchangeFee),c=a.minus(o),p=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(p)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let s=C.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=C.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=C.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),v(E,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=C.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),v(E,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=C.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var te=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=n}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),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(r.balance),a=m(i.balance),o=m(r.existentialDeposit),u=m(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:o,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=i.minus(r),a=r===b?b:n.div(r).multipliedBy(100).decimalPlaces(2),o=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let p=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(p)&&o.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),o=[],u=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!u||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let p=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(p)&&o.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a.toNumber(),errors:o}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=O.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString(),s?M(s.protocolFee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateLrnaInGivenOut(e,t,s){let r=O.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=O.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString(),s?M(s.protocolFee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateOutGivenLrnaIn(e,t,s){let r=O.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?M(s.assetFee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=O.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(Z-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=O.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(Z-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=O.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(Z-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=O.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(Z-e.decimalsIn)).decimalPlaces(0,1)}};var se=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,n,a,o,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=n,this.id=a,this.fee=o,this.totalIssuance=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(r.balance),a=m(i.balance),o=m(r.existentialDeposit),u=m(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?he:r.tradeable,tradeableOut:this.id===t?he:i.tradeable,assetInED:o,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=T(s.fee),a=[],o=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!o||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),n=T(s.fee),a=[],o=O.isSellAllowed(e.tradeableIn),u=O.isBuyAllowed(e.tradeableOut);return(!o||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:a}}calculateIn(e,t,s){let r=_.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?M(s.fee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateAddOneAsset(e,t,s){let r=_.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateSharesForAmount(e,t,s){let r=_.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateInGivenOut(e,t,s){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,s):e.assetIn==this.id?this.calculateSharesForAmount(e,t,s):this.calculateIn(e,t,s)}spotPriceInGivenOut(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0");if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=v(E,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=v(E,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=_.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?M(s.fee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateWithdrawOneAsset(e,t,s){let r=_.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateShares(e,t,s){let r=_.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?M(s.fee).toString():b.toString()),i=m(r);return i.isNegative()?b:i}calculateOutGivenIn(e,t,s){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,s):e.assetOut==this.id?this.calculateShares(e,t,s):this.calculateOut(e,t,s)}spotPriceOutGivenIn(e){let t=_.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0");if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=v(E,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=v(E,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=_.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var A=require("@galacticcouncil/math-xyk"),z=class{static getSpotPrice(e,t,s){return(0,A.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,A.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,A.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,A.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,A.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,A.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,A.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,A.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,A.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,A.calculate_liquidity_out_asset_b)(e,t,s,r)}};var re=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(r.balance),a=m(i.balance),o=m(r.existentialDeposit),u=m(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:o,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),n=T(s.exchangeFee),a=r.plus(i),o=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&o.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),n=T(s.exchangeFee),a=r.minus(i),o=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&o.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(e,t){let s=z.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=z.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=z.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=v(E,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=z.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=v(E,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=z.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var ie=class{static get(e){switch(e.type){case"Xyk":return re.fromPool(e);case"Omnipool":return te.fromPool(e);case"Lbp":return ee.fromPool(e);case"Stableswap":return se.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var $=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new ae,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),n=this.getPaths(e,null,r,t).map(a=>a[a.length-1].assetOut);return this.toAssets([...new Set(n)],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(a=>this.validPath(a,s)).map(a=>this.toHops(a,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 i=this.getPoolMap(s);return{assets:r,poolsMap:i}}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,ie.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,i])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function wt(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ne(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ye(l,e){return E.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function je(l,e){return e.div(l).minus(E).multipliedBy(100).decimalPlaces(2)}var pe=class extends ${isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return i.isGreaterThan(n)?-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(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?T(e.min):void 0,s=e.max?T(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 i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),a=super.getPaths(e,t,n,i);if(a.length===0)throw new j(e,t);let o;if(r)o=await this.toSellSwaps(s,r,n);else{let w=a.map(async Ee=>await this.toSellSwaps(s,Ee,n)),q=await Promise.all(w);o=this.findBestSellRoute(q)}let u=o[0],c=o[o.length-1],p=this.isDirectTrade(o),h=o.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,q)=>w.multipliedBy(q)),d=v(h,c.assetOutDecimals),g=p?c.calculatedOut:this.calculateDelta0Y(u.amountIn,o,n),P=c.amountOut,y=p?c.tradeFeePct:Ye(g,P).toNumber(),S=g.minus(P),B=this.getRouteFeeRange(o),R=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(d),N=ne(g,R),W=w=>this.poolService.buildSellTx(e,t,u.amountIn,w,o.map(q=>q));return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:S,tradeFeePct:y,tradeFeeRange:B,priceImpactPct:N.toNumber(),swaps:o,toTx:W,toHuman(){return{type:"Sell",amountIn:F(u.amountIn,u.assetInDecimals),amountOut:F(c.amountOut,c.assetOutDecimals),spotPrice:F(d,c.assetOutDecimals),tradeFee:F(S,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:B,priceImpactPct:N.toNumber(),swaps:o.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1]:u=e;let c=a.calculateOutGivenIn(o,u);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1].amountOut:u=v(m(e),o.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(o,a),{amountOut:p,calculatedOut:h,feePct:d,errors:g}=a.validateAndSell(o,u,c),P=this.getPoolFeeRange(c),y=a.spotPriceOutGivenIn(o),S=u.shiftedBy(-1*o.decimalsIn).multipliedBy(y),B=ne(h,S);r.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:u,calculatedOut:h,amountOut:p,spotPrice:y,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:B.toNumber(),errors:g,toHuman(){return{...n,amountIn:F(u,o.decimalsIn),calculatedOut:F(h,o.decimalsOut),amountOut:F(p,o.decimalsOut),spotPrice:F(y,o.decimalsOut),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:B.toNumber(),errors:g}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)throw new j(e,t);let n=s.map(g=>g.tokens.find(P=>P.id===e)).filter(g=>!!g).sort((g,P)=>Number(P.balance)-Number(g.balance)),{balance:a,decimals:o}=n[0],c=m(a).shiftedBy(-1*o).div(100).multipliedBy(.1),p=i.map(async g=>await this.toSellSwaps(c,g,r)),h=await Promise.all(p);return this.findBestSellRoute(h).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.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 n=await this.getMostLiquidRoute(e,t),a=await this.toSellSwaps("1",n,r),o=a.map(p=>p.spotPrice.shiftedBy(-1*p.assetOutDecimals)).reduce((p,h)=>p.multipliedBy(h)),u=a[a.length-1].assetOutDecimals;return{amount:v(o,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,n=r[0].amountIn;return i.isGreaterThan(n)?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 i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),a=super.getPaths(e,t,n,i);if(a.length===0)throw new j(e,t);let o;if(r)o=await this.toBuySwaps(s,r,n);else{let w=a.map(async Ee=>await this.toBuySwaps(s,Ee,n)),q=await Promise.all(w);o=this.findBestBuyRoute(q)}let u=o[o.length-1],c=o[0],p=this.isDirectTrade(o),h=o.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,q)=>w.multipliedBy(q)),d=v(h,c.assetInDecimals),g=p?c.calculatedIn:this.calculateDelta0X(u.amountOut,o,n),P=c.amountIn,y=p?c.tradeFeePct:je(g,P).toNumber(),S=P.minus(g),B=this.getRouteFeeRange(o),R=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(d),N;g.isZero()?N=-100:N=ne(R,g).toNumber();let W=w=>this.poolService.buildBuyTx(e,t,u.amountOut,w,o.map(q=>q));return{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:S,tradeFeePct:y,tradeFeeRange:B,priceImpactPct:N,swaps:o,toTx:W,toHuman(){return{type:"Buy",amountOut:F(u.amountOut,u.assetOutDecimals),amountIn:F(c.amountIn,c.assetInDecimals),spotPrice:F(d,c.assetInDecimals),tradeFee:F(S,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:B,priceImpactPct:N,swaps:o.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=r[0];let c=a.calculateInGivenOut(o,u);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=v(m(e),o.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(o,a),{amountIn:p,calculatedIn:h,feePct:d,errors:g}=a.validateAndBuy(o,u,c),P=this.getPoolFeeRange(c),y=a.spotPriceInGivenOut(o),S=u.shiftedBy(-1*o.decimalsOut).multipliedBy(y),B;h.isZero()?B=-100:B=ne(S,h).toNumber(),r.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:u,calculatedIn:h,amountIn:p,spotPrice:y,tradeFeePct:d,tradeFeeRange:P,priceImpactPct:B,errors:g,toHuman(){return{...n,amountOut:F(u,o.decimalsOut),calculatedIn:F(h,o.decimalsIn),amountIn:F(p,o.decimalsIn),spotPrice:F(y,o.decimalsIn),tradeFeePct:d,tradeFeeRange:P,priceImpactPct:B,errors:g}}})}return r}};function vt(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function It(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}0&&(module.exports={AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HUB_ASSET_ID,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
1
+ "use strict";var De=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var ft=Object.getOwnPropertyNames;var yt=Object.prototype.hasOwnProperty;var St=(l,e)=>{for(var t in e)De(l,t,{get:e[t],enumerable:!0})},xt=(l,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ft(e))!yt.call(l,r)&&r!==t&&De(l,r,{get:()=>e[r],enumerable:!(s=bt(e,r))||s.enumerable});return l};var Bt=l=>xt(De({},"__esModule",{value:!0}),l);var Dt={};St(Dt,{AavePool:()=>ie,AssetClient:()=>j,AssetNotFound:()=>Xe,BASILISK_PARACHAIN_ID:()=>It,BalanceClient:()=>X,BigNumber:()=>x.BigNumber,CachingPoolService:()=>Me,DECIMAL_PLACES:()=>st,DENOMINATOR:()=>fe,FarmClient:()=>Se,HUB_ASSET_ID:()=>ue,HYDRADX_OMNIPOOL_ADDRESS:()=>ce,HYDRADX_PARACHAIN_ID:()=>wt,HYDRADX_SS58_PREFIX:()=>Y,INFINITY:()=>Tt,LbpMath:()=>H,LbpPool:()=>ee,ONE:()=>F,OmniMath:()=>B,OmniPool:()=>te,PolkadotApiClient:()=>G,PoolConfigNotFound:()=>We,PoolError:()=>$,PoolFactory:()=>ne,PoolNotFound:()=>me,PoolService:()=>Z,PoolType:()=>k,ProviderConfigNotFound:()=>je,RUNTIME_DECIMALS:()=>V,RouteNotFound:()=>J,Router:()=>K,SYSTEM_ASSET_DECIMALS:()=>Ot,SYSTEM_ASSET_ID:()=>D,StableMath:()=>R,StableSwap:()=>se,StorageConfigNotFound:()=>Ye,SubscriptionNotSupported:()=>$e,TRADEABLE_DEFAULT:()=>be,TradeRouter:()=>de,TradeType:()=>Ge,XykMath:()=>z,XykPool:()=>re,ZERO:()=>P,bnum:()=>p,buildRoute:()=>Ae,calculateBuyFee:()=>Ze,calculateDiffToAvg:()=>Mt,calculateDiffToRef:()=>oe,calculateSellFee:()=>Ve,findNestedKey:()=>qe,findNestedObj:()=>At,scale:()=>O});module.exports=Bt(Dt);var he=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var vt=5,ae=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=[],i=new he,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let a=i.dequeue();if(a==null||a.length>vt)return r;let o=a[a.length-1];(s===null||o[0]===s)&&r.push(a),e.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,a)){let m=[...a];m.push(c),i.enqueue(m)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,n]of t){let a=parseInt(i),o=parseInt(n);s.get(a)?.push([o,r])}return s}};function Ce(l){let e={};for(let t of l){let s=t.tokens.length;for(let r=0;r<s;r++){e[t.tokens[r].id]||(e[t.tokens[r].id]=[]);for(let i=0;i<s;i++){if(r==i)continue;let n=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(n)}}}return e}var le=class{getProposals(e,t,s){let r=Ce(s),i=Object.keys(r),n=i.map(c=>r[c]).flat(),a=new ae,o=a.buildAndPopulateGraph(i,n),u=a.findPaths(o,parseInt(e),t?parseInt(t):null);return this.parsePaths(u)}parsePaths(e){let t=[];for(let s of e){let r=[];for(let i=0;i<s.length;i++){let n=s[i],a=s[i+1];if(a==null)break;r.push(this.toEdge(n,a))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var Pe=(l,e=new Map)=>t=>{let s;return e.has(t)?e.get(t):(e.set(t,s=l(t)),s)};var it=require("@polkadot/util-crypto"),nt=require("@polkadot/util"),ot=require("viem");var Qe=[{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"},{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"},{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"}];var et=require("@polkadot/util-crypto"),tt=require("@polkadot/util"),V=18,be=15,D="0",Ot=12,ue="1",wt=2034,Y=63,It=2090,fe=1e3,ce=(0,et.encodeAddress)((0,tt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Y);var k=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i))(k||{}),$=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))($||{}),Ge=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ge||{});var ye=class{static encodeEvmAddress(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static decodeEvmAddress(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))}};function qe(l,e){let t=[];return JSON.stringify(l,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function At(l,e,t){let s;return JSON.stringify(l,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}var as=require("@galacticcouncil/api-augment/hydradx"),ls=require("@galacticcouncil/api-augment/basilisk"),G=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let 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 j=class extends G{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:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,s,r){if(e==D){let m=this.api.consts.balances.existentialDeposit;return{id:D,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:a,existentialDeposit:o}=t,{symbol:u,decimals:c}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:u,decimals:c,icon:u,type:n.toHuman(),isSufficient:a?a.toHuman():!0,location:r?.toJSON(),existentialDeposit:o.toString()}}getBond(e,t,s,r){let[i,n]=r,{assetType:a,isSufficient:o,existentialDeposit:u}=t,{symbol:c,decimals:m}=this.getToken(i.toString(),t,s),h=n.toNumber(),g=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",g.format(h)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:m,icon:c,type:a.toString(),isSufficient:o.toHuman(),existentialDeposit:u.toString(),underlyingAssetId:i.toString(),maturity:h}}getShares(e,t,s,r){let{assets:i}=r,{name:n,symbol:a,assetType:o,isSufficient:u,existentialDeposit:c}=t,h=i.map(b=>b.toString()).map(b=>{let{symbol:y}=this.getToken(b,t,s);return[b,y]}),g=Object.fromEntries(h),d=Object.values(g);return{id:e,name:d.join(", "),symbol:a?.isSome?a.toHuman():n.toHuman(),decimals:18,icon:d.join("/"),type:o.toString(),isSufficient:u.toHuman(),existentialDeposit:c.toString(),meta:g}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),n=s?.find(a=>a.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:n}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:n.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,i,n,a]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),o=this.getSupportedAssets(s),u=this.normalizeMetadata(o,a),c=o.map(([{args:[m]},h])=>{let g=h.unwrap(),d=r.get(m.toString()),{assetType:b}=g;switch(b.toString()){case"Bond":let y=n.get(m.toString());return this.getBond(m.toString(),g,u,y);case"StableSwap":let v=i.get(m.toString());return this.getShares(m.toString(),g,u,v);case"External":return this.getExternal(m.toString(),g,t,d);default:return this.getToken(m.toString(),g,u,d)}});return e?c:c.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var x=require("bignumber.js"),st=12;x.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:st});var P=p(0),F=p(1),Tt=p("Infinity");function O(l,e){let t=new x.BigNumber(e.toString()),s=new x.BigNumber(10).pow(t);return l.times(s)}function p(l){return new x.BigNumber(l.toString())}var X=class extends G{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===D?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let{free:s,reserved:r,frozen:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(D,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(n=>n.type!=="Erc20").filter(n=>n.id!==D).map(n=>[e,n.id]);return this.api.query.tokens.accounts.multi(i,n=>{let a=[];n.forEach((o,u)=>{let c=this.calculateFreeBalance(o),m=i[u][1];a.push([m,c])}),s(a)})}async subscribeErc20Balance(e,t,s){let r=t.filter(n=>n.type==="Erc20"),i=async()=>{let n=[];(await Promise.all(r.map(async o=>[o.id,await this.getErc20Balance(e,o.id)]))).forEach(([o,u])=>{n.push([o,u])}),s(n)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,n=new x.BigNumber(t),a=new x.BigNumber(s||i),o=new x.BigNumber(r||0n),u=a.gt(o)?a:o;return n.minus(u)}};var He=require("@polkadot/util-crypto"),Ue=require("@galacticcouncil/math-liquidity-mining");var rt=require("@polkadot/types"),ze=require("@polkadot/util"),Se=class extends G{balanceClient;constructor(e){super(e),this.balanceClient=new X(e)}secondsInYear=new x.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,a=i.unwrap().toString(),o=n.toString(),u=(await this.api.query.omnipoolWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(o),!1).toString(),d=u.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,n]=r.args,a=i.unwrap().toString(),o=n.toString(),u=(await this.api.query.xykWarehouseLM.globalFarm(o)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,o,a)).unwrap(),m=await this.getOraclePrice(u)??u.priceAdjustment.toString(),g=this.getAccountResolver(this.api.registry)(Number(o),!0).toString(),d=u.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(g,d);return{assetId:e,globalFarm:u,yieldFarm:c,priceAdjustment:m,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new x.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),a=n.price.n.toString(),o=n.price.d.toString(),u;return Number(t)<Number(s)?u=(0,Ue.fixed_from_rational)(a,o):u=(0,Ue.fixed_from_rational)(o,a),u}getGlobalRewardPerPeriod(e,t,s,r){let n=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return n.gte(s)?s:n}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}padEndU8a(e,t){return(0,ze.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",i=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new rt.GenericAccountId32(e,this.padEndU8a((0,ze.u8aConcat)(r,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,He.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,He.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let s=6,r=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return r.length?r.map(({yieldFarm:a,globalFarm:o,priceAdjustment:u,potBalance:c})=>{let m=new x.BigNumber(o.totalSharesZ.toString()),h=o.plannedYieldingPeriods.toString(),g=new x.BigNumber(o.yieldPerPeriod.toString()),d=new x.BigNumber(o.maxRewardPerPeriod.toString()),b=o.blocksPerPeriod.toString(),y=new x.BigNumber(a.multiplier.toString()).shiftedBy(-18),v=this.secondsInYear.div(new x.BigNumber(s).times(b)),S;if(m.isZero())S=g.times(y).times(v);else{let M=this.getGlobalRewardPerPeriod(m,g,d,u);S=this.getPoolYieldPerPeriod(M,y,m,u).times(v)}let E=new x.BigNumber(o.pendingRewards.toString()).plus(o.accumulatedPaidRewards.toString()),N=d.times(h),W=c?E.plus(c):N;return E.div(W).gte(.999)?P:S.div(t==="isolatedpool"?2:1).times(100)}).reduce((a,o)=>a.plus(o),P).toString():void 0}};var q=class extends X{pools=[];subs=[];assets=new Map([]);mem=0;memPools=Pe(e=>(this.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));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 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,`pools(${this.augmentedPools.length})`,"\u2705"),this.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let i=this.subscribePoolChange(t);s.push(i)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let i=this.subscribeSystemPoolBalance(t);s.push(i)}if(this.hasErc20Asset(t)){let i=this.subscribeErc20PoolBalance(t);s.push(i)}if(this.hasShareAsset(t)){let i=this.subscribeSharePoolBalance(t);s.push(i)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}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} [${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))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(ce,[t],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,i])=>{let n=e.tokens.findIndex(a=>a.id==r);n>=0&&t(e,r)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var Nt=["Supply","Withdraw","Repay","Borrow"],xe=class extends q{isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:s,liqudityIn:r,liqudityOut:i})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return(0,it.encodeAddress)((0,nt.stringToU8a)(s.padEnd(32,"\0")),Y)}subscribePoolChange(e){let t=e.tokens.map(i=>i.id),[s]=e.tokens,r=this.getReserveH160Id(s);return this.api.query.system.events(i=>{i.forEach(n=>{let{event:a}=n,o=`${a.section}:${a.method}`;if(o==="router:Executed"){let{assetIn:u,assetOut:c}=a.data.toHuman(),m=u.replace(/,/g,""),h=c.replace(/,/g,"");t.includes(m)&&t.includes(h)&&(this.log("Sync AAVE [router:Executed]",t),this.updatePoolState(e))}if(o==="evm:Log"){let{log:u}=a.data.toHuman();try{let{eventName:c,args:m}=(0,ot.decodeEventLog)({abi:Qe,topics:u.topics,data:u.data});Nt.includes(c)&&m.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${s.symbol}(${s.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(n=>{let a=n.id===t.id?r.toString():i.toString();return{...n,balance:a}})}getReserveH160Id(e){return e.type==="Erc20"?qe(e.location,"accountKey20").accountKey20.key:ye.encodeEvmAddress(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};var U=require("@galacticcouncil/math-lbp"),H=class{static getSpotPrice(e,t,s,r,i){return(0,U.get_spot_price)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return(0,U.calculate_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return(0,U.calculate_out_given_in)(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return(0,U.calculate_linear_weights)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,U.calculate_pool_trade_fee)(e,t,s)}};var Be=class extends q{MAX_FINAL_WEIGHT=O(p(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,n])=>this.isActivePool(n.unwrap(),s)).map(async([{args:[i]},n])=>{let a=n.unwrap(),o=i.toString(),u=await this.getPoolDelta(o,a,s.toString());return this.poolsData.set(i.toString(),a),{address:o,type:"Lbp",fee:a.fee.toJSON(),...u,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){let s=this.pools.find(r=>r.address===t);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getPoolType(){return"Lbp"}async subscribePoolChange(e){return this.api.query.parachainSystem.validationData(async t=>{let{relayParentNumber:s}=t.unwrap(),r=this.poolsData.get(e.address);if(this.isActivePool(r,s)){let n=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,n)}else{let n=this.pools.findIndex(a=>a.address==e.address);this.pools.splice(n,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:n,initialWeight:a,finalWeight:o,repayTarget:u,feeCollector:c}=t,m=H.calculateLinearWeights(r.toString(),i.toString(),a.toString(),o.toString(),s),[h,g]=n,d=h.toString(),b=p(m),y=g.toString(),v=this.MAX_FINAL_WEIGHT.minus(p(b)),[S,E,N]=await Promise.all([this.isRepayFeeApplied(d,u.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,y)]);return{repayFeeApply:S,tokens:[{id:d,weight:b,balance:E.toString()},{id:y,weight:v,balance:N.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=p(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var at=require("@polkadot/util-crypto"),lt=require("@polkadot/util");function _(l,e){return l.shiftedBy(-1*e).toString()}function T(l){return l[0]/l[1]*100}function L(l){return l[0]/l[1]}function C(l){return[l/fe,fe]}var f=require("@galacticcouncil/math-omnipool");var B=class{static calculateSpotPrice(e,t,s,r){return(0,f.calculate_spot_price)(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return(0,f.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,s,r,i,n,a,o,u){return(0,f.calculate_in_given_out)(e,t,s,r,i,n,a,o,u)}static calculateLrnaInGivenOut(e,t,s,r,i){return(0,f.calculate_lrna_in_given_out)(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,n,a,o,u){return(0,f.calculate_out_given_in)(e,t,s,r,i,n,a,o,u)}static calculateOutGivenLrnaIn(e,t,s,r,i){return(0,f.calculate_out_given_lrna_in)(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return(0,f.calculate_pool_trade_fee)(e,t,s)}static calculateShares(e,t,s,r){return(0,f.calculate_shares)(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,n,a,o){return(0,f.calculate_liquidity_out)(e,t,s,r,i,n,a,o)}static calculateLiquidityLRNAOut(e,t,s,r,i,n,a,o){return(0,f.calculate_liquidity_lrna_out)(e,t,s,r,i,n,a,o)}static calculateCapDifference(e,t,s,r){let i=(0,x.BigNumber)(t),n=(0,x.BigNumber)(e),a=(0,x.BigNumber)(r),u=(0,x.BigNumber)(s).shiftedBy(-18);if(i.div(a).lt(u)){let m=u.times(a).minus(i).times(n),h=i.times((0,x.BigNumber)(1).minus(u));return m.div(h).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return(0,f.calculate_liquidity_hub_in)(e,t,s,r)}static isSellAllowed(e){return(0,f.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,f.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,f.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,f.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,s,r,i,n,a,o,u,c,m){return(0,f.recalculate_asset_fee)(e,t,s,r,i,n,a,o,u,c,m)}static recalculateProtocolFee(e,t,s,r,i,n,a,o,u,c,m){return(0,f.recalculate_protocol_fee)(e,t,s,r,i,n,a,o,u,c,m)}static verifyAssetCap(e,t,s,r){return(0,f.verify_asset_cap)(e,t,s,r)}};var ve=class extends q{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=s.map(async([{args:[o]},u])=>{let{hubReserve:c,shares:m,tradable:h,cap:g,protocolShares:d}=u.unwrap(),b=await this.getBalance(t,o.toString());return{id:o.toString(),hubReserves:p(c.toString()),shares:p(m.toString()),tradeable:h.bits.toNumber(),balance:b.toString(),cap:p(g.toString()),protocolShares:p(d.toString())}}),a=await Promise.all(n);return a.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:a,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,i="omnipool",n="Short",a=N=>N===D?[D,ue]:[ue,N],[o,u,c,m]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(i,a(s),n),this.api.query.emaOracle.oracles(i,a(r),n)]),[h,g,d]=this.getAssetFee(e,o.toNumber(),u,c),[b,y,v]=r===ue?[0,0,0]:this.getProtocolFee(e,o.toNumber(),u,m),S=h+b,E=d+v;return{assetFee:C(g),protocolFee:C(y),min:C(S),max:C(E)}}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,i)=>{let n=e.tokens[i];if(r.isNone)return n;let a=r.unwrap();return this.updateTokenState(n,a)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i,cap:n,protocolShares:a}=t;return{...e,hubReserves:p(s.toString()),shares:p(r.toString()),cap:p(n.toString()),protocolShares:p(a.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:i,balanceOut:n}=e,{minFee:a,maxFee:o,decay:u,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,m=C(a.toNumber()),h=C(o.toNumber());if(s.isNone||r.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[g]=r.unwrap(),{assetFee:d,timestamp:b}=s.unwrap(),y=t-b.toNumber(),v=g.volume.bIn.toString(),S=g.volume.bOut.toString(),E=g.liquidity.b.toString();i===D&&(v=g.volume.aIn.toString(),S=g.volume.aOut.toString(),E=g.liquidity.a.toString());let N=C(d.toNumber()),W=B.recalculateAssetFee(v,S,E,"9",n.toString(),T(N).toString(),y.toString(),T(m).toString(),T(h).toString(),u.toString(),c.toString());return[a.toNumber(),Number(W)*1e4,o.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:i,balanceIn:n}=e,{minFee:a,maxFee:o,decay:u,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,m=C(a.toNumber()),h=C(o.toNumber());if(s.isNone||r.isNone)return[a.toNumber(),a.toNumber(),o.toNumber()];let[g]=r.unwrap(),{protocolFee:d,timestamp:b}=s.unwrap(),y=t-b.toNumber(),v=g.volume.bIn.toString(),S=g.volume.bOut.toString(),E=g.liquidity.b.toString();i===D&&(v=g.volume.aIn.toString(),S=g.volume.aOut.toString(),E=g.liquidity.a.toString());let N=C(d.toNumber()),W=B.recalculateProtocolFee(v,S,E,"9",n.toString(),T(N).toString(),y.toString(),T(m).toString(),T(h).toString(),u.toString(),c.toString());return[a.toNumber(),Number(W)*1e4,o.toNumber()]}getPoolId(){return(0,at.encodeAddress)((0,lt.stringToU8a)("modlomnipool".padEnd(32,"\0")),Y)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Oe=class extends q{isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[s]},r])=>{let i=s.toString(),[n,a]=r.unwrap(),[o,u]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,a.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:o.toString()},{id:a.toString(),balance:u.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t){return{exchangeFee:this.getExchangeFee()}}getPoolType(){return"Xyk"}subscribePoolChange(e){throw new Error("Pool change subscription not supported!")}getExchangeFee(){return this.api.consts.xyk.getExchangeFee.toJSON()}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toJSON(),t=this.api.consts.xyk.maxOutRatio.toJSON(),s=this.api.consts.xyk.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var Ie=require("@polkadot/util-crypto");var I=require("@galacticcouncil/math-stableswap"),R=class{static getPoolAddress(e){return(0,I.pool_account_name)(e)}static calculateAmplification(e,t,s,r,i){return(0,I.calculate_amplification)(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,n){return(0,I.calculate_in_given_out)(e,t,s,r,i,n)}static calculateAddOneAsset(e,t,s,r,i,n){return(0,I.calculate_add_one_asset)(e,t,s,r,i,n)}static calculateSharesForAmount(e,t,s,r,i,n){return(0,I.calculate_shares_for_amount)(e,t,s,r,i,n)}static calculateOutGivenIn(e,t,s,r,i,n){return(0,I.calculate_out_given_in)(e,t,s,r,i,n)}static calculateLiquidityOutOneAsset(e,t,s,r,i,n){return(0,I.calculate_liquidity_out_one_asset)(e,t,s,r,i,n)}static calculateShares(e,t,s,r,i){return(0,I.calculate_shares)(e,t,s,r,i)}static calculateSpotPriceWithFee(e,t,s,r,i,n,a){return(0,I.calculate_spot_price_with_fee)(e,t,s,r,i,n,a)}static calculatePoolTradeFee(e,t,s){return(0,I.calculate_pool_trade_fee)(e,t,s)}};var we=class extends q{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},n])=>{let a=n.unwrap(),o=i.toString(),u=this.getPoolAddress(o),[c,m]=await Promise.all([this.getPoolDelta(o,a,s.toString()),this.getPoolTokens(u,o,a)]);return this.stablePools.set(u,a),{address:u,id:o,type:"Stableswap",fee:C(a.fee.toNumber()),tokens:m,...c,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:n,finalBlock:a}=t,o=R.calculateAmplification(r.toString(),i.toString(),n.toString(),a.toString(),s),u=await this.api.query.tokens.totalIssuance(e);return{amplification:o,totalIssuance:u.toString()}}async getPoolTokens(e,t,s){let{assets:r}=s,i=r.map(async o=>{let[u,c]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:u.bits.toNumber(),balance:c.toString()}}),n=await Promise.all(i),a=await this.api.query.omnipool.assets(t);if(a.isSome){let{tradable:o}=a.unwrap(),u=await this.getBalance(ce,t);n.push({id:t,tradeable:o.bits.toNumber(),balance:u.toString()})}return n}getPoolAddress(e){let t=Number(e),s=R.getPoolAddress(t);return(0,Ie.encodeAddress)((0,Ie.blake2AsHex)(s),Y)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Ae(l){return l.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var me=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},We=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},J=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Xe=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Ye=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},$e=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"}};var Z=class extends G{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Pe(e=>(this.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new j(this.api),this.aaveClient=new xe(this.api),this.xykClient=new Oe(this.api),this.omniClient=new ve(this.api),this.lbpClient=new Be(this.api),this.stableClient=new we(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}unsubscribe(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new me(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let n;this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):n=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Ae(i));let a=()=>n;return{hex:n.toHex(),name:"RouterBuy",get:a}}buildSellTx(e,t,s,r,i){let n;this.isDirectOmnipoolTrade(i)?n=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):n=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Ae(i));let a=()=>n;return{hex:n.toHex(),name:"RouterSell",get:a}}};var pe=(l,e)=>l===e?0:l==null?e==null?0:-1:e==null?l==null?0:1:typeof l.compare=="function"?l.compare(e):typeof e.compare=="function"?-e.compare(l):l<e?-1:l>e?1:0;var Te=(l,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(l(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Ft=Te(()=>"illegal argument(s)"),ut=l=>{throw new Ft(l)};var _t=Te(()=>"index out of bounds"),Je=l=>{throw new _t(l)},Ne=(l,e,t)=>(l<e||l>=t)&&Je(l);var ct=23283064365386963e-26,Fe=class{float(e=1){return this.int()*ct*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*ct-.5)*2*e}normMinMax(e,t){let s=this.minmax(e,t);return this.float()<.5?s:-s}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let s=(t|0)-e;return s?e+this.int()%s:e}minmaxUint(e,t){e>>>=0;let s=(t>>>0)-e;return s?e+this.int()%s:e}};var _e=class extends Fe{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var mt=new _e(Math.random);var pt=l=>l!=null&&typeof l!="function"&&l.length!==void 0;var dt=Object.getPrototypeOf({}),Re="function",gt="string",Q=(l,e)=>{let t;if(l===e)return!0;if(l!=null){if(typeof l.equiv===Re)return l.equiv(e)}else return l==e;if(e!=null){if(typeof e.equiv===Re)return e.equiv(l)}else return l==e;return typeof l===gt||typeof e===gt?!1:(t=Object.getPrototypeOf(l),(t==null||t===dt)&&(t=Object.getPrototypeOf(e),t==null||t===dt)?Lt(l,e):typeof l!==Re&&l.length!==void 0&&typeof e!==Re&&e.length!==void 0?Rt(l,e):l instanceof Set&&e instanceof Set?Et(l,e):l instanceof Map&&e instanceof Map?kt(l,e):l instanceof Date&&e instanceof Date?l.getTime()===e.getTime():l instanceof RegExp&&e instanceof RegExp?l.toString()===e.toString():l!==l&&e!==e)},Rt=(l,e,t=Q)=>{let s=l.length;if(s===e.length)for(;s-- >0&&t(l[s],e[s]););return s<0},Et=(l,e,t=Q)=>l.size===e.size&&t([...l.keys()].sort(),[...e.keys()].sort()),kt=(l,e,t=Q)=>l.size===e.size&&t([...l].sort(),[...e].sort()),Lt=(l,e,t=Q)=>{if(Object.keys(l).length!==Object.keys(e).length)return!1;for(let s in l)if(!e.hasOwnProperty(s)||!t(l[s],e[s]))return!1;return!0};var Ke=class{value;constructor(e){this.value=e}deref(){return this.value}};var ht=l=>l instanceof Ke;var Ee=class l{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return Pt("next",this._head)}reverseIterator(){return Pt("prev",this.tail)}clear(){this.release()}compare(e,t=pe){let s=this._length;if(s<e._length)return-1;if(s>e._length)return 1;if(s===0)return 0;{let r=this._head,i=e._head,n=0;for(;s-- >0&&n===0;)n=t(r.value,i.value),r=r.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let s of e)t.into(s);return t}equiv(e){if(!(e instanceof l||pt(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),s=this._head;for(let r=this._length;r-- >0;){if(!Q(s.value,t.next().value))return!1;s=s.next}return!0}filter(e){let t=this.empty();return this.traverse(s=>(e(s.value)&&t.append(s.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head&&this._head.value}insertSorted(e,t){t=t||pe;for(let s=this._head,r=this._length;r-- >0;){if(t(e,s.value)<=0)return this.insertBefore(s,e);s=s.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCellUnsafe(e){let t,s;for(e<=this._length>>>1?(t=this._head,s="next"):(t=this.tail,s="prev",e=this._length-e-1);e-- >0&&t;)t=t[s];return t}peek(){return this.tail&&this.tail.value}$reduce(e,t){let s=this._head;for(let r=this._length;r-- >0&&!ht(t);)t=e(t,s.value),s=s.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let s=this._length;s-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,s=(this._length>>>1)+(this._length&1);for(;e&&t&&s>0;){let r=e.value;e.value=t.value,t.value=r,e=e.next,t=t.prev,s--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let s=this.nthCell(e);return!s&&Je(e),s.value=t,s}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let s=e.value;e.value=t.value,t.value=s}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,s){if(!this._head)return;let r=t;do{if(!e(r))break;r=r.next}while(r!==s);return r}_map(e,t){return this.traverse(s=>(e.append(t(s.value)),!0)),e}};function*Pt(l,e){for(;e;)yield e.value,e=e[l]}var ke=class l extends Ee{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new l(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new l}insertAfter(e,t){let s={value:t,next:e.next,prev:e};return e.next?e.next.prev=s:this._tail=s,e.next=s,this._length++,s}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(Ne(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let s={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=s:this._head=s,e.prev=s,this._length++,s}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(Ne(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new l,e)}nth(e,t){let s=this.nthCell(e);return s?s.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let s=this.nthCell(e),r=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==r&&n.next?i(n.next):void 0}});return s?i(s):void 0}shuffle(e,t=mt){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let s=this._head;for(;s;){let r=s.next;t.probability(.5)?this.asHead(s):this.asTail(s),s=r}}return this}slice(e=0,t=this.length){let s=e<0?e+this._length:e,r=t<0?t+this._length:t;(s<0||r<0)&&ut("invalid indices: ${from} / ${to}");let i=new l,n=this.nthCell(s);for(;n&&++s<=r;)i.push(n.value),n=n.next;return i}sort(e=pe){if(!this._length)return this;let t=1;for(;;){let s=this._head;this._head=void 0,this._tail=void 0;let r=0;for(;s;){r++;let i=s,n=0;for(let o=0;o<t&&(n++,i=i.next,!!i);o++);let a=t;for(;n>0||a>0&&i;){let o;n===0?(o=i,i=i.next,a--):!i||a===0||e(s.value,i.value)<=0?(o=s,s=s.next,n--):(o=i,i=i.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}s=i}if(this._tail.next=void 0,r<=1)return this;t*=2}}splice(e,t=0,s){let r;typeof e=="number"?(e<0&&(e+=this._length),Ne(e,0,this._length),r=this.nthCellUnsafe(e)):r=e;let i=new l;if(t>0)for(;r&&t-- >0;)this.remove(r),i.push(r.value),r=r.next;else r&&(r=r.next);if(s)if(r)for(let n of s)this.insertBefore(r,n);else for(let n of s)this.push(n);return i}};var Le=class l{map;items;opts;_size;constructor(e,t){let s={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=s.map(),this.items=new ke,this._size=0,this.opts=s,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new l(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let s=this.map.get(e);return s?this.resetEntry(s):t}set(e,t){let s=this.opts.ksize(e)+this.opts.vsize(t),r=this.map.get(e),i=Math.max(0,s-(r?r.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(r,e,t,s):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let s=this.map.get(e);return s?this.resetEntry(s):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:s}=this.opts;for(;this._size>t||this.length>=s;){let r=this.items.drop();if(!r)return!1;this.map.delete(r.k),e?.(r.k,r.v),this._size-=r.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,s,r){e?(this.opts.update?.(t,e.value.v,s),e.value.v=s,e.value.s=r,this.items.asTail(e)):(this.items.push({k:t,v:s,s:r}),this.map.set(t,this.items.tail))}};var Me=class extends Z{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Le(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 i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){this.log(`Destroying pool cache!
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var ee=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,s,r,i,n,a){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=n,this.repayFeeApply=a}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(o=>[o.id,o])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),a=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let a=this.calculateTradeFee(t,s),o=T(this.repayFeeApply?s.repayFee:s.exchangeFee),u=t.plus(a),c=this.calculateInGivenOut(e,u),m=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:o,errors:i}}else{let a=this.calculateInGivenOut(e,t),o=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let a=this.calculateOutGivenIn(e,t),o=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:i}}else{let a=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(a,s),u=T(this.repayFeeApply?s.repayFee:s.exchangeFee),c=a.minus(o),m=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:a,amountOut:c,feePct:u,errors:i}}}calculateInGivenOut(e,t){let s=H.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=H.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=H.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),O(F,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=H.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),O(F,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let s=H.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(s)}};var te=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,s,r,i,n){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=n}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),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),a=p(i.balance),o=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:o,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=i.minus(r),a=r===P?P:n.div(r).multipliedBy(100).decimalPlaces(2),o=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&o.push("MaxOutRatioExceeded");let h=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(h)&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:a.toNumber(),errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),a=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),o=[],u=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!u||!c)&&o.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&o.push("MaxInRatioExceeded");let h=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(h)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:a.toNumber(),errors:o}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?L(s.assetFee).toString():P.toString(),s?L(s.protocolFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?L(s.assetFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?L(s.assetFee).toString():P.toString(),s?L(s.protocolFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?L(s.assetFee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(V-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(V-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(V-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(V-e.decimalsIn)).decimalPlaces(0,1)}};var se=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,n,a,o,u){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=n,this.id=a,this.fee=o,this.totalIssuance=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),a=p(i.balance),o=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:a,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?be:r.tradeable,tradeableOut:this.id===t?be:i.tradeable,assetInED:o,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),n=T(s.fee),a=[],o=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!o||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),n=T(s.fee),a=[],o=B.isSellAllowed(e.tradeableIn),u=B.isBuyAllowed(e.tradeableOut);return(!o||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n,errors:a}}calculateIn(e,t,s){let r=R.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?L(s.fee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateAddOneAsset(e,t,s){let r=R.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?L(s.fee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateSharesForAmount(e,t,s){let r=R.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?L(s.fee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}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=R.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0");if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let r=O(F,e.decimalsIn-e.decimalsOut);return p(t).div(r)}let s=O(F,18-e.decimalsIn);return p(t).div(s)}calculateOut(e,t,s){let r=R.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?L(s.fee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateWithdrawOneAsset(e,t,s){let r=R.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?L(s.fee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}calculateShares(e,t,s){let r=R.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?L(s.fee).toString():P.toString()),i=p(r);return i.isNegative()?P:i}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=R.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0");if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let r=O(F,e.decimalsOut-e.decimalsIn);return p(t).div(r)}let s=O(F,18-e.decimalsOut);return p(t).div(s)}calculateTradeFee(e,t){let s=R.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return p(s)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};var A=require("@galacticcouncil/math-xyk"),z=class{static getSpotPrice(e,t,s){return(0,A.get_spot_price)(e,t,s)}static calculateInGivenOut(e,t,s){return(0,A.calculate_in_given_out)(e,t,s)}static calculateOutGivenIn(e,t,s){return(0,A.calculate_out_given_in)(e,t,s)}static calculatePoolTradeFee(e,t,s){return(0,A.calculate_pool_trade_fee)(e,t,s)}static calculateLiquidityIn(e,t,s){return(0,A.calculate_liquidity_in)(e,t,s)}static calculateSpotPrice(e,t){return(0,A.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return(0,A.calculate_spot_price_with_fee)(e,t,s,r)}static calculateShares(e,t,s){return(0,A.calculate_shares)(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return(0,A.calculate_liquidity_out_asset_a)(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return(0,A.calculate_liquidity_out_asset_b)(e,t,s,r)}};var re=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),a=p(i.balance),o=p(r.existentialDeposit),u=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:o,assetOutED:u}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),n=T(s.exchangeFee),a=r.plus(i),o=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&o.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&o.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(c)&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),n=T(s.exchangeFee),a=r.minus(i),o=[];(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&o.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&o.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(c)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:a,feePct:n,errors:o}}calculateInGivenOut(e,t){let s=z.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=z.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=p(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=z.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=O(F,18-e.decimalsOut);return p(t).div(s)}spotPriceOutGivenIn(e){let t=z.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=O(F,18-e.decimalsIn);return p(t).div(s)}calculateTradeFee(e,t){let s=z.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(s)}};var ie=class l{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new l(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,i){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(o=>[o.id,o])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(r.balance),a=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:a,assetInED:P,assetOutED:P}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=[];return e.balanceOut.isLessThan(t)&&i.push("MaxOutRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=[];return e.balanceIn.isLessThan(t)&&i.push("MaxInRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:i}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return O(F,e.decimalsOut)}spotPriceOutGivenIn(e){return O(F,e.decimalsIn)}calculateTradeFee(e,t){return P}};var ne=class{static get(e){switch(e.type){case"Aave":return ie.fromPool(e);case"Xyk":return re.fromPool(e);case"Omnipool":return te.fromPool(e);case"Lbp":return ee.fromPool(e);case"Stableswap":return se.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var K=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new le,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),n=this.getPaths(e,null,r,t).map(a=>a[a.length-1].assetOut);return this.toAssets([...new Set(n)],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(a=>this.validPath(a,s)).map(a=>this.toHops(a,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 i=this.getPoolMap(s);return{assets:r,poolsMap:i}}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,ne.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,i])=>{let n=t.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function Mt(l,e){return l.minus(e).abs().div(l.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function oe(l,e){return l.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ve(l,e){return F.minus(e.div(l)).multipliedBy(100).decimalPlaces(2)}function Ze(l,e){return e.div(l).minus(F).multipliedBy(100).decimalPlaces(2)}var de=class extends K{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,n=r[r.length-1].amountOut;return i.isGreaterThan(n)?-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(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,r]}}getPoolFeeRange(e){let t=e.min?T(e.min):void 0,s=e.max?T(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 i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),a=super.getPaths(e,t,n,i);if(a.length===0)throw new J(e,t);let o;if(r)o=await this.toSellSwaps(s,r,n);else{let w=a.map(async ge=>await this.toSellSwaps(s,ge,n)),M=await Promise.all(w);o=this.findBestSellRoute(M)}let u=o[0],c=o[o.length-1],m=this.isDirectTrade(o),h=o.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,M)=>w.multipliedBy(M)),g=O(h,c.assetOutDecimals),d=m?c.calculatedOut:this.calculateDelta0Y(u.amountIn,o,n),b=c.amountOut,y=m?c.tradeFeePct:Ve(d,b).toNumber(),v=d.minus(b),S=this.getRouteFeeRange(o),E=u.amountIn.shiftedBy(-1*u.assetInDecimals).multipliedBy(g),N=oe(d,E),W=w=>this.poolService.buildSellTx(e,t,u.amountIn,w,o.map(M=>M));return{type:"Sell",amountIn:u.amountIn,amountOut:c.amountOut,spotPrice:g,tradeFee:v,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:N.toNumber(),swaps:o,toTx:W,toHuman(){return{type:"Sell",amountIn:_(u.amountIn,u.assetInDecimals),amountOut:_(c.amountOut,c.assetOutDecimals),spotPrice:_(g,c.assetOutDecimals),tradeFee:_(v,c.assetOutDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:N.toNumber(),swaps:o.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1]:u=e;let c=a.calculateOutGivenIn(o,u);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i>0?u=r[i-1].amountOut:u=O(p(e),o.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(o,a),{amountOut:m,calculatedOut:h,feePct:g,errors:d}=a.validateAndSell(o,u,c),b=this.getPoolFeeRange(c),y=a.spotPriceOutGivenIn(o),v=u.shiftedBy(-1*o.decimalsIn).multipliedBy(y),S=oe(h,v);r.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:u,calculatedOut:h,amountOut:m,spotPrice:y,tradeFeePct:g,tradeFeeRange:b,priceImpactPct:S.toNumber(),errors:d,toHuman(){return{...n,amountIn:_(u,o.decimalsIn),calculatedOut:_(h,o.decimalsOut),amountOut:_(m,o.decimalsOut),spotPrice:_(y,o.decimalsOut),tradeFeePct:g,tradeFeeRange:b,priceImpactPct:S.toNumber(),errors:d}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)throw new J(e,t);let n=s.map(d=>d.tokens.find(b=>b.id===e)).filter(d=>!!d).sort((d,b)=>Number(b.balance)-Number(d.balance)),{balance:a,decimals:o}=n[0],c=p(a).shiftedBy(-1*o).div(100).multipliedBy(.1),m=i.map(async d=>await this.toSellSwaps(c,d,r)),h=await Promise.all(m);return this.findBestSellRoute(h).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 n=await this.getMostLiquidRoute(e,t),a=await this.toSellSwaps("1",n,r),o=a.map(m=>m.spotPrice.shiftedBy(-1*m.assetOutDecimals)).reduce((m,h)=>m.multipliedBy(h)),u=a[a.length-1].assetOutDecimals;return{amount:O(o,u),decimals:u}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,n=r[0].amountIn;return i.isGreaterThan(n)?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 i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:n}=await super.validateTokenPair(e,t,i),a=super.getPaths(e,t,n,i);if(a.length===0)throw new J(e,t);let o;if(r)o=await this.toBuySwaps(s,r,n);else{let w=a.map(async ge=>await this.toBuySwaps(s,ge,n)),M=await Promise.all(w);o=this.findBestBuyRoute(M)}let u=o[o.length-1],c=o[0],m=this.isDirectTrade(o),h=o.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,M)=>w.multipliedBy(M)),g=O(h,c.assetInDecimals),d=m?c.calculatedIn:this.calculateDelta0X(u.amountOut,o,n),b=c.amountIn,y=m?c.tradeFeePct:Ze(d,b).toNumber(),v=b.minus(d),S=this.getRouteFeeRange(o),E=u.amountOut.shiftedBy(-1*u.assetOutDecimals).multipliedBy(g),N;d.isZero()?N=-100:N=oe(E,d).toNumber();let W=w=>this.poolService.buildBuyTx(e,t,u.amountOut,w,o.map(M=>M));return{type:"Buy",amountOut:u.amountOut,amountIn:c.amountIn,spotPrice:g,tradeFee:v,tradeFeePct:y,tradeFeeRange:S,priceImpactPct:N,swaps:o,toTx:W,toHuman(){return{type:"Buy",amountOut:_(u.amountOut,u.assetOutDecimals),amountIn:_(c.amountIn,c.assetInDecimals),spotPrice:_(g,c.assetInDecimals),tradeFee:_(v,c.assetInDecimals),tradeFeePct:y,tradeFeeRange:S,priceImpactPct:N,swaps:o.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=e:u=r[0];let c=a.calculateInGivenOut(o,u);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let n=t[i],a=s.get(n.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(n.assetIn,n.assetOut),u;i==t.length-1?u=O(p(e),o.decimalsOut).decimalPlaces(0,1):u=r[0].amountIn;let c=await this.poolService.getPoolFees(o,a),{amountIn:m,calculatedIn:h,feePct:g,errors:d}=a.validateAndBuy(o,u,c),b=this.getPoolFeeRange(c),y=a.spotPriceInGivenOut(o),v=u.shiftedBy(-1*o.decimalsOut).multipliedBy(y),S;h.isZero()?S=-100:S=oe(v,h).toNumber(),r.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:u,calculatedIn:h,amountIn:m,spotPrice:y,tradeFeePct:g,tradeFeeRange:b,priceImpactPct:S,errors:d,toHuman(){return{...n,amountOut:_(u,o.decimalsOut),calculatedIn:_(h,o.decimalsIn),amountIn:_(m,o.decimalsIn),spotPrice:_(y,o.decimalsIn),tradeFeePct:g,tradeFeeRange:b,priceImpactPct:S,errors:d}}})}return r}};0&&(module.exports={AavePool,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BigNumber,CachingPoolService,DECIMAL_PLACES,DENOMINATOR,FarmClient,HUB_ASSET_ID,HYDRADX_OMNIPOOL_ADDRESS,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,ONE,OmniMath,OmniPool,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TradeRouter,TradeType,XykMath,XykPool,ZERO,bnum,buildRoute,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,findNestedKey,findNestedObj,scale});
package/build/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- var re=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 Te=5,Y=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=[],i=new re,o=[];for(o.push([t,""]),i.enqueue(o);i.size()>0;){let n=i.dequeue();if(n==null||n.length>Te)return r;let a=n[n.length-1];(s===null||a[0]===s)&&r.push(n),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,n)){let u=[...n];u.push(c),i.enqueue(u)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,i,o]of t){let n=parseInt(i),a=parseInt(o);s.get(n)?.push([a,r])}return s}};function ge(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 i=0;i<s;i++){if(r==i)continue;let o=[t.address,t.tokens[r].id,t.tokens[i].id];e[t.tokens[r].id].push(o)}}}return e}var z=class{getProposals(e,t,s){let r=ge(s),i=Object.keys(r),o=i.map(c=>r[c]).flat(),n=new Y,a=n.buildAndPopulateGraph(i,o),l=n.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 i=0;i<s.length;i++){let o=s[i],n=s[i+1];if(n==null)break;r.push(this.toEdge(o,n))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};import{memoize1 as Pt}from"@thi.ng/memoize";import{BigNumber as O}from"bignumber.js";var ve=12;O.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:ve});var P=m(0),v=m(1),zt=m("Infinity");function I(p,e){let t=new O(e.toString()),s=new O(10).pow(t);return p.times(s)}function m(p){return new O(p.toString())}var E=(r=>(r.XYK="Xyk",r.LBP="Lbp",r.Stable="Stableswap",r.Omni="Omnipool",r))(E||{}),J=(i=>(i.UnknownError="UnknownError",i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i))(J||{}),ye=(t=>(t.Buy="Buy",t.Sell="Sell",t))(ye||{});import{calculate_in_given_out as Re,calculate_out_given_in as Ee,calculate_linear_weights as ke,calculate_pool_trade_fee as _e,get_spot_price as Le}from"@galacticcouncil/math-lbp";var D=class{static getSpotPrice(e,t,s,r,i){return Le(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i){return Re(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i){return Ee(e,t,s,r,i)}static calculateLinearWeights(e,t,s,r,i){return ke(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return _e(e,t,s)}};import{memoize1 as Ce}from"@thi.ng/memoize";import{encodeAddress as De}from"@polkadot/util-crypto";import{stringToU8a as Me}from"@polkadot/util";var j=18,de=15,_="0",Vt=12,ie="1",es=2034,$=63,ts=2090,be=1e3,oe=De(Me("modlomnipool".padEnd(32,"\0")),$);import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var q=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}};var H=class extends q{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},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:i}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},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:i,assetType:o,isSufficient:n,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:o.toHuman(),isSufficient:n?n.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[i,o]=r,{assetType:n,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(i.toString(),t,s),b=o.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(b)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:b}}getShares(e,t,s,r){let{assets:i}=r,{name:o,symbol:n,assetType:a,isSufficient:l,existentialDeposit:c}=t,b=i.map(h=>h.toString()).map(h=>{let{symbol:f}=this.getToken(h,t,s);return[h,f]}),d=Object.fromEntries(b),g=Object.values(d);return{id:e,name:g.join(", "),symbol:n?.isSome?n.toHuman():o.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let i=this.getToken(e,t,new Map,r),o=s?.find(n=>n.internalId===i.id);return o?{...i,decimals:o.decimals,name:o.name,symbol:o.symbol,icon:o.symbol,isWhiteListed:o.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:i,symbol:o}=r.unwrap();return[s.toString(),{decimals:Number(i.toString()),symbol:o.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,i,o,n]=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,n),c=a.map(([{args:[u]},b])=>{let d=b.unwrap(),g=r.get(u.toString()),{assetType:h}=d;switch(h.toString()){case"Bond":let f=o.get(u.toString());return this.getBond(u.toString(),d,l,f);case"StableSwap":let y=i.get(u.toString());return this.getShares(u.toString(),d,l,y);case"External":return this.getExternal(u.toString(),d,t,g);default:return this.getToken(u.toString(),d,l,g)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var W=class extends q{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:i}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:i}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:i})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(_,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let i=t.filter(o=>o.type!=="Erc20").filter(o=>o.id!==_).map(o=>[e,o.id]);return this.api.query.tokens.accounts.multi(i,o=>{let n=[];o.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=i[l][1];n.push([u,c])}),s(n)})}async subscribeErc20Balance(e,t,s){let r=t.filter(o=>o.type==="Erc20"),i=async()=>{let o=[];(await Promise.all(r.map(async a=>[a.id,await this.getErc20Balance(e,a.id)]))).forEach(([a,l])=>{o.push([a,l])}),s(o)};return await i(),this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:i}=e,o=new O(t),n=new O(s||i),a=new O(r||0n),l=n.gt(a)?n:a;return o.minus(l)}};import{isAddress as Se}from"@polkadot/util-crypto";import{fixed_from_rational as Be}from"@galacticcouncil/math-liquidity-mining";var he=class extends q{constructor(e){super(e)}secondsInYear=new O(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,o]=r.args,n=i.unwrap().toString(),a=o.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString();return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,i])=>{let[,o]=r.args,n=i.unwrap().toString(),a=o.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString();return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new O(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(i.isNone)return;let[o]=i.unwrap(),n=o.price.n.toString(),a=o.price.d.toString(),l;return Number(t)<Number(s)?l=Be(n,a):l=Be(a,n),l}getGlobalRewardPerPeriod(e,t,s,r){let o=e.times(t).shiftedBy(-18).times(r).shiftedBy(-18);return o.gte(s)?s:o}getPoolYieldPerPeriod(e,t,s,r){return e.times(t).div(s.times(r).shiftedBy(-18))}async getFarmApr(e,t){if(t==="isolatedpool"&&!Se(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Se(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:n,globalFarm:a,priceAdjustment:l})=>{let c=new O(a.totalSharesZ.toString()),u=a.plannedYieldingPeriods.toString(),b=new O(a.yieldPerPeriod.toString()),d=new O(a.maxRewardPerPeriod.toString()),g=a.blocksPerPeriod.toString(),h=new O(n.multiplier.toString()).shiftedBy(-18),f=this.secondsInYear.div(new O(s).times(g)),y;if(c.isZero())y=b.times(h).times(f);else{let C=this.getGlobalRewardPerPeriod(c,b,d,l);y=this.getPoolYieldPerPeriod(C,h,c,l).times(f)}let S=new O(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),T=d.times(u);return S.div(T).gte(.99)?P:y.times(100)}).reduce((n,a)=>n.plus(a),P).toString():void 0}};var M=class extends W{pools=[];subs=[];assets=new Map([]);mem=0;memPools=Ce(e=>(console.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));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 this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return console.log(e,`pools(${this.augmentedPools.length})`,"\u2705"),console.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[this.subscribeTokensPoolBalance(t)];try{let r=this.subscribePoolChange(t);s.push(r)}catch{}if(this.hasSystemAsset(t)){let r=this.subscribeSystemPoolBalance(t);s.push(r)}if(this.hasErc20Asset(t)){let r=this.subscribeErc20PoolBalance(t);s.push(r)}if(this.hasShareAsset(t)){let r=this.subscribeSharePoolBalance(t);s.push(r)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}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("...");console.log(`${e.type} [${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))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(oe,[t],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,i])=>{let o=e.tokens.findIndex(n=>n.id==r);o>=0&&t(e,r)&&(e.tokens[o].balance=i.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(i=>i.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var ne=class extends M{MAX_FINAL_WEIGHT=I(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([i,o])=>this.isActivePool(o.unwrap(),s)).map(async([{args:[i]},o])=>{let n=o.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,n,s.toString());return this.poolsData.set(i.toString(),n),{address:a,type:"Lbp",fee:n.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 o=await this.getPoolDelta(e.address,r,s.toString());Object.assign(e,o)}else{let o=this.pools.findIndex(n=>n.address==e.address);this.pools.splice(o,1)}})}async getPoolDelta(e,t,s){let{start:r,end:i,assets:o,initialWeight:n,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=D.calculateLinearWeights(r.toString(),i.toString(),n.toString(),a.toString(),s),[b,d]=o,g=b.toString(),h=m(u),f=d.toString(),y=this.MAX_FINAL_WEIGHT.minus(m(h)),[S,T,A]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,f)]);return{repayFeeApply:S,tokens:[{id:g,weight:h,balance:T.toString()},{id:f,weight:y,balance:A.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=m(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as rt}from"@polkadot/util-crypto";import{stringToU8a as it}from"@polkadot/util";function F(p,e){return p.shiftedBy(-1*e).toString()}function x(p){return p[0]/p[1]*100}function R(p){return p[0]/p[1]}function k(p){return[p/be,be]}import{calculate_in_given_out as Ge,calculate_lrna_in_given_out as qe,calculate_out_given_in as He,calculate_out_given_lrna_in as We,calculate_pool_trade_fee as Xe,calculate_spot_price as Ue,calculate_lrna_spot_price as Ye,calculate_shares as ze,calculate_liquidity_out as Je,calculate_liquidity_lrna_out as je,calculate_liquidity_hub_in as $e,is_sell_allowed as Ze,is_buy_allowed as Ke,is_add_liquidity_allowed as Qe,is_remove_liquidity_allowed as Ve,recalculate_asset_fee as et,recalculate_protocol_fee as tt,verify_asset_cap as st}from"@galacticcouncil/math-omnipool";var B=class{static calculateSpotPrice(e,t,s,r){return Ue(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return Ye(e,t)}static calculateInGivenOut(e,t,s,r,i,o,n,a,l){return Ge(e,t,s,r,i,o,n,a,l)}static calculateLrnaInGivenOut(e,t,s,r,i){return qe(e,t,s,r,i)}static calculateOutGivenIn(e,t,s,r,i,o,n,a,l){return He(e,t,s,r,i,o,n,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,i){return We(e,t,s,r,i)}static calculatePoolTradeFee(e,t,s){return Xe(e,t,s)}static calculateShares(e,t,s,r){return ze(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,i,o,n,a){return Je(e,t,s,r,i,o,n,a)}static calculateLiquidityLRNAOut(e,t,s,r,i,o,n,a){return je(e,t,s,r,i,o,n,a)}static calculateCapDifference(e,t,s,r){let i=O(t),o=O(e),n=O(r),l=O(s).shiftedBy(-18);if(i.div(n).lt(l)){let u=l.times(n).minus(i).times(o),b=i.times(O(1).minus(l));return u.div(b).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return $e(e,t,s,r)}static isSellAllowed(e){return Ze(e)}static isBuyAllowed(e){return Ke(e)}static isAddLiquidityAllowed(e){return Qe(e)}static isRemoveLiquidityAllowed(e){return Ve(e)}static recalculateAssetFee(e,t,s,r,i,o,n,a,l,c,u){return et(e,t,s,r,i,o,n,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,i,o,n,a,l,c,u){return tt(e,t,s,r,i,o,n,a,l,c,u)}static verifyAssetCap(e,t,s,r){return st(e,t,s,r)}};var ae=class extends M{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),o=s.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:b,cap:d,protocolShares:g}=l.unwrap(),h=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:b.bits.toNumber(),balance:h.toString(),cap:m(d.toString()),protocolShares:m(g.toString())}}),n=await Promise.all(o);return n.push({id:e,tradeable:r.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:n,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,i="omnipool",o="Short",n=A=>A===_?[_,ie]:[ie,A],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(i,n(s),o),this.api.query.emaOracle.oracles(i,n(r),o)]),[b,d,g]=this.getAssetFee(e,a.toNumber(),l,c),[h,f,y]=r===ie?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),S=b+h,T=g+y;return{assetFee:k(d),protocolFee:k(f),min:k(S),max:k(T)}}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,i)=>{let o=e.tokens[i];if(r.isNone)return o;let n=r.unwrap();return this.updateTokenState(o,n)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:i,cap:o,protocolShares:n}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(o.toString()),protocolShares:m(n.toString()),tradeable:i.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:i,balanceOut:o}=e,{minFee:n,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=k(n.toNumber()),b=k(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:g,timestamp:h}=s.unwrap(),f=t-h.toNumber(),y=d.volume.bIn.toString(),S=d.volume.bOut.toString(),T=d.liquidity.b.toString();i===_&&(y=d.volume.aIn.toString(),S=d.volume.aOut.toString(),T=d.liquidity.a.toString());let A=k(g.toNumber()),C=B.recalculateAssetFee(y,S,T,"9",o.toString(),x(A).toString(),f.toString(),x(u).toString(),x(b).toString(),l.toString(),c.toString());return[n.toNumber(),Number(C)*1e4,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:i,balanceIn:o}=e,{minFee:n,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=k(n.toNumber()),b=k(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:g,timestamp:h}=s.unwrap(),f=t-h.toNumber(),y=d.volume.bIn.toString(),S=d.volume.bOut.toString(),T=d.liquidity.b.toString();i===_&&(y=d.volume.aIn.toString(),S=d.volume.aOut.toString(),T=d.liquidity.a.toString());let A=k(g.toNumber()),C=B.recalculateProtocolFee(y,S,T,"9",o.toString(),x(A).toString(),f.toString(),x(u).toString(),x(b).toString(),l.toString(),c.toString());return[n.toNumber(),Number(C)*1e4,a.toNumber()]}getPoolId(){return rt(it("modlomnipool".padEnd(32,"\0")),$)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var le=class extends M{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 i=s.toString(),[o,n]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(i,o.toString()),this.getBalance(i,n.toString())]);return{address:i,type:"Xyk",tokens:[{id:o.toString(),balance:a.toString()},{id:n.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{blake2AsHex as bt,encodeAddress as ht}from"@polkadot/util-crypto";import{calculate_in_given_out as ot,calculate_out_given_in as nt,calculate_amplification as at,calculate_add_one_asset as lt,calculate_liquidity_out_one_asset as ct,calculate_pool_trade_fee as ut,calculate_shares as mt,calculate_shares_for_amount as pt,calculate_spot_price_with_fee as gt,pool_account_name as dt}from"@galacticcouncil/math-stableswap";var N=class{static getPoolAddress(e){return dt(e)}static calculateAmplification(e,t,s,r,i){return at(e,t,s,r,i)}static calculateInGivenOut(e,t,s,r,i,o){return ot(e,t,s,r,i,o)}static calculateAddOneAsset(e,t,s,r,i,o){return lt(e,t,s,r,i,o)}static calculateSharesForAmount(e,t,s,r,i,o){return pt(e,t,s,r,i,o)}static calculateOutGivenIn(e,t,s,r,i,o){return nt(e,t,s,r,i,o)}static calculateLiquidityOutOneAsset(e,t,s,r,i,o){return ct(e,t,s,r,i,o)}static calculateShares(e,t,s,r,i){return mt(e,t,s,r,i)}static calculateSpotPriceWithFee(e,t,s,r,i,o,n){return gt(e,t,s,r,i,o,n)}static calculatePoolTradeFee(e,t,s){return ut(e,t,s)}};var ce=class extends M{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[i]},o])=>{let n=o.unwrap(),a=i.toString(),l=this.getPoolAddress(a),[c,u]=await Promise.all([this.getPoolDelta(a,n,s.toString()),this.getPoolTokens(l,a,n)]);return this.stablePools.set(l,n),{address:l,id:a,type:"Stableswap",fee:k(n.fee.toNumber()),tokens:u,...c,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),i=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,i)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:i,initialBlock:o,finalBlock:n}=t,a=N.calculateAmplification(r.toString(),i.toString(),o.toString(),n.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,i=r.map(async a=>{let[l,c]=await Promise.all([this.api.query.stableswap.assetTradability(t,a.toString()),this.getBalance(e,a.toString())]);return{id:a.toString(),tradeable:l.bits.toNumber(),balance:c.toString()}}),o=await Promise.all(i),n=await this.api.query.omnipool.assets(t);if(n.isSome){let{tradable:a}=n.unwrap(),l=await this.getBalance(oe,t);o.push({id:t,tradeable:a.bits.toNumber(),balance:l.toString()})}return o}getPoolAddress(e){let t=Number(e),s=N.getPoolAddress(t);return ht(bt(s),$)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Pe(p){return p.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var ue=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Oe=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},X=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},we=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Ie=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},xe=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ae=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var Z=class{api;assetClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Pt(e=>(console.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){this.api=e,this.assetClient=new H(this.api),this.xykClient=new le(this.api),this.omniClient=new ae(this.api),this.lbpClient=new ne(this.api),this.stableClient=new ce(this.api),this.clients=[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()}unsubscribe(){this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){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 ue(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,i){let o;this.isDirectOmnipoolTrade(i)?o=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):o=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Pe(i));let n=()=>o;return{hex:o.toHex(),name:"RouterBuy",get:n}}buildSellTx(e,t,s,r,i){let o;this.isDirectOmnipoolTrade(i)?o=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):o=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Pe(i));let n=()=>o;return{hex:o.toHex(),name:"RouterSell",get:n}}};import{LRUCache as ft}from"@thi.ng/cache";var fe=class extends Z{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new ft(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 i=await super.getPoolFees(e,t);return this.feeCache.set(s,i),i}}async destroy(){console.log(`Destroying pool cache!
2
- Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var K=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,i,o,n){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=o,this.repayFeeApply=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(r.balance),n=m(i.balance);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:n,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let o=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),r===e.assetOut){let n=this.calculateTradeFee(t,s),a=x(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(n),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let n=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,s){let r=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let o=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),r===e.assetIn){let n=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:n,feePct:0,errors:i}}else{let n=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(n,s),l=x(this.repayFeeApply?s.repayFee:s.exchangeFee),c=n.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let s=D.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=D.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=D.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),I(v,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=D.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),I(v,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=D.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var Q=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,i,o){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=o}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),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(r.balance),n=m(i.balance),a=m(r.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),o=i.minus(r),n=r===P?P:o.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let b=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(b)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:n.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),n=r.minus(i).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let b=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(b)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:n.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?R(s.assetFee).toString():P.toString(),s?R(s.protocolFee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?R(s.assetFee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?R(s.assetFee).toString():P.toString(),s?R(s.protocolFee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?R(s.assetFee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(j-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(j-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(j-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(j-e.decimalsIn)).decimalPlaces(0,1)}};var V=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,i,o,n,a,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=o,this.id=n,this.fee=a,this.totalIssuance=l}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(r.balance),n=m(i.balance),a=m(r.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:n,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?de:r.tradeable,tradeableOut:this.id===t?de:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,s),o=x(s.fee),n=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:t,feePct:o,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,s),o=x(s.fee),n=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:i,feePct:o,errors:n}}calculateIn(e,t,s){let r=N.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?R(s.fee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}calculateAddOneAsset(e,t,s){let r=N.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?R(s.fee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}calculateSharesForAmount(e,t,s){let r=N.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?R(s.fee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}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=N.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0");if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=I(v,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=I(v,18-e.decimalsIn);return m(t).div(s)}calculateOut(e,t,s){let r=N.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?R(s.fee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}calculateWithdrawOneAsset(e,t,s){let r=N.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?R(s.fee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}calculateShares(e,t,s){let r=N.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?R(s.fee).toString():P.toString()),i=m(r);return i.isNegative()?P:i}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=N.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0");if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=I(v,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=I(v,18-e.decimalsOut);return m(t).div(s)}calculateTradeFee(e,t){let s=N.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return m(s)}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{calculate_in_given_out as yt,calculate_out_given_in as St,calculate_pool_trade_fee as Bt,get_spot_price as Ot,calculate_liquidity_in as wt,calculate_shares as It,calculate_spot_price as xt,calculate_spot_price_with_fee as At,calculate_liquidity_out_asset_a as Ft,calculate_liquidity_out_asset_b as Nt}from"@galacticcouncil/math-xyk";var G=class{static getSpotPrice(e,t,s){return Ot(e,t,s)}static calculateInGivenOut(e,t,s){return yt(e,t,s)}static calculateOutGivenIn(e,t,s){return St(e,t,s)}static calculatePoolTradeFee(e,t,s){return Bt(e,t,s)}static calculateLiquidityIn(e,t,s){return wt(e,t,s)}static calculateSpotPrice(e,t){return xt(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return At(e,t,s,r)}static calculateShares(e,t,s){return It(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Ft(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Nt(e,t,s,r)}};var ee=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,i){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),i=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(r.balance),n=m(i.balance),a=m(r.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(r,s),o=x(s.exchangeFee),n=r.plus(i),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 n.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:o,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(r,s),o=x(s.exchangeFee),n=r.minus(i),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 n.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:o,errors:a}}calculateInGivenOut(e,t){let s=G.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=G.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=G.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=I(v,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=G.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=I(v,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=G.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var te=class{static get(e){switch(e.type){case"Xyk":return ee.fromPool(e);case"Omnipool":return Q.fromPool(e);case"Lbp":return K.fromPool(e);case"Stableswap":return V.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var U=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new z,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),o=this.getPaths(e,null,r,t).map(n=>n[n.length-1].assetOut);return this.toAssets([...new Set(o)],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(n=>this.validPath(n,s)).map(n=>this.toHops(n,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 i=this.getPoolMap(s);return{assets:r,poolsMap:i}}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,te.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,i])=>{let o=t.get(s);return{poolAddress:s,poolId:o?.id,pool:o?.type,assetIn:r,assetOut:i}})}toAssets(e,t){return e.map(s=>t.get(s))}};function qo(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function se(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Fe(p,e){return v.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function Ne(p,e){return e.div(p).minus(v).multipliedBy(100).decimalPlaces(2)}var me=class extends U{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let i=s[s.length-1].amountOut,o=r[r.length-1].amountOut;return i.isGreaterThan(o)?-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(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,o)=>i+o),r=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,o)=>i+o);return[s,r]}}getPoolFeeRange(e){let t=e.min?x(e.min):void 0,s=e.max?x(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 i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,i),n=super.getPaths(e,t,o,i);if(n.length===0)throw new X(e,t);let a;if(r)a=await this.toSellSwaps(s,r,o);else{let w=n.map(async pe=>await this.toSellSwaps(s,pe,o)),L=await Promise.all(w);a=this.findBestSellRoute(L)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),b=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetOutDecimals)).reduce((w,L)=>w.multipliedBy(L)),d=I(b,c.assetOutDecimals),g=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,o),h=c.amountOut,f=u?c.tradeFeePct:Fe(g,h).toNumber(),y=g.minus(h),S=this.getRouteFeeRange(a),T=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),A=se(g,T),C=w=>this.poolService.buildSellTx(e,t,l.amountIn,w,a.map(L=>L));return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:y,tradeFeePct:f,tradeFeeRange:S,priceImpactPct:A.toNumber(),swaps:a,toTx:C,toHuman(){return{type:"Sell",amountIn:F(l.amountIn,l.assetInDecimals),amountOut:F(c.amountOut,c.assetOutDecimals),spotPrice:F(d,c.assetOutDecimals),tradeFee:F(y,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:S,priceImpactPct:A.toNumber(),swaps:a.map(w=>w.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let i=0;i<t.length;i++){let o=t[i],n=s.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i>0?l=r[i-1]:l=e;let c=n.calculateOutGivenIn(a,l);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let i=0;i<t.length;i++){let o=t[i],n=s.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i>0?l=r[i-1].amountOut:l=I(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,n),{amountOut:u,calculatedOut:b,feePct:d,errors:g}=n.validateAndSell(a,l,c),h=this.getPoolFeeRange(c),f=n.spotPriceOutGivenIn(a),y=l.shiftedBy(-1*a.decimalsIn).multipliedBy(f),S=se(b,y);r.push({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:b,amountOut:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:S.toNumber(),errors:g,toHuman(){return{...o,amountIn:F(l,a.decimalsIn),calculatedOut:F(b,a.decimalsOut),amountOut:F(u,a.decimalsOut),spotPrice:F(f,a.decimalsOut),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:S.toNumber(),errors:g}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),i=super.getPaths(e,t,r,s);if(i.length===0)throw new X(e,t);let o=s.map(g=>g.tokens.find(h=>h.id===e)).filter(g=>!!g).sort((g,h)=>Number(h.balance)-Number(g.balance)),{balance:n,decimals:a}=o[0],c=m(n).shiftedBy(-1*a).div(100).multipliedBy(.1),u=i.map(async g=>await this.toSellSwaps(c,g,r)),b=await Promise.all(u);return this.findBestSellRoute(b).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.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 o=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",o,r),a=n.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,b)=>u.multipliedBy(b)),l=n[n.length-1].assetOutDecimals;return{amount:I(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let i=s[0].amountIn,o=r[0].amountIn;return i.isGreaterThan(o)?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 i=await super.getPools();if(i.length===0)throw new Error("No pools configured");let{poolsMap:o}=await super.validateTokenPair(e,t,i),n=super.getPaths(e,t,o,i);if(n.length===0)throw new X(e,t);let a;if(r)a=await this.toBuySwaps(s,r,o);else{let w=n.map(async pe=>await this.toBuySwaps(s,pe,o)),L=await Promise.all(w);a=this.findBestBuyRoute(L)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),b=a.map(w=>w.spotPrice.shiftedBy(-1*w.assetInDecimals)).reduce((w,L)=>w.multipliedBy(L)),d=I(b,c.assetInDecimals),g=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,o),h=c.amountIn,f=u?c.tradeFeePct:Ne(g,h).toNumber(),y=h.minus(g),S=this.getRouteFeeRange(a),T=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),A;g.isZero()?A=-100:A=se(T,g).toNumber();let C=w=>this.poolService.buildBuyTx(e,t,l.amountOut,w,a.map(L=>L));return{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:y,tradeFeePct:f,tradeFeeRange:S,priceImpactPct:A,swaps:a,toTx:C,toHuman(){return{type:"Buy",amountOut:F(l.amountOut,l.assetOutDecimals),amountIn:F(c.amountIn,c.assetInDecimals),spotPrice:F(d,c.assetInDecimals),tradeFee:F(y,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:S,priceImpactPct:A,swaps:a.map(w=>w.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let o=t[i],n=s.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i==t.length-1?l=e:l=r[0];let c=n.calculateInGivenOut(a,l);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let i=t.length-1;i>=0;i--){let o=t[i],n=s.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i==t.length-1?l=I(m(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,n),{amountIn:u,calculatedIn:b,feePct:d,errors:g}=n.validateAndBuy(a,l,c),h=this.getPoolFeeRange(c),f=n.spotPriceInGivenOut(a),y=l.shiftedBy(-1*a.decimalsOut).multipliedBy(f),S;b.isZero()?S=-100:S=se(y,b).toNumber(),r.unshift({...o,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:b,amountIn:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:S,errors:g,toHuman(){return{...o,amountOut:F(l,a.decimalsOut),calculatedIn:F(b,a.decimalsIn),amountIn:F(u,a.decimalsIn),spotPrice:F(f,a.decimalsIn),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:S,errors:g}}})}return r}};import{memoize1 as ln}from"@thi.ng/memoize";function fn(p,e){let t=[];return JSON.stringify(p,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function yn(p,e,t){let s;return JSON.stringify(p,(r,i)=>(i&&i[e]===t&&(s=i),i)),s}export{H as AssetClient,we as AssetNotFound,ts as BASILISK_PARACHAIN_ID,W as BalanceClient,O as BigNumber,fe as CachingPoolService,ve as DECIMAL_PLACES,be as DENOMINATOR,he as FarmClient,ie as HUB_ASSET_ID,oe as HYDRADX_OMNIPOOL_ADDRESS,es as HYDRADX_PARACHAIN_ID,$ as HYDRADX_SS58_PREFIX,zt as INFINITY,D as LbpMath,K as LbpPool,v as ONE,B as OmniMath,Q as OmniPool,Oe as PoolConfigNotFound,J as PoolError,te as PoolFactory,ue as PoolNotFound,Z as PoolService,E as PoolType,Ae as ProviderConfigNotFound,j as RUNTIME_DECIMALS,X as RouteNotFound,U as Router,Vt as SYSTEM_ASSET_DECIMALS,_ as SYSTEM_ASSET_ID,N as StableMath,V as StableSwap,Ie as StorageConfigNotFound,xe as SubscriptionNotSupported,de as TRADEABLE_DEFAULT,me as TradeRouter,ye as TradeType,G as XykMath,ee as XykPool,P as ZERO,m as bnum,Pe as buildRoute,Ne as calculateBuyFee,qo as calculateDiffToAvg,se as calculateDiffToRef,Fe as calculateSellFee,fn as findNestedKey,yn as findNestedObj,I as scale};
1
+ var ie=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 Le=5,$=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=[],o=new ie,i=[];for(i.push([t,""]),o.enqueue(i);o.size()>0;){let n=o.dequeue();if(n==null||n.length>Le)return r;let a=n[n.length-1];(s===null||a[0]===s)&&r.push(n),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,n)){let u=[...n];u.push(c),o.enqueue(u)}})}return r}buildAndPopulateGraph(e,t){let s=new Map;for(let r of e)s.set(parseInt(r),[]);for(let[r,o,i]of t){let n=parseInt(o),a=parseInt(i);s.get(n)?.push([a,r])}return s}};function Pe(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 o=0;o<s;o++){if(r==o)continue;let i=[t.address,t.tokens[r].id,t.tokens[o].id];e[t.tokens[r].id].push(i)}}}return e}var K=class{getProposals(e,t,s){let r=Pe(s),o=Object.keys(r),i=o.map(c=>r[c]).flat(),n=new $,a=n.buildAndPopulateGraph(o,i),l=n.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 o=0;o<s.length;o++){let i=s[o],n=s[o+1];if(n==null)break;r.push(this.toEdge(i,n))}t.push(r)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};import{memoize1 as vt}from"@thi.ng/memoize";import{encodeAddress as He}from"@polkadot/util-crypto";import{stringToU8a as Ue}from"@polkadot/util";import{decodeEventLog as We}from"viem";var Oe=[{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"},{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"},{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"}];import{encodeAddress as De}from"@polkadot/util-crypto";import{stringToU8a as Me}from"@polkadot/util";var J=18,he=15,L="0",is=12,ne="1",ns=2034,U=63,as=2090,fe=1e3,ae=De(Me("modlomnipool".padEnd(32,"\0")),U);var R=(o=>(o.Aave="Aave",o.LBP="Lbp",o.Omni="Omnipool",o.Stable="Stableswap",o.XYK="Xyk",o))(R||{}),W=(o=>(o.UnknownError="UnknownError",o.InsufficientTradingAmount="InsufficientTradingAmount",o.MaxInRatioExceeded="MaxInRatioExceeded",o.MaxOutRatioExceeded="MaxOutRatioExceeded",o.TradeNotAllowed="TradeNotAllowed",o))(W||{}),xe=(t=>(t.Buy="Buy",t.Sell="Sell",t))(xe||{});var le=class{static encodeEvmAddress(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static decodeEvmAddress(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))}};function Ie(p,e){let t=[];return JSON.stringify(p,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function ms(p,e,t){let s;return JSON.stringify(p,(r,o)=>(o&&o[e]===t&&(s=o),o)),s}import{memoize1 as qe}from"@thi.ng/memoize";import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var M=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let 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 X=class extends M{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:o}=s.unwrap();return[t.toString(),{decimals:r.toNumber(),symbol:o.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==L){let u=this.api.consts.balances.existentialDeposit;return{id:L,name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:o,assetType:i,isSufficient:n,existentialDeposit:a}=t,{symbol:l,decimals:c}=s.get(e)??{};return{id:e,name:o.toHuman(),symbol:l,decimals:c,icon:l,type:i.toHuman(),isSufficient:n?n.toHuman():!0,location:r?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,s,r){let[o,i]=r,{assetType:n,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(o.toString(),t,s),b=i.toNumber(),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(b)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:o.toString(),maturity:b}}getShares(e,t,s,r){let{assets:o}=r,{name:i,symbol:n,assetType:a,isSufficient:l,existentialDeposit:c}=t,b=o.map(h=>h.toString()).map(h=>{let{symbol:f}=this.getToken(h,t,s);return[h,f]}),d=Object.fromEntries(b),g=Object.values(d);return{id:e,name:g.join(", "),symbol:n?.isSome?n.toHuman():i.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:d}}getExternal(e,t,s,r){let o=this.getToken(e,t,new Map,r),i=s?.find(n=>n.internalId===o.id);return i?{...o,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:o}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[s]},r])=>{let{decimals:o,symbol:i}=r.unwrap();return[s.toString(),{decimals:Number(o.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,o,i,n]=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,n),c=a.map(([{args:[u]},b])=>{let d=b.unwrap(),g=r.get(u.toString()),{assetType:h}=d;switch(h.toString()){case"Bond":let f=i.get(u.toString());return this.getBond(u.toString(),d,l,f);case"StableSwap":let S=o.get(u.toString());return this.getShares(u.toString(),d,l,S);case"External":return this.getExternal(u.toString(),d,t,g);default:return this.getToken(u.toString(),d,l,g)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};import{BigNumber as O}from"bignumber.js";var Ce=12;O.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Ce});var P=m(0),T=m(1),Ss=m("Infinity");function I(p,e){let t=new O(e.toString()),s=new O(10).pow(t);return p.times(s)}function m(p){return new O(p.toString())}var H=class extends M{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===L?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:o}=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:o})}async getErc20Balance(e,t){let{free:s,reserved:r,frozen:o}=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance({free:s,feeFrozen:r,frozen:o})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(L,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let o=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==L).map(i=>[e,i.id]);return this.api.query.tokens.accounts.multi(o,i=>{let n=[];i.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=o[l][1];n.push([u,c])}),s(n)})}async subscribeErc20Balance(e,t,s){let r=t.filter(i=>i.type==="Erc20"),o=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 o(),this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let{free:t,miscFrozen:s,feeFrozen:r,frozen:o}=e,i=new O(t),n=new O(s||o),a=new O(r||0n),l=n.gt(a)?n:a;return i.minus(l)}};import{isAddress as we}from"@polkadot/util-crypto";import{fixed_from_rational as Ae}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Ge}from"@polkadot/types";import{u8aConcat as Te}from"@polkadot/util";var ye=class extends M{balanceClient;constructor(e){super(e),this.balanceClient=new H(e)}secondsInYear=new O(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,o])=>{let[,i]=r.args,n=o.unwrap().toString(),a=i.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,g);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,o])=>{let[,i]=r.args,n=o.unwrap().toString(),a=i.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),d=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(d,g);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 O(1).shiftedBy(18).toString();let o=await this.api.query.emaOracle.oracles("omnipool",r,"TenMinutes");if(o.isNone)return;let[i]=o.unwrap(),n=i.price.n.toString(),a=i.price.d.toString(),l;return Number(t)<Number(s)?l=Ae(n,a):l=Ae(a,n),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 Te(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",o=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Ge(e,this.padEndU8a(Te(r,o,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!we(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&we(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:n,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new O(a.totalSharesZ.toString()),b=a.plannedYieldingPeriods.toString(),d=new O(a.yieldPerPeriod.toString()),g=new O(a.maxRewardPerPeriod.toString()),h=a.blocksPerPeriod.toString(),f=new O(n.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new O(s).times(h)),y;if(u.isZero())y=d.times(f).times(S);else{let k=this.getGlobalRewardPerPeriod(u,d,g,l);y=this.getPoolYieldPerPeriod(k,f,u,l).times(S)}let N=new O(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),A=g.times(b),G=c?N.plus(c):A;return N.div(G).gte(.999)?P:y.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,a)=>n.plus(a),P).toString():void 0}};var D=class extends H{pools=[];subs=[];assets=new Map([]);mem=0;memPools=qe(e=>(this.log(this.getPoolType(),"mem pools",e,"\u2705"),this.getPools()));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 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,`pools(${this.augmentedPools.length})`,"\u2705"),this.log(e,`subs(${this.subs.length})`,"\u2705"),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let o=this.subscribePoolChange(t);s.push(o)}catch{}if(t.type==="Aave")return s;let r=this.subscribeTokensPoolBalance(t);if(s.push(r),this.hasSystemAsset(t)){let o=this.subscribeSystemPoolBalance(t);s.push(o)}if(this.hasErc20Asset(t)){let o=this.subscribeErc20PoolBalance(t);s.push(o)}if(this.hasShareAsset(t)){let o=this.subscribeSharePoolBalance(t);s.push(o)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasShareAsset(e){return e.type==="Stableswap"&&e.id}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} [${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))}subscribeSharePoolBalance(e){let t=this.assets.get(e.id);return this.subscribeTokenBalance(ae,[t],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,o])=>{let i=e.tokens.findIndex(n=>n.id==r);i>=0&&t(e,r)&&(e.tokens[i].balance=o.toString())})}}updateBalanceCallback(e){return function(t,s){let r=e.tokens.findIndex(o=>o.id==t);r>=0&&(e.tokens[r].balance=s.toString())}}};var Xe=["Supply","Withdraw","Repay","Borrow"],ce=class extends D{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:o})=>({address:this.getPoolId(t.toString(),s.toString()),type:"Aave",tokens:[{id:t.toString(),balance:r.toString()},{id:s.toString(),balance:o.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t){return{}}getPoolType(){return"Aave"}getPoolId(e,t){let s=e+"/"+t;return He(Ue(s.padEnd(32,"\0")),U)}subscribePoolChange(e){let t=e.tokens.map(o=>o.id),[s]=e.tokens,r=this.getReserveH160Id(s);return this.api.query.system.events(o=>{o.forEach(i=>{let{event:n}=i,a=`${n.section}:${n.method}`;if(a==="router:Executed"){let{assetIn:l,assetOut:c}=n.data.toHuman(),u=l.replace(/,/g,""),b=c.replace(/,/g,"");t.includes(u)&&t.includes(b)&&(this.log("Sync AAVE [router:Executed]",t),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=n.data.toHuman();try{let{eventName:c,args:u}=We({abi:Oe,topics:l.topics,data:l.data});Xe.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${s.symbol}(${s.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut:o}=await this.api.call.aaveTradeExecutor.pool(t.id,s.id);e.tokens=e.tokens.map(i=>{let n=i.id===t.id?r.toString():o.toString();return{...i,balance:n}})}getReserveH160Id(e){return e.type==="Erc20"?Ie(e.location,"accountKey20").accountKey20.key:le.encodeEvmAddress(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as Ye,calculate_out_given_in as ze,calculate_linear_weights as $e,calculate_pool_trade_fee as Ke,get_spot_price as Je}from"@galacticcouncil/math-lbp";var C=class{static getSpotPrice(e,t,s,r,o){return Je(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o){return Ye(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o){return ze(e,t,s,r,o)}static calculateLinearWeights(e,t,s,r,o){return $e(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return Ke(e,t,s)}};var ue=class extends D{MAX_FINAL_WEIGHT=I(m(100),6);poolsData=new Map([]);isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:s}=t.unwrap(),r=e.filter(([o,i])=>this.isActivePool(i.unwrap(),s)).map(async([{args:[o]},i])=>{let n=i.unwrap(),a=o.toString(),l=await this.getPoolDelta(a,n,s.toString());return this.poolsData.set(o.toString(),n),{address:a,type:"Lbp",fee:n.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(n=>n.address==e.address);this.pools.splice(i,1)}})}async getPoolDelta(e,t,s){let{start:r,end:o,assets:i,initialWeight:n,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=C.calculateLinearWeights(r.toString(),o.toString(),n.toString(),a.toString(),s),[b,d]=i,g=b.toString(),h=m(u),f=d.toString(),S=this.MAX_FINAL_WEIGHT.minus(m(h)),[y,N,A]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,f)]);return{repayFeeApply:y,tokens:[{id:g,weight:h,balance:N.toString()},{id:f,weight:S,balance:A.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let s=e.start.unwrap().toNumber(),r=e.end.unwrap().toNumber();return t.toNumber()>=s&&t.toNumber()<r}async isRepayFeeApplied(e,t,s){let r=m(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{encodeAddress as dt}from"@polkadot/util-crypto";import{stringToU8a as bt}from"@polkadot/util";function v(p,e){return p.shiftedBy(-1*e).toString()}function w(p){return p[0]/p[1]*100}function E(p){return p[0]/p[1]}function _(p){return[p/fe,fe]}import{calculate_in_given_out as je,calculate_lrna_in_given_out as Ze,calculate_out_given_in as Ve,calculate_out_given_lrna_in as Qe,calculate_pool_trade_fee as et,calculate_spot_price as tt,calculate_lrna_spot_price as st,calculate_shares as rt,calculate_liquidity_out as ot,calculate_liquidity_lrna_out as it,calculate_liquidity_hub_in as nt,is_sell_allowed as at,is_buy_allowed as lt,is_add_liquidity_allowed as ct,is_remove_liquidity_allowed as ut,recalculate_asset_fee as mt,recalculate_protocol_fee as pt,verify_asset_cap as gt}from"@galacticcouncil/math-omnipool";var B=class{static calculateSpotPrice(e,t,s,r){return tt(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return st(e,t)}static calculateInGivenOut(e,t,s,r,o,i,n,a,l){return je(e,t,s,r,o,i,n,a,l)}static calculateLrnaInGivenOut(e,t,s,r,o){return Ze(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o,i,n,a,l){return Ve(e,t,s,r,o,i,n,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,o){return Qe(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return et(e,t,s)}static calculateShares(e,t,s,r){return rt(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,o,i,n,a){return ot(e,t,s,r,o,i,n,a)}static calculateLiquidityLRNAOut(e,t,s,r,o,i,n,a){return it(e,t,s,r,o,i,n,a)}static calculateCapDifference(e,t,s,r){let o=O(t),i=O(e),n=O(r),l=O(s).shiftedBy(-18);if(o.div(n).lt(l)){let u=l.times(n).minus(o).times(i),b=o.times(O(1).minus(l));return u.div(b).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return nt(e,t,s,r)}static isSellAllowed(e){return at(e)}static isBuyAllowed(e){return lt(e)}static isAddLiquidityAllowed(e){return ct(e)}static isRemoveLiquidityAllowed(e){return ut(e)}static recalculateAssetFee(e,t,s,r,o,i,n,a,l,c,u){return mt(e,t,s,r,o,i,n,a,l,c,u)}static recalculateProtocolFee(e,t,s,r,o,i,n,a,l,c,u){return pt(e,t,s,r,o,i,n,a,l,c,u)}static verifyAssetCap(e,t,s,r){return gt(e,t,s,r)}};var me=class extends D{isSupported(){return this.api.query.omnipool!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[s,r,o]=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:b,cap:d,protocolShares:g}=l.unwrap(),h=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:b.bits.toNumber(),balance:h.toString(),cap:m(d.toString()),protocolShares:m(g.toString())}}),n=await Promise.all(i);return n.push({id:e,tradeable:r.bits.toNumber(),balance:o.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:n,...this.getPoolLimits()}]}async getPoolFees(e,t){let s=e.assetOut,r=e.assetIn,o="omnipool",i="Short",n=A=>A===L?[L,ne]:[ne,A],[a,l,c,u]=await Promise.all([this.api.query.system.number(),this.api.query.dynamicFees.assetFee(s),this.api.query.emaOracle.oracles(o,n(s),i),this.api.query.emaOracle.oracles(o,n(r),i)]),[b,d,g]=this.getAssetFee(e,a.toNumber(),l,c),[h,f,S]=r===ne?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),y=b+h,N=g+S;return{assetFee:_(d),protocolFee:_(f),min:_(y),max:_(N)}}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,o)=>{let i=e.tokens[o];if(r.isNone)return i;let n=r.unwrap();return this.updateTokenState(i,n)})})}updateTokenState(e,t){let{hubReserve:s,shares:r,tradable:o,cap:i,protocolShares:n}=t;return{...e,hubReserves:m(s.toString()),shares:m(r.toString()),cap:m(i.toString()),protocolShares:m(n.toString()),tradeable:o.bits.toNumber()}}getAssetFee(e,t,s,r){let{assetOut:o,balanceOut:i}=e,{minFee:n,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.assetFeeParameters,u=_(n.toNumber()),b=_(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[d]=r.unwrap(),{assetFee:g,timestamp:h}=s.unwrap(),f=t-h.toNumber(),S=d.volume.bIn.toString(),y=d.volume.bOut.toString(),N=d.liquidity.b.toString();o===L&&(S=d.volume.aIn.toString(),y=d.volume.aOut.toString(),N=d.liquidity.a.toString());let A=_(g.toNumber()),G=B.recalculateAssetFee(S,y,N,"9",i.toString(),w(A).toString(),f.toString(),w(u).toString(),w(b).toString(),l.toString(),c.toString());return[n.toNumber(),Number(G)*1e4,a.toNumber()]}getProtocolFee(e,t,s,r){let{assetIn:o,balanceIn:i}=e,{minFee:n,maxFee:a,decay:l,amplification:c}=this.api.consts.dynamicFees.protocolFeeParameters,u=_(n.toNumber()),b=_(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[d]=r.unwrap(),{protocolFee:g,timestamp:h}=s.unwrap(),f=t-h.toNumber(),S=d.volume.bIn.toString(),y=d.volume.bOut.toString(),N=d.liquidity.b.toString();o===L&&(S=d.volume.aIn.toString(),y=d.volume.aOut.toString(),N=d.liquidity.a.toString());let A=_(g.toNumber()),G=B.recalculateProtocolFee(S,y,N,"9",i.toString(),w(A).toString(),f.toString(),w(u).toString(),w(b).toString(),l.toString(),c.toString());return[n.toNumber(),Number(G)*1e4,a.toNumber()]}getPoolId(){return dt(bt("modlomnipool".padEnd(32,"\0")),U)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};var pe=class extends D{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 o=s.toString(),[i,n]=r.unwrap(),[a,l]=await Promise.all([this.getBalance(o,i.toString()),this.getBalance(o,n.toString())]);return{address:o,type:"Xyk",tokens:[{id:i.toString(),balance:a.toString()},{id:n.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{blake2AsHex as At,encodeAddress as Tt}from"@polkadot/util-crypto";import{calculate_in_given_out as Pt,calculate_out_given_in as ht,calculate_amplification as ft,calculate_add_one_asset as yt,calculate_liquidity_out_one_asset as St,calculate_pool_trade_fee as Bt,calculate_shares as Ot,calculate_shares_for_amount as xt,calculate_spot_price_with_fee as It,pool_account_name as wt}from"@galacticcouncil/math-stableswap";var F=class{static getPoolAddress(e){return wt(e)}static calculateAmplification(e,t,s,r,o){return ft(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o,i){return Pt(e,t,s,r,o,i)}static calculateAddOneAsset(e,t,s,r,o,i){return yt(e,t,s,r,o,i)}static calculateSharesForAmount(e,t,s,r,o,i){return xt(e,t,s,r,o,i)}static calculateOutGivenIn(e,t,s,r,o,i){return ht(e,t,s,r,o,i)}static calculateLiquidityOutOneAsset(e,t,s,r,o,i){return St(e,t,s,r,o,i)}static calculateShares(e,t,s,r,o){return Ot(e,t,s,r,o)}static calculateSpotPriceWithFee(e,t,s,r,o,i,n){return It(e,t,s,r,o,i,n)}static calculatePoolTradeFee(e,t,s){return Bt(e,t,s)}};var ge=class extends D{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[o]},i])=>{let n=i.unwrap(),a=o.toString(),l=this.getPoolAddress(a),[c,u]=await Promise.all([this.getPoolDelta(a,n,s.toString()),this.getPoolTokens(l,a,n)]);return this.stablePools.set(l,n),{address:l,id:a,type:"Stableswap",fee:_(n.fee.toNumber()),tokens:u,...c,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).fee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toNumber(),r=this.stablePools.get(e.address),o=await this.getPoolDelta(e.id,r,s.toString());Object.assign(e,o)})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:o,initialBlock:i,finalBlock:n}=t,a=F.calculateAmplification(r.toString(),o.toString(),i.toString(),n.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,o=r.map(async a=>{let[l,c]=await Promise.all([this.api.query.stableswap.assetTradability(t,a.toString()),this.getBalance(e,a.toString())]);return{id:a.toString(),tradeable:l.bits.toNumber(),balance:c.toString()}}),i=await Promise.all(o),n=await this.api.query.omnipool.assets(t);if(n.isSome){let{tradable:a}=n.unwrap(),l=await this.getBalance(ae,t);i.push({id:t,tradeable:a.bits.toNumber(),balance:l.toString()})}return i}getPoolAddress(e){let t=Number(e),s=F.getPoolAddress(t);return Tt(At(s),U)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function Se(p){return p.map(({assetIn:e,assetOut:t,pool:s,poolId:r})=>s==="Stableswap"?{pool:{Stableswap:r},assetIn:e,assetOut:t}:{pool:s,assetIn:e,assetOut:t})}var de=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"}},Y=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Ne=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Fe=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Re=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ee=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var j=class extends M{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=vt(e=>(this.log("Registry mem sync",e,"\u2705"),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new X(this.api),this.aaveClient=new ce(this.api),this.xykClient=new pe(this.api),this.omniClient=new me(this.api),this.lbpClient=new ue(this.api),this.stableClient=new ge(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()}unsubscribe(){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 de(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}buildBuyTx(e,t,s,r,o){let i;this.isDirectOmnipoolTrade(o)?i=this.api.tx.omnipool.buy(t,e,s.toFixed(),r.toFixed()):i=this.api.tx.router.buy(e,t,s.toFixed(),r.toFixed(),Se(o));let n=()=>i;return{hex:i.toHex(),name:"RouterBuy",get:n}}buildSellTx(e,t,s,r,o){let i;this.isDirectOmnipoolTrade(o)?i=this.api.tx.omnipool.sell(e,t,s.toFixed(),r.toFixed()):i=this.api.tx.router.sell(e,t,s.toFixed(),r.toFixed(),Se(o));let n=()=>i;return{hex:i.toHex(),name:"RouterSell",get:n}}};import{LRUCache as Nt}from"@thi.ng/cache";var Be=class extends j{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Nt(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 o=await super.getPoolFees(e,t);return this.feeCache.set(s,o),o}}async destroy(){this.log(`Destroying pool cache!
2
+ Items: [${this.feeCache.length}]`),this.feeCache.release(),this.disconnectSubscribeNewHeads?.()}};var Z=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,o,i,n){this.type="Lbp",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.fee=i,this.repayFeeApply=n}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),o=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),n=m(o.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:n,decimalsIn:r.decimals,decimalsOut:o.decimals,weightIn:r.weight,weightOut:o.weight}}validateAndBuy(e,t,s){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&o.push("MaxOutRatioExceeded"),r===e.assetOut){let n=this.calculateTradeFee(t,s),a=w(this.repayFeeApply?s.repayFee:s.exchangeFee),l=t.plus(n),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&o.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:o}}else{let n=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(a)&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,amountOut:t,feePct:0,errors:o}}}validateAndSell(e,t,s){let r=this.tokens[0].id,o=[];t.isLessThan(this.minTradingLimit)&&o.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&o.push("MaxInRatioExceeded"),r===e.assetIn){let n=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(a)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:n,feePct:0,errors:o}}else{let n=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(n,s),l=w(this.repayFeeApply?s.repayFee:s.exchangeFee),c=n.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:c,feePct:l,errors:o}}}calculateInGivenOut(e,t){let s=C.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=C.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=C.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),I(T,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=C.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),I(T,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let s=C.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(s)}};var V=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,o,i){this.type="Omnipool",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,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),o=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),n=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:r.hubReserves,hubReservesOut:o.hubReserves,sharesIn:r.shares,sharesOut:o.shares,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:n,tradeableIn:r.tradeable,tradeableOut:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),i=o.minus(r),n=r===P?P:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let b=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(b)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:n.toNumber(),errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),n=r.minus(o).div(r).multipliedBy(100).decimalPlaces(2),a=[],l=B.isSellAllowed(e.tradeableIn),c=B.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let b=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(b)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:n.toNumber(),errors:a}}calculateInGivenOut(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,s);let r=B.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?E(s.assetFee).toString():P.toString(),s?E(s.protocolFee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}calculateLrnaInGivenOut(e,t,s){let r=B.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?E(s.assetFee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=B.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?E(s.assetFee).toString():P.toString(),s?E(s.protocolFee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}calculateOutGivenLrnaIn(e,t,s){let r=B.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?E(s.assetFee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=B.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(J-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=B.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(J-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=B.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(J-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=B.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(J-e.decimalsIn)).decimalPlaces(0,1)}};var Q=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance)}constructor(e,t,s,r,o,i,n,a,l){this.type="Stableswap",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o,this.amplification=i,this.id=n,this.fee=a,this.totalIssuance=l}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),n=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:n,decimalsIn:r.decimals,decimalsOut:o.decimals,tradeableIn:this.id===e?he:r.tradeable,tradeableOut:this.id===t?he:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),i=w(s.fee),n=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount"),{amountIn:o,calculatedIn:r,amountOut:t,feePct:i,errors:n}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateOutGivenIn(e,t,s),i=w(s.fee),n=[],a=B.isSellAllowed(e.tradeableIn),l=B.isBuyAllowed(e.tradeableOut);return(!a||!l)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:r,amountOut:o,feePct:i,errors:n}}calculateIn(e,t,s){let r=F.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?E(s.fee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}calculateAddOneAsset(e,t,s){let r=F.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?E(s.fee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}calculateSharesForAmount(e,t,s){let r=F.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?E(s.fee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}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");if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=I(T,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=I(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?E(s.fee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}calculateWithdrawOneAsset(e,t,s){let r=F.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?E(s.fee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}calculateShares(e,t,s){let r=F.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?E(s.fee).toString():P.toString()),o=m(r);return o.isNegative()?P:o}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");if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=I(T,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=I(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)}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{calculate_in_given_out as Ft,calculate_out_given_in as Rt,calculate_pool_trade_fee as Et,get_spot_price as kt,calculate_liquidity_in as _t,calculate_shares as Lt,calculate_spot_price as Dt,calculate_spot_price_with_fee as Mt,calculate_liquidity_out_asset_a as Ct,calculate_liquidity_out_asset_b as Gt}from"@galacticcouncil/math-xyk";var q=class{static getSpotPrice(e,t,s){return kt(e,t,s)}static calculateInGivenOut(e,t,s){return Ft(e,t,s)}static calculateOutGivenIn(e,t,s){return Rt(e,t,s)}static calculatePoolTradeFee(e,t,s){return Et(e,t,s)}static calculateLiquidityIn(e,t,s){return _t(e,t,s)}static calculateSpotPrice(e,t){return Dt(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Mt(e,t,s,r)}static calculateShares(e,t,s){return Lt(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Ct(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Gt(e,t,s,r)}};var ee=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,o){this.type="Xyk",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),o=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),n=m(o.balance),a=m(r.existentialDeposit),l=m(o.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:n,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateTradeFee(r,s),i=w(s.exchangeFee),n=r.plus(o),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 n.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:r,amountOut:t,feePct:i,errors:a}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,s),i=w(s.exchangeFee),n=r.minus(o),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 n.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:n,feePct:i,errors:a}}calculateInGivenOut(e,t){let s=q.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}calculateOutGivenIn(e,t){let s=q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?P:r}spotPriceInGivenOut(e){let t=q.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=I(T,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=q.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=I(T,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=q.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var te=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,s,r,o){this.type="Aave",this.address=e,this.tokens=t,this.maxInRatio=s,this.maxOutRatio=r,this.minTradingLimit=o}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(a=>[a.id,a])),r=s.get(e),o=s.get(t);if(r==null)throw new Error("Pool does not contain tokenIn");if(o==null)throw new Error("Pool does not contain tokenOut");let i=m(r.balance),n=m(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:n,assetInED:P,assetOutED:P}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=[];return e.balanceOut.isLessThan(t)&&o.push("MaxOutRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=[];return e.balanceIn.isLessThan(t)&&o.push("MaxInRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:o}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return I(T,e.decimalsOut)}spotPriceOutGivenIn(e){return I(T,e.decimalsIn)}calculateTradeFee(e,t){return P}};var se=class{static get(e){switch(e.type){case"Aave":return te.fromPool(e);case"Xyk":return ee.fromPool(e);case"Omnipool":return V.fromPool(e);case"Lbp":return Z.fromPool(e);case"Stableswap":return Q.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var z=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new K,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(n=>n[n.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(n=>this.validPath(n,s)).map(n=>this.toHops(n,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 o=this.getPoolMap(s);return{assets:r,poolsMap:o}}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,o])=>{let i=t.get(s);return{poolAddress:s,poolId:i?.id,pool:i?.type,assetIn:r,assetOut:o}})}toAssets(e,t){return e.map(s=>t.get(s))}};function Ln(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function re(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function ke(p,e){return T.minus(e.div(p)).multipliedBy(100).decimalPlaces(2)}function _e(p,e){return e.div(p).minus(T).multipliedBy(100).decimalPlaces(2)}var be=class extends z{isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((s,r)=>{let o=s[s.length-1].amountOut,i=r[r.length-1].amountOut;return o.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(o=>o.tradeFeeRange?.[0]??o.tradeFeePct).reduce((o,i)=>o+i),r=e.map(o=>o.tradeFeeRange?.[1]??o.tradeFeePct).reduce((o,i)=>o+i);return[s,r]}}getPoolFeeRange(e){let t=e.min?w(e.min):void 0,s=e.max?w(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 o=await super.getPools();if(o.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,o),n=super.getPaths(e,t,i,o);if(n.length===0)throw new Y(e,t);let a;if(r)a=await this.toSellSwaps(s,r,i);else{let x=n.map(async oe=>await this.toSellSwaps(s,oe,i)),k=await Promise.all(x);a=this.findBestSellRoute(k)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),b=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,k)=>x.multipliedBy(k)),d=I(b,c.assetOutDecimals),g=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,i),h=c.amountOut,f=u?c.tradeFeePct:ke(g,h).toNumber(),S=g.minus(h),y=this.getRouteFeeRange(a),N=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(d),A=re(g,N),G=x=>this.poolService.buildSellTx(e,t,l.amountIn,x,a.map(k=>k));return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:d,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A.toNumber(),swaps:a,toTx:G,toHuman(){return{type:"Sell",amountIn:v(l.amountIn,l.assetInDecimals),amountOut:v(c.amountOut,c.assetOutDecimals),spotPrice:v(d,c.assetOutDecimals),tradeFee:v(S,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A.toNumber(),swaps:a.map(x=>x.toHuman())}}}}calculateDelta0Y(e,t,s){let r=[];for(let o=0;o<t.length;o++){let i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.assetOut),l;o>0?l=r[o-1]:l=e;let c=n.calculateOutGivenIn(a,l);r.push(c)}return r[r.length-1]}async toSellSwaps(e,t,s){let r=[];for(let o=0;o<t.length;o++){let i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.assetOut),l;o>0?l=r[o-1].amountOut:l=I(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,n),{amountOut:u,calculatedOut:b,feePct:d,errors:g}=n.validateAndSell(a,l,c),h=this.getPoolFeeRange(c),f=n.spotPriceOutGivenIn(a),S=l.shiftedBy(-1*a.decimalsIn).multipliedBy(f),y=re(b,S);r.push({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:b,amountOut:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:y.toNumber(),errors:g,toHuman(){return{...i,amountIn:v(l,a.decimalsIn),calculatedOut:v(b,a.decimalsOut),amountOut:v(u,a.decimalsOut),spotPrice:v(f,a.decimalsOut),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:y.toNumber(),errors:g}}})}return r}async getMostLiquidRoute(e,t){let s=await super.getPools(),{poolsMap:r}=await super.validateTokenPair(e,t,s),o=super.getPaths(e,t,r,s);if(o.length===0)throw new Y(e,t);let i=s.map(g=>g.tokens.find(h=>h.id===e)).filter(g=>!!g).sort((g,h)=>Number(h.balance)-Number(g.balance)),{balance:n,decimals:a}=i[0],c=m(n).shiftedBy(-1*a).div(100).multipliedBy(.1),u=o.map(async g=>await this.toSellSwaps(c,g,r)),b=await Promise.all(u);return this.findBestSellRoute(b).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.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),n=await this.toSellSwaps("1",i,r),a=n.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,b)=>u.multipliedBy(b)),l=n[n.length-1].assetOutDecimals;return{amount:I(a,l),decimals:l}}findBestBuyRoute(e){let t=e.sort((s,r)=>{let o=s[0].amountIn,i=r[0].amountIn;return o.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 o=await super.getPools();if(o.length===0)throw new Error("No pools configured");let{poolsMap:i}=await super.validateTokenPair(e,t,o),n=super.getPaths(e,t,i,o);if(n.length===0)throw new Y(e,t);let a;if(r)a=await this.toBuySwaps(s,r,i);else{let x=n.map(async oe=>await this.toBuySwaps(s,oe,i)),k=await Promise.all(x);a=this.findBestBuyRoute(k)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),b=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,k)=>x.multipliedBy(k)),d=I(b,c.assetInDecimals),g=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,i),h=c.amountIn,f=u?c.tradeFeePct:_e(g,h).toNumber(),S=h.minus(g),y=this.getRouteFeeRange(a),N=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(d),A;g.isZero()?A=-100:A=re(N,g).toNumber();let G=x=>this.poolService.buildBuyTx(e,t,l.amountOut,x,a.map(k=>k));return{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:d,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A,swaps:a,toTx:G,toHuman(){return{type:"Buy",amountOut:v(l.amountOut,l.assetOutDecimals),amountIn:v(c.amountIn,c.assetInDecimals),spotPrice:v(d,c.assetInDecimals),tradeFee:v(S,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A,swaps:a.map(x=>x.toHuman())}}}}calculateDelta0X(e,t,s){let r=[];for(let o=t.length-1;o>=0;o--){let i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.assetOut),l;o==t.length-1?l=e:l=r[0];let c=n.calculateInGivenOut(a,l);r.unshift(c)}return r[0]}async toBuySwaps(e,t,s){let r=[];for(let o=t.length-1;o>=0;o--){let i=t[o],n=s.get(i.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(i.assetIn,i.assetOut),l;o==t.length-1?l=I(m(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,n),{amountIn:u,calculatedIn:b,feePct:d,errors:g}=n.validateAndBuy(a,l,c),h=this.getPoolFeeRange(c),f=n.spotPriceInGivenOut(a),S=l.shiftedBy(-1*a.decimalsOut).multipliedBy(f),y;b.isZero()?y=-100:y=re(S,b).toNumber(),r.unshift({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:b,amountIn:u,spotPrice:f,tradeFeePct:d,tradeFeeRange:h,priceImpactPct:y,errors:g,toHuman(){return{...i,amountOut:v(l,a.decimalsOut),calculatedIn:v(b,a.decimalsIn),amountIn:v(u,a.decimalsIn),spotPrice:v(f,a.decimalsIn),tradeFeePct:d,tradeFeeRange:h,priceImpactPct:y,errors:g}}})}return r}};import{memoize1 as sa}from"@thi.ng/memoize";export{te as AavePool,X as AssetClient,Ne as AssetNotFound,as as BASILISK_PARACHAIN_ID,H as BalanceClient,O as BigNumber,Be as CachingPoolService,Ce as DECIMAL_PLACES,fe as DENOMINATOR,ye as FarmClient,ne as HUB_ASSET_ID,ae as HYDRADX_OMNIPOOL_ADDRESS,ns as HYDRADX_PARACHAIN_ID,U as HYDRADX_SS58_PREFIX,Ss as INFINITY,C as LbpMath,Z as LbpPool,T as ONE,B as OmniMath,V as OmniPool,M as PolkadotApiClient,ve as PoolConfigNotFound,W as PoolError,se as PoolFactory,de as PoolNotFound,j as PoolService,R as PoolType,Ee as ProviderConfigNotFound,J as RUNTIME_DECIMALS,Y as RouteNotFound,z as Router,is as SYSTEM_ASSET_DECIMALS,L as SYSTEM_ASSET_ID,F as StableMath,Q as StableSwap,Fe as StorageConfigNotFound,Re as SubscriptionNotSupported,he as TRADEABLE_DEFAULT,be as TradeRouter,xe as TradeType,q as XykMath,ee as XykPool,P as ZERO,m as bnum,Se as buildRoute,_e as calculateBuyFee,Ln as calculateDiffToAvg,re as calculateDiffToRef,ke as calculateSellFee,Ie as findNestedKey,ms as findNestedObj,I as scale};
@@ -1,7 +1,9 @@
1
1
  import { ApiPromise } from '@polkadot/api';
2
2
  import { PalletLiquidityMiningGlobalFarmData } from '@polkadot/types/lookup';
3
3
  import { PolkadotApiClient } from './PolkadotApi';
4
+ import { BalanceClient } from './BalanceClient';
4
5
  export declare class FarmClient extends PolkadotApiClient {
6
+ protected readonly balanceClient: BalanceClient;
5
7
  constructor(api: ApiPromise);
6
8
  private secondsInYear;
7
9
  private getOmnipoolFarms;
@@ -9,6 +11,8 @@ export declare class FarmClient extends PolkadotApiClient {
9
11
  getOraclePrice(globalFarm: PalletLiquidityMiningGlobalFarmData): Promise<string | undefined>;
10
12
  private getGlobalRewardPerPeriod;
11
13
  private getPoolYieldPerPeriod;
14
+ private padEndU8a;
15
+ private getAccountResolver;
12
16
  /**
13
17
  * Return list of all available assets from substrate based pools
14
18
  * @param {string} id - asset id within omnipool or address of isolated pool
@@ -6,4 +6,6 @@ export declare abstract class PolkadotApiClient {
6
6
  constructor(api: ApiPromise);
7
7
  get chainDecimals(): number;
8
8
  get chainToken(): string;
9
+ protected log(message?: any, ...optionalParams: any[]): void;
10
+ private getLogValue;
9
11
  }
@@ -1,3 +1,4 @@
1
1
  export { AssetClient } from './AssetClient';
2
2
  export { BalanceClient } from './BalanceClient';
3
3
  export { FarmClient } from './FarmClient';
4
+ export { PolkadotApiClient } from './PolkadotApi';
@@ -1,15 +1,17 @@
1
1
  import { ApiPromise } from '@polkadot/api';
2
+ import { AavePoolClient } from './aave/AavePoolClient';
2
3
  import { LbpPoolClient } from './lbp/LbpPoolClient';
3
4
  import { OmniPoolClient } from './omni/OmniPoolClient';
4
5
  import { XykPoolClient } from './xyk/XykPoolClient';
5
6
  import { StableSwapClient } from './stable/StableSwapClient';
6
- import { AssetClient } from '../client';
7
+ import { AssetClient, PolkadotApiClient } from '../client';
7
8
  import { Asset, ExternalAsset, Hop, IPoolService, Pool, PoolBase, PoolFees, PoolPair, PoolType, Transaction } from '../types';
8
9
  import { BigNumber } from '../utils/bignumber';
9
10
  import { PoolClient } from './PoolClient';
10
- export declare class PoolService implements IPoolService {
11
+ export declare class PoolService extends PolkadotApiClient implements IPoolService {
11
12
  protected readonly api: ApiPromise;
12
13
  protected readonly assetClient: AssetClient;
14
+ protected readonly aaveClient: AavePoolClient;
13
15
  protected readonly xykClient: XykPoolClient;
14
16
  protected readonly omniClient: OmniPoolClient;
15
17
  protected readonly lbpClient: LbpPoolClient;
@@ -6,7 +6,7 @@ export declare function buildRoute(route: Hop[]): ({
6
6
  assetIn: string;
7
7
  assetOut: string;
8
8
  } | {
9
- pool: PoolType.XYK | PoolType.LBP | PoolType.Omni;
9
+ pool: PoolType.Aave | PoolType.LBP | PoolType.Omni | PoolType.XYK;
10
10
  assetIn: string;
11
11
  assetOut: string;
12
12
  })[];
@@ -0,0 +1,126 @@
1
+ export declare const AAVE_ABI: readonly [{
2
+ readonly anonymous: false;
3
+ readonly inputs: readonly [{
4
+ readonly indexed: true;
5
+ readonly internalType: "address";
6
+ readonly name: "reserve";
7
+ readonly type: "address";
8
+ }, {
9
+ readonly indexed: false;
10
+ readonly internalType: "address";
11
+ readonly name: "user";
12
+ readonly type: "address";
13
+ }, {
14
+ readonly indexed: true;
15
+ readonly internalType: "address";
16
+ readonly name: "onBehalfOf";
17
+ readonly type: "address";
18
+ }, {
19
+ readonly indexed: false;
20
+ readonly internalType: "uint256";
21
+ readonly name: "amount";
22
+ readonly type: "uint256";
23
+ }, {
24
+ readonly indexed: true;
25
+ readonly internalType: "uint16";
26
+ readonly name: "referralCode";
27
+ readonly type: "uint16";
28
+ }];
29
+ readonly name: "Supply";
30
+ readonly type: "event";
31
+ }, {
32
+ readonly anonymous: false;
33
+ readonly inputs: readonly [{
34
+ readonly indexed: true;
35
+ readonly internalType: "address";
36
+ readonly name: "reserve";
37
+ readonly type: "address";
38
+ }, {
39
+ readonly indexed: true;
40
+ readonly internalType: "address";
41
+ readonly name: "user";
42
+ readonly type: "address";
43
+ }, {
44
+ readonly indexed: true;
45
+ readonly internalType: "address";
46
+ readonly name: "to";
47
+ readonly type: "address";
48
+ }, {
49
+ readonly indexed: false;
50
+ readonly internalType: "uint256";
51
+ readonly name: "amount";
52
+ readonly type: "uint256";
53
+ }];
54
+ readonly name: "Withdraw";
55
+ readonly type: "event";
56
+ }, {
57
+ readonly anonymous: false;
58
+ readonly inputs: readonly [{
59
+ readonly indexed: true;
60
+ readonly internalType: "address";
61
+ readonly name: "reserve";
62
+ readonly type: "address";
63
+ }, {
64
+ readonly indexed: false;
65
+ readonly internalType: "address";
66
+ readonly name: "user";
67
+ readonly type: "address";
68
+ }, {
69
+ readonly indexed: true;
70
+ readonly internalType: "address";
71
+ readonly name: "onBehalfOf";
72
+ readonly type: "address";
73
+ }, {
74
+ readonly indexed: false;
75
+ readonly internalType: "uint256";
76
+ readonly name: "amount";
77
+ readonly type: "uint256";
78
+ }, {
79
+ readonly indexed: false;
80
+ readonly internalType: "enum DataTypes.InterestRateMode";
81
+ readonly name: "interestRateMode";
82
+ readonly type: "uint8";
83
+ }, {
84
+ readonly indexed: false;
85
+ readonly internalType: "uint256";
86
+ readonly name: "borrowRate";
87
+ readonly type: "uint256";
88
+ }, {
89
+ readonly indexed: true;
90
+ readonly internalType: "uint16";
91
+ readonly name: "referralCode";
92
+ readonly type: "uint16";
93
+ }];
94
+ readonly name: "Borrow";
95
+ readonly type: "event";
96
+ }, {
97
+ readonly anonymous: false;
98
+ readonly inputs: readonly [{
99
+ readonly indexed: true;
100
+ readonly internalType: "address";
101
+ readonly name: "reserve";
102
+ readonly type: "address";
103
+ }, {
104
+ readonly indexed: true;
105
+ readonly internalType: "address";
106
+ readonly name: "user";
107
+ readonly type: "address";
108
+ }, {
109
+ readonly indexed: true;
110
+ readonly internalType: "address";
111
+ readonly name: "repayer";
112
+ readonly type: "address";
113
+ }, {
114
+ readonly indexed: false;
115
+ readonly internalType: "uint256";
116
+ readonly name: "amount";
117
+ readonly type: "uint256";
118
+ }, {
119
+ readonly indexed: false;
120
+ readonly internalType: "bool";
121
+ readonly name: "useATokens";
122
+ readonly type: "bool";
123
+ }];
124
+ readonly name: "Repay";
125
+ readonly type: "event";
126
+ }];
@@ -0,0 +1,21 @@
1
+ import { BuyTransfer, Pool, PoolBase, PoolFees, PoolPair, PoolToken, PoolType, SellTransfer } from '../../types';
2
+ import { BigNumber } from '../../utils/bignumber';
3
+ export declare class AavePool implements Pool {
4
+ type: PoolType;
5
+ address: string;
6
+ tokens: PoolToken[];
7
+ maxInRatio: number;
8
+ maxOutRatio: number;
9
+ minTradingLimit: number;
10
+ static fromPool(pool: PoolBase): AavePool;
11
+ constructor(address: string, tokens: PoolToken[], maxInRation: number, maxOutRatio: number, minTradeLimit: number);
12
+ validatePair(_tokenIn: string, _tokenOut: string): boolean;
13
+ parsePair(tokenIn: string, tokenOut: string): PoolPair;
14
+ validateAndBuy(poolPair: PoolPair, amountOut: BigNumber, _fees: PoolFees): BuyTransfer;
15
+ validateAndSell(poolPair: PoolPair, amountIn: BigNumber, _fees: PoolFees): SellTransfer;
16
+ calculateInGivenOut(_poolPair: PoolPair, amountOut: BigNumber): BigNumber;
17
+ calculateOutGivenIn(_poolPair: PoolPair, amountIn: BigNumber): BigNumber;
18
+ spotPriceInGivenOut(poolPair: PoolPair): BigNumber;
19
+ spotPriceOutGivenIn(poolPair: PoolPair): BigNumber;
20
+ calculateTradeFee(_amount: BigNumber, _fees: PoolFees): BigNumber;
21
+ }
@@ -0,0 +1,14 @@
1
+ import { UnsubscribePromise } from '@polkadot/api-base/types';
2
+ import { PoolBase, PoolType, PoolFees, PoolPair } from '../../types';
3
+ import { PoolClient } from '../PoolClient';
4
+ export declare class AavePoolClient extends PoolClient {
5
+ isSupported(): boolean;
6
+ loadPools(): Promise<PoolBase[]>;
7
+ getPoolFees(_poolPair: PoolPair, _address: string): Promise<PoolFees>;
8
+ getPoolType(): PoolType;
9
+ private getPoolId;
10
+ protected subscribePoolChange(pool: PoolBase): UnsubscribePromise;
11
+ private updatePoolState;
12
+ private getReserveH160Id;
13
+ private getPoolLimits;
14
+ }
@@ -0,0 +1,7 @@
1
+ import type { Struct, u128, u32 } from '@polkadot/types-codec';
2
+ export interface AaveTradeExecutorPoolData extends Struct {
3
+ readonly reserve: u32;
4
+ readonly atoken: u32;
5
+ readonly liqudityIn: u128;
6
+ readonly liqudityOut: u128;
7
+ }
@@ -2,6 +2,7 @@ export { CachingPoolService } from './CachingPoolService';
2
2
  export { PoolFactory } from './PoolFactory';
3
3
  export { PoolService } from './PoolService';
4
4
  export * from './PoolUtils';
5
+ export { AavePool } from './aave/AavePool';
5
6
  export { XykPool } from './xyk/XykPool';
6
7
  export { XykMath } from './xyk/XykMath';
7
8
  export { OmniPool } from './omni/OmniPool';
@@ -1,9 +1,10 @@
1
1
  import { BigNumber } from './utils/bignumber';
2
2
  export declare enum PoolType {
3
- XYK = "Xyk",
3
+ Aave = "Aave",
4
4
  LBP = "Lbp",
5
+ Omni = "Omnipool",
5
6
  Stable = "Stableswap",
6
- Omni = "Omnipool"
7
+ XYK = "Xyk"
7
8
  }
8
9
  export declare enum PoolError {
9
10
  UnknownError = "UnknownError",
@@ -0,0 +1,5 @@
1
+ export declare class ERC20Mapping {
2
+ static encodeEvmAddress(assetId: string): string;
3
+ static decodeEvmAddress(evmAddress: string): number | null;
4
+ static isAssetAddress(address: string): boolean;
5
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk",
3
- "version": "5.6.0",
3
+ "version": "5.7.0-pr146-35311fb",
4
4
  "description": "Galactic off-chain routing & optimization of orders across pools for best price execution",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {
@@ -57,6 +57,7 @@
57
57
  "@polkadot/types-create": "~14.0.1",
58
58
  "@polkadot/types-known": "~14.0.1",
59
59
  "@polkadot/util": "~13.1.1",
60
- "@polkadot/util-crypto": "~13.1.1"
60
+ "@polkadot/util-crypto": "~13.1.1",
61
+ "viem": "^2.23.7"
61
62
  }
62
63
  }