@galacticcouncil/sdk 6.2.0 → 7.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +99 -41
- package/build/index.cjs +2 -2
- package/build/index.mjs +2 -2
- package/build/types/{client → api}/PolkadotApi.d.ts +3 -0
- package/build/types/api/index.d.ts +2 -3
- package/build/types/api/types.d.ts +8 -0
- package/build/types/client/AssetClient.d.ts +2 -2
- package/build/types/client/BalanceClient.d.ts +1 -1
- package/build/types/client/FarmClient.d.ts +1 -1
- package/build/types/client/index.d.ts +0 -1
- package/build/types/consts.d.ts +6 -7
- package/build/types/errors.d.ts +1 -1
- package/build/types/{pool/aave/AaveAbi.d.ts → evm/abi/Aave.d.ts} +48 -0
- package/build/types/evm/abi/Erc20.d.ts +150 -0
- package/build/types/evm/abi/index.d.ts +1 -0
- package/build/types/evm/chain.d.ts +2 -0
- package/build/types/evm/client.d.ts +11 -0
- package/build/types/evm/const.d.ts +4 -0
- package/build/types/evm/index.d.ts +4 -0
- package/build/types/index.d.ts +7 -4
- package/build/types/pool/CachingPoolService.d.ts +2 -2
- package/build/types/pool/PoolClient.d.ts +2 -1
- package/build/types/pool/PoolFactory.d.ts +1 -1
- package/build/types/pool/PoolService.d.ts +10 -14
- package/build/types/pool/aave/AavePool.d.ts +3 -3
- package/build/types/pool/aave/AavePoolClient.d.ts +1 -1
- package/build/types/pool/index.d.ts +1 -1
- package/build/types/pool/lbp/LbpPool.d.ts +3 -3
- package/build/types/pool/lbp/LbpPoolClient.d.ts +1 -1
- package/build/types/pool/omni/OmniPool.d.ts +3 -3
- package/build/types/pool/omni/OmniPoolClient.d.ts +1 -1
- package/build/types/pool/stable/StableSwap.d.ts +3 -3
- package/build/types/pool/stable/StableSwapClient.d.ts +1 -1
- package/build/types/pool/types.d.ts +81 -0
- package/build/types/pool/xyk/XykPool.d.ts +3 -3
- package/build/types/pool/xyk/XykPoolClient.d.ts +1 -1
- package/build/types/{api → sor}/Router.d.ts +2 -1
- package/build/types/{api → sor}/TradeRouter.d.ts +3 -1
- package/build/types/sor/TradeUtils.d.ts +25 -0
- package/build/types/sor/index.d.ts +4 -0
- package/build/types/{route → sor/route}/graph.d.ts +1 -1
- package/build/types/{route → sor/route}/suggester.d.ts +1 -1
- package/build/types/sor/types.d.ts +34 -0
- package/build/types/types.d.ts +8 -127
- package/build/types/utils/erc20.d.ts +3 -3
- package/build/types/utils/h160.d.ts +11 -0
- package/build/types/utils/mapper.d.ts +1 -1
- package/build/types/utils/math.d.ts +8 -0
- package/package.json +1 -1
- package/build/types/api/WalletCtx.d.ts +0 -20
- package/build/types/pool/PoolUtils.d.ts +0 -12
- package/build/types/{route → sor/route}/bfs.d.ts +0 -0
- package/build/types/{route → sor/route}/index.d.ts +1 -1
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var te=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,J=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 te,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 he(g){let e={};for(let t of g){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=he(s),o=Object.keys(r),i=o.map(c=>r[c]).flat(),n=new J,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 Rt}from"@thi.ng/memoize";import{encodeAddress as Ue}from"@polkadot/util-crypto";import{stringToU8a as We}from"@polkadot/util";import{decodeEventLog as Xe}from"viem";var Be=[{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,Z=15,L="0",ls=12,se="1",cs=2034,W=63,us=2090,fe=1e3,ms=De(Me("modlomnipool".padEnd(32,"\0")),W);var R=(o=>(o.Aave="Aave",o.LBP="Lbp",o.Omni="Omnipool",o.Stable="Stableswap",o.XYK="Xyk",o))(R||{}),X=(o=>(o.UnknownError="UnknownError",o.InsufficientTradingAmount="InsufficientTradingAmount",o.MaxInRatioExceeded="MaxInRatioExceeded",o.MaxOutRatioExceeded="MaxOutRatioExceeded",o.TradeNotAllowed="TradeNotAllowed",o))(X||{}),Oe=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Oe||{});var re=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 xe(g,e){let t=[];return JSON.stringify(g,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Ps(g,e,t){let s;return JSON.stringify(g,(r,o)=>(o&&o[e]===t&&(s=o),o)),s}var bs=(g,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as He}from"@thi.ng/memoize";import{TLRUCache as qe}from"@thi.ng/cache";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 Y=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),P=i.toNumber(),p=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",p.format(P)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:o.toString(),maturity:P}}getShares(e,t,s,r){let{assets:o}=r,{name:i,symbol:n,assetType:a,isSufficient:l,existentialDeposit:c}=t,P=o.map(b=>b.toString()).map(b=>{let{symbol:f}=this.getToken(b,t,s);return[b,f]}),p=Object.fromEntries(P),d=Object.values(p);return{id:e,name:d.join(", "),symbol:n?.isSome?n.toHuman():i.toHuman(),decimals:18,icon:d.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:p}}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]},P])=>{let p=P.unwrap(),d=r.get(u.toString()),{assetType:b}=p;switch(b.toString()){case"Bond":let f=i.get(u.toString());return this.getBond(u.toString(),p,l,f);case"StableSwap":let S=o.get(u.toString());return this.getShares(u.toString(),p,l,S);case"External":return this.getExternal(u.toString(),p,t,d);default:return this.getToken(u.toString(),p,l,d)}});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 h=m(0),v=m(1),Is=m("Infinity");function w(g,e){let t=new O(e.toString()),s=new O(10).pow(t);return g.times(s)}function m(g){return new O(g.toString())}var q=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:0n,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 Ie}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Ge}from"@polkadot/types";import{u8aConcat as Ae}from"@polkadot/util";var ye=class extends M{balanceClient;constructor(e){super(e),this.balanceClient=new q(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(),p=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(p,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([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(),p=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(p,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,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 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=Ie(n,a):l=Ie(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 Ae(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(Ae(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()),P=a.plannedYieldingPeriods.toString(),p=new O(a.yieldPerPeriod.toString()),d=new O(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),f=new O(n.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new O(s).times(b)),y;if(u.isZero())y=p.times(f).times(S);else{let _=this.getGlobalRewardPerPeriod(u,p,d,l);y=this.getPoolYieldPerPeriod(_,f,u,l).times(S)}let A=new O(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),T=d.times(P),G=c?A.plus(c):T;return A.div(G).gte(.999)?h:y.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,a)=>n.plus(a),h).toString():void 0}};var D=class extends q{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new qe(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=He(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let 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)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,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 Ye=["Supply","Withdraw","Repay","Borrow"],oe=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 Ue(We(s.padEnd(32,"\0")),W)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);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,""),P=c.replace(/,/g,"");(u===s.id||P===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${P}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=n.data.toHuman();try{let{eventName:c,args:u}=Xe({abi:Be,topics:l.topics,data:l.data});Ye.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut: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"?xe(e.location,"accountKey20").accountKey20.key:re.encodeEvmAddress(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as $e,calculate_out_given_in as ze,calculate_linear_weights as Je,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 $e(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 Je(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return Ke(e,t,s)}};var ie=class extends D{MAX_FINAL_WEIGHT=w(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),[P,p]=i,d=P.toString(),b=m(u),f=p.toString(),S=this.MAX_FINAL_WEIGHT.minus(m(b)),[y,A,T]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,f)]);return{repayFeeApply:y,tokens:[{id:d,weight:b,balance:A.toString()},{id:f,weight:S,balance:T.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 Pt}from"@polkadot/util-crypto";import{stringToU8a as bt}from"@polkadot/util";function F(g,e){return g.shiftedBy(-1*e).toString()}function I(g){return g[0]/g[1]*100}function k(g){return g[0]/g[1]}function E(g){return[g/fe,fe]}import{calculate_in_given_out as Ze,calculate_lrna_in_given_out as Ve,calculate_out_given_in as Qe,calculate_out_given_lrna_in as et,calculate_pool_trade_fee as tt,calculate_spot_price as st,calculate_lrna_spot_price as rt,calculate_shares as ot,calculate_liquidity_out as it,calculate_liquidity_lrna_out as nt,calculate_liquidity_hub_in as at,is_sell_allowed as lt,is_buy_allowed as ct,is_add_liquidity_allowed as ut,is_remove_liquidity_allowed as mt,recalculate_asset_fee as pt,recalculate_protocol_fee as gt,verify_asset_cap as dt}from"@galacticcouncil/math-omnipool";var x=class{static calculateSpotPrice(e,t,s,r){return st(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return rt(e,t)}static calculateInGivenOut(e,t,s,r,o,i,n,a,l){return Ze(e,t,s,r,o,i,n,a,l)}static calculateLrnaInGivenOut(e,t,s,r,o){return Ve(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o,i,n,a,l){return Qe(e,t,s,r,o,i,n,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,o){return et(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return tt(e,t,s)}static calculateShares(e,t,s,r){return ot(e,t,s,r)}static calculateLiquidityOut(e,t,s,r,o,i,n,a){return it(e,t,s,r,o,i,n,a)}static calculateLiquidityLRNAOut(e,t,s,r,o,i,n,a){return nt(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),P=o.times(O(1).minus(l));return u.div(P).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return at(e,t,s,r)}static isSellAllowed(e){return lt(e)}static isBuyAllowed(e){return ct(e)}static isAddLiquidityAllowed(e){return ut(e)}static isRemoveLiquidityAllowed(e){return mt(e)}static recalculateAssetFee(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 recalculateProtocolFee(e,t,s,r,o,i,n,a,l,c,u){return gt(e,t,s,r,o,i,n,a,l,c,u)}static verifyAssetCap(e,t,s,r){return dt(e,t,s,r)}};var ne=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:P,cap:p,protocolShares:d}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:P.bits.toNumber(),balance:b.toString(),cap:m(p.toString()),protocolShares:m(d.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=T=>T===L?[L,se]:[se,T],[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)]),[P,p,d]=this.getAssetFee(e,a.toNumber(),l,c),[b,f,S]=r===se?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),y=P+b,A=d+S;return{assetFee:E(p),protocolFee:E(f),min:E(y),max:E(A)}}getPoolType(){return"Omnipool"}async subscribePoolChange(e){let t=e.tokens.map(s=>s.id);return this.api.query.omnipool.assets.multi(t,s=>{e.tokens=s.map((r,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=E(n.toNumber()),P=E(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[p]=r.unwrap(),{assetFee:d,timestamp:b}=s.unwrap(),f=t-b.toNumber(),S=p.volume.bIn.toString(),y=p.volume.bOut.toString(),A=p.liquidity.b.toString();o===L&&(S=p.volume.aIn.toString(),y=p.volume.aOut.toString(),A=p.liquidity.a.toString());let T=E(d.toNumber()),G=x.recalculateAssetFee(S,y,A,"9",i.toString(),I(T).toString(),f.toString(),I(u).toString(),I(P).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=E(n.toNumber()),P=E(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[p]=r.unwrap(),{protocolFee:d,timestamp:b}=s.unwrap(),f=t-b.toNumber(),S=p.volume.bIn.toString(),y=p.volume.bOut.toString(),A=p.liquidity.b.toString();o===L&&(S=p.volume.aIn.toString(),y=p.volume.aOut.toString(),A=p.liquidity.a.toString());let T=E(d.toNumber()),G=x.recalculateProtocolFee(S,y,A,"9",i.toString(),I(T).toString(),f.toString(),I(u).toString(),I(P).toString(),l.toString(),c.toString());return[n.toNumber(),Number(G)*1e4,a.toNumber()]}getPoolId(){return Pt(bt("modlomnipool".padEnd(32,"\0")),W)}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 ae=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 vt,encodeAddress as Ft}from"@polkadot/util-crypto";import{calculate_in_given_out as ht,calculate_out_given_in as ft,calculate_amplification as yt,calculate_add_one_asset as St,calculate_liquidity_out_one_asset as Bt,calculate_pool_trade_fee as Ot,calculate_shares as xt,calculate_shares_for_amount as wt,calculate_spot_price_with_fee as It,pool_account_name as At,recalculate_peg as Tt}from"@galacticcouncil/math-stableswap";var N=class{static getPoolAddress(e){return At(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,o){return yt(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o,i,n){return ht(e,t,s,r,o,i,n)}static calculateAddOneAsset(e,t,s,r,o,i,n){return St(e,t,s,r,o,i,n)}static calculateSharesForAmount(e,t,s,r,o,i,n){return wt(e,t,s,r,o,i,n)}static calculateOutGivenIn(e,t,s,r,o,i,n){return ft(e,t,s,r,o,i,n)}static calculateLiquidityOutOneAsset(e,t,s,r,o,i,n){return Bt(e,t,s,r,o,i,n)}static calculateShares(e,t,s,r,o,i){return xt(e,t,s,r,o,i)}static calculateSpotPriceWithFee(e,t,s,r,o,i,n,a){return It(e,t,s,r,o,i,n,a)}static calculatePoolTradeFee(e,t,s){return Ot(e,t,s)}static recalculatePegs(e,t,s,r,o){let i=Tt(e,t,s,r,o);return JSON.parse(i)}};var Nt=340282366920938463463374607431768211455n,le=class extends D{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[o]},i])=>{let n=i.unwrap(),a=o.toString(),l=this.getPoolAddress(a),[c,u,P]=await Promise.all([this.getPoolDelta(a,n,s.toString()),this.getPoolTokens(l,a,n),this.getPoolPegs(a,n,s.toString())]);return this.stablePools.set(l,n),{address:l,id:a,type:"Stableswap",fee:E(n.fee.toNumber()),tokens:u,...c,...P,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[o,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,o,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:o,initialBlock:i,finalBlock:n}=t,a=N.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 n=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),i=await Promise.all(o);return i.push({id:t,tradeable:Z,balance:Nt.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=N.defaultPegs(e.assets.length);return{pegsFee:E(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let o=r.unwrap(),i=await this.getLatestPegs(t,o,s),n=this.getRecentPegs(o),a=o.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=N.recalculatePegs(JSON.stringify(n),JSON.stringify(i),s,a.replace(/%/g,""),l.replace(/%/g,"")),P=Number(c)*1e4;return{pegsFee:E(P),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(o=>o.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,o=Array.from(e.assets.entries()).map(([n,a])=>a.toString()),i=r.map(async(n,a)=>{if(n.isOracle){let[l,c,u]=n.asOracle,P=[u.toString(),o[a]].map(y=>Number(y)).sort((y,A)=>y-A),p=await this.api.query.emaOracle.oracles(l,P,c),[{price:d,updatedAt:b}]=p.unwrap(),f=d.n.toString(),S=d.d.toString();return u.toString()===P[0].toString()?[[f,S],b.toString()]:[[S,f],b.toString()]}else return[n.asValue.map(l=>l.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=N.getPoolAddress(t);return Ft(vt(s),W)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};function ce(g){return g.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"}},Te=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},$=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ve=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Fe=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Ne=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Re=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var V=class extends M{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=Rt(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new Y(this.api),this.aaveClient=new oe(this.api),this.xykClient=new ae(this.api),this.omniClient=new ne(this.api),this.lbpClient=new ie(this.api),this.stableClient=new le(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 ue(t.type)}}isDirectOmnipoolTrade(e){return e.length==1&&e[0].pool=="Omnipool"}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}buildBuyTx(e,t,s,r,o){let i;return 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(),ce(o)),{hex:i.toHex(),name:"RouterBuy",get:()=>i,dryRun:n=>this.dryRun(n,i)}}buildSellTx(e,t,s,r,o){let i;return 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(),ce(o)),{hex:i.toHex(),name:"RouterSell",get:()=>i,dryRun:n=>this.dryRun(n,i)}}buildSellAllTx(e,t,s,r){let o=this.api.tx.router.sellAll(e,t,s.toFixed(),ce(r));return{hex:o.toHex(),name:"RouterSellAll",get:()=>o,dryRun:i=>this.dryRun(i,o)}}};import{LRUCache as Et}from"@thi.ng/cache";var Se=class extends V{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new Et(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 me=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new g(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=I(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=I(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()?h: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()?h:r}spotPriceInGivenOut(e){let t=C.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),w(v,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=C.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),w(v,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 pe=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new g(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===h?h:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=x.isSellAllowed(e.tradeableIn),c=x.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 P=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(P)&&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=x.isSellAllowed(e.tradeableIn),c=x.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 P=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(P)&&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=x.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString(),s?k(s.protocolFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateLrnaInGivenOut(e,t,s){let r=x.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateOutGivenIn(e,t,s){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,s);let r=x.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString(),s?k(s.protocolFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}calculateOutGivenLrnaIn(e,t,s){let r=x.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():h.toString()),o=m(r);return o.isNegative()?h:o}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=x.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=x.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=x.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=x.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(j-e.decimalsIn)).decimalPlaces(0,1)}};var ge=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new g(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,o,i,n,a,l,c,u){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,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),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?Z:r.tradeable,tradeableOut:this.id===t?Z:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),i=I(s.fee),n=[],a=x.isSellAllowed(e.tradeableIn),l=x.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=I(s.fee),n=[],a=x.isSellAllowed(e.tradeableIn),l=x.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=N.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateAddOneAsset(e,t,s){let r=N.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateSharesForAmount(e,t,s){let r=N.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h: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=N.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let r=w(v,e.decimalsIn-e.decimalsOut);return m(t).div(r)}let s=w(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?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateWithdrawOneAsset(e,t,s){let r=N.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h:o}calculateShares(e,t,s){let r=N.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?k(s.fee).toString():h.toString(),this.getPegs()),o=m(r);return o.isNegative()?h: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=N.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let r=w(v,e.decimalsOut-e.decimalsIn);return m(t).div(r)}let s=w(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)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{calculate_in_given_out as kt,calculate_out_given_in as _t,calculate_pool_trade_fee as Lt,get_spot_price as Dt,calculate_liquidity_in as Mt,calculate_shares as Ct,calculate_spot_price as Gt,calculate_spot_price_with_fee as Ht,calculate_liquidity_out_asset_a as qt,calculate_liquidity_out_asset_b as Ut}from"@galacticcouncil/math-xyk";var U=class{static getSpotPrice(e,t,s){return Dt(e,t,s)}static calculateInGivenOut(e,t,s){return kt(e,t,s)}static calculateOutGivenIn(e,t,s){return _t(e,t,s)}static calculatePoolTradeFee(e,t,s){return Lt(e,t,s)}static calculateLiquidityIn(e,t,s){return Mt(e,t,s)}static calculateSpotPrice(e,t){return Gt(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Ht(e,t,s,r)}static calculateShares(e,t,s){return Ct(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return qt(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Ut(e,t,s,r)}};var de=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new g(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=I(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=I(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=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}calculateOutGivenIn(e,t){let s=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=m(s);return r.isNegative()?h:r}spotPriceInGivenOut(e){let t=U.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=w(v,18-e.decimalsOut);return m(t).div(s)}spotPriceOutGivenIn(e){let t=U.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=w(v,18-e.decimalsIn);return m(t).div(s)}calculateTradeFee(e,t){let s=U.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(s)}};var Pe=class g{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new g(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:h,assetOutED:h}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=[];return t.isGreaterThan(e.balanceOut)&&o.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=[];return r.isGreaterThan(e.balanceOut)&&o.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:o}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return w(v,e.decimalsOut)}spotPriceOutGivenIn(e){return w(v,e.decimalsIn)}calculateTradeFee(e,t){return h}};var Q=class{static get(e){switch(e.type){case"Aave":return Pe.fromPool(e);case"Xyk":return de.fromPool(e);case"Omnipool":return pe.fromPool(e);case"Lbp":return me.fromPool(e);case"Stableswap":return ge.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,Q.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 ta(g,e){return g.minus(e).abs().div(g.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ee(g,e){return g.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ee(g,e){return v.minus(e.div(g)).multipliedBy(100).decimalPlaces(2)}function ke(g,e){return e.div(g).minus(v).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?I(e.min):void 0,s=e.max?I(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 $(e,t);let a;if(r)a=await this.toSellSwaps(s,r,i);else{let B=n.map(async H=>await this.toSellSwaps(s,H,i)),_=await Promise.all(B);a=this.findBestSellRoute(_)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),P=a.map(B=>B.spotPrice.shiftedBy(-1*B.assetOutDecimals)).reduce((B,_)=>B.multipliedBy(_)),p=w(P,c.assetOutDecimals),d=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,i),b=c.amountOut,f=u?c.tradeFeePct:Ee(d,b).toNumber(),S=d.minus(b),y=this.getRouteFeeRange(a),A=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(p),T=ee(d,A),G=(B,_=!1)=>{let H=a.map(_e=>_e);return _?this.poolService.buildSellAllTx(e,t,B,H):this.poolService.buildSellTx(e,t,l.amountIn,B,H)};return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:p,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T.toNumber(),swaps:a,toTx:G,toHuman(){return{type:"Sell",amountIn:F(l.amountIn,l.assetInDecimals),amountOut:F(c.amountOut,c.assetOutDecimals),spotPrice:F(p,c.assetOutDecimals),tradeFee:F(S,c.assetOutDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T.toNumber(),swaps:a.map(B=>B.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=w(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,n),{amountOut:u,calculatedOut:P,feePct:p,errors:d}=n.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),f=n.spotPriceOutGivenIn(a),S=l.shiftedBy(-1*a.decimalsIn).multipliedBy(f),y=ee(P,S);r.push({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:P,amountOut:u,spotPrice:f,tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:d,toHuman(){return{...i,amountIn:F(l,a.decimalsIn),calculatedOut:F(P,a.decimalsOut),amountOut:F(u,a.decimalsOut),spotPrice:F(f,a.decimalsOut),tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y.toNumber(),errors:d}}})}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 $(e,t);let l=s.filter(p=>p.tokens.some(d=>d.id===e&&d.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(d=>d.id===e)).map(p=>p.map(d=>m(d.balance).shiftedBy(-1*d.decimals)).reduce((d,b)=>d.plus(b))).sort((p,d)=>d.isLessThan(p)?-1:1)[0].div(100).multipliedBy(.1),c=o.map(async p=>await this.toSellSwaps(l,p,r)),u=await Promise.all(c);return this.findBestSellRoute(u).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.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,P)=>u.multipliedBy(P)),l=n[n.length-1].assetOutDecimals;return{amount:w(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 $(e,t);let a;if(r)a=await this.toBuySwaps(s,r,i);else{let B=n.map(async H=>await this.toBuySwaps(s,H,i)),_=await Promise.all(B);a=this.findBestBuyRoute(_)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),P=a.map(B=>B.spotPrice.shiftedBy(-1*B.assetInDecimals)).reduce((B,_)=>B.multipliedBy(_)),p=w(P,c.assetInDecimals),d=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,i),b=c.amountIn,f=u?c.tradeFeePct:ke(d,b).toNumber(),S=b.minus(d),y=this.getRouteFeeRange(a),A=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(p),T;d.isZero()?T=-100:T=ee(A,d).toNumber();let G=B=>{let _=a.map(H=>H);return this.poolService.buildBuyTx(e,t,l.amountOut,B,_)};return{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:p,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T,swaps:a,toTx:G,toHuman(){return{type:"Buy",amountOut:F(l.amountOut,l.assetOutDecimals),amountIn:F(c.amountIn,c.assetInDecimals),spotPrice:F(p,c.assetInDecimals),tradeFee:F(S,c.assetInDecimals),tradeFeePct:f,tradeFeeRange:y,priceImpactPct:T,swaps:a.map(B=>B.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=w(m(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,n),{amountIn:u,calculatedIn:P,feePct:p,errors:d}=n.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),f=n.spotPriceInGivenOut(a),S=l.shiftedBy(-1*a.decimalsOut).multipliedBy(f),y;P.isZero()?y=-100:y=ee(S,P).toNumber(),r.unshift({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:P,amountIn:u,spotPrice:f,tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y,errors:d,toHuman(){return{...i,amountOut:F(l,a.decimalsOut),calculatedIn:F(P,a.decimalsIn),amountIn:F(u,a.decimalsIn),spotPrice:F(f,a.decimalsIn),tradeFeePct:p,tradeFeeRange:b,priceImpactPct:y,errors:d}}})}return r}};import{memoize1 as Oa}from"@thi.ng/memoize";export{Nt as AMOUNT_MAX,Pe as AavePool,oe as AavePoolClient,Y as AssetClient,ve as AssetNotFound,us as BASILISK_PARACHAIN_ID,q as BalanceClient,O as BigNumber,Se as CachingPoolService,Ce as DECIMAL_PLACES,fe as DENOMINATOR,ye as FarmClient,se as HUB_ASSET_ID,ms as HYDRADX_OMNIPOOL_ADDRESS,cs as HYDRADX_PARACHAIN_ID,W as HYDRADX_SS58_PREFIX,Is as INFINITY,C as LbpMath,me as LbpPool,ie as LbpPoolClient,v as ONE,x as OmniMath,pe as OmniPool,ne as OmniPoolClient,M as PolkadotApiClient,Te as PoolConfigNotFound,X as PoolError,Q as PoolFactory,ue as PoolNotFound,V as PoolService,R as PoolType,Re as ProviderConfigNotFound,j as RUNTIME_DECIMALS,$ as RouteNotFound,z as Router,ls as SYSTEM_ASSET_DECIMALS,L as SYSTEM_ASSET_ID,N as StableMath,ge as StableSwap,le as StableSwapClient,Fe as StorageConfigNotFound,Ne as SubscriptionNotSupported,Z as TRADEABLE_DEFAULT,be as TradeRouter,Oe as TradeType,U as XykMath,de as XykPool,ae as XykPoolClient,h as ZERO,bs as bnFormatter,m as bnum,ce as buildRoute,ke as calculateBuyFee,ta as calculateDiffToAvg,ee as calculateDiffToRef,Ee as calculateSellFee,xe as findNestedKey,Ps as findNestedObj,w as scale};
|
|
1
|
+
var hs=2090,xe=1e3,re="1",bs=2034,H=63,z=18,_="0",fs=12,J=15;import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var L=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}async dryRun(e,t){let s;try{s=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(r){throw console.error(r),new Error("Dry run execution failed!")}if(s.isOk)return s.asOk;throw console.log(s.asErr.toHuman()),new Error("Dry run execution error!")}log(e,...t){let s=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");this.getLogValue(s)&&console.log(e,...t)}getLogValue(e){switch(e){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}};var K=class extends L{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},s])=>[t.toString(),s.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},s])=>{let{decimals:r,symbol: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==_){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: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),g=i.toNumber(),p=new Intl.DateTimeFormat("en-GB"),P=[c,"Bond",p.format(g)].join(" ");return{id:e,name:P,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:o.toString(),maturity:g}}getShares(e,t,s,r){let{assets:o}=r,{name:i,symbol:n,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=o.map(h=>h.toString()).map(h=>{let{symbol:f}=this.getToken(h,t,s);return[h,f]}),p=Object.fromEntries(g),P=Object.values(p);return{id:e,name:P.join(", "),symbol:n?.isSome?n.toHuman():i.toHuman(),decimals:18,icon:P.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:p}}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]},g])=>{let p=g.unwrap(),P=r.get(u.toString()),{assetType:h}=p;switch(h.toString()){case"Bond":let f=i.get(u.toString());return this.getBond(u.toString(),p,l,f);case"StableSwap":let S=o.get(u.toString());return this.getShares(u.toString(),p,l,S);case"External":return this.getExternal(u.toString(),p,t,P);default:return this.getToken(u.toString(),p,l,P)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};import{BigNumber as w}from"bignumber.js";var je=12;w.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:je});var b=d(0),T=d(1),Ns=d("Infinity");function B(m,e){let t=new w(e.toString()),s=new w(10).pow(t);return m.times(s)}function d(m){return new w(m.toString())}var G=class extends L{constructor(e){super(e)}async getBalance(e,t){let s=await this.api.query.assetRegistry.assets(t),{assetType:r}=s.unwrap();return r.toString()==="Erc20"?this.getErc20Balance(e,t):t===_?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:0n,frozen:o})}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:s})=>t(_,this.calculateFreeBalance(s)))}async subscribeTokenBalance(e,t,s){let o=t.filter(i=>i.type!=="Erc20").filter(i=>i.id!==_).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 w(t),n=new w(s||o),a=new w(r||0n),l=n.gt(a)?n:a;return i.minus(l)}};import{fixed_from_rational as Ne}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Ze}from"@polkadot/types";import{u8aConcat as Re}from"@polkadot/util";import{isAddress as Ee}from"@polkadot/util-crypto";var we=class extends L{balanceClient;constructor(e){super(e),this.balanceClient=new G(e)}secondsInYear=new w(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,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(),p=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(p,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([r,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(),p=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),P=l.rewardCurrency.toString(),h=await this.balanceClient.getTokenBalanceData(p,P);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:h.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),s=e.incentivizedAsset.toString(),r=[t,s].sort();if(t===s)return new w(1).shiftedBy(18).toString();let 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=Ne(n,a):l=Ne(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 Re(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,s)=>{let r="modl",o=s?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Ze(e,this.padEndU8a(Re(r,o,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!Ee(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&Ee(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 w(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),p=new w(a.yieldPerPeriod.toString()),P=new w(a.maxRewardPerPeriod.toString()),h=a.blocksPerPeriod.toString(),f=new w(n.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new w(s).times(h)),y;if(u.isZero())y=p.times(f).times(S);else{let U=this.getGlobalRewardPerPeriod(u,p,P,l);y=this.getPoolYieldPerPeriod(U,f,u,l).times(S)}let I=new w(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),A=P.times(g),x=c?I.plus(c):A;return I.div(x).gte(.999)?b:y.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,a)=>n.plus(a),b).toString():void 0}};var oe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ke=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"}},_e=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Le=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},De=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Ce=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var ne=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var Me="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ge=1000000n,Oe=5,He=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{defineChain as Qe}from"viem";var qe=["https://rpc.hydradx.cloud","https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Ue=["wss://rpc.hydradx.cloud","wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],We=Qe({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{public:{http:qe,webSocket:Ue},default:{http:qe,webSocket:Ue}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1});import{createPublicClient as Xe,createWalletClient as et,custom as tt,http as st,webSocket as rt}from"viem";var ie=class{chain;constructor(e){this.chain=e||We}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return Xe({chain:this.chain,transport:st()})}getWsProvider(){return Xe({chain:this.chain,transport:rt()})}getSigner(e){return et({account:e,chain:this.chain,transport:tt(window.ethereum)})}};import{LRUCache as is}from"@thi.ng/cache";import{memoize1 as ns}from"@thi.ng/memoize";var R=(o=>(o.Aave="Aave",o.LBP="Lbp",o.Omni="Omnipool",o.Stable="Stableswap",o.XYK="Xyk",o))(R||{}),Y=(o=>(o.UnknownError="UnknownError",o.InsufficientTradingAmount="InsufficientTradingAmount",o.MaxInRatioExceeded="MaxInRatioExceeded",o.MaxOutRatioExceeded="MaxOutRatioExceeded",o.TradeNotAllowed="TradeNotAllowed",o))(Y||{});var ae=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,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=d(r.balance),n=d(o.balance);return{assetIn:e,assetOut:t,decimalsIn:r.decimals,decimalsOut:o.decimals,balanceIn:i,balanceOut:n,assetInED:b,assetOutED:b}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=[];return t.isGreaterThan(e.balanceOut)&&o.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:o}}validateAndSell(e,t,s){let r=this.calculateOutGivenIn(e,t),o=[];return r.isGreaterThan(e.balanceOut)&&o.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:o}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return B(T,e.decimalsOut)}spotPriceOutGivenIn(e){return B(T,e.decimalsIn)}calculateTradeFee(e,t){return b}};import{encodeAddress as it}from"@polkadot/util-crypto";import{stringToU8a as at}from"@polkadot/util";import{decodeEventLog as lt}from"viem";var $=class{static fromAssetId(e){let t=Number(e),s=Buffer.alloc(20,0);return s[15]=1,s.writeUInt32BE(t,16),"0x"+s.toString("hex")}static toAssetId(e){let t=Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Buffer.from("0000000000000000000000000000000100000000","hex"),s=Buffer.from(e.replace("0x",""),"hex");return s.length!==20?!1:s.subarray(0,16).equals(t.subarray(0,16))}};function Ye(m,e){let t=[];return JSON.stringify(m,(s,r)=>(r&&r[e]&&t.push(r),r)),t[0]}function Ar(m,e,t){let s;return JSON.stringify(m,(r,o)=>(o&&o[e]===t&&(s=o),o)),s}var vr=(m,e)=>typeof e=="bigint"?e.toString():e;import{memoize1 as ot}from"@thi.ng/memoize";import{TLRUCache as nt}from"@thi.ng/cache";var D=class extends G{pools=[];subs=[];assets=new Map([]);mem=0;memPoolsCache=new nt(null,{maxlen:1,ttl:60*60*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=ot(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e){super(e)}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return await this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools(),this.subs=this.subscribe();let e=this.getPoolType();return this.log(e,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(e,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}subscribe(){return this.augmentedPools.map(t=>{let s=[];try{let 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)}return this.subscribeLog(t),s}).flat()}hasSystemAsset(e){return e.tokens.some(t=>t.id==="0")}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t())})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(s,r)=>s.id!==r;return this.subscribeTokenBalance(e.address,e.tokens,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){return this.subscribeErc20Balance(e.address,e.tokens,this.updateBalancesCallback(e,()=>!0))}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let s=this.assets.get(t.id);return{...t,...s}}),e}updateBalancesCallback(e,t){return function(s){s.forEach(([r,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 ct=["Supply","Withdraw","Repay","Borrow"],le=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 it(at(s.padEnd(32,"\0")),63)}subscribePoolChange(e){let[t,s]=e.tokens,r=this.getReserveH160Id(t);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,""),g=c.replace(/,/g,"");(u===s.id||g===s.id)&&(this.log(`Sync AAVE [router:Executed] :: ${u}:${g}`),this.updatePoolState(e))}if(a==="evm:Log"){let{log:l}=n.data.toHuman();try{let{eventName:c,args:u}=lt({abi:ne,topics:l.topics,data:l.data});ct.includes(c)&&u.reserve.toLowerCase()===r.toLowerCase()&&(this.log(`Sync AAVE [evm:Log] :: ${c} ${t.symbol}(${t.id})`),this.updatePoolState(e))}catch{}}})})}async updatePoolState(e){let[t,s]=e.tokens,{liqudityIn:r,liqudityOut: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"?Ye(e.location,"accountKey20").accountKey20.key:$.fromAssetId(e.id)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}};import{calculate_in_given_out as ut,calculate_out_given_in as mt,calculate_linear_weights as pt,calculate_pool_trade_fee as dt,get_spot_price as gt}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(e,t,s,r,o){return gt(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o){return ut(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o){return mt(e,t,s,r,o)}static calculateLinearWeights(e,t,s,r,o){return pt(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return dt(e,t,s)}};function F(m,e){return m.shiftedBy(-1*e).toString()}function v(m){return m[0]/m[1]*100}function k(m){return m[0]/m[1]}function E(m){return[m/1e3,1e3]}var ce=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.fee,e.repayFeeApply)}constructor(e,t,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=d(r.balance),n=d(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=v(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=v(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=M.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=d(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=M.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),r=d(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=M.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),B(T,e.decimalsOut).toString());return d(t)}spotPriceOutGivenIn(e){let t=M.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),B(T,e.decimalsIn).toString());return d(t)}calculateTradeFee(e,t){let s=M.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return d(s)}};var ue=class extends D{MAX_FINAL_WEIGHT=B(d(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=M.calculateLinearWeights(r.toString(),o.toString(),n.toString(),a.toString(),s),[g,p]=i,P=g.toString(),h=d(u),f=p.toString(),S=this.MAX_FINAL_WEIGHT.minus(d(h)),[y,I,A]=await Promise.all([this.isRepayFeeApplied(P,l.toString(),c.toString()),this.getBalance(e,P),this.getBalance(e,f)]);return{repayFeeApply:y,tokens:[{id:P,weight:h,balance:I.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=d(t);if(r.isZero())return!1;try{return(await this.getBalance(e,s)).isLessThan(r)}catch{return!0}}getRepayFee(){return this.api.consts.lbp.repayFee.toJSON()}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toJSON(),t=this.api.consts.lbp.maxOutRatio.toJSON(),s=this.api.consts.lbp.minTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as Pt,calculate_lrna_in_given_out as ht,calculate_out_given_in as bt,calculate_out_given_lrna_in as ft,calculate_pool_trade_fee as yt,calculate_spot_price as St,calculate_lrna_spot_price as xt,calculate_shares as wt,calculate_liquidity_out as Ot,calculate_liquidity_lrna_out as Bt,calculate_liquidity_hub_in as It,is_sell_allowed as At,is_buy_allowed as vt,is_add_liquidity_allowed as Tt,is_remove_liquidity_allowed as Ft,recalculate_asset_fee as Nt,recalculate_protocol_fee as Rt,verify_asset_cap as Et}from"@galacticcouncil/math-omnipool";var O=class{static calculateSpotPrice(e,t,s,r){return St(e,t,s,r)}static calculateLrnaSpotPrice(e,t){return xt(e,t)}static calculateInGivenOut(e,t,s,r,o,i,n,a,l){return Pt(e,t,s,r,o,i,n,a,l)}static calculateLrnaInGivenOut(e,t,s,r,o){return ht(e,t,s,r,o)}static calculateOutGivenIn(e,t,s,r,o,i,n,a,l){return bt(e,t,s,r,o,i,n,a,l)}static calculateOutGivenLrnaIn(e,t,s,r,o){return ft(e,t,s,r,o)}static calculatePoolTradeFee(e,t,s){return yt(e,t,s)}static calculateShares(e,t,s,r){return wt(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 Bt(e,t,s,r,o,i,n,a)}static calculateCapDifference(e,t,s,r){let o=w(t),i=w(e),n=w(r),l=w(s).shiftedBy(-18);if(o.div(n).lt(l)){let u=l.times(n).minus(o).times(i),g=o.times(w(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,s,r){return It(e,t,s,r)}static isSellAllowed(e){return At(e)}static isBuyAllowed(e){return vt(e)}static isAddLiquidityAllowed(e){return Tt(e)}static isRemoveLiquidityAllowed(e){return Ft(e)}static recalculateAssetFee(e,t,s,r,o,i,n,a,l,c,u){return Nt(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 Rt(e,t,s,r,o,i,n,a,l,c,u)}static verifyAssetCap(e,t,s,r){return Et(e,t,s,r)}};var me=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.hubAssetId)}constructor(e,t,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=d(r.balance),n=d(o.balance),a=d(r.existentialDeposit),l=d(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===b?b:i.div(r).multipliedBy(100).decimalPlaces(2),a=[],l=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(g)&&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=O.isSellAllowed(e.tradeableIn),c=O.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||r.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(g)&&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=O.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():b.toString(),s?k(s.protocolFee).toString():b.toString()),o=d(r);return o.isNegative()?b:o}calculateLrnaInGivenOut(e,t,s){let r=O.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():b.toString()),o=d(r);return o.isNegative()?b:o}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?k(s.assetFee).toString():b.toString(),s?k(s.protocolFee).toString():b.toString()),o=d(r);return o.isNegative()?b:o}calculateOutGivenLrnaIn(e,t,s){let r=O.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),s?k(s.assetFee).toString():b.toString()),o=d(r);return o.isNegative()?b:o}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 d(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=O.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return d(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=O.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return d(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=O.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return d(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as kt}from"@polkadot/util-crypto";import{stringToU8a as _t}from"@polkadot/util";var pe=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:g,cap:p,protocolShares:P}=l.unwrap(),h=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:d(c.toString()),shares:d(u.toString()),tradeable:g.bits.toNumber(),balance:h.toString(),cap:d(p.toString()),protocolShares:d(P.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===_?[_,re]:[re,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)]),[g,p,P]=this.getAssetFee(e,a.toNumber(),l,c),[h,f,S]=r===re?[0,0,0]:this.getProtocolFee(e,a.toNumber(),l,u),y=g+h,I=P+S;return{assetFee:E(p),protocolFee:E(f),min:E(y),max:E(I)}}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:d(s.toString()),shares:d(r.toString()),cap:d(i.toString()),protocolShares:d(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=E(n.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[p]=r.unwrap(),{assetFee:P,timestamp:h}=s.unwrap(),f=t-h.toNumber(),S=p.volume.bIn.toString(),y=p.volume.bOut.toString(),I=p.liquidity.b.toString();o===_&&(S=p.volume.aIn.toString(),y=p.volume.aOut.toString(),I=p.liquidity.a.toString());let A=E(P.toNumber()),x=O.recalculateAssetFee(S,y,I,"9",i.toString(),v(A).toString(),f.toString(),v(u).toString(),v(g).toString(),l.toString(),c.toString());return[n.toNumber(),Number(x)*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=E(n.toNumber()),g=E(a.toNumber());if(s.isNone||r.isNone)return[n.toNumber(),n.toNumber(),a.toNumber()];let[p]=r.unwrap(),{protocolFee:P,timestamp:h}=s.unwrap(),f=t-h.toNumber(),S=p.volume.bIn.toString(),y=p.volume.bOut.toString(),I=p.liquidity.b.toString();o===_&&(S=p.volume.aIn.toString(),y=p.volume.aOut.toString(),I=p.liquidity.a.toString());let A=E(P.toNumber()),x=O.recalculateProtocolFee(S,y,I,"9",i.toString(),v(A).toString(),f.toString(),v(u).toString(),v(g).toString(),l.toString(),c.toString());return[n.toNumber(),Number(x)*1e4,a.toNumber()]}getPoolId(){return kt(_t("modlomnipool".padEnd(32,"\0")),63)}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toJSON(),t=this.api.consts.omnipool.maxOutRatio.toJSON(),s=this.api.consts.omnipool.minimumTradingLimit.toJSON();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:s}}};import{calculate_in_given_out as Lt,calculate_out_given_in as Dt,calculate_pool_trade_fee as Ct,get_spot_price as Mt,calculate_liquidity_in as Gt,calculate_shares as Ht,calculate_spot_price as qt,calculate_spot_price_with_fee as Ut,calculate_liquidity_out_asset_a as Wt,calculate_liquidity_out_asset_b as Xt}from"@galacticcouncil/math-xyk";var q=class{static getSpotPrice(e,t,s){return Mt(e,t,s)}static calculateInGivenOut(e,t,s){return Lt(e,t,s)}static calculateOutGivenIn(e,t,s){return Dt(e,t,s)}static calculatePoolTradeFee(e,t,s){return Ct(e,t,s)}static calculateLiquidityIn(e,t,s){return Gt(e,t,s)}static calculateSpotPrice(e,t){return qt(e,t)}static calculateSpotPriceWithFee(e,t,s,r){return Ut(e,t,s,r)}static calculateShares(e,t,s){return Ht(e,t,s)}static calculateLiquidityOutAssetA(e,t,s,r){return Wt(e,t,s,r)}static calculateLiquidityOutAssetB(e,t,s,r){return Xt(e,t,s,r)}};var de=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit)}constructor(e,t,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=d(r.balance),n=d(o.balance),a=d(r.existentialDeposit),l=d(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=v(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=v(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=d(s);return r.isNegative()?b:r}calculateOutGivenIn(e,t){let s=q.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),r=d(s);return r.isNegative()?b:r}spotPriceInGivenOut(e){let t=q.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),s=B(T,18-e.decimalsOut);return d(t).div(s)}spotPriceOutGivenIn(e){let t=q.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),s=B(T,18-e.decimalsIn);return d(t).div(s)}calculateTradeFee(e,t){let s=q.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return d(s)}};var ge=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{calculate_in_given_out as Yt,calculate_out_given_in as $t,calculate_amplification as zt,calculate_add_one_asset as Jt,calculate_liquidity_out_one_asset as Kt,calculate_pool_trade_fee as Vt,calculate_shares as jt,calculate_shares_for_amount as Zt,calculate_spot_price_with_fee as Qt,pool_account_name as es,recalculate_peg as ts}from"@galacticcouncil/math-stableswap";var N=class{static getPoolAddress(e){return es(e)}static defaultPegs(e){let t=[];for(let s=0;s<e;s++)t.push(["1","1"]);return t}static calculateAmplification(e,t,s,r,o){return zt(e,t,s,r,o)}static calculateInGivenOut(e,t,s,r,o,i,n){return Yt(e,t,s,r,o,i,n)}static calculateAddOneAsset(e,t,s,r,o,i,n){return Jt(e,t,s,r,o,i,n)}static calculateSharesForAmount(e,t,s,r,o,i,n){return Zt(e,t,s,r,o,i,n)}static calculateOutGivenIn(e,t,s,r,o,i,n){return $t(e,t,s,r,o,i,n)}static calculateLiquidityOutOneAsset(e,t,s,r,o,i,n){return Kt(e,t,s,r,o,i,n)}static calculateShares(e,t,s,r,o,i){return jt(e,t,s,r,o,i)}static calculateSpotPriceWithFee(e,t,s,r,o,i,n,a){return Qt(e,t,s,r,o,i,n,a)}static calculatePoolTradeFee(e,t,s){return Vt(e,t,s)}static recalculatePegs(e,t,s,r,o){let i=ts(e,t,s,r,o);return JSON.parse(i)}};var Pe=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new m(e.address,e.tokens,e.maxInRatio,e.maxOutRatio,e.minTradingLimit,e.amplification,e.id,e.fee,e.totalIssuance,e.pegs,e.pegsFee)}constructor(e,t,s,r,o,i,n,a,l,c,u){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,this.pegs=c,this.pegsFee=u}validatePair(e,t){return!0}parsePair(e,t){let s=new Map(this.tokens.map(c=>[c.id,c])),r=s.get(e),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=d(r.balance),n=d(o.balance),a=d(r.existentialDeposit),l=d(o.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:n,decimalsIn:r.decimals,decimalsOut:o.decimals,tradeableIn:this.id===e?15:r.tradeable,tradeableOut:this.id===t?15:o.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,s){let r=this.calculateInGivenOut(e,t),o=this.calculateInGivenOut(e,t,s),i=v(s.fee),n=[],a=O.isSellAllowed(e.tradeableIn),l=O.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=v(s.fee),n=[],a=O.isSellAllowed(e.tradeableIn),l=O.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=N.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,s?k(s.fee).toString():b.toString(),this.getPegs()),o=d(r);return o.isNegative()?b:o}calculateAddOneAsset(e,t,s){let r=N.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,s?k(s.fee).toString():b.toString(),this.getPegs()),o=d(r);return o.isNegative()?b:o}calculateSharesForAmount(e,t,s){let r=N.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,s?k(s.fee).toString():b.toString(),this.getPegs()),o=d(r);return o.isNegative()?b: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=N.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return d(t);if(e.assetIn==this.id){let r=B(T,e.decimalsIn-e.decimalsOut);return d(t).div(r)}let s=B(T,18-e.decimalsIn);return d(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?k(s.fee).toString():b.toString(),this.getPegs()),o=d(r);return o.isNegative()?b:o}calculateWithdrawOneAsset(e,t,s){let r=N.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,s?k(s.fee).toString():b.toString(),this.getPegs()),o=d(r);return o.isNegative()?b:o}calculateShares(e,t,s){let r=N.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,s?k(s.fee).toString():b.toString(),this.getPegs()),o=d(r);return o.isNegative()?b: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=N.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return d(t);if(e.assetOut==this.id){let r=B(T,e.decimalsOut-e.decimalsIn);return d(t).div(r)}let s=B(T,18-e.decimalsOut);return d(t).div(s)}calculateTradeFee(e,t){let s=N.calculatePoolTradeFee(e.toString(),t.fee[0],t.fee[1]);return d(s)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:s,decimals:r})=>({asset_id:Number(t),amount:s,decimals:r}));return JSON.stringify(e)}getAssets(e,t){let s={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([s])}};import{blake2AsHex as ss,encodeAddress as rs}from"@polkadot/util-crypto";var os=340282366920938463463374607431768211455n,he=class extends D{stablePools=new Map([]);isSupported(){return this.api.query.stableswap!==void 0}isPegSupported(){return this.api.query.stableswap.poolPegs!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),s=t.toNumber(),r=e.map(async([{args:[o]},i])=>{let n=i.unwrap(),a=o.toString(),l=this.getPoolAddress(a),[c,u,g]=await Promise.all([this.getPoolDelta(a,n,s.toString()),this.getPoolTokens(l,a,n),this.getPoolPegs(a,n,s.toString())]);return this.stablePools.set(l,n),{address:l,id:a,type:"Stableswap",fee:E(n.fee.toNumber()),tokens:u,...c,...g,...this.getPoolLimits()}});return Promise.all(r)}async getPoolFees(e,t){return{fee:this.pools.find(r=>r.address===t).pegsFee}}getPoolType(){return"Stableswap"}async subscribePoolChange(e){return this.api.query.system.number(async t=>{let s=t.toString(),r=this.stablePools.get(e.address);if(r){let[o,i]=await Promise.all([this.getPoolDelta(e.id,r,s),this.getPoolPegs(e.id,r,s)]);Object.assign(e,o,i)}})}async getPoolDelta(e,t,s){let{initialAmplification:r,finalAmplification:o,initialBlock:i,finalBlock:n}=t,a=N.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 n=>{let[a,l]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:a.bits.toNumber(),balance:l.toString()}}),i=await Promise.all(o);return i.push({id:t,tradeable:15,balance:os.toString()}),i}getPoolDefaultPegs(e){let t=e.fee,s=N.defaultPegs(e.assets.length);return{pegsFee:E(t.toNumber()),pegs:s}}async getPoolPegs(e,t,s){if(!this.isPegSupported())return this.getPoolDefaultPegs(t);let r=await this.api.query.stableswap.poolPegs(e);if(r.isNone)return this.getPoolDefaultPegs(t);let o=r.unwrap(),i=await this.getLatestPegs(t,o,s),n=this.getRecentPegs(o),a=o.maxPegUpdate.toHuman(),l=t.fee.toHuman(),[c,u]=N.recalculatePegs(JSON.stringify(n),JSON.stringify(i),s,a.replace(/%/g,""),l.replace(/%/g,"")),g=Number(c)*1e4;return{pegsFee:E(g),pegs:u}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([s,r])=>r.map(o=>o.toString()))}async getLatestPegs(e,t,s){let{source:r}=t,o=Array.from(e.assets.entries()).map(([n,a])=>a.toString()),i=r.map(async(n,a)=>{if(n.isOracle){let[l,c,u]=n.asOracle,g=[u.toString(),o[a]].map(y=>Number(y)).sort((y,I)=>y-I),p=await this.api.query.emaOracle.oracles(l,g,c),[{price:P,updatedAt:h}]=p.unwrap(),f=P.n.toString(),S=P.d.toString();return u.toString()===g[0].toString()?[[f,S],h.toString()]:[[S,f],h.toString()]}else return[n.asValue.map(l=>l.toString()),s]});return Promise.all(i)}getPoolAddress(e){let t=Number(e),s=N.getPoolAddress(t);return rs(ss(s),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toJSON()}}};var V=class extends L{api;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;clients=[];onChainAssets=[];memRegistry=ns(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e){super(e),this.api=e,this.assetClient=new K(this.api),this.aaveClient=new le(this.api),this.xykClient=new ge(this.api),this.omniClient=new pe(this.api),this.lbpClient=new ue(this.api),this.stableClient=new he(this.api),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient]}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(s=>s.withAssets(t)),this.onChainAssets=t}async getPools(e){return this.isRegistrySynced||await this.memRegistry(1),e.length==0?(await Promise.all(this.clients.filter(r=>r.isSupported()).map(r=>r.getPoolsMem()))).flat():(await Promise.all(this.clients.filter(s=>e.some(r=>r===s.getPoolType())).map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(e,t.address);case"Xyk":return this.xykClient.getPoolFees(e,t.address);case"Omnipool":return this.omniClient.getPoolFees(e,t.address);case"Lbp":return this.lbpClient.getPoolFees(e,t.address);case"Stableswap":return this.stableClient.getPoolFees(e,t.address);default:throw new oe(t.type)}}};var Be=class extends V{feeCache;disconnectSubscribeNewHeads=null;constructor(e){super(e),this.feeCache=new is(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 j=class{static get(e){switch(e.type){case"Aave":return ae.fromPool(e);case"Xyk":return de.fromPool(e);case"Omnipool":return me.fromPool(e);case"Lbp":return ce.fromPool(e);case"Stableswap":return Pe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var be=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var as=5,Z=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 be,i=[];for(i.push([t,""]),o.enqueue(i);o.size()>0;){let n=o.dequeue();if(n==null||n.length>as)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 Ie(m){let e={};for(let t of m){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 Q=class{getProposals(e,t,s){let r=Ie(s),o=Object.keys(r),i=o.map(c=>r[c]).flat(),n=new Z,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()]}};var ee=class{routeSuggester;routerOptions;poolService;defaultRouterOptions={includeOnly:[]};constructor(e,t){this.poolService=e,this.routeSuggester=new Q,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,j.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))}};var ls=d("100");function qa(m,e){return m.minus(e).abs().div(m.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function te(m,e){return m.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function $e(m,e){return T.minus(e.div(m)).multipliedBy(100).decimalPlaces(2)}function ze(m,e){return e.div(m).minus(T).multipliedBy(100).decimalPlaces(2)}function se(m,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),m.div(ls).multipliedBy(e).decimalPlaces(0,1)}var Ae=(t=>(t.Buy="Buy",t.Sell="Sell",t))(Ae||{});var ve=class extends ee{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?v(e.min):void 0,s=e.max?v(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 X(e,t);let a;if(r)a=await this.toSellSwaps(s,r,i);else{let x=n.map(async U=>await this.toSellSwaps(s,U,i)),C=await Promise.all(x);a=this.findBestSellRoute(C)}let l=a[0],c=a[a.length-1],u=this.isDirectTrade(a),g=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetOutDecimals)).reduce((x,C)=>x.multipliedBy(C)),p=B(g,c.assetOutDecimals),P=u?c.calculatedOut:this.calculateDelta0Y(l.amountIn,a,i),h=c.amountOut,f=u?c.tradeFeePct:$e(P,h).toNumber(),S=P.minus(h),y=this.getRouteFeeRange(a),I=l.amountIn.shiftedBy(-1*l.assetInDecimals).multipliedBy(p),A=te(P,I);return{type:"Sell",amountIn:l.amountIn,amountOut:c.amountOut,spotPrice:p,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A.toNumber(),swaps:a,toHuman(){return{type:"Sell",amountIn:F(l.amountIn,l.assetInDecimals),amountOut:F(c.amountOut,c.assetOutDecimals),spotPrice:F(p,c.assetOutDecimals),tradeFee:F(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=B(d(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,n),{amountOut:u,calculatedOut:g,feePct:p,errors:P}=n.validateAndSell(a,l,c),h=this.getPoolFeeRange(c),f=n.spotPriceOutGivenIn(a),S=l.shiftedBy(-1*a.decimalsIn).multipliedBy(f),y=te(g,S);r.push({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,calculatedOut:g,amountOut:u,spotPrice:f,tradeFeePct:p,tradeFeeRange:h,priceImpactPct:y.toNumber(),errors:P,isSupply(){return n.type==="Aave"&&n.tokens[0].id===i.assetIn},isWithdraw(){return n.type==="Aave"&&n.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:F(l,a.decimalsIn),calculatedOut:F(g,a.decimalsOut),amountOut:F(u,a.decimalsOut),spotPrice:F(f,a.decimalsOut),tradeFeePct:p,tradeFeeRange:h,priceImpactPct:y.toNumber(),errors:P}}})}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 X(e,t);let l=s.filter(p=>p.tokens.some(P=>P.id===e&&P.id!==p.id)).map(p=>p.type==="Aave"?p.tokens:p.tokens.filter(P=>P.id===e)).map(p=>p.map(P=>d(P.balance).shiftedBy(-1*P.decimals)).reduce((P,h)=>P.plus(h))).sort((p,P)=>P.isLessThan(p)?-1:1)[0].div(100).multipliedBy(.1),c=o.map(async p=>await this.toSellSwaps(l,p,r)),u=await Promise.all(c);return this.findBestSellRoute(u).map(p=>({poolAddress:p.poolAddress,poolId:p?.poolId,pool:p.pool,assetIn:p.assetIn,assetOut:p.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,g)=>u.multipliedBy(g)),l=n[n.length-1].assetOutDecimals;return{amount:B(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 X(e,t);let a;if(r)a=await this.toBuySwaps(s,r,i);else{let x=n.map(async U=>await this.toBuySwaps(s,U,i)),C=await Promise.all(x);a=this.findBestBuyRoute(C)}let l=a[a.length-1],c=a[0],u=this.isDirectTrade(a),g=a.map(x=>x.spotPrice.shiftedBy(-1*x.assetInDecimals)).reduce((x,C)=>x.multipliedBy(C)),p=B(g,c.assetInDecimals),P=u?c.calculatedIn:this.calculateDelta0X(l.amountOut,a,i),h=c.amountIn,f=u?c.tradeFeePct:ze(P,h).toNumber(),S=h.minus(P),y=this.getRouteFeeRange(a),I=l.amountOut.shiftedBy(-1*l.assetOutDecimals).multipliedBy(p),A;return P.isZero()?A=-100:A=te(I,P).toNumber(),{type:"Buy",amountOut:l.amountOut,amountIn:c.amountIn,spotPrice:p,tradeFee:S,tradeFeePct:f,tradeFeeRange:y,priceImpactPct:A,swaps:a,toHuman(){return{type:"Buy",amountOut:F(l.amountOut,l.assetOutDecimals),amountIn:F(c.amountIn,c.assetInDecimals),spotPrice:F(p,c.assetInDecimals),tradeFee:F(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=B(d(e),a.decimalsOut).decimalPlaces(0,1):l=r[0].amountIn;let c=await this.poolService.getPoolFees(a,n),{amountIn:u,calculatedIn:g,feePct:p,errors:P}=n.validateAndBuy(a,l,c),h=this.getPoolFeeRange(c),f=n.spotPriceInGivenOut(a),S=l.shiftedBy(-1*a.decimalsOut).multipliedBy(f),y;g.isZero()?y=-100:y=te(S,g).toNumber(),r.unshift({...i,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountOut:l,calculatedIn:g,amountIn:u,spotPrice:f,tradeFeePct:p,tradeFeeRange:h,priceImpactPct:y,errors:P,isSupply(){return n.type==="Aave"&&n.tokens[0].id===i.assetIn},isWithdraw(){return n.type==="Aave"&&n.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:F(l,a.decimalsOut),calculatedIn:F(g,a.decimalsIn),amountIn:F(u,a.decimalsIn),spotPrice:F(f,a.decimalsIn),tradeFeePct:p,tradeFeeRange:h,priceImpactPct:y,errors:P}}})}return r}};import{encodeFunctionData as Ps}from"viem";import{decodeAddress as fe,encodeAddress as Ke}from"@polkadot/util-crypto";import{hexToU8a as cs,isHex as us,u8aToHex as ms}from"@polkadot/util";import{Buffer as W}from"buffer";var Je=W.from("ETH\0");function ps(m){if(!m)return!1;try{let e=fe(m,!0);return W.from(e.subarray(0,Je.length)).equals(Je)}catch{return!1}}function ds(m){return!!/^0x[a-fA-F0-9]{40}$/.test(m)}function gs(m){try{let e=us(m)?cs(m):fe(m);return Ke(e),!0}catch{return!1}}var ye=class m{static prefixBytes=W.from("ETH\0");static toAccount=e=>{let t=W.from(e.slice(2),"hex");return Ke(new Uint8Array(W.concat([m.prefixBytes,t,W.alloc(8)])),63)};static fromAccount=e=>{let s=fe(e).slice(m.prefixBytes.length,-8);return"0x"+W.from(s).toString("hex")};static fromSS58=e=>{let s=fe(e).slice(0,20);return ms(s)};static fromAny=e=>{if(ds(e))return e;if(ps(e))return m.fromAccount(e);if(gs(e))return m.fromSS58(e);throw new Error("Unknown address type")}};var Te=class extends L{balanceClient;evmClient;constructor(e){super(e),this.balanceClient=new G(e),this.evmClient=new ie}buildBuyTx(e,t=1){if(e.type!=="Buy")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:o}=e,i=o[0],n=o[o.length-1],a=se(s,t),l=i.assetIn,c=n.assetOut,u=s.plus(a),g;return this.isDirectOmnipoolTrade(o)?g=this.api.tx.omnipool.buy(c,l,r.toFixed(),u.toFixed()):g=this.api.tx.router.buy(l,c,r.toFixed(),u.toFixed(),this.buildRoute(o)),{hex:g.toHex(),name:"RouterBuy",get:()=>g,dryRun:p=>this.dryRun(p,g)}}buildSellTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountIn:s,amountOut:r,swaps:o}=e,i=o[0],n=o[o.length-1],a=se(r,t),l=i.assetIn,c=n.assetOut,u=r.minus(a),g;return this.isDirectOmnipoolTrade(o)?g=this.api.tx.omnipool.sell(l,c,s.toFixed(),u.toFixed()):g=this.api.tx.router.sell(l,c,s.toFixed(),u.toFixed(),this.buildRoute(o)),{hex:g.toHex(),name:"RouterSell",get:()=>g,dryRun:p=>this.dryRun(p,g)}}buildSellAllTx(e,t=1){if(e.type!=="Sell")throw new Error("Not permitted");let{amountOut:s,swaps:r}=e,o=r[0],i=r[r.length-1],n=se(s,t),a=o.assetIn,l=i.assetOut,c=s.minus(n),u=this.api.tx.router.sellAll(a,l,c.toFixed(),this.buildRoute(r));return{hex:u.toHex(),name:"RouterSellAll",get:()=>u,dryRun:g=>this.dryRun(g,u)}}async buildWithdrawAndSellReserveTx(e,t,s=1){let{amountIn:r,amountOut:o,swaps:i}=t,n=i[0],a=i[i.length-1];if(!n.isWithdraw())throw new Error("Not permitted");let l=n.assetIn,c=n.assetOut,[u,g]=await Promise.all([this.evmClient.getProvider().getGasPrice(),this.balanceClient.getBalance(e,l)]),p=r.isGreaterThanOrEqualTo(g.minus(5)),P=u*10n/100n,h=ye.fromAny(e),f=p?He:BigInt(r.toFixed()),S=$.fromAssetId(c),y=Ps({abi:ne,functionName:"withdraw",args:[S,f,h]}),I=this.api.tx.evm.call(h,Me,y,0n,Ge,u+P,u+P,null,[]),A=se(o,s),x=c,C=a.assetOut,U=o.minus(A),Fe=this.api.tx.router.sell(x,C,r.minus(5).toFixed(),U.toFixed(),this.buildRoute(i.slice(1))),Se=this.api.tx.utility.batchAll([I,Fe]);return{hex:Se.toHex(),name:"WithdrawAndRouterReserveSell",get:()=>Se,dryRun:Ve=>this.dryRun(Ve,Se)}}buildRoute(e){return e.map(({assetIn:t,assetOut:s,pool:r,poolId:o})=>r==="Stableswap"?{pool:{Stableswap:o},assetIn:t,assetOut:s}:{pool:r,assetIn:t,assetOut:s})}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};export{ne as AAVE_ABI,Ge as AAVE_GAS_LIMIT,Me as AAVE_PROXY,Oe as AAVE_ROUNDING_THRESHOLD,He as AAVE_UINT_256_MAX,os as AMOUNT_MAX,ae as AavePool,le as AavePoolClient,K as AssetClient,_e as AssetNotFound,hs as BASILISK_PARACHAIN_ID,G as BalanceClient,w as BigNumber,Be as CachingPoolService,je as DECIMAL_PLACES,xe as DENOMINATOR,$ as ERC20,ie as EvmClient,we as FarmClient,ye as H160,re as HUB_ASSET_ID,bs as HYDRADX_PARACHAIN_ID,H as HYDRADX_SS58_PREFIX,Ns as INFINITY,M as LbpMath,ce as LbpPool,ue as LbpPoolClient,T as ONE,O as OmniMath,me as OmniPool,pe as OmniPoolClient,ke as PoolConfigNotFound,Y as PoolError,j as PoolFactory,oe as PoolNotFound,V as PoolService,R as PoolType,Ce as ProviderConfigNotFound,z as RUNTIME_DECIMALS,X as RouteNotFound,ee as Router,fs as SYSTEM_ASSET_DECIMALS,_ as SYSTEM_ASSET_ID,N as StableMath,Pe as StableSwap,he as StableSwapClient,Le as StorageConfigNotFound,De as SubscriptionNotSupported,J as TRADEABLE_DEFAULT,ve as TradeRouter,Ae as TradeType,Te as TradeUtils,q as XykMath,de as XykPool,ge as XykPoolClient,b as ZERO,vr as bnFormatter,d as bnum,ze as calculateBuyFee,qa as calculateDiffToAvg,te as calculateDiffToRef,$e as calculateSellFee,We as evmMainnet,Ye as findNestedKey,Ar as findNestedObj,se as getFraction,ps as isEvmAccount,ds as isEvmAddress,gs as isSs58Address,B as scale};
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { ApiPromise } from '@polkadot/api';
|
|
2
|
+
import { CallDryRunEffects } from '@polkadot/types/interfaces';
|
|
3
|
+
import { SubmittableExtrinsic } from '@polkadot/api/promise/types';
|
|
2
4
|
import '@galacticcouncil/api-augment/hydradx';
|
|
3
5
|
import '@galacticcouncil/api-augment/basilisk';
|
|
4
6
|
export declare abstract class PolkadotApiClient {
|
|
@@ -6,6 +8,7 @@ export declare abstract class PolkadotApiClient {
|
|
|
6
8
|
constructor(api: ApiPromise);
|
|
7
9
|
get chainDecimals(): number;
|
|
8
10
|
get chainToken(): string;
|
|
11
|
+
dryRun(account: string, extrinsic: SubmittableExtrinsic): Promise<CallDryRunEffects>;
|
|
9
12
|
protected log(message?: any, ...optionalParams: any[]): void;
|
|
10
13
|
private getLogValue;
|
|
11
14
|
}
|
|
@@ -1,3 +1,2 @@
|
|
|
1
|
-
export
|
|
2
|
-
export
|
|
3
|
-
export { WalletCtx } from './WalletCtx';
|
|
1
|
+
export * from './PolkadotApi';
|
|
2
|
+
export * from './types';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type CallDryRunEffects } from '@polkadot/types/interfaces';
|
|
2
|
+
import { type SubmittableExtrinsic } from '@polkadot/api/promise/types';
|
|
3
|
+
export interface Transaction {
|
|
4
|
+
hex: string;
|
|
5
|
+
name?: string;
|
|
6
|
+
get(): SubmittableExtrinsic;
|
|
7
|
+
dryRun(account: string): Promise<CallDryRunEffects>;
|
|
8
|
+
}
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import type { HydradxRuntimeXcmAssetLocation, PalletStableswapPoolInfo } from '@polkadot/types/lookup';
|
|
2
|
+
import { ApiPromise } from '@polkadot/api';
|
|
2
3
|
import { ITuple } from '@polkadot/types-codec/types';
|
|
3
4
|
import { u32, u64 } from '@polkadot/types-codec';
|
|
4
|
-
import {
|
|
5
|
+
import { PolkadotApiClient } from '../api';
|
|
5
6
|
import { Asset, AssetMetadata, ExternalAsset } from '../types';
|
|
6
|
-
import { PolkadotApiClient } from './PolkadotApi';
|
|
7
7
|
export declare class AssetClient extends PolkadotApiClient {
|
|
8
8
|
private SUPPORTED_TYPES;
|
|
9
9
|
constructor(api: ApiPromise);
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { ApiPromise } from '@polkadot/api';
|
|
2
2
|
import { OrmlTokensAccountData } from '@polkadot/types/lookup';
|
|
3
3
|
import { UnsubscribePromise } from '@polkadot/api-base/types';
|
|
4
|
+
import { PolkadotApiClient } from '../api';
|
|
4
5
|
import { Asset } from '../types';
|
|
5
6
|
import { BigNumber } from '../utils/bignumber';
|
|
6
|
-
import { PolkadotApiClient } from './PolkadotApi';
|
|
7
7
|
export declare class BalanceClient extends PolkadotApiClient {
|
|
8
8
|
constructor(api: ApiPromise);
|
|
9
9
|
getBalance(account: string, assetId: string): Promise<BigNumber>;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ApiPromise } from '@polkadot/api';
|
|
2
2
|
import { PalletLiquidityMiningGlobalFarmData } from '@polkadot/types/lookup';
|
|
3
|
-
import { PolkadotApiClient } from '
|
|
3
|
+
import { PolkadotApiClient } from '../api';
|
|
4
4
|
import { BalanceClient } from './BalanceClient';
|
|
5
5
|
export declare class FarmClient extends PolkadotApiClient {
|
|
6
6
|
protected readonly balanceClient: BalanceClient;
|
package/build/types/consts.d.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
|
-
export declare const
|
|
2
|
-
export declare const
|
|
3
|
-
export declare const SYSTEM_ASSET_ID = "0";
|
|
4
|
-
export declare const SYSTEM_ASSET_DECIMALS = 12;
|
|
1
|
+
export declare const BASILISK_PARACHAIN_ID = 2090;
|
|
2
|
+
export declare const DENOMINATOR = 1000;
|
|
5
3
|
export declare const HUB_ASSET_ID = "1";
|
|
6
4
|
export declare const HYDRADX_PARACHAIN_ID = 2034;
|
|
7
5
|
export declare const HYDRADX_SS58_PREFIX = 63;
|
|
8
|
-
export declare const
|
|
9
|
-
export declare const
|
|
10
|
-
export declare const
|
|
6
|
+
export declare const RUNTIME_DECIMALS = 18;
|
|
7
|
+
export declare const SYSTEM_ASSET_ID = "0";
|
|
8
|
+
export declare const SYSTEM_ASSET_DECIMALS = 12;
|
|
9
|
+
export declare const TRADEABLE_DEFAULT = 15;
|
package/build/types/errors.d.ts
CHANGED
|
@@ -53,6 +53,28 @@ export declare const AAVE_ABI: readonly [{
|
|
|
53
53
|
}];
|
|
54
54
|
readonly name: "Withdraw";
|
|
55
55
|
readonly type: "event";
|
|
56
|
+
}, {
|
|
57
|
+
readonly inputs: readonly [{
|
|
58
|
+
readonly internalType: "address";
|
|
59
|
+
readonly name: "asset";
|
|
60
|
+
readonly type: "address";
|
|
61
|
+
}, {
|
|
62
|
+
readonly internalType: "uint256";
|
|
63
|
+
readonly name: "amount";
|
|
64
|
+
readonly type: "uint256";
|
|
65
|
+
}, {
|
|
66
|
+
readonly internalType: "address";
|
|
67
|
+
readonly name: "to";
|
|
68
|
+
readonly type: "address";
|
|
69
|
+
}];
|
|
70
|
+
readonly name: "withdraw";
|
|
71
|
+
readonly outputs: readonly [{
|
|
72
|
+
readonly internalType: "uint256";
|
|
73
|
+
readonly name: "";
|
|
74
|
+
readonly type: "uint256";
|
|
75
|
+
}];
|
|
76
|
+
readonly stateMutability: "nonpayable";
|
|
77
|
+
readonly type: "function";
|
|
56
78
|
}, {
|
|
57
79
|
readonly anonymous: false;
|
|
58
80
|
readonly inputs: readonly [{
|
|
@@ -93,6 +115,32 @@ export declare const AAVE_ABI: readonly [{
|
|
|
93
115
|
}];
|
|
94
116
|
readonly name: "Borrow";
|
|
95
117
|
readonly type: "event";
|
|
118
|
+
}, {
|
|
119
|
+
readonly inputs: readonly [{
|
|
120
|
+
readonly internalType: "address";
|
|
121
|
+
readonly name: "asset";
|
|
122
|
+
readonly type: "address";
|
|
123
|
+
}, {
|
|
124
|
+
readonly internalType: "uint256";
|
|
125
|
+
readonly name: "amount";
|
|
126
|
+
readonly type: "uint256";
|
|
127
|
+
}, {
|
|
128
|
+
readonly internalType: "uint256";
|
|
129
|
+
readonly name: "interestRateMode";
|
|
130
|
+
readonly type: "uint256";
|
|
131
|
+
}, {
|
|
132
|
+
readonly internalType: "uint16";
|
|
133
|
+
readonly name: "referralCode";
|
|
134
|
+
readonly type: "uint16";
|
|
135
|
+
}, {
|
|
136
|
+
readonly internalType: "address";
|
|
137
|
+
readonly name: "onBehalfOf";
|
|
138
|
+
readonly type: "address";
|
|
139
|
+
}];
|
|
140
|
+
readonly name: "borrow";
|
|
141
|
+
readonly outputs: readonly [];
|
|
142
|
+
readonly stateMutability: "nonpayable";
|
|
143
|
+
readonly type: "function";
|
|
96
144
|
}, {
|
|
97
145
|
readonly anonymous: false;
|
|
98
146
|
readonly inputs: readonly [{
|