@galacticcouncil/sdk 9.12.0 → 9.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";var St=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Ar=Object.getOwnPropertyNames;var Fr=Object.prototype.hasOwnProperty;var Er=(c,e)=>{for(var t in e)St(c,t,{get:e[t],enumerable:!0})},Rr=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ar(e))!Fr.call(c,s)&&s!==t&&St(c,s,{get:()=>e[s],enumerable:!(r=Ir(e,s))||r.enumerable});return c};var Nr=c=>Rr(St({},"__esModule",{value:!0}),c);var es={};Er(es,{AaveClient:()=>oe,AavePool:()=>Ee,AavePoolClient:()=>Ce,AaveUtils:()=>ee,AssetClient:()=>te,AssetNotFound:()=>Ft,BASILISK_PARACHAIN_ID:()=>ds,BalanceClient:()=>q,BalanceClientV2:()=>ce,BigNumber:()=>v.BigNumber,CachingPoolService:()=>ge,ChainParams:()=>ue,DECIMAL_PLACES:()=>Zt,DEFAULT_BLOCK_TIME:()=>zt,DEFAULT_MIN_BUDGET:()=>Xt,ERC20:()=>V,EvmClient:()=>Fe,FarmClient:()=>Ze,H160:()=>Y,HUB_ASSET_ID:()=>Qe,HYDRADX_PARACHAIN_ID:()=>gs,HYDRADX_SS58_PREFIX:()=>z,INFINITY:()=>_r,LbpMath:()=>X,LbpPool:()=>ke,LbpPoolClient:()=>De,ONE:()=>R,ORDER_MIN_BLOCK_PERIOD:()=>Yt,OmniMath:()=>E,OmniPool:()=>Me,OmniPoolClient:()=>Le,PERBILL_DENOMINATOR:()=>$t,PERMILL_DENOMINATOR:()=>ne,PolkadotApiClient:()=>H,PoolConfigNotFound:()=>At,PoolError:()=>se,PoolFactory:()=>he,PoolNotFound:()=>Ie,PoolService:()=>de,PoolType:()=>N,ProviderConfigNotFound:()=>Nt,RUNTIME_DECIMALS:()=>we,RouteNotFound:()=>Ae,Router:()=>ye,SYSTEM_ASSET_DECIMALS:()=>Kt,SYSTEM_ASSET_ID:()=>D,StableMath:()=>M,StableSwap:()=>ae,StableSwapClient:()=>Ue,StorageConfigNotFound:()=>Et,SubscriptionNotSupported:()=>Rt,TRADEABLE_DEFAULT:()=>Te,TWAP_BLOCK_PERIOD:()=>Pe,TWAP_MAX_DURATION:()=>gt,TWAP_MAX_PRICE_IMPACT:()=>dt,TWAP_TX_MULTIPLIER:()=>Qr,TradeOrderError:()=>Wt,TradeOrderType:()=>pt,TradeRouteBuilder:()=>W,TradeRouter:()=>be,TradeScheduler:()=>Se,TradeType:()=>mt,TxBuilderFactory:()=>xe,XykMath:()=>J,XykPool:()=>He,XykPoolClient:()=>Ge,ZERO:()=>S,bnFormatter:()=>Xr,bnum:()=>p,calculateBuyFee:()=>qt,calculateDiffToAvg:()=>jr,calculateDiffToRef:()=>fe,calculateSellFee:()=>Ut,createChain:()=>_t,createSdkContext:()=>Zr,findNestedKey:()=>_e,findNestedObj:()=>zr,getFraction:()=>ie,hashPools:()=>Ht,isEvmAccount:()=>jt,isEvmAddress:()=>Qt,isSs58Address:()=>Jt,scale:()=>I,toBn:()=>Cr,toDecimals:()=>B});module.exports=Nr(es);var je=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Vt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",Bt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Be=1000000n;var ls=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var oe=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:xt,args:[Bt],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:vt,address:xt,args:[Bt,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:je,address:Vt,args:[e],functionName:"getUserAccountData"})}};var Z=require("@polkadot/util-crypto"),le=require("@polkadot/util"),j=require("buffer");var ds=2090,ne=1e6,$t=1e9,Qe="1",gs=2034,z=63,we=18,D="0",Kt=12,Te=15;var wt="ETH\0";function jt(c){if(!c)return!1;try{let e=(0,Z.decodeAddress)(c,!0),t=j.Buffer.from(wt);return j.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Qt(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function Jt(c){try{let e=(0,le.isHex)(c)?(0,le.hexToU8a)(c):(0,Z.decodeAddress)(c);return(0,Z.encodeAddress)(e),!0}catch{return!1}}var Y=class c{static toAccount=e=>{let t=j.Buffer.from(e.slice(2),"hex"),r=j.Buffer.from(wt);return(0,Z.encodeAddress)(new Uint8Array(j.Buffer.concat([r,t,j.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,Z.decodeAddress)(e),r=j.Buffer.from(wt),s=t.slice(r.length,-8);return"0x"+j.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,Z.decodeAddress)(e).slice(0,20);return(0,le.u8aToHex)(r)};static fromAny=e=>{if(Qt(e))return e;if(jt(e))return c.fromAccount(e);if(Jt(e))return c.fromSS58(e);throw new Error("Unknown address type")}};var Oe=require("buffer"),V=class{static fromAssetId(e){let t=Number(e),r=Oe.Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Oe.Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Oe.Buffer.from("0000000000000000000000000000000100000000","hex"),r=Oe.Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var v=require("bignumber.js"),Zt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Zt});var S=p(0),R=p(1),_r=p("Infinity");function I(c,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return c.times(r).decimalPlaces(4)}function p(c){return new v.BigNumber(c.toString())}function Cr(c,e){let t=p(c);return I(t,e)}function B(c,e){return c.shiftedBy(-1*e).toString()}var Je=p("1e27"),kr=p("1.01"),Dr=p("31536000"),ee=class{client;constructor(e){this.client=new oe(e)}async getSummary(e){let t=Y.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[a,l]=s,[u,m,g,h,d,f]=i,b=p(f).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),x=p(u),P=p(m),w=[];for(let A of a){let F=A.underlyingAsset.toLowerCase(),T=o.find(({underlyingAsset:Or})=>Or.toLowerCase()===F);if(!T)throw new Error("Missing pool reserve for "+F);let k=p(A.scaledATokenBalance),U=p(T.liquidityIndex),Ve=p(T.liquidityRate),$e=p(T.availableLiquidity),ft=p(T.priceInMarketReferenceCurrency),bt=n+6,Pt=this.calculateLinearInterest(Ve,T.lastUpdateTimestamp,bt),Ke=U.multipliedBy(Pt).dividedBy(Je).decimalPlaces(0,v.BigNumber.ROUND_DOWN),xr=k.multipliedBy(Ke).dividedBy(Je).decimalPlaces(0,v.BigNumber.ROUND_DOWN),Br=p(l!==0&&l===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold).div(1e4),wr=T.usageAsCollateralEnabled&&A.usageAsCollateralEnabledOnUser&&p(A.scaledATokenBalance).gt(0),Tr=V.toAssetId(F);w.push({aTokenBalance:xr,availableLiquidity:$e,decimals:Number(T.decimals),isCollateral:wr,priceInRef:ft,reserveId:Tr,reserveAsset:F,reserveLiquidationThreshold:Br})}return{healthFactor:b.toNumber(),totalCollateral:x,totalDebt:P,reserves:w}}async hasBorrowPositions(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=V.fromAssetId(t),a=n.find(x=>x.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:u,priceInRef:m,reserveLiquidationThreshold:g}=a,h=I(p(r),l).decimalPlaces(0,1),d=u?h.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):S,f=s.minus(d);return f.lte(0)?0:f.multipliedBy(g).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=V.fromAssetId(t),a=n.find(b=>b.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:m}=a,h=I(p(r),l).decimalPlaces(0,1).multipliedBy(u).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),d=s.plus(h);return d.lte(0)?0:d.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=V.fromAssetId(t),o=s.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let o=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:o,reserveLiquidationThreshold:a,isCollateral:l}=e,u=s;if(l&&t.gt(0)){let g=p(r).minus(kr);if(g.gt(0)){let d=g.multipliedBy(t).dividedBy(a).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(o).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);u=v.BigNumber.minimum(s,d)}else u=S}return{amount:v.BigNumber.minimum(u,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Je:e.multipliedBy(s).dividedBy(Dr).plus(Je).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function er(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var Ns=require("@galacticcouncil/api-augment/hydradx"),_s=require("@galacticcouncil/api-augment/basilisk"),H=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");er(r)&&console.log(e,...t)}};var te=class extends H{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e=="0"){let m=this.api.consts.balances.existentialDeposit;return{id:"0",name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:u}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:u,icon:l,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:u,decimals:m}=this.getToken(i.toString(),t,r),g=n.toNumber(),h=new Intl.DateTimeFormat("en-GB"),d=[u,"Bond",h.format(g)].join(" ");return{id:e,name:d,symbol:u+"b",decimals:m,icon:u,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:l,existentialDeposit:u}=t,g=i.map(f=>f.toString()).map(f=>{let{symbol:b}=this.getToken(f,t,r);return[f,b]}),h=Object.fromEntries(g),d=Object.values(h);return{id:e,name:d.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:d.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:u.toString(),meta:h}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,o),u=a.map(([{args:[m]},g])=>{let h=g.unwrap(),d=s.get(m.toString()),{assetType:f}=h;switch(f.toString()){case"Bond":let b=n.get(m.toString());return this.getBond(m.toString(),h,l,b);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),h,l,x);case"External":return this.getExternal(m.toString(),h,t,d);default:return this.getToken(m.toString(),h,l,d)}});return e?u:u.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var q=class extends H{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let u=this.calculateFreeBalance(a),m=i[l][1];o.push([m,u])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:u}=l.unwrap();return u.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return(0,v.BigNumber)(t).lt(r)?(0,v.BigNumber)(0):(0,v.BigNumber)(t).minus(r)}};var ce=class extends H{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let u=i[l][1],m=this.calculateBalance(a);o.push([u,m])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:u}=l.unwrap();return u.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=(0,v.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",n=t.plus(s).toString();return{free:t.toString(),total:n,transferable:i,reserved:s,frozen:r}}};var ue=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),p(this._minOrderBudget)}};var Tt=require("@galacticcouncil/math-liquidity-mining"),tr=require("@polkadot/types"),Ot=require("@polkadot/util"),It=require("@polkadot/util-crypto");var Ze=class extends H{balanceClient;constructor(e){super(e),this.balanceClient=new q(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),u=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),d=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,d);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:m,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),u=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),d=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,d);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:m,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,Tt.fixed_from_rational)(o,a):l=(0,Tt.fixed_from_rational)(a,o),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,Ot.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new tr.GenericAccountId32(e,this.padEndU8a((0,Ot.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,It.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,It.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:u})=>{let m=new v.BigNumber(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),h=new v.BigNumber(a.yieldPerPeriod.toString()),d=new v.BigNumber(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),b=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(r).times(f)),P;if(m.isZero())P=h.times(b).times(x);else{let k=this.getGlobalRewardPerPeriod(m,h,d,l);P=this.getPoolYieldPerPeriod(k,b,m,l).times(x)}let w=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),A=d.times(g),F=u?w.plus(u):A;return w.div(F).gte(.999)?S:P.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var Ie=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ae=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Rt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Nt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var rr=require("viem"),Mr=["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"],_t=c=>{let t=[c.endpoint,...Mr],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,rr.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};var Q=require("viem");function sr(c){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return c.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Fe=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=_t(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:(0,Q.http)()})}getWsProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:sr(this.wsProvider)})}getSigner(e){return(0,Q.createWalletClient)({account:e,chain:this.chain,transport:(0,Q.custom)(window.ethereum)})}};var re=(c,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=c(t)),r)};var N=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n.HSM="Hsm",n))(N||{}),se=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(se||{});var Ee=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return I(R,e.decimalsOut)}spotPriceOutGivenIn(e){return I(R,e.decimalsIn)}calculateTradeFee(e,t){return S}};var pr=require("@polkadot/util-crypto"),dr=require("@polkadot/util"),gr=require("viem");var Re=(c,e)=>c===e?0:c==null?e==null?0:-1:e==null?c==null?0:1:typeof c.compare=="function"?c.compare(e):typeof e.compare=="function"?-e.compare(c):c<e?-1:c>e?1:0;var et=(c,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(c(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Lr=et(()=>"illegal argument(s)"),ir=c=>{throw new Lr(c)};var Hr=et(()=>"index out of bounds"),Ct=c=>{throw new Hr(c)},tt=(c,e,t)=>(c<e||c>=t)&&Ct(c);var nr=23283064365386963e-26,rt=class{float(e=1){return this.int()*nr*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*nr-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var st=class extends rt{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var ar=new st(Math.random);var or=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var lr=Object.getPrototypeOf({}),it="function",cr="string",me=(c,e)=>{let t;if(c===e)return!0;if(c!=null){if(typeof c.equiv===it)return c.equiv(e)}else return c==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(c)}else return c==e;return typeof c===cr||typeof e===cr?!1:(t=Object.getPrototypeOf(c),(t==null||t===lr)&&(t=Object.getPrototypeOf(e),t==null||t===lr)?Wr(c,e):typeof c!==it&&c.length!==void 0&&typeof e!==it&&e.length!==void 0?Gr(c,e):c instanceof Set&&e instanceof Set?Ur(c,e):c instanceof Map&&e instanceof Map?qr(c,e):c instanceof Date&&e instanceof Date?c.getTime()===e.getTime():c instanceof RegExp&&e instanceof RegExp?c.toString()===e.toString():c!==c&&e!==e)},Gr=(c,e,t=me)=>{let r=c.length;if(r===e.length)for(;r-- >0&&t(c[r],e[r]););return r<0},Ur=(c,e,t=me)=>c.size===e.size&&t([...c.keys()].sort(),[...e.keys()].sort()),qr=(c,e,t=me)=>c.size===e.size&&t([...c].sort(),[...e].sort()),Wr=(c,e,t=me)=>{if(Object.keys(c).length!==Object.keys(e).length)return!1;for(let r in c)if(!e.hasOwnProperty(r)||!t(c[r],e[r]))return!1;return!0};var kt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ur=c=>c instanceof kt;var nt=class c{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return mr("next",this._head)}reverseIterator(){return mr("prev",this.tail)}clear(){this.release()}compare(e,t=Re){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof c||or(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!me(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head?.value}insertSorted(e,t){t=t||Re;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail?.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!ur(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&Ct(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*mr(c,e){for(;e;)yield e.value,e=e[c]}var at=class c extends nt{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new c}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(tt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(tt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new c,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=ar){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&ir("invalid indices: ${from} / ${to}");let i=new c,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.next;return i}sort(e=Re){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(a=r,r=r.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),tt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new c;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var ot=class c{map;items;opts;_size;constructor(e,t){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=r.map(),this.items=new at,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e),i=Math.max(0,r-(s?s.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(s,e,t,r):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let r=this.map.get(e);return r?this.resetEntry(r):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:r}=this.opts;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var pe=class c extends ot{constructor(e,t){super(e,{ttl:3600*1e3,autoExtend:!1,...t})}empty(){return new c(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let r=this.map.get(e);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return t}set(e,t,r=this.opts.ttl){let s=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var Dt=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var Ne=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:Dt,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Dt,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,o,a,l]=r,u=i.number-(i.timestamp-l)/BigInt(t),m=Number(u);return{price:o,decimals:s,updatedAt:m<0?0:m}}};var G=class extends q{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new pe(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=re(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Ne(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(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();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=this.augmentedPools.map(async r=>{let s=[],i=await this.subscribeTokensPoolBalance(r);if(s.push(i),this.hasSystemAsset(r)){let n=await this.subscribeSystemPoolBalance(r);s.push(n)}if(this.hasErc20Asset(r)){let n=await this.subscribeErc20PoolBalance(r);s.push(n)}return this.subscribeLog(r),s}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}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()).catch(t=>console.warn("Unsub failed",t))})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,i])=>{let n=e.tokens.findIndex(o=>o.id==s);n>=0&&t(e,s)&&(e.tokens[n].balance=i.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(i=>i.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};function _e(c,e){let t=[];return JSON.stringify(c,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function zr(c,e,t){let r;return JSON.stringify(c,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Xr=(c,e)=>typeof e=="bigint"?e.toString():e;var Yr=["Supply","Withdraw","Repay","Borrow"],Ce=class extends G{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return(0,pr.encodeAddress)((0,dr.stringToU8a)(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?_e(e.location,"accountKey20").accountKey20.key:V.fromAssetId(e.id)}isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,n]=r.data.toJSON();this.pools.filter(o=>o.tokens.some(a=>a.id===i.toString()||a.id===n.toString())).forEach(o=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${n}`),this.updatePoolState(o)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:o}=(0,gr.decodeEventLog)({abi:je,topics:i.topics,data:i.data});if(Yr.includes(n)){let a=o.reserve.toLowerCase();this.pools.filter(l=>{let[u]=l.tokens;return this.getReserveH160Id(u).toLowerCase()===a}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${n} ${a}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}};var $=require("@galacticcouncil/math-lbp"),X=class{static getSpotPrice(e,t,r,s,i){return(0,$.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,$.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,$.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,$.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}};var y=class c{static toPct(e){let[t,r]=e;return c.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return c.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var ke=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new c(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),a=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),u=this.calculateInGivenOut(e,l),m=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:u,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),I(R,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=X.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),I(R,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var De=class extends G{MAX_FINAL_WEIGHT=I(p(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:u}=t,m=X.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[g,h]=n,d=g.toString(),f=p(m),b=h.toString(),x=this.MAX_FINAL_WEIGHT.minus(p(f)),[P,w,A]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),u.toString()),this.getBalance(e,d),this.getBalance(e,b)]);return{repayFeeApply:P,tokens:[{id:d,weight:f,balance:w.toString()},{id:b,weight:x,balance:A.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t>=r&&t<s}async isRepayFeeApplied(e,t,r){let s=p(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,n])=>this.isActivePool(n.unwrap(),r.toNumber())).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,o,r.toString());this.poolsData.set(i.toString(),o);let[u,m]=o.fee;return{address:a,type:"Lbp",fee:y.fromRate(u.toNumber(),m.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let n=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,n)}else{let n=this.pools.findIndex(o=>o.address==r.address);this.pools.splice(n,1)}})})}};var O=require("@galacticcouncil/math-omnipool");var E=class{static calculateSpotPrice(e,t,r,s){return(0,O.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,O.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,l){return(0,O.calculate_in_given_out)(e,t,r,s,i,n,o,a,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,O.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,l){return(0,O.calculate_out_given_in)(e,t,r,s,i,n,o,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,O.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,O.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_out)(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_lrna_out)(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(s),l=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(l)){let m=l.times(o).minus(i).times(n),g=i.times((0,v.BigNumber)(1).minus(l));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,O.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,O.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,O.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,O.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,O.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,l,u,m){return(0,O.recalculate_asset_fee)(e,t,r,s,i,n,o,a,l,u,m)}static recalculateProtocolFee(e,t,r,s,i,n,o,a,l,u,m){return(0,O.recalculate_protocol_fee)(e,t,r,s,i,n,o,a,l,u,m)}static verifyAssetCap(e,t,r,s){return(0,O.verify_asset_cap)(e,t,r,s)}};var Me=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new c(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=E.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=E.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=E.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=E.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=E.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=E.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=E.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=E.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var fr=require("@polkadot/util-crypto"),br=require("@polkadot/util");var hr="omnipool",yr="Short",Le=class extends G{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new pe(null,{ttl:6*1e3});memOracleQuery=re(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(hr,t,yr)},this.memQueryCache);memFeesQuery=re(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=re(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return(0,fr.encodeAddress)((0,br.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[a]},l])=>{let{hubReserve:u,shares:m,tradable:g,cap:h,protocolShares:d}=l.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(u.toString()),shares:p(m.toString()),tradeable:g.bits.toNumber(),balance:f.toString(),cap:p(h.toString()),protocolShares:p(d.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,n;if(this.isAssetConfigSupported()&&(n=await this.getDynamicFeesConfiguration(s).then(P=>P.unwrapOr(null))),n?.isFixed){let P=n.asFixed.assetFee.toNumber(),w=n.asFixed.protocolFee.toNumber();return{assetFee:y.fromPermill(P),protocolFee:y.fromPermill(w)}}let[o,a,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[u,m,g]=this.getAssetFee(t,e,o,a,n?.isDynamic?n.asDynamic.assetFeeParams:void 0),[h,d,f]=i==="1"?[0,0,0]:this.getProtocolFee(t,e,o,l,n?.isDynamic?n.asDynamic.protocolFeeParams:void 0),b=u+h,x=g+f;return{assetFee:y.fromPermill(m),protocolFee:y.fromPermill(d),min:y.fromPermill(b),max:y.fromPermill(x)}}getAssetFee(e,t,r,s,i){let{assetOut:n,balanceOut:o}=e,{minFee:a,maxFee:l,decay:u,amplification:m}=i||this.api.consts.dynamicFees.assetFeeParameters,g=y.fromPermill(a.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[d]=s.unwrap(),{assetFee:f,timestamp:b}=r.unwrap(),x=Math.max(1,t-b.toNumber()),P=d.volume.bIn.toString(),w=d.volume.bOut.toString(),A=d.liquidity.b.toString();n==="0"&&(P=d.volume.aIn.toString(),w=d.volume.aOut.toString(),A=d.liquidity.a.toString());let F=y.fromPermill(f.toNumber()),T=E.recalculateAssetFee(P,w,A,"9",o.toString(),y.toRaw(F).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),u.toString(),m.toString());return[a.toNumber(),Number(T)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:n,balanceIn:o}=e,{minFee:a,maxFee:l,decay:u,amplification:m}=i||this.api.consts.dynamicFees.protocolFeeParameters,g=y.fromPermill(a.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[d]=s.unwrap(),{protocolFee:f,timestamp:b}=r.unwrap(),x=Math.max(1,t-b.toNumber()),P=d.volume.bIn.toString(),w=d.volume.bOut.toString(),A=d.liquidity.b.toString();n==="0"&&(P=d.volume.aIn.toString(),w=d.volume.aOut.toString(),A=d.liquidity.a.toString());let F=y.fromPermill(f.toNumber()),T=E.recalculateProtocolFee(P,w,A,"9",o.toString(),y.toRaw(F).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),u.toString(),m.toString());return[a.toNumber(),Number(T)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,u)=>{let m=e.tokens[u];if(l.isNone)return m;let g=l.unwrap();return this.updateTokenState(m,g)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,u)=>{let m=t[u];this.dynamicFees.set(m,l)})});if(r.push(i),this.isAssetConfigSupported()){let a=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((u,m)=>{let g=t[m];this.dynamicFeesConfiguration.set(g,u)})});r.push(a)}let n=t.map(a=>{let l=this.getOracleKey(a);return[hr,l,yr]}),o=await this.api.query.emaOracle.oracles.multi(n,a=>{a.forEach(async(l,u)=>{let m=n[u],[g,h,d]=m;this.oracles.set(h.join(":"),l)})});return r.push(o),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}};var _=require("@galacticcouncil/math-xyk"),J=class{static getSpotPrice(e,t,r){return(0,_.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,_.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,_.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,_.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,_.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,_.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,_.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,_.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,_.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,_.calculate_liquidity_out_asset_b)(e,t,r,s)}};var He=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let u=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(u)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let u=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(u)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let r=J.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=J.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=J.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=I(R,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=J.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=I(R,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=J.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var Ge=class extends G{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};var C=require("@galacticcouncil/math-stableswap"),M=class{static getPoolAddress(e){return(0,C.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return(0,C.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,o){return(0,C.calculate_in_given_out)(e,t,r,s,i,n,o)}static calculateAddOneAsset(e,t,r,s,i,n,o){return(0,C.calculate_add_one_asset)(e,t,r,s,i,n,o)}static calculateSharesForAmount(e,t,r,s,i,n,o){return(0,C.calculate_shares_for_amount)(e,t,r,s,i,n,o)}static calculateOutGivenIn(e,t,r,s,i,n,o){return(0,C.calculate_out_given_in)(e,t,r,s,i,n,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,o){return(0,C.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,o)}static calculateShares(e,t,r,s,i,n){return(0,C.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,o,a){return(0,C.calculate_spot_price_with_fee)(e,t,r,s,i,n,o,a)}static recalculatePegs(e,t,r,s,i){let n=(0,C.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var ae=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new c(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);return(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);return(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateIn(e,t,r){let s=M.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=M.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=M.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=M.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=I(R,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=I(R,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=M.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=M.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=M.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=M.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=I(R,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=I(R,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var lt=require("@polkadot/util-crypto");var Ue=class extends G{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=M.getPoolAddress(t);return(0,lt.encodeAddress)((0,lt.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=M.calculateAmplification(s.toString(),i.toString(),n.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async n=>{let[o,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:o.bits.toNumber(),balance:a.toString()}});return Promise.all(i)}isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},o])=>{try{let a=o.unwrap(),l=n.toString(),u=this.getPoolAddress(l),[m,g,h]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(u,l,a),this.getPoolPegs(l,a,r.toString())]);return g.push({id:l,tradeable:15,balance:m.totalIssuance}),this.poolsData.set(u,a),{address:u,id:l,type:"Stableswap",fee:y.fromPermill(a.fee.toNumber()),tokens:g,...m,...h,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${n.toString()}
|
|
2
|
-
`,String(a)),null}});return(await Promise.all(s)).filter(n=>n!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=y.fromPermill(i.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[u,m]=M.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,y.toRaw(a).toString(),y.toRaw(l).toString()),g=Number(u)*1e6;return{pegsFee:y.fromPermill(g),pegs:m}}getDefaultPegs(e){let t=e.fee,r=M.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=s.map(async(o,a)=>{if(o.isOracle){let[l,u,m]=o.asOracle,g=[m.toString(),i[a]].map(P=>Number(P)).sort((P,w)=>P-w),h=await this.api.query.emaOracle.oracles(l,g,u),[{price:d,updatedAt:f}]=h.unwrap(),b=d.n.toString(),x=d.d.toString();return m.toString()===g[0].toString()?[[b,x],f.toString()]:[[x,b],f.toString()]}else if(o.isMmOracle){let l=o.asMmOracle,{price:u,decimals:m,updatedAt:g}=await this.mmOracle.getData(l.toString()),h=10**m;return[[u.toString(),h.toString()],g.toString()]}else{if(o.isValue)return[o.asValue.map(l=>l.toString()),r];throw Error(o.type+" is not supported")}});return Promise.all(n)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[i,n]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),o=r.tokens.map(a=>a.id===r.id?{...a,balance:i.totalIssuance}:a);Object.assign(r,{tokens:o},i,n)}})})}};var L=require("@galacticcouncil/math-hsm"),K=class{static calculateCollateralInGivenHollarOut(e,t,r){return(0,L.calculate_collateral_in_given_hollar_out)(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return(0,L.calculate_collateral_out_given_hollar_in)(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return(0,L.calculate_hollar_out_given_collateral_in)(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return(0,L.calculate_hollar_in_given_collateral_out)(e,t,r)}static calculateImbalance(e,t,r){return(0,L.calculate_imbalance)(e,t,r)}static calculateBuybackLimit(e,t){return(0,L.calculate_buyback_limit)(e,t)}static calculateBuybackPriceWithFee(e,t,r){return(0,L.calculate_buyback_price_with_fee)(e,t,r)}static calculateMaxPrice(e,t){return(0,L.calculate_max_price)(e,t)}};var ct=class c extends ae{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new c(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let n=this.calculateBuyPrice(e,t,r),o=this.calculateMaxPrice(e);return n.gt(o)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=K.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=K.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return p(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=K.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=K.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return p(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=K.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return p(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=K.calculateBuybackLimit(t.toString(),y.toRaw(this.buyBackRate).toString());return p(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(p(10).pow(e.decimalsIn));return r.dividedBy(p(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=K.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return p(s).div(p(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=I(R,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=I(R,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[I(R,18).toString(),I(R,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};var Mt=require("@polkadot/util"),Lt=require("@polkadot/util-crypto"),Pr=require("viem");var qe=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var We=class{client;constructor(e){this.client=e.getWsProvider()}async getFacilitatorCapacity(e,t){let[r,s]=await this.client.readContract({abi:qe,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var Vr=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],ut=class extends G{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new We(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return(0,Lt.encodeAddress)((0,Mt.stringToU8a)(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return(0,Lt.encodeAddress)((0,Mt.stringToU8a)("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return _e(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),n=Y.fromAny(i),o=this.getHollarAddress(t.unwrap()),a=await this.ghoTokenClient.getFacilitatorCapacity(o,n),l=r.map(async([{args:[m]},g])=>{let h=g.unwrap(),d=m.toString(),{poolId:f,maxBuyPriceCoefficient:b,maxInHolding:x,purchaseFee:P,buyBackFee:w,buybackRate:A}=h,F=s.find(T=>T.id===f.toString());if(F){let T=this.getPoolId(f.toString()),k=await this.getBalance(i,d);return{...F,address:T,type:"Hsm",tokens:F.tokens.filter(U=>U.id!==f.toString()),hsmAddress:i,hsmMintCapacity:p(a),hollarId:e,hollarH160:o,collateralId:d,collateralBalance:k,maxBuyPriceCoefficient:p(b.toString()),maxInHolding:p(x.unwrap().toString()),purchaseFee:y.fromPermill(P.toNumber()),buyBackFee:y.fromPermill(w.toNumber()),buyBackRate:y.fromPerbill(A.toNumber())}}});return(await Promise.all(l)).filter(m=>m!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:o}=(0,Pr.decodeEventLog)({abi:qe,topics:i.topics,data:i.data}),[a]=this.pools,{hsmAddress:l,hollarH160:u}=a,m=Y.fromAny(l),g=m.toLowerCase()===o.facilitatorAddress.toLowerCase();if(Vr.includes(n)&&g){let h=await this.ghoTokenClient.getFacilitatorCapacity(u,m);this.log(`Sync HSM facilitator via [evm:Log] :: ${n} ${h}`),this.pools.forEach(d=>{Object.assign(d,{hsmMintCapacity:h})})}}catch{}}})}async subscribeBalances(){let e=this.pools.map(async r=>{let{collateralId:s,hsmAddress:i,tokens:n}=r,o=n.find(l=>l.id===s),a=l=>{let[u]=l,[m,g]=u;Object.assign(r,{collateralBalance:g})};return o.type==="Erc20"?this.subscribeErc20Balance(i,a,[s]):this.subscribeTokenBalance(i,a,[s])}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}async subscribeUpdates(){return()=>{}}};var de=class extends H{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=re(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new te(this.api),this.aaveClient=new Ce(this.api,t),this.xykClient=new Ge(this.api,t),this.omniClient=new Le(this.api,t),this.lbpClient=new De(this.api,t),this.stableClient=new Ue(this.api,t),this.hsmClient=new ut(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Ie(t.type)}}};var ge=class extends de{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var he=class{static get(e){switch(e.type){case"Aave":return Ee.fromPool(e);case"Xyk":return He.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return ke.fromPool(e);case"Stableswap":return ae.fromPool(e);case"Hsm":return ct.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Sr=require("@noble/hashes/sha256"),vr=require("@noble/hashes/utils");function Ht(c){let e=c.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,Sr.sha256)(t);return(0,vr.bytesToHex)(r)}var ze=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $r=8,Xe=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new ze,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(!o||o.length>$r)continue;let a=o[o.length-1];(r===null||a[0]===r)&&s.push(o),e.get(a[0])?.forEach(u=>{if(this.isNotVisited(u,o)){let m=[...o];m.push(u),i.enqueue(m)}})}return s}findShortestPaths(e,t,r){let s=[],i=new ze,n=[];n.push([t,""]),i.enqueue(n);let o=1/0;for(;i.size()>0;){let a=i.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<o?(o=a.length,s.length=0,s.push(a)):a.length===o&&s.push(a);continue}let u=e.get(l[0]);for(let m of u??[])this.isNotVisited(m,a)&&i.enqueue([...a,m])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let o=parseInt(i),a=parseInt(n);r.get(o)?.push([a,s])}return r}};function Gt(c){let e={};for(let t of c){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var Ye=class{getProposals(e,t,r){let s=r.filter(P=>P.type==="Xyk"),i=r.filter(P=>P.type!=="Xyk"),n=parseInt(e),o=parseInt(t),a=new Set(i.map(P=>P.tokens).flat().map(P=>P.id)),l=a.has(e),u=a.has(t),m=new Xe,g=P=>{let w=Gt(P),A=Object.keys(w),F=A.flatMap(T=>w[T]);return m.buildAndPopulateGraph(A,F)};if(!l&&!u){let P=s.filter(F=>F.tokens.find(T=>T.id===e)||F.tokens.find(T=>T.id===t)),w=g(P),A=m.findPaths(w,n,o);return this.parsePaths(A)}if(l&&u){let P=g(i),w=m.findPaths(P,n,o);return this.parsePaths(w)}let h=l?t:e,d=s.filter(P=>P.tokens.some(w=>w.id===h)),f=[...i,...d],b=g(f),x=m.findPaths(b,n,o);return this.parsePaths(x)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(n,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ye=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Ye,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}getProposals(e,t,r){let s=`${e}->${t}::${Ht(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,he.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}};var Kr=p("100");function jr(c,e){return c.minus(e).abs().div(c.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function fe(c,e){return c.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Ut(c,e){return R.minus(e.div(c)).multipliedBy(100).decimalPlaces(4)}function qt(c,e){return e.div(c).minus(R).multipliedBy(100).decimalPlaces(4)}function ie(c,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),c.div(Kr).multipliedBy(e).decimalPlaces(0,1)}var mt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(mt||{}),pt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(pt||{}),Wt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Wt||{});var be=class extends ye{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Ae(e,t);return{paths:i,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toSellSwaps(r,s,n);else{let a=i.map(async u=>await this.toSellSwaps(r,u,n)),l=await Promise.all(a);o=this.findBestSellRoute(l)}return this.buildSell(n,o)}async getSellTrades(e,t,r){let{paths:s,poolsMap:i}=await this.loadRouteContext(e,t),n=s.map(async a=>await this.toSellSwaps(r,a,i));return(await Promise.all(n)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildSell(i,a)).sort((a,l)=>a.amountOut.isGreaterThan(l.amountOut)?-1:1)}buildSell(e,t){let r=t[0],s=t[t.length-1],i=this.isDirectTrade(t),n=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetOutDecimals)).reduce((f,b)=>f.multipliedBy(b)),o=I(n,s.assetOutDecimals),a=i?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,u=i?s.tradeFeePct:Ut(a,l).toNumber(),m=a.minus(l),g=this.getRouteFeeRange(t),h=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(o),d=fe(a,h);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:o,tradeFee:m,tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:B(r.amountIn,r.assetInDecimals),amountOut:B(s.amountOut,s.assetOutDecimals),spotPrice:B(o,s.assetOutDecimals),tradeFee:B(m,s.assetOutDecimals),tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t.map(f=>f.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1]:l=e;let u=o.calculateOutGivenIn(a,l);s.push(u)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1].amountOut:l=I(p(e),a.decimalsIn).decimalPlaces(0,1);let u=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:g,feePct:h,errors:d}=o.validateAndSell(a,l,u),f=this.getPoolFeeRange(u),b=o.spotPriceOutGivenIn(a),x=l.shiftedBy(-1*a.decimalsIn).multipliedBy(b),P=fe(g,x);s.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:m,calculatedOut:g,spotPrice:b,tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:B(l,a.decimalsIn),amountOut:B(m,a.decimalsOut),calculatedOut:B(g,a.decimalsOut),spotPrice:B(b,a.decimalsOut),tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:d}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(h=>h.tokens.some(d=>d.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(d=>d.id===e)).map(h=>h.map(d=>p(d.balance).shiftedBy(-1*d.decimals)).reduce((d,f)=>d.plus(f))).sort((h,d)=>d.isLessThan(h)?-1:1)[0].div(100).multipliedBy(.1),u=r.map(async h=>await this.toSellSwaps(l,h,i)),m=await Promise.all(u);return this.findBestSellRoute(m).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,s),o=n.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,m)=>u.multipliedBy(m)),a=n[n.length-1].assetOutDecimals;return{amount:I(o,a),decimals:a}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toBuySwaps(r,s,n);else{let a=i.map(async u=>await this.toBuySwaps(r,u,n)),l=await Promise.all(a);o=this.findBestBuyRoute(l)}return this.buildBuy(n,o)}async getBuyTrades(e,t,r){let{paths:s,poolsMap:i}=await this.loadRouteContext(e,t),n=s.map(async a=>await this.toBuySwaps(r,a,i));return(await Promise.all(n)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildBuy(i,a)).sort((a,l)=>a.amountIn.isGreaterThan(l.amountIn)?1:-1)}buildBuy(e,t){let r=t[t.length-1],s=t[0],i=this.isDirectTrade(t),n=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetInDecimals)).reduce((f,b)=>f.multipliedBy(b)),o=I(n,s.assetInDecimals),a=i?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,u=i?s.tradeFeePct:qt(a,l).toNumber(),m=l.minus(a),g=this.getRouteFeeRange(t),h=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(o),d;return a.isZero()?d=-100:d=fe(h,a).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:o,tradeFee:m,tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d,swaps:t,toHuman(){return{type:"Buy",amountOut:B(r.amountOut,r.assetOutDecimals),amountIn:B(s.amountIn,s.assetInDecimals),spotPrice:B(o,s.assetInDecimals),tradeFee:B(m,s.assetInDecimals),tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d,swaps:t.map(f=>f.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=e:l=s[0];let u=o.calculateInGivenOut(a,l);s.unshift(u)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=I(p(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let u=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:g,feePct:h,errors:d}=o.validateAndBuy(a,l,u),f=this.getPoolFeeRange(u),b=o.spotPriceInGivenOut(a),x=l.shiftedBy(-1*a.decimalsOut).multipliedBy(b),P;g.isZero()?P=-100:P=fe(x,g).toNumber(),s.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:m,amountOut:l,calculatedIn:g,spotPrice:b,tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P,errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:B(m,a.decimalsIn),amountOut:B(l,a.decimalsOut),calculatedIn:B(g,a.decimalsIn),spotPrice:B(b,a.decimalsIn),tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P,errors:d}}})}return s}};var zt=6e3,Xt=p(1e15),Pe=6,dt=-5,gt=360*60*1e3,Qr=3,Yt=6;var W=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var Se=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??zt,minBudgetInNative:t.minBudgetInNative??Xt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:u}=o,m=l[0],g=l[l.length-1],{assetInDecimals:h}=m,{assetOutDecimals:d}=g,f=Math.abs(u),b=this.getMinimumTradeCount(a,n),x=this.getOptimalTradeCount(f),P=i?Math.round(s/i):x,w=Math.ceil(s/b),A=Math.round(s/x),F=Math.round(s/P),T=a.dividedBy(P).decimalPlaces(0,1),k=await this.router.getBestSell(e,t,B(T,h)),U=a.isLessThan(n),Ve=[];U&&Ve.push("OrderTooSmall");let $e=k.amountOut.multipliedBy(P),ft=this.toBlockPeriod(F),bt=k.tradeFee.multipliedBy(P),Pt=W.build(l),Ke={assetIn:e,assetOut:t,errors:Ve,frequencyMin:w,frequencyOpt:A,frequency:F,tradeCount:P,tradeFee:bt,tradeImpactPct:k.priceImpactPct,tradePeriod:ft,tradeRoute:Pt,type:"Dca"};return{...Ke,amountIn:a,amountOut:$e,tradeAmountIn:k.amountIn,tradeAmountOut:k.amountOut,toHuman(){return{...Ke,amountIn:B(a,h),amountOut:B($e,d),tradeAmountIn:B(k.amountIn,h),tradeAmountOut:B(k.amountOut,d)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:o,priceImpactPct:a}=i,l=o[0],u=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=u,h=Math.abs(a),d=this.getTwapTradeCount(h),f=n.dividedBy(d).decimalPlaces(0,1),b=await this.router.getBestSell(l.assetIn,u.assetOut,B(f,m)),x=d===1,P=n.isLessThan(s),w=b.priceImpactPct<dt,A=[];P||x?A.push("OrderTooSmall"):w&&A.push("OrderImpactTooBig");let F=b.amountOut.multipliedBy(d),T=b.tradeFee.multipliedBy(d),k=W.build(o),U={assetIn:e,assetOut:t,errors:A,tradeCount:d,tradeImpactPct:b.priceImpactPct,tradePeriod:Pe,tradeRoute:k,type:"TwapSell"};return{...U,amountIn:n,amountOut:F,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:T,toHuman(){return{...U,amountIn:B(n,m),amountOut:B(F,g),tradeAmountIn:B(b.amountIn,m),tradeAmountOut:B(b.amountOut,g),tradeFee:B(T,g)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:o,priceImpactPct:a}=i,l=o[0],u=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=u,h=Math.abs(a),d=this.getTwapTradeCount(h),f=n.dividedBy(d).decimalPlaces(0,1),b=await this.router.getBestBuy(l.assetIn,u.assetOut,B(f,g)),x=b.amountIn.multipliedBy(d),P=d===1,w=x.isLessThan(s),A=b.priceImpactPct<dt,F=[];w||P?F.push("OrderTooSmall"):A&&F.push("OrderImpactTooBig");let T=b.tradeFee.multipliedBy(d),k=W.build(o),U={assetIn:e,assetOut:t,errors:F,tradeCount:d,tradeImpactPct:b.priceImpactPct,tradePeriod:Pe,tradeRoute:k,type:"TwapBuy"};return{...U,amountIn:x,amountOut:n,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:T,toHuman(){return{...U,amountIn:B(x,m),amountOut:B(n,g),tradeAmountIn:B(b.amountIn,m),tradeAmountOut:B(b.amountOut,g),tradeFee:B(T,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>gt){let s=gt/(this.blockTime*Pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Yt)}};var ve=class extends H{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new q(e),this.aaveUtils=new ee(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),Be)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var ht=class extends ve{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=ie(e,this.slippagePct),o=s.assetIn,a=i.assetOut,l=e.plus(n),u;return this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.buy(a,o,t.toFixed(),l.toFixed()):u=this.api.tx.router.buy(o,a,t.toFixed(),l.toFixed(),W.build(r)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=ie(t,this.slippagePct),o=s.assetIn,a=i.assetOut,l=t.minus(n),u;if(this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.sell(o,a,e.toFixed(),l.toFixed()):u=this.api.tx.router.sell(o,a,e.toFixed(),l.toFixed(),W.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(u);return this.wrapTx("RouterSellAll",g,Be)}return this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=ie(e,this.slippagePct),n=r.assetIn,o=s.assetOut,a=e.minus(i),l=this.api.tx.router.sellAll(n,o,a.toFixed(),W.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,Be)}return this.wrapTx("RouterSellAll",l)}};var yt=class extends ve{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,o=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=ie(i,this.slippagePct),l=i.minus(a),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=ie(s,this.slippagePct),l=s.plus(a),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",u)}};var xe=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new ht(this.api,this.evm).setTrade(e)}order(e){return new yt(this.api,this.evm).setOrder(e)}};var Jr={router:{}};function Zr(c,e=Jr){let t=new ue(c),r=new Fe(c),s=new ge(c,r),i=new ee(r),n=new be(s,e.router),o=new Se(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:n,scheduler:o},client:{asset:new te(c),balance:new q(c),balanceV2:new ce(c)},ctx:{pool:s},evm:r,tx:new xe(c,r),destroy:()=>{s.destroy()}}}0&&(module.exports={AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BalanceClientV2,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,DEFAULT_BLOCK_TIME,DEFAULT_MIN_BUDGET,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,ORDER_MIN_BLOCK_PERIOD,OmniMath,OmniPool,OmniPoolClient,PERBILL_DENOMINATOR,PERMILL_DENOMINATOR,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TWAP_BLOCK_PERIOD,TWAP_MAX_DURATION,TWAP_MAX_PRICE_IMPACT,TWAP_TX_MULTIPLIER,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,hashPools,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
|
|
1
|
+
"use strict";var St=Object.defineProperty;var Ir=Object.getOwnPropertyDescriptor;var Ar=Object.getOwnPropertyNames;var Fr=Object.prototype.hasOwnProperty;var Er=(c,e)=>{for(var t in e)St(c,t,{get:e[t],enumerable:!0})},Nr=(c,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ar(e))!Fr.call(c,s)&&s!==t&&St(c,s,{get:()=>e[s],enumerable:!(r=Ir(e,s))||r.enumerable});return c};var Rr=c=>Nr(St({},"__esModule",{value:!0}),c);var es={};Er(es,{AaveClient:()=>oe,AavePool:()=>Ee,AavePoolClient:()=>Ce,AaveUtils:()=>ee,AssetClient:()=>te,AssetNotFound:()=>Ft,BASILISK_PARACHAIN_ID:()=>ds,BalanceClient:()=>U,BalanceClientV2:()=>ce,BigNumber:()=>v.BigNumber,CachingPoolService:()=>ge,ChainParams:()=>ue,DECIMAL_PLACES:()=>Zt,DEFAULT_BLOCK_TIME:()=>zt,DEFAULT_MIN_BUDGET:()=>Xt,ERC20:()=>V,EvmClient:()=>Fe,FarmClient:()=>Ze,H160:()=>Y,HUB_ASSET_ID:()=>Qe,HYDRADX_PARACHAIN_ID:()=>gs,HYDRADX_SS58_PREFIX:()=>z,INFINITY:()=>_r,LbpMath:()=>X,LbpPool:()=>ke,LbpPoolClient:()=>De,ONE:()=>N,ORDER_MIN_BLOCK_PERIOD:()=>Yt,OmniMath:()=>E,OmniPool:()=>Me,OmniPoolClient:()=>Le,PERBILL_DENOMINATOR:()=>$t,PERMILL_DENOMINATOR:()=>ne,PolkadotApiClient:()=>H,PoolConfigNotFound:()=>At,PoolError:()=>se,PoolFactory:()=>he,PoolNotFound:()=>Ie,PoolService:()=>de,PoolType:()=>_,ProviderConfigNotFound:()=>Rt,RUNTIME_DECIMALS:()=>we,RouteNotFound:()=>Ae,Router:()=>ye,SYSTEM_ASSET_DECIMALS:()=>Kt,SYSTEM_ASSET_ID:()=>R,StableMath:()=>M,StableSwap:()=>ae,StableSwapClient:()=>Ge,StorageConfigNotFound:()=>Et,SubscriptionNotSupported:()=>Nt,TRADEABLE_DEFAULT:()=>Te,TWAP_BLOCK_PERIOD:()=>Pe,TWAP_MAX_DURATION:()=>gt,TWAP_MAX_PRICE_IMPACT:()=>dt,TWAP_TX_MULTIPLIER:()=>Qr,TradeOrderError:()=>Wt,TradeOrderType:()=>pt,TradeRouteBuilder:()=>W,TradeRouter:()=>be,TradeScheduler:()=>Se,TradeType:()=>mt,TxBuilderFactory:()=>xe,XykMath:()=>J,XykPool:()=>He,XykPoolClient:()=>qe,ZERO:()=>S,bnFormatter:()=>Xr,bnum:()=>p,calculateBuyFee:()=>Ut,calculateDiffToAvg:()=>jr,calculateDiffToRef:()=>fe,calculateSellFee:()=>Gt,createChain:()=>_t,createSdkContext:()=>Zr,findNestedKey:()=>_e,findNestedObj:()=>zr,getFraction:()=>ie,hashPools:()=>Ht,isEvmAccount:()=>jt,isEvmAddress:()=>Qt,isSs58Address:()=>Jt,scale:()=>I,toBn:()=>Cr,toDecimals:()=>B});module.exports=Rr(es);var je=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Vt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",Bt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Be=1000000n;var ls=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var oe=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:xt,args:[Bt],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:vt,address:xt,args:[Bt,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:je,address:Vt,args:[e],functionName:"getUserAccountData"})}};var Z=require("@polkadot/util-crypto"),le=require("@polkadot/util"),j=require("buffer");var ds=2090,ne=1e6,$t=1e9,Qe="1",gs=2034,z=63,we=18,R="0",Kt=12,Te=15;var wt="ETH\0";function jt(c){if(!c)return!1;try{let e=(0,Z.decodeAddress)(c,!0),t=j.Buffer.from(wt);return j.Buffer.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Qt(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function Jt(c){try{let e=(0,le.isHex)(c)?(0,le.hexToU8a)(c):(0,Z.decodeAddress)(c);return(0,Z.encodeAddress)(e),!0}catch{return!1}}var Y=class c{static toAccount=e=>{let t=j.Buffer.from(e.slice(2),"hex"),r=j.Buffer.from(wt);return(0,Z.encodeAddress)(new Uint8Array(j.Buffer.concat([r,t,j.Buffer.alloc(8)])),63)};static fromAccount=e=>{let t=(0,Z.decodeAddress)(e),r=j.Buffer.from(wt),s=t.slice(r.length,-8);return"0x"+j.Buffer.from(s).toString("hex")};static fromSS58=e=>{let r=(0,Z.decodeAddress)(e).slice(0,20);return(0,le.u8aToHex)(r)};static fromAny=e=>{if(Qt(e))return e;if(jt(e))return c.fromAccount(e);if(Jt(e))return c.fromSS58(e);throw new Error("Unknown address type")}};var Oe=require("buffer"),V=class{static fromAssetId(e){let t=Number(e),r=Oe.Buffer.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Oe.Buffer.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Oe.Buffer.from("0000000000000000000000000000000100000000","hex"),r=Oe.Buffer.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};var v=require("bignumber.js"),Zt=12;v.BigNumber.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Zt});var S=p(0),N=p(1),_r=p("Infinity");function I(c,e){let t=new v.BigNumber(e.toString()),r=new v.BigNumber(10).pow(t);return c.times(r).decimalPlaces(4)}function p(c){return new v.BigNumber(c.toString())}function Cr(c,e){let t=p(c);return I(t,e)}function B(c,e){return c.shiftedBy(-1*e).toString()}var Je=p("1e27"),kr=p("1.01"),Dr=p("31536000"),ee=class{client;constructor(e){this.client=new oe(e)}async getSummary(e){let t=Y.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[a,l]=s,[u,m,g,h,d,f]=i,b=p(f).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN),x=p(u),P=p(m),w=[];for(let A of a){let F=A.underlyingAsset.toLowerCase(),T=o.find(({underlyingAsset:Or})=>Or.toLowerCase()===F);if(!T)throw new Error("Missing pool reserve for "+F);let D=p(A.scaledATokenBalance),G=p(T.liquidityIndex),Ve=p(T.liquidityRate),$e=p(T.availableLiquidity),ft=p(T.priceInMarketReferenceCurrency),bt=n+6,Pt=this.calculateLinearInterest(Ve,T.lastUpdateTimestamp,bt),Ke=G.multipliedBy(Pt).dividedBy(Je).decimalPlaces(0,v.BigNumber.ROUND_DOWN),xr=D.multipliedBy(Ke).dividedBy(Je).decimalPlaces(0,v.BigNumber.ROUND_DOWN),Br=p(l!==0&&l===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold).div(1e4),wr=T.usageAsCollateralEnabled&&A.usageAsCollateralEnabledOnUser&&p(A.scaledATokenBalance).gt(0),Tr=V.toAssetId(F);w.push({aTokenBalance:xr,availableLiquidity:$e,decimals:Number(T.decimals),isCollateral:wr,priceInRef:ft,reserveId:Tr,reserveAsset:F,reserveLiquidationThreshold:Br})}return{healthFactor:b.toNumber(),totalCollateral:x,totalDebt:P,reserves:w}}async hasBorrowPositions(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=Y.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,l]=r;return p(l).dividedBy(1e18).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=V.fromAssetId(t),a=n.find(x=>x.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:u,priceInRef:m,reserveLiquidationThreshold:g}=a,h=I(p(r),l).decimalPlaces(0,1),d=u?h.multipliedBy(m).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN):S,f=s.minus(d);return f.lte(0)?0:f.multipliedBy(g).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=V.fromAssetId(t),a=n.find(b=>b.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:m}=a,h=I(p(r),l).decimalPlaces(0,1).multipliedBy(u).dividedBy(p(10).pow(l)).decimalPlaces(0,v.BigNumber.ROUND_DOWN),d=s.plus(h);return d.lte(0)?0:d.multipliedBy(m).dividedBy(i).decimalPlaces(6,v.BigNumber.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=V.fromAssetId(t),o=s.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let o=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:o,reserveLiquidationThreshold:a,isCollateral:l}=e,u=s;if(l&&t.gt(0)){let g=p(r).minus(kr);if(g.gt(0)){let d=g.multipliedBy(t).dividedBy(a).decimalPlaces(0,v.BigNumber.ROUND_DOWN).dividedBy(o).multipliedBy(p(10).pow(n)).decimalPlaces(0,v.BigNumber.ROUND_DOWN);u=v.BigNumber.minimum(s,d)}else u=S}return{amount:v.BigNumber.minimum(u,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Je:e.multipliedBy(s).dividedBy(Dr).plus(Je).decimalPlaces(0,v.BigNumber.ROUND_DOWN)}};function er(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var Rs=require("@galacticcouncil/api-augment/hydradx"),_s=require("@galacticcouncil/api-augment/basilisk"),H=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");er(r)&&console.log(e,...t)}};var te=class extends H{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e=="0"){let m=this.api.consts.balances.existentialDeposit;return{id:"0",name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:m.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:u}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:u,icon:l,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:u,decimals:m}=this.getToken(i.toString(),t,r),g=n.toNumber(),h=new Intl.DateTimeFormat("en-GB"),d=[u,"Bond",h.format(g)].join(" ");return{id:e,name:d,symbol:u+"b",decimals:m,icon:u,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:l,existentialDeposit:u}=t,g=i.map(f=>f.toString()).map(f=>{let{symbol:b}=this.getToken(f,t,r);return[f,b]}),h=Object.fromEntries(g),d=Object.values(h);return{id:e,name:d.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:d.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:u.toString(),meta:h}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,o),u=a.map(([{args:[m]},g])=>{let h=g.unwrap(),d=s.get(m.toString()),{assetType:f}=h;switch(f.toString()){case"Bond":let b=n.get(m.toString());return this.getBond(m.toString(),h,l,b);case"StableSwap":let x=i.get(m.toString());return this.getShares(m.toString(),h,l,x);case"External":return this.getExternal(m.toString(),h,t,d);default:return this.getToken(m.toString(),h,l,d)}});return e?u:u.filter(m=>this.isValidAsset(m))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var U=class extends H{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeSystemBalances(e,t){return this.api.query.system.account.multi(e,r=>{let s=[];r.forEach((i,n)=>{let o=this.calculateFreeBalance(i.data),a=e[n];s.push([a,o])}),t(s)})}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let u=this.calculateFreeBalance(a),m=i[l][1];o.push([m,u])}),t(o)})}async subscribeTokenBalances(e,t){return this.api.query.tokens.accounts.multi(e,r=>{let s=[];r.forEach((i,n)=>{let o=this.calculateFreeBalance(i),a=e[n];s.push([a,o])}),t(s)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:u}=l.unwrap();return u.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async subscribeErc20Balances(e,t){let r=async()=>{let s=await Promise.all(e.map(async i=>{let[n,o]=i;return[i,await this.getErc20Balance(n,o)]}));t(s)};return this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return(0,v.BigNumber)(t).lt(r)?(0,v.BigNumber)(0):(0,v.BigNumber)(t).minus(r)}};var ce=class extends H{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let u=i[l][1],m=this.calculateBalance(a);o.push([u,m])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:u}=l.unwrap();return u.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=(0,v.BigNumber)(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",n=t.plus(s).toString();return{free:t.toString(),total:n,transferable:i,reserved:s,frozen:r}}};var ue=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),p(this._minOrderBudget)}};var Tt=require("@galacticcouncil/math-liquidity-mining"),tr=require("@polkadot/types"),Ot=require("@polkadot/util"),It=require("@polkadot/util-crypto");var Ze=class extends H{balanceClient;constructor(e){super(e),this.balanceClient=new U(e)}secondsInYear=new v.BigNumber(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),u=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),d=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,d);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:m,potBalance:f.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),u=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),m=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),d=l.rewardCurrency.toString(),f=await this.balanceClient.getTokenBalanceData(h,d);return{assetId:e,globalFarm:l,yieldFarm:u,priceAdjustment:m,potBalance:f.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v.BigNumber(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),l;return Number(t)<Number(r)?l=(0,Tt.fixed_from_rational)(o,a):l=(0,Tt.fixed_from_rational)(a,o),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return(0,Ot.u8aConcat)(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new tr.GenericAccountId32(e,this.padEndU8a((0,Ot.u8aConcat)(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!(0,It.isAddress)(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&(0,It.isAddress)(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:u})=>{let m=new v.BigNumber(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),h=new v.BigNumber(a.yieldPerPeriod.toString()),d=new v.BigNumber(a.maxRewardPerPeriod.toString()),f=a.blocksPerPeriod.toString(),b=new v.BigNumber(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new v.BigNumber(r).times(f)),P;if(m.isZero())P=h.times(b).times(x);else{let D=this.getGlobalRewardPerPeriod(m,h,d,l);P=this.getPoolYieldPerPeriod(D,b,m,l).times(x)}let w=new v.BigNumber(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),A=d.times(g),F=u?w.plus(u):A;return w.div(F).gte(.999)?S:P.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var Ie=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},At=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ae=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},Ft=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},Et=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Nt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},Rt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};var rr=require("viem"),Mr=["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"],_t=c=>{let t=[c.endpoint,...Mr],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return(0,rr.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};var Q=require("viem");function sr(c){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return c.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Fe=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=_t(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:(0,Q.http)()})}getWsProvider(){return(0,Q.createPublicClient)({chain:this.chain,transport:sr(this.wsProvider)})}getSigner(e){return(0,Q.createWalletClient)({account:e,chain:this.chain,transport:(0,Q.custom)(window.ethereum)})}};var re=(c,e=new Map)=>t=>{let r;return e.has(t)?e.get(t):(e.set(t,r=c(t)),r)};var _=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n.HSM="Hsm",n))(_||{}),se=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(se||{});var Ee=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return I(N,e.decimalsOut)}spotPriceOutGivenIn(e){return I(N,e.decimalsIn)}calculateTradeFee(e,t){return S}};var pr=require("@polkadot/util-crypto"),dr=require("@polkadot/util"),gr=require("viem");var Ne=(c,e)=>c===e?0:c==null?e==null?0:-1:e==null?c==null?0:1:typeof c.compare=="function"?c.compare(e):typeof e.compare=="function"?-e.compare(c):c<e?-1:c>e?1:0;var et=(c,e=t=>t!==void 0?": "+t:"")=>class extends Error{origMessage;constructor(t){super(c(t)+e(t)),this.origMessage=t!==void 0?String(t):""}};var Lr=et(()=>"illegal argument(s)"),ir=c=>{throw new Lr(c)};var Hr=et(()=>"index out of bounds"),Ct=c=>{throw new Hr(c)},tt=(c,e,t)=>(c<e||c>=t)&&Ct(c);var nr=23283064365386963e-26,rt=class{float(e=1){return this.int()*nr*e}probability(e){return this.float()<e}norm(e=1){return(this.int()*nr-.5)*2*e}normMinMax(e,t){let r=this.minmax(e,t);return this.float()<.5?r:-r}minmax(e,t){return this.float()*(t-e)+e}minmaxInt(e,t){e|=0;let r=(t|0)-e;return r?e+this.int()%r:e}minmaxUint(e,t){e>>>=0;let r=(t>>>0)-e;return r?e+this.int()%r:e}};var st=class extends rt{constructor(e){super(),this.rnd=e}float(e=1){return this.rnd()*e}norm(e=1){return(this.rnd()-.5)*2*e}int(){return this.rnd()*4294967296>>>0}};var ar=new st(Math.random);var or=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var lr=Object.getPrototypeOf({}),it="function",cr="string",me=(c,e)=>{let t;if(c===e)return!0;if(c!=null){if(typeof c.equiv===it)return c.equiv(e)}else return c==e;if(e!=null){if(typeof e.equiv===it)return e.equiv(c)}else return c==e;return typeof c===cr||typeof e===cr?!1:(t=Object.getPrototypeOf(c),(t==null||t===lr)&&(t=Object.getPrototypeOf(e),t==null||t===lr)?Wr(c,e):typeof c!==it&&c.length!==void 0&&typeof e!==it&&e.length!==void 0?qr(c,e):c instanceof Set&&e instanceof Set?Gr(c,e):c instanceof Map&&e instanceof Map?Ur(c,e):c instanceof Date&&e instanceof Date?c.getTime()===e.getTime():c instanceof RegExp&&e instanceof RegExp?c.toString()===e.toString():c!==c&&e!==e)},qr=(c,e,t=me)=>{let r=c.length;if(r===e.length)for(;r-- >0&&t(c[r],e[r]););return r<0},Gr=(c,e,t=me)=>c.size===e.size&&t([...c.keys()].sort(),[...e.keys()].sort()),Ur=(c,e,t=me)=>c.size===e.size&&t([...c].sort(),[...e].sort()),Wr=(c,e,t=me)=>{if(Object.keys(c).length!==Object.keys(e).length)return!1;for(let r in c)if(!e.hasOwnProperty(r)||!t(c[r],e[r]))return!1;return!0};var kt=class{value;constructor(e){this.value=e}deref(){return this.value}};var ur=c=>c instanceof kt;var nt=class c{_head;_length=0;constructor(e){e&&this.into(e)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return mr("next",this._head)}reverseIterator(){return mr("prev",this.tail)}clear(){this.release()}compare(e,t=Ne){let r=this._length;if(r<e._length)return-1;if(r>e._length)return 1;if(r===0)return 0;{let s=this._head,i=e._head,n=0;for(;r-- >0&&n===0;)n=t(s.value,i.value),s=s.next,i=i.next;return n}}concat(...e){let t=this.copy();for(let r of e)t.into(r);return t}equiv(e){if(!(e instanceof c||or(e))||this._length!==e.length)return!1;if(!this._length||this===e)return!0;let t=e[Symbol.iterator](),r=this._head;for(let s=this._length;s-- >0;){if(!me(r.value,t.next().value))return!1;r=r.next}return!0}filter(e){let t=this.empty();return this.traverse(r=>(e(r.value)&&t.append(r.value),!0)),t}find(e){return this.traverse(t=>t.value!==e)}findWith(e){return this.traverse(t=>!e(t.value))}first(){return this._head?.value}insertSorted(e,t){t=t||Ne;for(let r=this._head,s=this._length;s-- >0;){if(t(e,r.value)<=0)return this.insertBefore(r,e);r=r.next}return this.append(e)}into(e){for(let t of e)this.append(t);return this}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCellUnsafe(e){let t,r;for(e<=this._length>>>1?(t=this._head,r="next"):(t=this.tail,r="prev",e=this._length-e-1);e-- >0&&t;)t=t[r];return t}peek(){return this.tail?.value}$reduce(e,t){let r=this._head;for(let s=this._length;s-- >0&&!ur(t);)t=e(t,r.value),r=r.next;return t}reduce(e,t){return this.$reduce(e,t)}release(){let e=this._head;if(!e)return!0;let t;for(let r=this._length;r-- >0;)t=e.next,delete e.value,delete e.prev,delete e.next,e=t;return this._head=void 0,this._length=0,!0}reverse(){let e=this._head,t=this.tail,r=(this._length>>>1)+(this._length&1);for(;e&&t&&r>0;){let s=e.value;e.value=t.value,t.value=s,e=e.next,t=t.prev,r--}return this}setHead(e){let t=this._head;return t?(t.value=e,t):this.prepend(e)}setNth(e,t){let r=this.nthCell(e);return!r&&Ct(e),r.value=t,r}setTail(e){let t=this.tail;return t?(t.value=e,t):this.append(e)}swap(e,t){if(e!==t){let r=e.value;e.value=t.value,t.value=r}return this}toArray(e=[]){return this.traverse(t=>(e.push(t.value),!0)),e}toJSON(){return this.toArray()}toString(){let e=[];return this.traverse(t=>(e.push(String(t.value)),!0)),e.join(", ")}traverse(e,t=this._head,r){if(!this._head)return;let s=t;do{if(!e(s))break;s=s.next}while(s!==r);return s}_map(e,t){return this.traverse(r=>(e.append(t(r.value)),!0)),e}};function*mr(c,e){for(;e;)yield e.value,e=e[c]}var at=class c extends nt{_tail;constructor(e){super(),e&&this.into(e)}get tail(){return this._tail}append(e){if(this._tail){let t={value:e,prev:this._tail};return this._tail.next=t,this._tail=t,this._length++,t}else return this.prepend(e)}asHead(e){return e===this._head?this:(this.remove(e),this._head.prev=e,e.next=this._head,e.prev=void 0,this._head=e,this._length++,this)}asTail(e){return e===this._tail?this:(this.remove(e),this._tail.next=e,e.prev=this._tail,e.next=void 0,this._tail=e,this._length++,this)}cons(e){return this.prepend(e),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let e=this._head;if(e)return this._head=e.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,e.value}empty(){return new c}insertAfter(e,t){let r={value:t,next:e.next,prev:e};return e.next?e.next.prev=r:this._tail=r,e.next=r,this._length++,r}insertAfterNth(e,t){return e<0&&(e+=this._length),e>=this._length-1?this.append(t):(tt(e,0,this._length),this.insertAfter(this.nthCellUnsafe(e),t))}insertBefore(e,t){let r={value:t,next:e,prev:e.prev};return e.prev?e.prev.next=r:this._head=r,e.prev=r,this._length++,r}insertBeforeNth(e,t){return e<0&&(e+=this._length),e<=0?this.prepend(t):(tt(e,0,this._length),this.insertBefore(this.nthCellUnsafe(e),t))}map(e){return this._map(new c,e)}nth(e,t){let r=this.nthCell(e);return r?r.value:t}nthCell(e){if(e<0&&(e+=this._length),!(e<0||e>=this._length))return this.nthCellUnsafe(e)}pop(){let e=this._tail;if(e)return this._tail=e.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,e.value}prepend(e){let t={value:e,next:this._head};return this._head?this._head.prev=t:this._tail=t,this._head=t,this._length++,t}push(e){return this.append(e),this}release(){return this._tail=void 0,super.release()}remove(e){return e.prev?e.prev.next=e.next:this._head=e.next,e.next?e.next.prev=e.prev:this._tail=e.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let e=this.peek();return this.pop(),this.prepend(e),this}}seq(e=0,t=this.length){if(e>=t||e<0)return;let r=this.nthCell(e),s=this.nthCell(t-1),i=n=>({first(){return n.value},next(){return n!==s&&n.next?i(n.next):void 0}});return r?i(r):void 0}shuffle(e,t=ar){if(this._length<2)return this;for(e=e!==void 0?e:Math.ceil(1.5*Math.log2(this._length));e>0;e--){let r=this._head;for(;r;){let s=r.next;t.probability(.5)?this.asHead(r):this.asTail(r),r=s}}return this}slice(e=0,t=this.length){let r=e<0?e+this._length:e,s=t<0?t+this._length:t;(r<0||s<0)&&ir("invalid indices: ${from} / ${to}");let i=new c,n=this.nthCell(r);for(;n&&++r<=s;)i.push(n.value),n=n.next;return i}sort(e=Ne){if(!this._length)return this;let t=1;for(;;){let r=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;r;){s++;let i=r,n=0;for(let a=0;a<t&&(n++,i=i.next,!!i);a++);let o=t;for(;n>0||o>0&&i;){let a;n===0?(a=i,i=i.next,o--):!i||o===0||e(r.value,i.value)<=0?(a=r,r=r.next,n--):(a=i,i=i.next,o--),this._tail?this._tail.next=a:this._head=a,a.prev=this._tail,this._tail=a}r=i}if(this._tail.next=void 0,s<=1)return this;t*=2}}splice(e,t=0,r){let s;typeof e=="number"?(e<0&&(e+=this._length),tt(e,0,this._length),s=this.nthCellUnsafe(e)):s=e;let i=new c;if(t>0)for(;s&&t-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(r)if(s)for(let n of r)this.insertBefore(s,n);else for(let n of r)this.push(n);return i}};var ot=class c{map;items;opts;_size;constructor(e,t){let r={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...t};this.map=r.map(),this.items=new at,this._size=0,this.opts=r,e&&this.into(e)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let e of this.items)yield[e.k,e]}*keys(){for(let e of this.items)yield e.k}*values(){for(let e of this.items)yield e.v}copy(){let e=this.empty();e.items=this.items.copy();let t=e.items.head;for(;t;)e.map.set(t.value.k,t),t=t.next;return e}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let e=this.opts.release;if(e){let t;for(;t=this.items.drop();)e(t.k,t.v);return!0}return this.items.release()}has(e){return this.map.has(e)}get(e,t){let r=this.map.get(e);return r?this.resetEntry(r):t}set(e,t){let r=this.opts.ksize(e)+this.opts.vsize(t),s=this.map.get(e),i=Math.max(0,r-(s?s.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(s,e,t,r):this._size-=i,t}into(e){for(let t of e)this.set(t[0],t[1]);return this}async getSet(e,t){let r=this.map.get(e);return r?this.resetEntry(r):this.set(e,await t())}delete(e){let t=this.map.get(e);return t?(this.removeEntry(t),!0):!1}resetEntry(e){return this.items.asTail(e),e.value.v}ensureSize(){let{release:e,maxsize:t,maxlen:r}=this.opts;for(;this._size>t||this.length>=r;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),e?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(e){let t=e.value;this.map.delete(t.k),this.items.remove(e),this.opts.release?.(t.k,t.v),this._size-=t.s}doSetEntry(e,t,r,s){e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,this.items.asTail(e)):(this.items.push({k:t,v:r,s}),this.map.set(t,this.items.tail))}};var pe=class c extends ot{constructor(e,t){super(e,{ttl:3600*1e3,autoExtend:!1,...t})}empty(){return new c(null,this.opts)}has(e){return this.get(e)!==void 0}get(e,t){let r=this.map.get(e);if(r){if(r.value.t>=Date.now())return this.resetEntry(r);this.removeEntry(r)}return t}set(e,t,r=this.opts.ttl){let s=this.opts.ksize(e)+this.opts.vsize(t),i=this.map.get(e),n=Math.max(0,s-(i?i.value.s:0));return this._size+=n,this.ensureSize()?this.doSetEntry(i,e,t,s,r):this._size-=n,t}async getSet(e,t,r=this.opts.ttl){let s=this.get(e);return s!==void 0?s:this.set(e,await t(),r)}prune(){let e=Date.now(),t=this.items.head,r=0;for(;t;)t.value.t<e&&(this.removeEntry(t),r++),t=t.next;return r}ensureSize(){let{maxlen:e,maxsize:t}=this.opts,r=Date.now(),s=this.items.head;for(;s&&(this._size>t||this.length>=e);)s.value.t<r&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(e,t,r,s,i=this.opts.ttl){let n=Date.now()+i;e?(this.opts.update?.(t,e.value.v,r),e.value.v=r,e.value.s=s,e.value.t=n,this.items.asTail(e)):(this.items.push({k:t,v:r,s,t:n,ttl:i}),this.map.set(t,this.items.tail))}resetEntry(e){return this.opts.autoExtend&&(e.value.t=Date.now()+e.value.ttl),super.resetEntry(e)}};var Dt=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var Re=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:Dt,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:Dt,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,o,a,l]=r,u=i.number-(i.timestamp-l)/BigInt(t),m=Number(u);return{price:o,decimals:s,updatedAt:m<0?0:m}}};var q=class extends U{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new pe(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=re(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new Re(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(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();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=[],t=[],r=[],s=[];for(let o of this.augmentedPools){let{address:a,tokens:l}=o;l.filter(u=>u.id==="0").forEach(()=>{e.push(a)}),l.filter(u=>u.type==="Token"&&u.id!=="0"&&u.id!==o.id).forEach(u=>{t.push([a,u.id])}),l.filter(u=>u.type==="Erc20").forEach(u=>{r.push([a,u.id])})}let i=o=>{o.forEach(([a,l])=>{let u=this.pools.find(m=>m.address===a);if(u){let m=u.tokens.findIndex(g=>g.id==="0");u.tokens[m].balance=l.toString()}})},n=o=>{o.forEach(([a,l])=>{let[u,m]=a,g=this.pools.find(h=>h.address===u);if(g){let h=g.tokens.findIndex(d=>d.id===m);g.tokens[h].balance=l.toString()}})};if(e.length>0){let o=await this.subscribeSystemBalances(e,i);s.push(o)}if(t.length>0){let o=await this.subscribeTokenBalances(t,n);s.push(o)}if(r.length>0){let o=await this.subscribeErc20Balances(r,n);s.push(o)}return()=>{for(let o of s)try{o()}catch(a){console.warn("Balance unsub failed",a)}}}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}};function _e(c,e){let t=[];return JSON.stringify(c,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function zr(c,e,t){let r;return JSON.stringify(c,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Xr=(c,e)=>typeof e=="bigint"?e.toString():e;var Yr=["Supply","Withdraw","Repay","Borrow"],Ce=class extends q{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return(0,pr.encodeAddress)((0,dr.stringToU8a)(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?_e(e.location,"accountKey20").accountKey20.key:V.fromAssetId(e.id)}isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,n]=r.data.toJSON();this.pools.filter(o=>o.tokens.some(a=>a.id===i.toString()||a.id===n.toString())).forEach(o=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${n}`),this.updatePoolState(o)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:o}=(0,gr.decodeEventLog)({abi:je,topics:i.topics,data:i.data});if(Yr.includes(n)){let a=o.reserve.toLowerCase();this.pools.filter(l=>{let[u]=l.tokens;return this.getReserveH160Id(u).toLowerCase()===a}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${n} ${a}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}};var $=require("@galacticcouncil/math-lbp"),X=class{static getSpotPrice(e,t,r,s,i){return(0,$.get_spot_price)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return(0,$.calculate_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return(0,$.calculate_out_given_in)(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return(0,$.calculate_linear_weights)(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return(0,$.calculate_pool_trade_fee)(e,t,r)}};var y=class c{static toPct(e){let[t,r]=e;return c.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return c.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var ke=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new c(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),a=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),u=this.calculateInGivenOut(e,l),m=e.balanceIn.div(this.maxInRatio);return u.isGreaterThan(m)&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),u=o.minus(a),m=e.balanceOut.div(this.maxOutRatio);return u.isGreaterThan(m)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:u,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=X.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=X.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=X.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),I(N,e.decimalsOut).toString());return p(t)}spotPriceOutGivenIn(e){let t=X.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),I(N,e.decimalsIn).toString());return p(t)}calculateTradeFee(e,t){let r=X.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return p(r)}};var De=class extends q{MAX_FINAL_WEIGHT=I(p(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:u}=t,m=X.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[g,h]=n,d=g.toString(),f=p(m),b=h.toString(),x=this.MAX_FINAL_WEIGHT.minus(p(f)),[P,w,A]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),u.toString()),this.getBalance(e,d),this.getBalance(e,b)]);return{repayFeeApply:P,tokens:[{id:d,weight:f,balance:w.toString()},{id:b,weight:x,balance:A.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t>=r&&t<s}async isRepayFeeApplied(e,t,r){let s=p(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,n])=>this.isActivePool(n.unwrap(),r.toNumber())).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,o,r.toString());this.poolsData.set(i.toString(),o);let[u,m]=o.fee;return{address:a,type:"Lbp",fee:y.fromRate(u.toNumber(),m.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let n=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,n)}else{let n=this.pools.findIndex(o=>o.address==r.address);this.pools.splice(n,1)}})})}};var O=require("@galacticcouncil/math-omnipool");var E=class{static calculateSpotPrice(e,t,r,s){return(0,O.calculate_spot_price)(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return(0,O.calculate_lrna_spot_price)(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,l){return(0,O.calculate_in_given_out)(e,t,r,s,i,n,o,a,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return(0,O.calculate_lrna_in_given_out)(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,l){return(0,O.calculate_out_given_in)(e,t,r,s,i,n,o,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return(0,O.calculate_out_given_lrna_in)(e,t,r,s,i)}static calculateShares(e,t,r,s){return(0,O.calculate_shares)(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_out)(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return(0,O.calculate_liquidity_lrna_out)(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=(0,v.BigNumber)(t),n=(0,v.BigNumber)(e),o=(0,v.BigNumber)(s),l=(0,v.BigNumber)(r).shiftedBy(-18);if(i.div(o).lt(l)){let m=l.times(o).minus(i).times(n),g=i.times((0,v.BigNumber)(1).minus(l));return m.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return(0,O.calculate_liquidity_hub_in)(e,t,r,s)}static isSellAllowed(e){return(0,O.is_sell_allowed)(e)}static isBuyAllowed(e){return(0,O.is_buy_allowed)(e)}static isAddLiquidityAllowed(e){return(0,O.is_add_liquidity_allowed)(e)}static isRemoveLiquidityAllowed(e){return(0,O.is_remove_liquidity_allowed)(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,l,u,m){return(0,O.recalculate_asset_fee)(e,t,r,s,i,n,o,a,l,u,m)}static recalculateProtocolFee(e,t,r,s,i,n,o,a,l,u,m){return(0,O.recalculate_protocol_fee)(e,t,r,s,i,n,o,a,l,u,m)}static verifyAssetCap(e,t,r,s){return(0,O.verify_asset_cap)(e,t,r,s)}};var Me=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new c(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let m=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(m)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let m=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(m)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=E.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=E.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=E.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=E.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=p(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=E.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=E.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=E.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=E.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return p(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};var fr=require("@polkadot/util-crypto"),br=require("@polkadot/util");var hr="omnipool",yr="Short",Le=class extends q{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new pe(null,{ttl:6*1e3});memOracleQuery=re(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(hr,t,yr)},this.memQueryCache);memFeesQuery=re(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=re(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return(0,fr.encodeAddress)((0,br.stringToU8a)("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[a]},l])=>{let{hubReserve:u,shares:m,tradable:g,cap:h,protocolShares:d}=l.unwrap(),f=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:p(u.toString()),shares:p(m.toString()),tradeable:g.bits.toNumber(),balance:f.toString(),cap:p(h.toString()),protocolShares:p(d.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,n;if(this.isAssetConfigSupported()&&(n=await this.getDynamicFeesConfiguration(s).then(P=>P.unwrapOr(null))),n?.isFixed){let P=n.asFixed.assetFee.toNumber(),w=n.asFixed.protocolFee.toNumber();return{assetFee:y.fromPermill(P),protocolFee:y.fromPermill(w)}}let[o,a,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[u,m,g]=this.getAssetFee(t,e,o,a,n?.isDynamic?n.asDynamic.assetFeeParams:void 0),[h,d,f]=i==="1"?[0,0,0]:this.getProtocolFee(t,e,o,l,n?.isDynamic?n.asDynamic.protocolFeeParams:void 0),b=u+h,x=g+f;return{assetFee:y.fromPermill(m),protocolFee:y.fromPermill(d),min:y.fromPermill(b),max:y.fromPermill(x)}}getAssetFee(e,t,r,s,i){let{assetOut:n,balanceOut:o}=e,{minFee:a,maxFee:l,decay:u,amplification:m}=i||this.api.consts.dynamicFees.assetFeeParameters,g=y.fromPermill(a.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[d]=s.unwrap(),{assetFee:f,timestamp:b}=r.unwrap(),x=Math.max(1,t-b.toNumber()),P=d.volume.bIn.toString(),w=d.volume.bOut.toString(),A=d.liquidity.b.toString();n==="0"&&(P=d.volume.aIn.toString(),w=d.volume.aOut.toString(),A=d.liquidity.a.toString());let F=y.fromPermill(f.toNumber()),T=E.recalculateAssetFee(P,w,A,"9",o.toString(),y.toRaw(F).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),u.toString(),m.toString());return[a.toNumber(),Number(T)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:n,balanceIn:o}=e,{minFee:a,maxFee:l,decay:u,amplification:m}=i||this.api.consts.dynamicFees.protocolFeeParameters,g=y.fromPermill(a.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[d]=s.unwrap(),{protocolFee:f,timestamp:b}=r.unwrap(),x=Math.max(1,t-b.toNumber()),P=d.volume.bIn.toString(),w=d.volume.bOut.toString(),A=d.liquidity.b.toString();n==="0"&&(P=d.volume.aIn.toString(),w=d.volume.aOut.toString(),A=d.liquidity.a.toString());let F=y.fromPermill(f.toNumber()),T=E.recalculateProtocolFee(P,w,A,"9",o.toString(),y.toRaw(F).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),u.toString(),m.toString());return[a.toNumber(),Number(T)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,u)=>{let m=e.tokens[u];if(l.isNone)return m;let g=l.unwrap();return this.updateTokenState(m,g)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,u)=>{let m=t[u];this.dynamicFees.set(m,l)})});if(r.push(i),this.isAssetConfigSupported()){let a=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((u,m)=>{let g=t[m];this.dynamicFeesConfiguration.set(g,u)})});r.push(a)}let n=t.map(a=>{let l=this.getOracleKey(a);return[hr,l,yr]}),o=await this.api.query.emaOracle.oracles.multi(n,a=>{a.forEach(async(l,u)=>{let m=n[u],[g,h,d]=m;this.oracles.set(h.join(":"),l)})});return r.push(o),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:p(r.toString()),shares:p(s.toString()),cap:p(n.toString()),protocolShares:p(o.toString()),tradeable:i.bits.toNumber()}}};var C=require("@galacticcouncil/math-xyk"),J=class{static getSpotPrice(e,t,r){return(0,C.get_spot_price)(e,t,r)}static calculateInGivenOut(e,t,r){return(0,C.calculate_in_given_out)(e,t,r)}static calculateOutGivenIn(e,t,r){return(0,C.calculate_out_given_in)(e,t,r)}static calculatePoolTradeFee(e,t,r){return(0,C.calculate_pool_trade_fee)(e,t,r)}static calculateLiquidityIn(e,t,r){return(0,C.calculate_liquidity_in)(e,t,r)}static calculateSpotPrice(e,t){return(0,C.calculate_spot_price)(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return(0,C.calculate_spot_price_with_fee)(e,t,r,s)}static calculateShares(e,t,r){return(0,C.calculate_shares)(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return(0,C.calculate_liquidity_out_asset_a)(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return(0,C.calculate_liquidity_out_asset_b)(e,t,r,s)}};var He=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new c(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let u=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(u)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let u=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(u)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let r=J.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=J.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=p(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=J.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=I(N,18-e.decimalsOut);return p(t).div(r)}spotPriceOutGivenIn(e){let t=J.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=I(N,18-e.decimalsIn);return p(t).div(r)}calculateTradeFee(e,t){let r=J.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return p(r)}};var qe=class extends q{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};var k=require("@galacticcouncil/math-stableswap"),M=class{static getPoolAddress(e){return(0,k.pool_account_name)(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return(0,k.calculate_amplification)(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,o){return(0,k.calculate_in_given_out)(e,t,r,s,i,n,o)}static calculateAddOneAsset(e,t,r,s,i,n,o){return(0,k.calculate_add_one_asset)(e,t,r,s,i,n,o)}static calculateSharesForAmount(e,t,r,s,i,n,o){return(0,k.calculate_shares_for_amount)(e,t,r,s,i,n,o)}static calculateOutGivenIn(e,t,r,s,i,n,o){return(0,k.calculate_out_given_in)(e,t,r,s,i,n,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,o){return(0,k.calculate_liquidity_out_one_asset)(e,t,r,s,i,n,o)}static calculateShares(e,t,r,s,i,n){return(0,k.calculate_shares)(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,o,a){return(0,k.calculate_spot_price_with_fee)(e,t,r,s,i,n,o,a)}static recalculatePegs(e,t,r,s,i){let n=(0,k.recalculate_peg)(e,t,r,s,i);return JSON.parse(n)}};var ae=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new c(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(u=>[u.id,u])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=p(s.balance),o=p(i.balance),a=p(s.existentialDeposit),l=p(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);return(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=E.isSellAllowed(e.tradeableIn),u=E.isBuyAllowed(e.tradeableOut);return(!l||!u)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateIn(e,t,r){let s=M.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=M.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=M.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=M.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return p(t);if(e.assetIn==this.id){let s=I(N,e.decimalsIn-e.decimalsOut);return p(t).div(s).decimalPlaces(0,1)}let r=I(N,18-e.decimalsIn);return p(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=M.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=M.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=M.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=p(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=M.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return p(t);if(e.assetOut==this.id){let s=I(N,e.decimalsOut-e.decimalsIn);return p(t).div(s).decimalPlaces(0,1)}let r=I(N,18-e.decimalsOut);return p(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};var lt=require("@polkadot/util-crypto");var Ge=class extends q{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=M.getPoolAddress(t);return(0,lt.encodeAddress)((0,lt.blake2AsHex)(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=M.calculateAmplification(s.toString(),i.toString(),n.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async n=>{let[o,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:o.bits.toNumber(),balance:a.toString()}});return Promise.all(i)}isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},o])=>{try{let a=o.unwrap(),l=n.toString(),u=this.getPoolAddress(l),[m,g,h]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(u,l,a),this.getPoolPegs(l,a,r.toString())]);return g.push({id:l,tradeable:15,balance:m.totalIssuance}),this.poolsData.set(u,a),{address:u,id:l,type:"Stableswap",fee:y.fromPermill(a.fee.toNumber()),tokens:g,...m,...h,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${n.toString()}
|
|
2
|
+
`,String(a)),null}});return(await Promise.all(s)).filter(n=>n!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=y.fromPermill(i.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[u,m]=M.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,y.toRaw(a).toString(),y.toRaw(l).toString()),g=Number(u)*1e6;return{pegsFee:y.fromPermill(g),pegs:m}}getDefaultPegs(e){let t=e.fee,r=M.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=s.map(async(o,a)=>{if(o.isOracle){let[l,u,m]=o.asOracle,g=[m.toString(),i[a]].map(P=>Number(P)).sort((P,w)=>P-w),h=await this.api.query.emaOracle.oracles(l,g,u),[{price:d,updatedAt:f}]=h.unwrap(),b=d.n.toString(),x=d.d.toString();return m.toString()===g[0].toString()?[[b,x],f.toString()]:[[x,b],f.toString()]}else if(o.isMmOracle){let l=o.asMmOracle,{price:u,decimals:m,updatedAt:g}=await this.mmOracle.getData(l.toString()),h=10**m;return[[u.toString(),h.toString()],g.toString()]}else{if(o.isValue)return[o.asValue.map(l=>l.toString()),r];throw Error(o.type+" is not supported")}});return Promise.all(n)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[i,n]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),o=r.tokens.map(a=>a.id===r.id?{...a,balance:i.totalIssuance}:a);Object.assign(r,{tokens:o},i,n)}})})}};var L=require("@galacticcouncil/math-hsm"),K=class{static calculateCollateralInGivenHollarOut(e,t,r){return(0,L.calculate_collateral_in_given_hollar_out)(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return(0,L.calculate_collateral_out_given_hollar_in)(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return(0,L.calculate_hollar_out_given_collateral_in)(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return(0,L.calculate_hollar_in_given_collateral_out)(e,t,r)}static calculateImbalance(e,t,r){return(0,L.calculate_imbalance)(e,t,r)}static calculateBuybackLimit(e,t){return(0,L.calculate_buyback_limit)(e,t)}static calculateBuybackPriceWithFee(e,t,r){return(0,L.calculate_buyback_price_with_fee)(e,t,r)}static calculateMaxPrice(e,t){return(0,L.calculate_max_price)(e,t)}};var ct=class c extends ae{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new c(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let n=this.calculateBuyPrice(e,t,r),o=this.calculateMaxPrice(e);return n.gt(o)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=K.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=K.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return p(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=K.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return p(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=K.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return p(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=K.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return p(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=K.calculateBuybackLimit(t.toString(),y.toRaw(this.buyBackRate).toString());return p(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(p(10).pow(e.decimalsIn));return r.dividedBy(p(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=K.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return p(s).div(p(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=I(N,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=I(N,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[I(N,18).toString(),I(N,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};var Mt=require("@polkadot/util"),Lt=require("@polkadot/util-crypto"),Pr=require("viem");var Ue=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var We=class{client;constructor(e){this.client=e.getWsProvider()}async getFacilitatorCapacity(e,t){let[r,s]=await this.client.readContract({abi:Ue,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var Vr=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],ut=class extends q{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new We(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return(0,Lt.encodeAddress)((0,Mt.stringToU8a)(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return(0,Lt.encodeAddress)((0,Mt.stringToU8a)("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return _e(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),n=Y.fromAny(i),o=this.getHollarAddress(t.unwrap()),a=await this.ghoTokenClient.getFacilitatorCapacity(o,n),l=r.map(async([{args:[m]},g])=>{let h=g.unwrap(),d=m.toString(),{poolId:f,maxBuyPriceCoefficient:b,maxInHolding:x,purchaseFee:P,buyBackFee:w,buybackRate:A}=h,F=s.find(T=>T.id===f.toString());if(F){let T=this.getPoolId(f.toString()),D=await this.getBalance(i,d);return{...F,address:T,type:"Hsm",tokens:F.tokens.filter(G=>G.id!==f.toString()),hsmAddress:i,hsmMintCapacity:p(a),hollarId:e,hollarH160:o,collateralId:d,collateralBalance:D,maxBuyPriceCoefficient:p(b.toString()),maxInHolding:p(x.unwrap().toString()),purchaseFee:y.fromPermill(P.toNumber()),buyBackFee:y.fromPermill(w.toNumber()),buyBackRate:y.fromPerbill(A.toNumber())}}});return(await Promise.all(l)).filter(m=>m!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:o}=(0,Pr.decodeEventLog)({abi:Ue,topics:i.topics,data:i.data}),[a]=this.pools,{hsmAddress:l,hollarH160:u}=a,m=Y.fromAny(l),g=m.toLowerCase()===o.facilitatorAddress.toLowerCase();if(Vr.includes(n)&&g){let h=await this.ghoTokenClient.getFacilitatorCapacity(u,m);this.log(`Sync HSM facilitator via [evm:Log] :: ${n} ${h}`),this.pools.forEach(d=>{Object.assign(d,{hsmMintCapacity:h})})}}catch{}}})}async subscribeBalances(){let e=[],t=[],r=[];for(let i of this.pools){let{tokens:n,hsmAddress:o,collateralId:a}=i;n.find(u=>u.id===a).type==="Erc20"?t.push([o,a]):e.push([o,a])}let s=i=>{i.forEach(([n,o])=>{let[a,l]=n,u=this.pools.find(m=>m.tokens.some(g=>g.id===l));u&&Object.assign(u,{collateralBalance:o})})};if(e.length>0){let i=await this.subscribeTokenBalances(e,s);r.push(i)}if(t.length>0){let i=await this.subscribeErc20Balances(t,s);r.push(i)}return()=>{for(let i of r)try{i()}catch(n){console.warn("Balance unsub failed",n)}}}async subscribeUpdates(){return()=>{}}};var de=class extends H{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=re(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new te(this.api),this.aaveClient=new Ce(this.api,t),this.xykClient=new qe(this.api,t),this.omniClient=new Le(this.api,t),this.lbpClient=new De(this.api,t),this.stableClient=new Ge(this.api,t),this.hsmClient=new ut(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Ie(t.type)}}};var ge=class extends de{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var he=class{static get(e){switch(e.type){case"Aave":return Ee.fromPool(e);case"Xyk":return He.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return ke.fromPool(e);case"Stableswap":return ae.fromPool(e);case"Hsm":return ct.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};var Sr=require("@noble/hashes/sha256"),vr=require("@noble/hashes/utils");function Ht(c){let e=c.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=(0,Sr.sha256)(t);return(0,vr.bytesToHex)(r)}var ze=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $r=8,Xe=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new ze,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(!o||o.length>$r)continue;let a=o[o.length-1];(r===null||a[0]===r)&&s.push(o),e.get(a[0])?.forEach(u=>{if(this.isNotVisited(u,o)){let m=[...o];m.push(u),i.enqueue(m)}})}return s}findShortestPaths(e,t,r){let s=[],i=new ze,n=[];n.push([t,""]),i.enqueue(n);let o=1/0;for(;i.size()>0;){let a=i.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<o?(o=a.length,s.length=0,s.push(a)):a.length===o&&s.push(a);continue}let u=e.get(l[0]);for(let m of u??[])this.isNotVisited(m,a)&&i.enqueue([...a,m])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let o=parseInt(i),a=parseInt(n);r.get(o)?.push([a,s])}return r}};function qt(c){let e={};for(let t of c){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var Ye=class{getProposals(e,t,r){let s=r.filter(P=>P.type==="Xyk"),i=r.filter(P=>P.type!=="Xyk"),n=parseInt(e),o=parseInt(t),a=new Set(i.map(P=>P.tokens).flat().map(P=>P.id)),l=a.has(e),u=a.has(t),m=new Xe,g=P=>{let w=qt(P),A=Object.keys(w),F=A.flatMap(T=>w[T]);return m.buildAndPopulateGraph(A,F)};if(!l&&!u){let P=s.filter(F=>F.tokens.find(T=>T.id===e)||F.tokens.find(T=>T.id===t)),w=g(P),A=m.findPaths(w,n,o);return this.parsePaths(A)}if(l&&u){let P=g(i),w=m.findPaths(P,n,o);return this.parsePaths(w)}let h=l?t:e,d=s.filter(P=>P.tokens.some(w=>w.id===h)),f=[...i,...d],b=g(f),x=m.findPaths(b,n,o);return this.parsePaths(x)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(n,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ye=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new Ye,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}getProposals(e,t,r){let s=`${e}->${t}::${Ht(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,he.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}};var Kr=p("100");function jr(c,e){return c.minus(e).abs().div(c.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function fe(c,e){return c.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Gt(c,e){return N.minus(e.div(c)).multipliedBy(100).decimalPlaces(4)}function Ut(c,e){return e.div(c).minus(N).multipliedBy(100).decimalPlaces(4)}function ie(c,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),c.div(Kr).multipliedBy(e).decimalPlaces(0,1)}var mt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(mt||{}),pt=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(pt||{}),Wt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Wt||{});var be=class extends ye{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Ae(e,t);return{paths:i,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toSellSwaps(r,s,n);else{let a=i.map(async u=>await this.toSellSwaps(r,u,n)),l=await Promise.all(a);o=this.findBestSellRoute(l)}return this.buildSell(n,o)}async getSellTrades(e,t,r){let{paths:s,poolsMap:i}=await this.loadRouteContext(e,t),n=s.map(async a=>await this.toSellSwaps(r,a,i));return(await Promise.all(n)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildSell(i,a)).sort((a,l)=>a.amountOut.isGreaterThan(l.amountOut)?-1:1)}buildSell(e,t){let r=t[0],s=t[t.length-1],i=this.isDirectTrade(t),n=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetOutDecimals)).reduce((f,b)=>f.multipliedBy(b)),o=I(n,s.assetOutDecimals),a=i?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,u=i?s.tradeFeePct:Gt(a,l).toNumber(),m=a.minus(l),g=this.getRouteFeeRange(t),h=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(o),d=fe(a,h);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:o,tradeFee:m,tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:B(r.amountIn,r.assetInDecimals),amountOut:B(s.amountOut,s.assetOutDecimals),spotPrice:B(o,s.assetOutDecimals),tradeFee:B(m,s.assetOutDecimals),tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t.map(f=>f.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1]:l=e;let u=o.calculateOutGivenIn(a,l);s.push(u)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1].amountOut:l=I(p(e),a.decimalsIn).decimalPlaces(0,1);let u=await this.poolService.getPoolFees(a,o),{amountOut:m,calculatedOut:g,feePct:h,errors:d}=o.validateAndSell(a,l,u),f=this.getPoolFeeRange(u),b=o.spotPriceOutGivenIn(a),x=l.shiftedBy(-1*a.decimalsIn).multipliedBy(b),P=fe(g,x);s.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:m,calculatedOut:g,spotPrice:b,tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:B(l,a.decimalsIn),amountOut:B(m,a.decimalsOut),calculatedOut:B(g,a.decimalsOut),spotPrice:B(b,a.decimalsOut),tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P.toNumber(),errors:d}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(h=>h.tokens.some(d=>d.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(d=>d.id===e)).map(h=>h.map(d=>p(d.balance).shiftedBy(-1*d.decimals)).reduce((d,f)=>d.plus(f))).sort((h,d)=>d.isLessThan(h)?-1:1)[0].div(100).multipliedBy(.1),u=r.map(async h=>await this.toSellSwaps(l,h,i)),m=await Promise.all(u);return this.findBestSellRoute(m).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,s),o=n.map(u=>u.spotPrice.shiftedBy(-1*u.assetOutDecimals)).reduce((u,m)=>u.multipliedBy(m)),a=n[n.length-1].assetOutDecimals;return{amount:I(o,a),decimals:a}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toBuySwaps(r,s,n);else{let a=i.map(async u=>await this.toBuySwaps(r,u,n)),l=await Promise.all(a);o=this.findBestBuyRoute(l)}return this.buildBuy(n,o)}async getBuyTrades(e,t,r){let{paths:s,poolsMap:i}=await this.loadRouteContext(e,t),n=s.map(async a=>await this.toBuySwaps(r,a,i));return(await Promise.all(n)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildBuy(i,a)).sort((a,l)=>a.amountIn.isGreaterThan(l.amountIn)?1:-1)}buildBuy(e,t){let r=t[t.length-1],s=t[0],i=this.isDirectTrade(t),n=t.map(f=>f.spotPrice.shiftedBy(-1*f.assetInDecimals)).reduce((f,b)=>f.multipliedBy(b)),o=I(n,s.assetInDecimals),a=i?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,u=i?s.tradeFeePct:Ut(a,l).toNumber(),m=l.minus(a),g=this.getRouteFeeRange(t),h=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(o),d;return a.isZero()?d=-100:d=fe(h,a).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:o,tradeFee:m,tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d,swaps:t,toHuman(){return{type:"Buy",amountOut:B(r.amountOut,r.assetOutDecimals),amountIn:B(s.amountIn,s.assetInDecimals),spotPrice:B(o,s.assetInDecimals),tradeFee:B(m,s.assetInDecimals),tradeFeePct:u,tradeFeeRange:g,priceImpactPct:d,swaps:t.map(f=>f.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=e:l=s[0];let u=o.calculateInGivenOut(a,l);s.unshift(u)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=I(p(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let u=await this.poolService.getPoolFees(a,o),{amountIn:m,calculatedIn:g,feePct:h,errors:d}=o.validateAndBuy(a,l,u),f=this.getPoolFeeRange(u),b=o.spotPriceInGivenOut(a),x=l.shiftedBy(-1*a.decimalsOut).multipliedBy(b),P;g.isZero()?P=-100:P=fe(x,g).toNumber(),s.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:m,amountOut:l,calculatedIn:g,spotPrice:b,tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P,errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:B(m,a.decimalsIn),amountOut:B(l,a.decimalsOut),calculatedIn:B(g,a.decimalsIn),spotPrice:B(b,a.decimalsIn),tradeFeePct:h,tradeFeeRange:f,priceImpactPct:P,errors:d}}})}return s}};var zt=6e3,Xt=p(1e15),Pe=6,dt=-5,gt=360*60*1e3,Qr=3,Yt=6;var W=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var Se=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??zt,minBudgetInNative:t.minBudgetInNative??Xt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:u}=o,m=l[0],g=l[l.length-1],{assetInDecimals:h}=m,{assetOutDecimals:d}=g,f=Math.abs(u),b=this.getMinimumTradeCount(a,n),x=this.getOptimalTradeCount(f),P=i?Math.round(s/i):x,w=Math.ceil(s/b),A=Math.round(s/x),F=Math.round(s/P),T=a.dividedBy(P).decimalPlaces(0,1),D=await this.router.getBestSell(e,t,B(T,h)),G=a.isLessThan(n),Ve=[];G&&Ve.push("OrderTooSmall");let $e=D.amountOut.multipliedBy(P),ft=this.toBlockPeriod(F),bt=D.tradeFee.multipliedBy(P),Pt=W.build(l),Ke={assetIn:e,assetOut:t,errors:Ve,frequencyMin:w,frequencyOpt:A,frequency:F,tradeCount:P,tradeFee:bt,tradeImpactPct:D.priceImpactPct,tradePeriod:ft,tradeRoute:Pt,type:"Dca"};return{...Ke,amountIn:a,amountOut:$e,tradeAmountIn:D.amountIn,tradeAmountOut:D.amountOut,toHuman(){return{...Ke,amountIn:B(a,h),amountOut:B($e,d),tradeAmountIn:B(D.amountIn,h),tradeAmountOut:B(D.amountOut,d)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",e);if(t)return this.minOrderBudget.times(t.amount).div(p(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:o,priceImpactPct:a}=i,l=o[0],u=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=u,h=Math.abs(a),d=this.getTwapTradeCount(h),f=n.dividedBy(d).decimalPlaces(0,1),b=await this.router.getBestSell(l.assetIn,u.assetOut,B(f,m)),x=d===1,P=n.isLessThan(s),w=b.priceImpactPct<dt,A=[];P||x?A.push("OrderTooSmall"):w&&A.push("OrderImpactTooBig");let F=b.amountOut.multipliedBy(d),T=b.tradeFee.multipliedBy(d),D=W.build(o),G={assetIn:e,assetOut:t,errors:A,tradeCount:d,tradeImpactPct:b.priceImpactPct,tradePeriod:Pe,tradeRoute:D,type:"TwapSell"};return{...G,amountIn:n,amountOut:F,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:T,toHuman(){return{...G,amountIn:B(n,m),amountOut:B(F,g),tradeAmountIn:B(b.amountIn,m),tradeAmountOut:B(b.amountOut,g),tradeFee:B(T,g)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:o,priceImpactPct:a}=i,l=o[0],u=o[o.length-1],{assetInDecimals:m}=l,{assetOutDecimals:g}=u,h=Math.abs(a),d=this.getTwapTradeCount(h),f=n.dividedBy(d).decimalPlaces(0,1),b=await this.router.getBestBuy(l.assetIn,u.assetOut,B(f,g)),x=b.amountIn.multipliedBy(d),P=d===1,w=x.isLessThan(s),A=b.priceImpactPct<dt,F=[];w||P?F.push("OrderTooSmall"):A&&F.push("OrderImpactTooBig");let T=b.tradeFee.multipliedBy(d),D=W.build(o),G={assetIn:e,assetOut:t,errors:F,tradeCount:d,tradeImpactPct:b.priceImpactPct,tradePeriod:Pe,tradeRoute:D,type:"TwapBuy"};return{...G,amountIn:x,amountOut:n,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:T,toHuman(){return{...G,amountIn:B(x,m),amountOut:B(n,g),tradeAmountIn:B(b.amountIn,m),tradeAmountOut:B(b.amountOut,g),tradeFee:B(T,m)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>gt){let s=gt/(this.blockTime*Pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Yt)}};var ve=class extends H{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new U(e),this.aaveUtils=new ee(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),Be)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var ht=class extends ve{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=ie(e,this.slippagePct),o=s.assetIn,a=i.assetOut,l=e.plus(n),u;return this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.buy(a,o,t.toFixed(),l.toFixed()):u=this.api.tx.router.buy(o,a,t.toFixed(),l.toFixed(),W.build(r)),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=ie(t,this.slippagePct),o=s.assetIn,a=i.assetOut,l=t.minus(n),u;if(this.isDirectOmnipoolTrade(r)?u=this.api.tx.omnipool.sell(o,a,e.toFixed(),l.toFixed()):u=this.api.tx.router.sell(o,a,e.toFixed(),l.toFixed(),W.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(u);return this.wrapTx("RouterSellAll",g,Be)}return this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=ie(e,this.slippagePct),n=r.assetIn,o=s.assetOut,a=e.minus(i),l=this.api.tx.router.sellAll(n,o,a.toFixed(),W.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let m=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",m,Be)}return this.wrapTx("RouterSellAll",l)}};var yt=class extends ve{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,o=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=ie(i,this.slippagePct),l=i.minus(a),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=ie(s,this.slippagePct),l=s.plus(a),u=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",u)}};var xe=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new ht(this.api,this.evm).setTrade(e)}order(e){return new yt(this.api,this.evm).setOrder(e)}};var Jr={router:{}};function Zr(c,e=Jr){let t=new ue(c),r=new Fe(c),s=new ge(c,r),i=new ee(r),n=new be(s,e.router),o=new Se(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:n,scheduler:o},client:{asset:new te(c),balance:new U(c),balanceV2:new ce(c)},ctx:{pool:s},evm:r,tx:new xe(c,r),destroy:()=>{s.destroy()}}}0&&(module.exports={AaveClient,AavePool,AavePoolClient,AaveUtils,AssetClient,AssetNotFound,BASILISK_PARACHAIN_ID,BalanceClient,BalanceClientV2,BigNumber,CachingPoolService,ChainParams,DECIMAL_PLACES,DEFAULT_BLOCK_TIME,DEFAULT_MIN_BUDGET,ERC20,EvmClient,FarmClient,H160,HUB_ASSET_ID,HYDRADX_PARACHAIN_ID,HYDRADX_SS58_PREFIX,INFINITY,LbpMath,LbpPool,LbpPoolClient,ONE,ORDER_MIN_BLOCK_PERIOD,OmniMath,OmniPool,OmniPoolClient,PERBILL_DENOMINATOR,PERMILL_DENOMINATOR,PolkadotApiClient,PoolConfigNotFound,PoolError,PoolFactory,PoolNotFound,PoolService,PoolType,ProviderConfigNotFound,RUNTIME_DECIMALS,RouteNotFound,Router,SYSTEM_ASSET_DECIMALS,SYSTEM_ASSET_ID,StableMath,StableSwap,StableSwapClient,StorageConfigNotFound,SubscriptionNotSupported,TRADEABLE_DEFAULT,TWAP_BLOCK_PERIOD,TWAP_MAX_DURATION,TWAP_MAX_PRICE_IMPACT,TWAP_TX_MULTIPLIER,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType,TxBuilderFactory,XykMath,XykPool,XykPoolClient,ZERO,bnFormatter,bnum,calculateBuyFee,calculateDiffToAvg,calculateDiffToRef,calculateSellFee,createChain,createSdkContext,findNestedKey,findNestedObj,getFraction,hashPools,isEvmAccount,isEvmAddress,isSs58Address,scale,toBn,toDecimals});
|
package/build/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var we=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var je=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var ot="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",ze="0x112b087b60C1a166130d59266363C45F8aa99db0",Qe="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ee=1000000n;var Bs=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var te=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:je,address:ze,args:[Qe],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:je,address:ze,args:[Qe,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:we,address:ot,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as Oe,encodeAddress as ut}from"@polkadot/util-crypto";import{hexToU8a as Ht,isHex as Gt,u8aToHex as Ut}from"@polkadot/util";import{Buffer as Y}from"buffer";var Os=2090,$=1e6,lt=1e9,Te="1",Is=2034,L=63,re=18,C="0",ct=12,se=15;var Je="ETH\0";function qt(p){if(!p)return!1;try{let e=Oe(p,!0),t=Y.from(Je);return Y.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Wt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Xt(p){try{let e=Gt(p)?Ht(p):Oe(p);return ut(e),!0}catch{return!1}}var W=class p{static toAccount=e=>{let t=Y.from(e.slice(2),"hex"),r=Y.from(Je);return ut(new Uint8Array(Y.concat([r,t,Y.alloc(8)])),63)};static fromAccount=e=>{let t=Oe(e),r=Y.from(Je),s=t.slice(r.length,-8);return"0x"+Y.from(s).toString("hex")};static fromSS58=e=>{let r=Oe(e).slice(0,20);return Ut(r)};static fromAny=e=>{if(Wt(e))return e;if(qt(e))return p.fromAccount(e);if(Xt(e))return p.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Ie}from"buffer";var X=class{static fromAssetId(e){let t=Number(e),r=Ie.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Ie.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Ie.from("0000000000000000000000000000000100000000","hex"),r=Ie.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as B}from"bignumber.js";var Yt=12;B.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Yt});var S=m(0),R=m(1),Ms=m("Infinity");function O(p,e){let t=new B(e.toString()),r=new B(10).pow(t);return p.times(r).decimalPlaces(4)}function m(p){return new B(p.toString())}function Ls(p,e){let t=m(p);return O(t,e)}function v(p,e){return p.shiftedBy(-1*e).toString()}var Ae=m("1e27"),Vt=m("1.01"),$t=m("31536000"),K=class{client;constructor(e){this.client=new te(e)}async getSummary(e){let t=W.fromAny(e),[r,s,a,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[n,l]=s,[c,u,g,h,d,b]=a,P=m(b).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN),x=m(c),f=m(u),w=[];for(let I of n){let A=I.underlyingAsset.toLowerCase(),T=o.find(({underlyingAsset:Lt})=>Lt.toLowerCase()===A);if(!T)throw new Error("Missing pool reserve for "+A);let E=m(I.scaledATokenBalance),M=m(T.liquidityIndex),Be=m(T.liquidityRate),xe=m(T.availableLiquidity),Ve=m(T.priceInMarketReferenceCurrency),$e=i+6,Ke=this.calculateLinearInterest(Be,T.lastUpdateTimestamp,$e),ve=M.multipliedBy(Ke).dividedBy(Ae).decimalPlaces(0,B.ROUND_DOWN),kt=E.multipliedBy(ve).dividedBy(Ae).decimalPlaces(0,B.ROUND_DOWN),_t=m(l!==0&&l===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold).div(1e4),Dt=T.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&m(I.scaledATokenBalance).gt(0),Mt=X.toAssetId(A);w.push({aTokenBalance:kt,availableLiquidity:xe,decimals:Number(T.decimals),isCollateral:Dt,priceInRef:Ve,reserveId:Mt,reserveAsset:A,reserveLiquidationThreshold:_t})}return{healthFactor:P.toNumber(),totalCollateral:x,totalDebt:f,reserves:w}}async hasBorrowPositions(e){let t=W.fromAny(e),r=await this.client.getUserAccountData(t),[s,a]=r;return a>0n}async getHealthFactor(e){let t=W.fromAny(e),r=await this.client.getUserAccountData(t),[s,a,i,o,n,l]=r;return m(l).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:a,reserves:i}=await this.getSummary(e),o=X.fromAssetId(t),n=i.find(x=>x.reserveAsset===o);if(!n)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:g}=n,h=O(m(r),l).decimalPlaces(0,1),d=c?h.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN):S,b=s.minus(d);return b.lte(0)?0:b.multipliedBy(g).dividedBy(a).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:a,reserves:i}=await this.getSummary(e),o=X.fromAssetId(t),n=i.find(P=>P.reserveAsset===o);if(!n)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=n,h=O(m(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN),d=s.plus(h);return d.lte(0)?0:d.multipliedBy(u).dividedBy(a).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:a}=await this.getSummary(e),i=X.fromAssetId(t),o=s.find(n=>n.reserveAsset===i);if(!o)throw new Error("Missing reserve data for "+i);return this.calculateWithdrawMax(o,r,a)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),a={};for(let i of r){let o=this.calculateWithdrawMax(i,t,s);i.reserveId&&(a[i.reserveId]=o)}return a}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:a,decimals:i,priceInRef:o,reserveLiquidationThreshold:n,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=m(r).minus(Vt);if(g.gt(0)){let d=g.multipliedBy(t).dividedBy(n).decimalPlaces(0,B.ROUND_DOWN).dividedBy(o).multipliedBy(m(10).pow(i)).decimalPlaces(0,B.ROUND_DOWN);c=B.minimum(s,d)}else c=S}return{amount:B.minimum(c,a),decimals:i}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ae:e.multipliedBy(s).dividedBy($t).plus(Ae).decimalPlaces(0,B.ROUND_DOWN)}};function mt(p){switch(p){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var _=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");mt(r)&&console.log(e,...t)}};var j=class extends _{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:a}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:a.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e=="0"){let u=this.api.consts.balances.existentialDeposit;return{id:"0",name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:a,assetType:i,isSufficient:o,existentialDeposit:n}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:a.toHuman(),symbol:l,decimals:c,icon:l,type:i.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:n.toString()}}getBond(e,t,r,s){let[a,i]=s,{assetType:o,isSufficient:n,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(a.toString(),t,r),g=i.toNumber(),h=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",h.format(g)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:u,icon:c,type:o.toString(),isSufficient:n.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:a.toString(),maturity:g}}getShares(e,t,r,s){let{assets:a}=s,{name:i,symbol:o,assetType:n,isSufficient:l,existentialDeposit:c}=t,g=a.map(b=>b.toString()).map(b=>{let{symbol:P}=this.getToken(b,t,r);return[b,P]}),h=Object.fromEntries(g),d=Object.values(h);return{id:e,name:d.join(", "),symbol:o?.isSome?o.toHuman():i.toHuman(),decimals:18,icon:d.join("/"),type:n.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:h}}getExternal(e,t,r,s){let a=this.getToken(e,t,new Map,s),i=r?.find(o=>o.internalId===a.id);return i?{...a,decimals:i.decimals,name:i.name,symbol:i.symbol,icon:i.symbol,isWhiteListed:i.isWhiteListed}:a}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:a,symbol:i}=s.unwrap();return[r.toString(),{decimals:Number(a.toString()),symbol:i.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,a,i,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),n=this.getSupportedAssets(r),l=this.normalizeMetadata(n,o),c=n.map(([{args:[u]},g])=>{let h=g.unwrap(),d=s.get(u.toString()),{assetType:b}=h;switch(b.toString()){case"Bond":let P=i.get(u.toString());return this.getBond(u.toString(),h,l,P);case"StableSwap":let x=a.get(u.toString());return this.getShares(u.toString(),h,l,x);case"External":return this.getExternal(u.toString(),h,t,d);default:return this.getToken(u.toString(),h,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)}};var H=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),a=r?r.map(i=>[e,i]):s.map(({args:[i,o]})=>[i.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(a,i=>{let o=[];i.forEach((n,l)=>{let c=this.calculateFreeBalance(n),u=a[l][1];o.push([u,c])}),t(o)})}async subscribeErc20Balance(e,t,r){let a=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([n,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[n]}])=>n.toString()))(),i=async()=>{let o=await Promise.all(a.map(async n=>[n,await this.getErc20Balance(e,n)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return B(t).lt(r)?B(0):B(t).minus(r)}};var ae=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),a=r?r.map(i=>[e,i]):s.map(({args:[i,o]})=>[i.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(a,i=>{let o=[];i.forEach((n,l)=>{let c=a[l][1],u=this.calculateBalance(n);o.push([c,u])}),t(o)})}async subscribeErc20Balance(e,t,r){let a=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([n,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[n]}])=>n.toString()))(),i=async()=>{let o=await Promise.all(a.map(async n=>[n,await this.getErc20Balance(e,n)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{i()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=B(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),a=t.gte(r)?t.minus(r).toString():"0",i=t.plus(s).toString();return{free:t.toString(),total:i,transferable:a,reserved:s,frozen:r}}};var ie=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as pt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as Kt}from"@polkadot/types";import{u8aConcat as dt}from"@polkadot/util";import{isAddress as gt}from"@polkadot/util-crypto";var Ze=class extends _{balanceClient;constructor(e){super(e),this.balanceClient=new H(e)}secondsInYear=new B(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,a])=>{let[,i]=s.args,o=a.unwrap().toString(),n=i.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(n)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,n,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(n),!1).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(h,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([s,a])=>{let[,i]=s.args,o=a.unwrap().toString(),n=i.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(n)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,n,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(n),!0).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(h,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new B(1).shiftedBy(18).toString();let a=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(a.isNone)return;let[i]=a.unwrap(),o=i.price.n.toString(),n=i.price.d.toString(),l;return Number(t)<Number(r)?l=pt(o,n):l=pt(n,o),l}getGlobalRewardPerPeriod(e,t,r,s){let i=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return i.gte(r)?r:i}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return dt(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",a=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new Kt(e,this.padEndU8a(dt(s,a,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!gt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&>(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:n,priceAdjustment:l,potBalance:c})=>{let u=new B(n.totalSharesZ.toString()),g=n.plannedYieldingPeriods.toString(),h=new B(n.yieldPerPeriod.toString()),d=new B(n.maxRewardPerPeriod.toString()),b=n.blocksPerPeriod.toString(),P=new B(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new B(r).times(b)),f;if(u.isZero())f=h.times(P).times(x);else{let E=this.getGlobalRewardPerPeriod(u,h,d,l);f=this.getPoolYieldPerPeriod(E,P,u,l).times(x)}let w=new B(n.pendingRewards.toString()).plus(n.accumulatedPaidRewards.toString()),I=d.times(g),A=c?w.plus(c):I;return w.div(A).gte(.999)?S:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,n)=>o.plus(n),S).toString():void 0}};var Fe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ht=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Re=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},yt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},bt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Pt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},ft=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{defineChain as jt}from"viem";var zt=["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"],St=p=>{let t=[p.endpoint,...zt],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return jt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};import{createPublicClient as xt,createWalletClient as Qt,custom as Jt,http as Zt}from"viem";function Bt(p){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return p.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Ne=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=St(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return xt({chain:this.chain,transport:Zt()})}getWsProvider(){return xt({chain:this.chain,transport:Bt(this.wsProvider)})}getSigner(e){return Qt({account:e,chain:this.chain,transport:Jt(window.ethereum)})}};import{memoize1 as cs}from"@thi.ng/memoize";var N=(i=>(i.Aave="Aave",i.LBP="Lbp",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="Xyk",i.HSM="Hsm",i))(N||{}),z=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(z||{});var Ee=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(n=>[n.id,n])),s=r.get(e),a=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");let i=m(s.balance),o=m(a.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:i,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return O(R,e.decimalsOut)}spotPriceOutGivenIn(e){return O(R,e.decimalsIn)}calculateTradeFee(e,t){return S}};import{encodeAddress as rr}from"@polkadot/util-crypto";import{stringToU8a as sr}from"@polkadot/util";import{decodeEventLog as ar}from"viem";import{memoize1 as er}from"@thi.ng/memoize";import{TLRUCache as tr}from"@thi.ng/cache";var et=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var ne=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,a]=await Promise.all([this.client.readContract({abi:et,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:et,address:e,functionName:"decimals"}),this.client.getBlock()]),[i,o,n,l]=r,c=a.number-(a.timestamp-l)/BigInt(t),u=Number(c);return{price:o,decimals:s,updatedAt:u<0?0:u}}};var D=class extends H{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new tr(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=er(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new ne(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(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();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=this.augmentedPools.map(async r=>{let s=[],a=await this.subscribeTokensPoolBalance(r);if(s.push(a),this.hasSystemAsset(r)){let i=await this.subscribeSystemPoolBalance(r);s.push(i)}if(this.hasErc20Asset(r)){let i=await this.subscribeErc20PoolBalance(r);s.push(i)}return this.subscribeLog(r),s}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}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()).catch(t=>console.warn("Unsub failed",t))})}subscribeLog(e){let t=e.address.substring(0,10).concat("...");this.log(`${e.type} mem ${this.mem} [${t}] balance subscribed`)}subscribeSystemPoolBalance(e){return this.subscribeSystemBalance(e.address,this.updateBalanceCallback(e))}subscribeTokensPoolBalance(e){let t=(r,s)=>r.id!==s;return this.subscribeTokenBalance(e.address,this.updateBalancesCallback(e,t))}subscribeErc20PoolBalance(e){let t=e.tokens.filter(r=>r.type==="Erc20").map(r=>r.id);return this.subscribeErc20Balance(e.address,this.updateBalancesCallback(e,()=>!0),t)}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}updateBalancesCallback(e,t){return function(r){r.forEach(([s,a])=>{let i=e.tokens.findIndex(o=>o.id==s);i>=0&&t(e,s)&&(e.tokens[i].balance=a.toString())})}}updateBalanceCallback(e){return function(t,r){let s=e.tokens.findIndex(a=>a.id==t);s>=0&&(e.tokens[s].balance=r.toString())}}};function Ce(p,e){let t=[];return JSON.stringify(p,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Si(p,e,t){let r;return JSON.stringify(p,(s,a)=>(a&&a[e]===t&&(r=a),a)),r}var Bi=(p,e)=>typeof e=="bigint"?e.toString():e;var ir=["Supply","Withdraw","Repay","Borrow"],ke=class extends D{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return rr(sr(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?Ce(e.location,"accountKey20").accountKey20.key:X.fromAssetId(e.id)}isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:a})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:a.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[a,i]=r.data.toJSON();this.pools.filter(o=>o.tokens.some(n=>n.id===a.toString()||n.id===i.toString())).forEach(o=>{this.log(`Sync AAVE via [router:Executed] :: ${a}:${i}`),this.updatePoolState(o)})}if(s==="evm:Log"){let[a]=r.data.toJSON();try{let{eventName:i,args:o}=ar({abi:we,topics:a.topics,data:a.data});if(ir.includes(i)){let n=o.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===n}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${i} ${n}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:a}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(i=>{let o=i.id===t.id?s.toString():a.toString();return{...i,balance:o}})}};import{calculate_in_given_out as nr,calculate_out_given_in as or,calculate_linear_weights as lr,calculate_pool_trade_fee as cr,get_spot_price as ur}from"@galacticcouncil/math-lbp";var U=class{static getSpotPrice(e,t,r,s,a){return ur(e,t,r,s,a)}static calculateInGivenOut(e,t,r,s,a){return nr(e,t,r,s,a)}static calculateOutGivenIn(e,t,r,s,a){return or(e,t,r,s,a)}static calculateLinearWeights(e,t,r,s,a){return lr(e,t,r,s,a)}static calculatePoolTradeFee(e,t,r){return cr(e,t,r)}};var y=class p{static toPct(e){let[t,r]=e;return p.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return p.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var _e=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(n=>[n.id,n])),s=r.get(e),a=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");let i=m(s.balance),o=m(a.balance);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:s.decimals,decimalsOut:a.decimals,weightIn:s.weight,weightOut:a.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,a=[];t.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount");let i=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(i)&&a.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),n=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:n,errors:a}}else{let o=this.calculateInGivenOut(e,t),n=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(n)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:a}}}validateAndSell(e,t,r){let s=this.tokens[0].id,a=[];t.isLessThan(this.minTradingLimit)&&a.push("InsufficientTradingAmount");let i=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(i)&&a.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),n=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(n)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:a}}else{let o=this.calculateOutGivenIn(e,t),n=this.calculateTradeFee(o,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(n),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(e,t){let r=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),O(R,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),O(R,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var De=class extends D{MAX_FINAL_WEIGHT=O(m(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:a,assets:i,initialWeight:o,finalWeight:n,repayTarget:l,feeCollector:c}=t,u=U.calculateLinearWeights(s.toString(),a.toString(),o.toString(),n.toString(),r),[g,h]=i,d=g.toString(),b=m(u),P=h.toString(),x=this.MAX_FINAL_WEIGHT.minus(m(b)),[f,w,I]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,P)]);return{repayFeeApply:f,tokens:[{id:d,weight:b,balance:w.toString()},{id:P,weight:x,balance:I.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t>=r&&t<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([a,i])=>this.isActivePool(i.unwrap(),r.toNumber())).map(async([{args:[a]},i])=>{let o=i.unwrap(),n=a.toString(),l=await this.getPoolDelta(n,o,r.toString());this.poolsData.set(a.toString(),o);let[c,u]=o.fee;return{address:n,type:"Lbp",fee:y.fromRate(c.toNumber(),u.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(a=>a.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let i=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,i)}else{let i=this.pools.findIndex(o=>o.address==r.address);this.pools.splice(i,1)}})})}};import{calculate_in_given_out as mr,calculate_lrna_in_given_out as pr,calculate_out_given_in as dr,calculate_out_given_lrna_in as gr,calculate_spot_price as hr,calculate_lrna_spot_price as yr,calculate_shares as br,calculate_liquidity_out as Pr,calculate_liquidity_lrna_out as fr,calculate_liquidity_hub_in as Sr,is_sell_allowed as Br,is_buy_allowed as xr,is_add_liquidity_allowed as vr,is_remove_liquidity_allowed as wr,recalculate_asset_fee as Tr,recalculate_protocol_fee as Or,verify_asset_cap as Ir}from"@galacticcouncil/math-omnipool";var F=class{static calculateSpotPrice(e,t,r,s){return hr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return yr(e,t)}static calculateInGivenOut(e,t,r,s,a,i,o,n,l){return mr(e,t,r,s,a,i,o,n,l)}static calculateLrnaInGivenOut(e,t,r,s,a){return pr(e,t,r,s,a)}static calculateOutGivenIn(e,t,r,s,a,i,o,n,l){return dr(e,t,r,s,a,i,o,n,l)}static calculateOutGivenLrnaIn(e,t,r,s,a){return gr(e,t,r,s,a)}static calculateShares(e,t,r,s){return br(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,a,i,o,n){return Pr(e,t,r,s,a,i,o,n)}static calculateLiquidityLRNAOut(e,t,r,s,a,i,o,n){return fr(e,t,r,s,a,i,o,n)}static calculateCapDifference(e,t,r,s){let a=B(t),i=B(e),o=B(s),l=B(r).shiftedBy(-18);if(a.div(o).lt(l)){let u=l.times(o).minus(a).times(i),g=a.times(B(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return Sr(e,t,r,s)}static isSellAllowed(e){return Br(e)}static isBuyAllowed(e){return xr(e)}static isAddLiquidityAllowed(e){return vr(e)}static isRemoveLiquidityAllowed(e){return wr(e)}static recalculateAssetFee(e,t,r,s,a,i,o,n,l,c,u){return Tr(e,t,r,s,a,i,o,n,l,c,u)}static recalculateProtocolFee(e,t,r,s,a,i,o,n,l,c,u){return Or(e,t,r,s,a,i,o,n,l,c,u)}static verifyAssetCap(e,t,r,s){return Ir(e,t,r,s)}};var Me=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),a=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");let i=m(s.balance),o=m(a.balance),n=m(s.existentialDeposit),l=m(a.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:a.hubReserves,sharesIn:s.shares,sharesOut:a.shares,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:i,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:a.tradeable,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),a=this.calculateInGivenOut(e,t,r),i=a.minus(s),o=s===S?S:i.div(s).multipliedBy(100).decimalPlaces(4),n=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&n.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return a.isGreaterThan(g)&&n.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),a=this.calculateOutGivenIn(e,t,r),o=s.minus(a).div(s).multipliedBy(100).decimalPlaces(4),n=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&n.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return a.isGreaterThan(g)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:o.toNumber(),errors:n}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=F.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),a=m(s);return a.isNegative()?S:a}calculateLrnaInGivenOut(e,t,r){let s=F.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),a=m(s);return a.isNegative()?S:a}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=F.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),a=m(s);return a.isNegative()?S:a}calculateOutGivenLrnaIn(e,t,r){let s=F.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),a=m(s);return a.isNegative()?S:a}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=F.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=F.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=F.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=F.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Ar}from"@polkadot/util-crypto";import{stringToU8a as Fr}from"@polkadot/util";import{memoize1 as tt}from"@thi.ng/memoize";import{TLRUCache as Rr}from"@thi.ng/cache";var vt="omnipool",wt="Short",Le=class extends D{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new Rr(null,{ttl:6*1e3});memOracleQuery=tt(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(vt,t,wt)},this.memQueryCache);memFeesQuery=tt(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=tt(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return Ar(Fr("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,a]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),i=r.map(async([{args:[n]},l])=>{let{hubReserve:c,shares:u,tradable:g,cap:h,protocolShares:d}=l.unwrap(),b=await this.getBalance(t,n.toString());return{id:n.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:g.bits.toNumber(),balance:b.toString(),cap:m(h.toString()),protocolShares:m(d.toString())}}),o=await Promise.all(i);return o.push({id:e,tradeable:s.bits.toNumber(),balance:a.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,a=t.assetIn,i;if(this.isAssetConfigSupported()&&(i=await this.getDynamicFeesConfiguration(s).then(f=>f.unwrapOr(null))),i?.isFixed){let f=i.asFixed.assetFee.toNumber(),w=i.asFixed.protocolFee.toNumber();return{assetFee:y.fromPermill(f),protocolFee:y.fromPermill(w)}}let[o,n,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(a)]),[c,u,g]=this.getAssetFee(t,e,o,n,i?.isDynamic?i.asDynamic.assetFeeParams:void 0),[h,d,b]=a==="1"?[0,0,0]:this.getProtocolFee(t,e,o,l,i?.isDynamic?i.asDynamic.protocolFeeParams:void 0),P=c+h,x=g+b;return{assetFee:y.fromPermill(u),protocolFee:y.fromPermill(d),min:y.fromPermill(P),max:y.fromPermill(x)}}getAssetFee(e,t,r,s,a){let{assetOut:i,balanceOut:o}=e,{minFee:n,maxFee:l,decay:c,amplification:u}=a||this.api.consts.dynamicFees.assetFeeParameters,g=y.fromPermill(n.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),l.toNumber()];let[d]=s.unwrap(),{assetFee:b,timestamp:P}=r.unwrap(),x=Math.max(1,t-P.toNumber()),f=d.volume.bIn.toString(),w=d.volume.bOut.toString(),I=d.liquidity.b.toString();i==="0"&&(f=d.volume.aIn.toString(),w=d.volume.aOut.toString(),I=d.liquidity.a.toString());let A=y.fromPermill(b.toNumber()),T=F.recalculateAssetFee(f,w,I,"9",o.toString(),y.toRaw(A).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),c.toString(),u.toString());return[n.toNumber(),Number(T)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,a){let{assetIn:i,balanceIn:o}=e,{minFee:n,maxFee:l,decay:c,amplification:u}=a||this.api.consts.dynamicFees.protocolFeeParameters,g=y.fromPermill(n.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[n.toNumber(),n.toNumber(),l.toNumber()];let[d]=s.unwrap(),{protocolFee:b,timestamp:P}=r.unwrap(),x=Math.max(1,t-P.toNumber()),f=d.volume.bIn.toString(),w=d.volume.bOut.toString(),I=d.liquidity.b.toString();i==="0"&&(f=d.volume.aIn.toString(),w=d.volume.aOut.toString(),I=d.liquidity.a.toString());let A=y.fromPermill(b.toNumber()),T=F.recalculateProtocolFee(f,w,I,"9",o.toString(),y.toRaw(A).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),c.toString(),u.toString());return[n.toNumber(),Number(T)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(n=>n.id),r=[],s=await this.api.query.omnipool.assets.multi(t,n=>{e.tokens=n.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let g=l.unwrap();return this.updateTokenState(u,g)})});r.push(s);let a=await this.api.query.dynamicFees.assetFee.multi(t,n=>{n.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});if(r.push(a),this.isAssetConfigSupported()){let n=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,u)=>{let g=t[u];this.dynamicFeesConfiguration.set(g,c)})});r.push(n)}let i=t.map(n=>{let l=this.getOracleKey(n);return[vt,l,wt]}),o=await this.api.query.emaOracle.oracles.multi(i,n=>{n.forEach(async(l,c)=>{let u=i[c],[g,h,d]=u;this.oracles.set(h.join(":"),l)})});return r.push(o),()=>{for(let n of r)try{n()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:a,cap:i,protocolShares:o}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(i.toString()),protocolShares:m(o.toString()),tradeable:a.bits.toNumber()}}};import{calculate_in_given_out as Nr,calculate_out_given_in as Er,calculate_pool_trade_fee as Cr,get_spot_price as kr,calculate_liquidity_in as _r,calculate_shares as Dr,calculate_spot_price as Mr,calculate_spot_price_with_fee as Lr,calculate_liquidity_out_asset_a as Hr,calculate_liquidity_out_asset_b as Gr}from"@galacticcouncil/math-xyk";var V=class{static getSpotPrice(e,t,r){return kr(e,t,r)}static calculateInGivenOut(e,t,r){return Nr(e,t,r)}static calculateOutGivenIn(e,t,r){return Er(e,t,r)}static calculatePoolTradeFee(e,t,r){return Cr(e,t,r)}static calculateLiquidityIn(e,t,r){return _r(e,t,r)}static calculateSpotPrice(e,t){return Mr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return Lr(e,t,r,s)}static calculateShares(e,t,r){return Dr(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Hr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Gr(e,t,r,s)}};var He=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),a=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");let i=m(s.balance),o=m(a.balance),n=m(s.existentialDeposit),l=m(a.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:a.decimals,balanceIn:i,balanceOut:o,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),a=this.calculateTradeFee(s,r),i=y.toPct(r.exchangeFee),o=s.plus(a),n=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&n.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&n.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:i,errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(s,r),i=y.toPct(r.exchangeFee),o=s.minus(a),n=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&n.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&n.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:i,errors:n}}calculateInGivenOut(e,t){let r=V.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=V.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=V.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=O(R,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=V.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=O(R,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=V.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var Ge=class extends D{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let a=r.toString(),[i,o]=s.unwrap(),[n,l]=await Promise.all([this.getBalance(a,i.toString()),this.getBalance(a,o.toString())]);return{address:a,type:"Xyk",tokens:[{id:i.toString(),balance:n.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};import{calculate_in_given_out as Ur,calculate_out_given_in as qr,calculate_amplification as Wr,calculate_add_one_asset as Xr,calculate_liquidity_out_one_asset as Yr,calculate_shares as Vr,calculate_shares_for_amount as $r,calculate_spot_price_with_fee as Kr,pool_account_name as jr,recalculate_peg as zr}from"@galacticcouncil/math-stableswap";var k=class{static getPoolAddress(e){return jr(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,a){return Wr(e,t,r,s,a)}static calculateInGivenOut(e,t,r,s,a,i,o){return Ur(e,t,r,s,a,i,o)}static calculateAddOneAsset(e,t,r,s,a,i,o){return Xr(e,t,r,s,a,i,o)}static calculateSharesForAmount(e,t,r,s,a,i,o){return $r(e,t,r,s,a,i,o)}static calculateOutGivenIn(e,t,r,s,a,i,o){return qr(e,t,r,s,a,i,o)}static calculateLiquidityOutOneAsset(e,t,r,s,a,i,o){return Yr(e,t,r,s,a,i,o)}static calculateShares(e,t,r,s,a,i){return Vr(e,t,r,s,a,i)}static calculateSpotPriceWithFee(e,t,r,s,a,i,o,n){return Kr(e,t,r,s,a,i,o,n)}static recalculatePegs(e,t,r,s,a){let i=zr(e,t,r,s,a);return JSON.parse(i)}};var J=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),a=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");let i=m(s.balance),o=m(a.balance),n=m(s.existentialDeposit),l=m(a.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:i,balanceOut:o,decimalsIn:s.decimals,decimalsOut:a.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:a.tradeable,assetInED:n,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),a=this.calculateInGivenOut(e,t,r),i=a.minus(s),o=s===S?S:i.div(s).multipliedBy(100).decimalPlaces(4),n=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&n.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:n}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),a=this.calculateOutGivenIn(e,t,r),o=s.minus(a).div(s).multipliedBy(100).decimalPlaces(4),n=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&n.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&n.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:a,feePct:o.toNumber(),errors:n}}calculateIn(e,t,r){let s=k.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),a=m(s);return a.isNegative()?S:a}calculateAddOneAsset(e,t,r){let s=k.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),a=m(s);return a.isNegative()?S:a}calculateSharesForAmount(e,t,r){let s=k.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),a=m(s);return a.isNegative()?S:a}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=O(R,e.decimalsIn-e.decimalsOut);return m(t).div(s).decimalPlaces(0,1)}let r=O(R,18-e.decimalsIn);return m(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=k.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),a=m(s);return a.isNegative()?S:a}calculateWithdrawOneAsset(e,t,r){let s=k.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),a=m(s);return a.isNegative()?S:a}calculateShares(e,t,r){let s=k.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),a=m(s);return a.isNegative()?S:a}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=O(R,e.decimalsOut-e.decimalsIn);return m(t).div(s).decimalPlaces(0,1)}let r=O(R,18-e.decimalsOut);return m(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as Qr,encodeAddress as Jr}from"@polkadot/util-crypto";var Ue=class extends D{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=k.getPoolAddress(t);return Jr(Qr(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:a,initialBlock:i,finalBlock:o}=t,n=k.calculateAmplification(s.toString(),a.toString(),i.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:n,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,a=s.map(async i=>{let[o,n]=await Promise.all([this.api.query.stableswap.assetTradability(t,i.toString()),this.getBalance(e,i.toString())]);return{id:i.toString(),tradeable:o.bits.toNumber(),balance:n.toString()}});return Promise.all(a)}isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[i]},o])=>{try{let n=o.unwrap(),l=i.toString(),c=this.getPoolAddress(l),[u,g,h]=await Promise.all([this.getPoolDelta(l,n,r.toString()),this.getPoolTokens(c,l,n),this.getPoolPegs(l,n,r.toString())]);return g.push({id:l,tradeable:15,balance:u.totalIssuance}),this.poolsData.set(c,n),{address:c,id:l,type:"Stableswap",fee:y.fromPermill(n.fee.toNumber()),tokens:g,...u,...h,...this.getPoolLimits()}}catch(n){return console.warn(`Skipping pool ${i.toString()}
|
|
2
|
-
`,String(n)),null}});return(await Promise.all(s)).filter(i=>i!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(a=>a.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let a=s.unwrap(),i=await this.getLatestPegs(t,a,r),o=this.getRecentPegs(a),n=y.fromPermill(a.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[c,u]=k.recalculatePegs(JSON.stringify(o),JSON.stringify(i),r,y.toRaw(n).toString(),y.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:y.fromPermill(g),pegs:u}}getDefaultPegs(e){let t=e.fee,r=k.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(a=>a.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,a=Array.from(e.assets.entries()).map(([o,n])=>n.toString()),i=s.map(async(o,n)=>{if(o.isOracle){let[l,c,u]=o.asOracle,g=[u.toString(),a[n]].map(f=>Number(f)).sort((f,w)=>f-w),h=await this.api.query.emaOracle.oracles(l,g,c),[{price:d,updatedAt:b}]=h.unwrap(),P=d.n.toString(),x=d.d.toString();return u.toString()===g[0].toString()?[[P,x],b.toString()]:[[x,P],b.toString()]}else if(o.isMmOracle){let l=o.asMmOracle,{price:c,decimals:u,updatedAt:g}=await this.mmOracle.getData(l.toString()),h=10**u;return[[c.toString(),h.toString()],g.toString()]}else{if(o.isValue)return[o.asValue.map(l=>l.toString()),r];throw Error(o.type+" is not supported")}});return Promise.all(i)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[a,i]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),o=r.tokens.map(n=>n.id===r.id?{...n,balance:a.totalIssuance}:n);Object.assign(r,{tokens:o},a,i)}})})}};import{calculate_collateral_in_given_hollar_out as Zr,calculate_collateral_out_given_hollar_in as es,calculate_hollar_in_given_collateral_out as ts,calculate_hollar_out_given_collateral_in as rs,calculate_imbalance as ss,calculate_max_price as as,calculate_buyback_limit as is,calculate_buyback_price_with_fee as ns}from"@galacticcouncil/math-hsm";var q=class{static calculateCollateralInGivenHollarOut(e,t,r){return Zr(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return es(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return rs(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return ts(e,t,r)}static calculateImbalance(e,t,r){return ss(e,t,r)}static calculateBuybackLimit(e,t){return is(e,t)}static calculateBuybackPriceWithFee(e,t,r){return ns(e,t,r)}static calculateMaxPrice(e,t){return as(e,t)}};var qe=class p extends J{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new p(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let a=this.calculateBuybackLimit(e);t.gt(a)&&s.push("MaxBuyBackExceeded");let i=this.calculateBuyPrice(e,t,r),o=this.calculateMaxPrice(e);return i.gt(o)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=q.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return m(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=q.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return m(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=q.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return m(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=q.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return m(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=q.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return m(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=q.calculateBuybackLimit(t.toString(),y.toRaw(this.buyBackRate).toString());return m(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(m(10).pow(e.decimalsIn));return r.dividedBy(m(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=q.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,a]=JSON.parse(r);return m(s).div(m(a)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=O(R,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=O(R,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[O(R,18).toString(),O(R,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};import{stringToU8a as Tt}from"@polkadot/util";import{encodeAddress as Ot}from"@polkadot/util-crypto";import{decodeEventLog as os}from"viem";var oe=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var le=class{client;constructor(e){this.client=e.getWsProvider()}async getFacilitatorCapacity(e,t){let[r,s]=await this.client.readContract({abi:oe,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var ls=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],We=class extends D{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new le(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return Ot(Tt(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return Ot(Tt("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return Ce(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let a=this.getFacilitatorAddress(),i=W.fromAny(a),o=this.getHollarAddress(t.unwrap()),n=await this.ghoTokenClient.getFacilitatorCapacity(o,i),l=r.map(async([{args:[u]},g])=>{let h=g.unwrap(),d=u.toString(),{poolId:b,maxBuyPriceCoefficient:P,maxInHolding:x,purchaseFee:f,buyBackFee:w,buybackRate:I}=h,A=s.find(T=>T.id===b.toString());if(A){let T=this.getPoolId(b.toString()),E=await this.getBalance(a,d);return{...A,address:T,type:"Hsm",tokens:A.tokens.filter(M=>M.id!==b.toString()),hsmAddress:a,hsmMintCapacity:m(n),hollarId:e,hollarH160:o,collateralId:d,collateralBalance:E,maxBuyPriceCoefficient:m(P.toString()),maxInHolding:m(x.unwrap().toString()),purchaseFee:y.fromPermill(f.toNumber()),buyBackFee:y.fromPermill(w.toNumber()),buyBackRate:y.fromPerbill(I.toNumber())}}});return(await Promise.all(l)).filter(u=>u!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[a]=r.data.toJSON();try{let{eventName:i,args:o}=os({abi:oe,topics:a.topics,data:a.data}),[n]=this.pools,{hsmAddress:l,hollarH160:c}=n,u=W.fromAny(l),g=u.toLowerCase()===o.facilitatorAddress.toLowerCase();if(ls.includes(i)&&g){let h=await this.ghoTokenClient.getFacilitatorCapacity(c,u);this.log(`Sync HSM facilitator via [evm:Log] :: ${i} ${h}`),this.pools.forEach(d=>{Object.assign(d,{hsmMintCapacity:h})})}}catch{}}})}async subscribeBalances(){let e=this.pools.map(async r=>{let{collateralId:s,hsmAddress:a,tokens:i}=r,o=i.find(l=>l.id===s),n=l=>{let[c]=l,[u,g]=c;Object.assign(r,{collateralBalance:g})};return o.type==="Erc20"?this.subscribeErc20Balance(a,n,[s]):this.subscribeTokenBalance(a,n,[s])}),t=await Promise.all(e);return()=>{for(let r of t.flat())try{r()}catch(s){console.warn("Balance unsub failed",s)}}}async subscribeUpdates(){return()=>{}}};var ce=class extends _{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=cs(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new j(this.api),this.aaveClient=new ke(this.api,t),this.xykClient=new Ge(this.api,t),this.omniClient=new Le(this.api,t),this.lbpClient=new De(this.api,t),this.stableClient=new Ue(this.api,t),this.hsmClient=new We(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Fe(t.type)}}};var ue=class extends ce{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var me=class{static get(e){switch(e.type){case"Aave":return Ee.fromPool(e);case"Xyk":return He.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return _e.fromPool(e);case"Stableswap":return J.fromPool(e);case"Hsm":return qe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as us}from"@noble/hashes/sha256";import{bytesToHex as ms}from"@noble/hashes/utils";function It(p){let e=p.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=us(t);return ms(r)}var pe=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 ps=8,de=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],a=new pe,i=[];for(i.push([t,""]),a.enqueue(i);a.size()>0;){let o=a.dequeue();if(!o||o.length>ps)continue;let n=o[o.length-1];(r===null||n[0]===r)&&s.push(o),e.get(n[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let u=[...o];u.push(c),a.enqueue(u)}})}return s}findShortestPaths(e,t,r){let s=[],a=new pe,i=[];i.push([t,""]),a.enqueue(i);let o=1/0;for(;a.size()>0;){let n=a.dequeue();if(!n)continue;let l=n[n.length-1];if(l[0]===r){n.length<o?(o=n.length,s.length=0,s.push(n)):n.length===o&&s.push(n);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,n)&&a.enqueue([...n,u])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,a,i]of t){let o=parseInt(a),n=parseInt(i);r.get(o)?.push([n,s])}return r}};function rt(p){let e={};for(let t of p){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let a=0;a<r;a++){if(s==a)continue;let i=[t.address,t.tokens[s].id,t.tokens[a].id];e[t.tokens[s].id].push(i)}}}return e}var ge=class{getProposals(e,t,r){let s=r.filter(f=>f.type==="Xyk"),a=r.filter(f=>f.type!=="Xyk"),i=parseInt(e),o=parseInt(t),n=new Set(a.map(f=>f.tokens).flat().map(f=>f.id)),l=n.has(e),c=n.has(t),u=new de,g=f=>{let w=rt(f),I=Object.keys(w),A=I.flatMap(T=>w[T]);return u.buildAndPopulateGraph(I,A)};if(!l&&!c){let f=s.filter(A=>A.tokens.find(T=>T.id===e)||A.tokens.find(T=>T.id===t)),w=g(f),I=u.findPaths(w,i,o);return this.parsePaths(I)}if(l&&c){let f=g(a),w=u.findPaths(f,i,o);return this.parsePaths(w)}let h=l?t:e,d=s.filter(f=>f.tokens.some(w=>w.id===h)),b=[...a,...d],P=g(b),x=u.findPaths(P,i,o);return this.parsePaths(x)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=r[a+1];if(o==null)break;s.push(this.toEdge(i,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var he=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new ge,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}getProposals(e,t,r){let s=`${e}->${t}::${It(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let a=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,a),a}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,me.get(t)]))}toHops(e,t){return e.map(([r,s,a])=>{let i=t.get(r);return{poolAddress:r,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:a}})}};var ds=m("100");function Ou(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ye(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function At(p,e){return R.minus(e.div(p)).multipliedBy(100).decimalPlaces(4)}function Ft(p,e){return e.div(p).minus(R).multipliedBy(100).decimalPlaces(4)}function Q(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(ds).multipliedBy(e).decimalPlaces(0,1)}var st=(t=>(t.Buy="Buy",t.Sell="Sell",t))(st||{}),at=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(at||{}),Rt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Rt||{});var be=class extends he{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),a=super.getPaths(e,t,r);if(a.length===0)throw new Re(e,t);return{paths:a,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let a=r[r.length-1].amountOut,i=s[s.length-1].amountOut;return a.isGreaterThan(i)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(a=>a.tradeFeeRange?.[0]??a.tradeFeePct).reduce((a,i)=>a+i),s=e.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,i)=>a+i);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:a,poolsMap:i}=await this.loadRouteContext(e,t),o;if(s)o=await this.toSellSwaps(r,s,i);else{let n=a.map(async c=>await this.toSellSwaps(r,c,i)),l=await Promise.all(n);o=this.findBestSellRoute(l)}return this.buildSell(i,o)}async getSellTrades(e,t,r){let{paths:s,poolsMap:a}=await this.loadRouteContext(e,t),i=s.map(async n=>await this.toSellSwaps(r,n,a));return(await Promise.all(i)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildSell(a,n)).sort((n,l)=>n.amountOut.isGreaterThan(l.amountOut)?-1:1)}buildSell(e,t){let r=t[0],s=t[t.length-1],a=this.isDirectTrade(t),i=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetOutDecimals)).reduce((b,P)=>b.multipliedBy(P)),o=O(i,s.assetOutDecimals),n=a?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,c=a?s.tradeFeePct:At(n,l).toNumber(),u=n.minus(l),g=this.getRouteFeeRange(t),h=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(o),d=ye(n,h);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:o,tradeFee:u,tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:v(r.amountIn,r.assetInDecimals),amountOut:v(s.amountOut,s.assetOutDecimals),spotPrice:v(o,s.assetOutDecimals),tradeFee:v(u,s.assetOutDecimals),tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t.map(b=>b.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let a=0;a<t.length;a++){let i=t[a],o=r.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(i.assetIn,i.assetOut),l;a>0?l=s[a-1]:l=e;let c=o.calculateOutGivenIn(n,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let a=0;a<t.length;a++){let i=t[a],o=r.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(i.assetIn,i.assetOut),l;a>0?l=s[a-1].amountOut:l=O(m(e),n.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(n,o),{amountOut:u,calculatedOut:g,feePct:h,errors:d}=o.validateAndSell(n,l,c),b=this.getPoolFeeRange(c),P=o.spotPriceOutGivenIn(n),x=l.shiftedBy(-1*n.decimalsIn).multipliedBy(P),f=ye(g,x);s.push({...i,assetInDecimals:n.decimalsIn,assetOutDecimals:n.decimalsOut,amountIn:l,amountOut:u,calculatedOut:g,spotPrice:P,tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:v(l,n.decimalsIn),amountOut:v(u,n.decimalsOut),calculatedOut:v(g,n.decimalsOut),spotPrice:v(P,n.decimalsOut),tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:d}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:a}=await this.loadRouteContext(e,t),l=s.filter(h=>h.tokens.some(d=>d.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(d=>d.id===e)).map(h=>h.map(d=>m(d.balance).shiftedBy(-1*d.decimals)).reduce((d,b)=>d.plus(b))).sort((h,d)=>d.isLessThan(h)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async h=>await this.toSellSwaps(l,h,a)),u=await Promise.all(c);return this.findBestSellRoute(u).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,a=await this.getMostLiquidRoute(e,t),i=await this.toSellSwaps("1",a,s),o=i.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,u)=>c.multipliedBy(u)),n=i[i.length-1].assetOutDecimals;return{amount:O(o,n),decimals:n}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let a=r[0].amountIn,i=s[0].amountIn;return a.isGreaterThan(i)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:a,poolsMap:i}=await this.loadRouteContext(e,t),o;if(s)o=await this.toBuySwaps(r,s,i);else{let n=a.map(async c=>await this.toBuySwaps(r,c,i)),l=await Promise.all(n);o=this.findBestBuyRoute(l)}return this.buildBuy(i,o)}async getBuyTrades(e,t,r){let{paths:s,poolsMap:a}=await this.loadRouteContext(e,t),i=s.map(async n=>await this.toBuySwaps(r,n,a));return(await Promise.all(i)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildBuy(a,n)).sort((n,l)=>n.amountIn.isGreaterThan(l.amountIn)?1:-1)}buildBuy(e,t){let r=t[t.length-1],s=t[0],a=this.isDirectTrade(t),i=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetInDecimals)).reduce((b,P)=>b.multipliedBy(P)),o=O(i,s.assetInDecimals),n=a?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,c=a?s.tradeFeePct:Ft(n,l).toNumber(),u=l.minus(n),g=this.getRouteFeeRange(t),h=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(o),d;return n.isZero()?d=-100:d=ye(h,n).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:o,tradeFee:u,tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d,swaps:t,toHuman(){return{type:"Buy",amountOut:v(r.amountOut,r.assetOutDecimals),amountIn:v(s.amountIn,s.assetInDecimals),spotPrice:v(o,s.assetInDecimals),tradeFee:v(u,s.assetInDecimals),tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d,swaps:t.map(b=>b.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let a=t.length-1;a>=0;a--){let i=t[a],o=r.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(i.assetIn,i.assetOut),l;a==t.length-1?l=e:l=s[0];let c=o.calculateInGivenOut(n,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let a=t.length-1;a>=0;a--){let i=t[a],o=r.get(i.poolAddress);if(o==null)throw new Error("Pool does not exit");let n=o.parsePair(i.assetIn,i.assetOut),l;a==t.length-1?l=O(m(e),n.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(n,o),{amountIn:u,calculatedIn:g,feePct:h,errors:d}=o.validateAndBuy(n,l,c),b=this.getPoolFeeRange(c),P=o.spotPriceInGivenOut(n),x=l.shiftedBy(-1*n.decimalsOut).multipliedBy(P),f;g.isZero()?f=-100:f=ye(x,g).toNumber(),s.unshift({...i,assetInDecimals:n.decimalsIn,assetOutDecimals:n.decimalsOut,amountIn:u,amountOut:l,calculatedIn:g,spotPrice:P,tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f,errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===i.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:v(u,n.decimalsIn),amountOut:v(l,n.decimalsOut),calculatedIn:v(g,n.decimalsIn),spotPrice:v(P,n.decimalsIn),tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f,errors:d}}})}return s}};var Nt=6e3,Et=m(1e15),Pe=6,it=-5,nt=360*60*1e3,Vu=3,Ct=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:a})=>s==="Stableswap"?{pool:{Stableswap:a},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var fe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Nt,minBudgetInNative:t.minBudgetInNative??Et})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,a){let[i,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:l,priceImpactPct:c}=o,u=l[0],g=l[l.length-1],{assetInDecimals:h}=u,{assetOutDecimals:d}=g,b=Math.abs(c),P=this.getMinimumTradeCount(n,i),x=this.getOptimalTradeCount(b),f=a?Math.round(s/a):x,w=Math.ceil(s/P),I=Math.round(s/x),A=Math.round(s/f),T=n.dividedBy(f).decimalPlaces(0,1),E=await this.router.getBestSell(e,t,v(T,h)),M=n.isLessThan(i),Be=[];M&&Be.push("OrderTooSmall");let xe=E.amountOut.multipliedBy(f),Ve=this.toBlockPeriod(A),$e=E.tradeFee.multipliedBy(f),Ke=G.build(l),ve={assetIn:e,assetOut:t,errors:Be,frequencyMin:w,frequencyOpt:I,frequency:A,tradeCount:f,tradeFee:$e,tradeImpactPct:E.priceImpactPct,tradePeriod:Ve,tradeRoute:Ke,type:"Dca"};return{...ve,amountIn:n,amountOut:xe,tradeAmountIn:E.amountIn,tradeAmountOut:E.amountOut,toHuman(){return{...ve,amountIn:v(n,h),amountOut:v(xe,d),tradeAmountIn:v(E.amountIn,h),tradeAmountOut:v(E.amountOut,d)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:i,swaps:o,priceImpactPct:n}=a,l=o[0],c=o[o.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,h=Math.abs(n),d=this.getTwapTradeCount(h),b=i.dividedBy(d).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,c.assetOut,v(b,u)),x=d===1,f=i.isLessThan(s),w=P.priceImpactPct<it,I=[];f||x?I.push("OrderTooSmall"):w&&I.push("OrderImpactTooBig");let A=P.amountOut.multipliedBy(d),T=P.tradeFee.multipliedBy(d),E=G.build(o),M={assetIn:e,assetOut:t,errors:I,tradeCount:d,tradeImpactPct:P.priceImpactPct,tradePeriod:Pe,tradeRoute:E,type:"TwapSell"};return{...M,amountIn:i,amountOut:A,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:T,toHuman(){return{...M,amountIn:v(i,u),amountOut:v(A,g),tradeAmountIn:v(P.amountIn,u),tradeAmountOut:v(P.amountOut,g),tradeFee:v(T,g)}}}}async getTwapBuyOrder(e,t,r){let[s,a]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:i,swaps:o,priceImpactPct:n}=a,l=o[0],c=o[o.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,h=Math.abs(n),d=this.getTwapTradeCount(h),b=i.dividedBy(d).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,c.assetOut,v(b,g)),x=P.amountIn.multipliedBy(d),f=d===1,w=x.isLessThan(s),I=P.priceImpactPct<it,A=[];w||f?A.push("OrderTooSmall"):I&&A.push("OrderImpactTooBig");let T=P.tradeFee.multipliedBy(d),E=G.build(o),M={assetIn:e,assetOut:t,errors:A,tradeCount:d,tradeImpactPct:P.priceImpactPct,tradePeriod:Pe,tradeRoute:E,type:"TwapBuy"};return{...M,amountIn:x,amountOut:i,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:T,toHuman(){return{...M,amountIn:v(x,u),amountOut:v(i,g),tradeAmountIn:v(P.amountIn,u),tradeAmountOut:v(P.amountOut,g),tradeFee:v(T,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>nt){let s=nt/(this.blockTime*Pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Ct)}};var Z=class extends _{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new H(e),this.aaveUtils=new K(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),ee)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Xe=class extends Z{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:a,assetOut:i}=s,n=(await this.balanceClient.getBalance(this.beneficiary,a)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,i)).amount.isGreaterThanOrEqualTo(n)),l&&e.isGreaterThanOrEqualTo(n)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],a=r[r.length-1],i=Q(e,this.slippagePct),o=s.assetIn,n=a.assetOut,l=e.plus(i),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(n,o,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(o,n,t.toFixed(),l.toFixed(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],a=r[r.length-1],i=Q(t,this.slippagePct),o=s.assetIn,n=a.assetOut,l=t.minus(i),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(o,n,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(o,n,e.toFixed(),l.toFixed(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,ee)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],a=Q(e,this.slippagePct),i=r.assetIn,o=s.assetOut,n=e.minus(a),l=this.api.tx.router.sellAll(i,o,n.toFixed(),G.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,ee)}return this.wrapTx("RouterSellAll",l)}};var Ye=class extends Z{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:a,tradeRoute:i}=this.order,o=this.api.tx.dca.schedule({owner:this.beneficiary,period:a,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:i}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:i,tradeRoute:o}=this.order,n=Q(a,this.slippagePct),l=a.minus(n),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:a,tradePeriod:i,tradeRoute:o}=this.order,n=Q(s,this.slippagePct),l=s.plus(n),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:a.toFixed(),maxAmountIn:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var Se=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new Xe(this.api,this.evm).setTrade(e)}order(e){return new Ye(this.api,this.evm).setOrder(e)}};var gs={router:{}};function Wm(p,e=gs){let t=new ie(p),r=new Ne(p),s=new ue(p,r),a=new K(r),i=new be(s,e.router),o=new fe(i,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:a,router:i,scheduler:o},client:{asset:new j(p),balance:new H(p),balanceV2:new ae(p)},ctx:{pool:s},evm:r,tx:new Se(p,r),destroy:()=>{s.destroy()}}}export{te as AaveClient,Ee as AavePool,ke as AavePoolClient,K as AaveUtils,j as AssetClient,yt as AssetNotFound,Os as BASILISK_PARACHAIN_ID,H as BalanceClient,ae as BalanceClientV2,B as BigNumber,ue as CachingPoolService,ie as ChainParams,Yt as DECIMAL_PLACES,Nt as DEFAULT_BLOCK_TIME,Et as DEFAULT_MIN_BUDGET,X as ERC20,Ne as EvmClient,Ze as FarmClient,W as H160,Te as HUB_ASSET_ID,Is as HYDRADX_PARACHAIN_ID,L as HYDRADX_SS58_PREFIX,Ms as INFINITY,U as LbpMath,_e as LbpPool,De as LbpPoolClient,R as ONE,Ct as ORDER_MIN_BLOCK_PERIOD,F as OmniMath,Me as OmniPool,Le as OmniPoolClient,lt as PERBILL_DENOMINATOR,$ as PERMILL_DENOMINATOR,_ as PolkadotApiClient,ht as PoolConfigNotFound,z as PoolError,me as PoolFactory,Fe as PoolNotFound,ce as PoolService,N as PoolType,ft as ProviderConfigNotFound,re as RUNTIME_DECIMALS,Re as RouteNotFound,he as Router,ct as SYSTEM_ASSET_DECIMALS,C as SYSTEM_ASSET_ID,k as StableMath,J as StableSwap,Ue as StableSwapClient,bt as StorageConfigNotFound,Pt as SubscriptionNotSupported,se as TRADEABLE_DEFAULT,Pe as TWAP_BLOCK_PERIOD,nt as TWAP_MAX_DURATION,it as TWAP_MAX_PRICE_IMPACT,Vu as TWAP_TX_MULTIPLIER,Rt as TradeOrderError,at as TradeOrderType,G as TradeRouteBuilder,be as TradeRouter,fe as TradeScheduler,st as TradeType,Se as TxBuilderFactory,V as XykMath,He as XykPool,Ge as XykPoolClient,S as ZERO,Bi as bnFormatter,m as bnum,Ft as calculateBuyFee,Ou as calculateDiffToAvg,ye as calculateDiffToRef,At as calculateSellFee,St as createChain,Wm as createSdkContext,Ce as findNestedKey,Si as findNestedObj,Q as getFraction,It as hashPools,qt as isEvmAccount,Wt as isEvmAddress,Xt as isSs58Address,O as scale,Ls as toBn,v as toDecimals};
|
|
1
|
+
var we=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var Qe=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var ot="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",je="0x112b087b60C1a166130d59266363C45F8aa99db0",ze="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ee=1000000n;var Bs=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var te=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:Qe,address:je,args:[ze],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:Qe,address:je,args:[ze,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:we,address:ot,args:[e],functionName:"getUserAccountData"})}};import{decodeAddress as Oe,encodeAddress as ut}from"@polkadot/util-crypto";import{hexToU8a as Ht,isHex as Gt,u8aToHex as Ut}from"@polkadot/util";import{Buffer as Y}from"buffer";var Os=2090,K=1e6,lt=1e9,Te="1",Is=2034,L=63,re=18,R="0",ct=12,se=15;var Je="ETH\0";function qt(p){if(!p)return!1;try{let e=Oe(p,!0),t=Y.from(Je);return Y.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Wt(p){return!!/^0x[a-fA-F0-9]{40}$/.test(p)}function Xt(p){try{let e=Gt(p)?Ht(p):Oe(p);return ut(e),!0}catch{return!1}}var W=class p{static toAccount=e=>{let t=Y.from(e.slice(2),"hex"),r=Y.from(Je);return ut(new Uint8Array(Y.concat([r,t,Y.alloc(8)])),63)};static fromAccount=e=>{let t=Oe(e),r=Y.from(Je),s=t.slice(r.length,-8);return"0x"+Y.from(s).toString("hex")};static fromSS58=e=>{let r=Oe(e).slice(0,20);return Ut(r)};static fromAny=e=>{if(Wt(e))return e;if(qt(e))return p.fromAccount(e);if(Xt(e))return p.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Ie}from"buffer";var X=class{static fromAssetId(e){let t=Number(e),r=Ie.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Ie.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Ie.from("0000000000000000000000000000000100000000","hex"),r=Ie.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as B}from"bignumber.js";var Yt=12;B.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Yt});var S=m(0),N=m(1),Ms=m("Infinity");function O(p,e){let t=new B(e.toString()),r=new B(10).pow(t);return p.times(r).decimalPlaces(4)}function m(p){return new B(p.toString())}function Ls(p,e){let t=m(p);return O(t,e)}function v(p,e){return p.shiftedBy(-1*e).toString()}var Ae=m("1e27"),Vt=m("1.01"),Kt=m("31536000"),$=class{client;constructor(e){this.client=new te(e)}async getSummary(e){let t=W.fromAny(e),[r,s,i,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[o]=r,[a,l]=s,[c,u,g,h,d,b]=i,P=m(b).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN),x=m(c),f=m(u),w=[];for(let I of a){let A=I.underlyingAsset.toLowerCase(),T=o.find(({underlyingAsset:Lt})=>Lt.toLowerCase()===A);if(!T)throw new Error("Missing pool reserve for "+A);let C=m(I.scaledATokenBalance),M=m(T.liquidityIndex),Be=m(T.liquidityRate),xe=m(T.availableLiquidity),Ve=m(T.priceInMarketReferenceCurrency),Ke=n+6,$e=this.calculateLinearInterest(Be,T.lastUpdateTimestamp,Ke),ve=M.multipliedBy($e).dividedBy(Ae).decimalPlaces(0,B.ROUND_DOWN),kt=C.multipliedBy(ve).dividedBy(Ae).decimalPlaces(0,B.ROUND_DOWN),_t=m(l!==0&&l===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold).div(1e4),Dt=T.usageAsCollateralEnabled&&I.usageAsCollateralEnabledOnUser&&m(I.scaledATokenBalance).gt(0),Mt=X.toAssetId(A);w.push({aTokenBalance:kt,availableLiquidity:xe,decimals:Number(T.decimals),isCollateral:Dt,priceInRef:Ve,reserveId:Mt,reserveAsset:A,reserveLiquidationThreshold:_t})}return{healthFactor:P.toNumber(),totalCollateral:x,totalDebt:f,reserves:w}}async hasBorrowPositions(e){let t=W.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=W.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,n,o,a,l]=r;return m(l).dividedBy(1e18).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=X.fromAssetId(t),a=n.find(x=>x.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:g}=a,h=O(m(r),l).decimalPlaces(0,1),d=c?h.multipliedBy(u).dividedBy(m(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN):S,b=s.minus(d);return b.lte(0)?0:b.multipliedBy(g).dividedBy(i).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:n}=await this.getSummary(e),o=X.fromAssetId(t),a=n.find(P=>P.reserveAsset===o);if(!a)throw new Error("Missing reserve ctx for "+o);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=a,h=O(m(r),l).decimalPlaces(0,1).multipliedBy(c).dividedBy(m(10).pow(l)).decimalPlaces(0,B.ROUND_DOWN),d=s.plus(h);return d.lte(0)?0:d.multipliedBy(u).dividedBy(i).decimalPlaces(6,B.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),n=X.fromAssetId(t),o=s.find(a=>a.reserveAsset===n);if(!o)throw new Error("Missing reserve data for "+n);return this.calculateWithdrawMax(o,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let n of r){let o=this.calculateWithdrawMax(n,t,s);n.reserveId&&(i[n.reserveId]=o)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:n,priceInRef:o,reserveLiquidationThreshold:a,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let g=m(r).minus(Vt);if(g.gt(0)){let d=g.multipliedBy(t).dividedBy(a).decimalPlaces(0,B.ROUND_DOWN).dividedBy(o).multipliedBy(m(10).pow(n)).decimalPlaces(0,B.ROUND_DOWN);c=B.minimum(s,d)}else c=S}return{amount:B.minimum(c,i),decimals:n}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ae:e.multipliedBy(s).dividedBy(Kt).plus(Ae).decimalPlaces(0,B.ROUND_DOWN)}};function mt(p){switch(p){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var _=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");mt(r)&&console.log(e,...t)}};var Q=class extends _{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e=="0"){let u=this.api.consts.balances.existentialDeposit;return{id:"0",name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:i,assetType:n,isSufficient:o,existentialDeposit:a}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:n.toHuman(),isSufficient:o?o.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,n]=s,{assetType:o,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(i.toString(),t,r),g=n.toNumber(),h=new Intl.DateTimeFormat("en-GB"),d=[c,"Bond",h.format(g)].join(" ");return{id:e,name:d,symbol:c+"b",decimals:u,icon:c,type:o.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:g}}getShares(e,t,r,s){let{assets:i}=s,{name:n,symbol:o,assetType:a,isSufficient:l,existentialDeposit:c}=t,g=i.map(b=>b.toString()).map(b=>{let{symbol:P}=this.getToken(b,t,r);return[b,P]}),h=Object.fromEntries(g),d=Object.values(h);return{id:e,name:d.join(", "),symbol:o?.isSome?o.toHuman():n.toHuman(),decimals:18,icon:d.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:h}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),n=r?.find(o=>o.internalId===i.id);return n?{...i,decimals:n.decimals,name:n.name,symbol:n.symbol,icon:n.symbol,isWhiteListed:n.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:n}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:n.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,n,o]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,o),c=a.map(([{args:[u]},g])=>{let h=g.unwrap(),d=s.get(u.toString()),{assetType:b}=h;switch(b.toString()){case"Bond":let P=n.get(u.toString());return this.getBond(u.toString(),h,l,P);case"StableSwap":let x=i.get(u.toString());return this.getShares(u.toString(),h,l,x);case"External":return this.getExternal(u.toString(),h,t,d);default:return this.getToken(u.toString(),h,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)}};var H=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeSystemBalances(e,t){return this.api.query.system.account.multi(e,r=>{let s=[];r.forEach((i,n)=>{let o=this.calculateFreeBalance(i.data),a=e[n];s.push([a,o])}),t(s)})}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=i[l][1];o.push([u,c])}),t(o)})}async subscribeTokenBalances(e,t){return this.api.query.tokens.accounts.multi(e,r=>{let s=[];r.forEach((i,n)=>{let o=this.calculateFreeBalance(i),a=e[n];s.push([a,o])}),t(s)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async subscribeErc20Balances(e,t){let r=async()=>{let s=await Promise.all(e.map(async i=>{let[n,o]=i;return[i,await this.getErc20Balance(n,o)]}));t(s)};return this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return B(t).lt(r)?B(0):B(t).minus(r)}};var ie=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(n=>[e,n]):s.map(({args:[n,o]})=>[n.toString(),o.toString()]);return this.api.query.tokens.accounts.multi(i,n=>{let o=[];n.forEach((a,l)=>{let c=i[l][1],u=this.calculateBalance(a);o.push([c,u])}),t(o)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),n=async()=>{let o=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(o)};return this.api.rpc.chain.subscribeNewHeads(async()=>{n()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=B(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",n=t.plus(s).toString();return{free:t.toString(),total:n,transferable:i,reserved:s,frozen:r}}};var ae=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as pt}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as $t}from"@polkadot/types";import{u8aConcat as dt}from"@polkadot/util";import{isAddress as gt}from"@polkadot/util-crypto";var Ze=class extends _{balanceClient;constructor(e){super(e),this.balanceClient=new H(e)}secondsInYear=new B(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(h,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([s,i])=>{let[,n]=s.args,o=i.unwrap().toString(),a=n.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,o)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),d=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(h,d);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new B(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[n]=i.unwrap(),o=n.price.n.toString(),a=n.price.d.toString(),l;return Number(t)<Number(r)?l=pt(o,a):l=pt(a,o),l}getGlobalRewardPerPeriod(e,t,r,s){let n=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return n.gte(r)?r:n}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return dt(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new $t(e,this.padEndU8a(dt(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!gt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&>(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:o,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new B(a.totalSharesZ.toString()),g=a.plannedYieldingPeriods.toString(),h=new B(a.yieldPerPeriod.toString()),d=new B(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),P=new B(o.multiplier.toString()).shiftedBy(-18),x=this.secondsInYear.div(new B(r).times(b)),f;if(u.isZero())f=h.times(P).times(x);else{let C=this.getGlobalRewardPerPeriod(u,h,d,l);f=this.getPoolYieldPerPeriod(C,P,u,l).times(x)}let w=new B(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),I=d.times(g),A=c?w.plus(c):I;return w.div(A).gte(.999)?S:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((o,a)=>o.plus(a),S).toString():void 0}};var Fe=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},ht=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ne=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},yt=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},bt=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Pt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},ft=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{defineChain as Qt}from"viem";var jt=["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"],St=p=>{let t=[p.endpoint,...jt],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return Qt({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://explorer.evm.hydration.cloud"}},testnet:!1})};import{createPublicClient as xt,createWalletClient as zt,custom as Jt,http as Zt}from"viem";function Bt(p){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return p.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Re=class{wsProvider;chain;constructor(e){let{provider:t}=e._options;this.wsProvider=t,this.chain=St(t)}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return xt({chain:this.chain,transport:Zt()})}getWsProvider(){return xt({chain:this.chain,transport:Bt(this.wsProvider)})}getSigner(e){return zt({account:e,chain:this.chain,transport:Jt(window.ethereum)})}};import{memoize1 as cs}from"@thi.ng/memoize";var E=(n=>(n.Aave="Aave",n.LBP="Lbp",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="Xyk",n.HSM="Hsm",n))(E||{}),j=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(j||{});var Ee=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(s.balance),o=m(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:S,assetOutED:S}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return O(N,e.decimalsOut)}spotPriceOutGivenIn(e){return O(N,e.decimalsIn)}calculateTradeFee(e,t){return S}};import{encodeAddress as rr}from"@polkadot/util-crypto";import{stringToU8a as sr}from"@polkadot/util";import{decodeEventLog as ir}from"viem";import{memoize1 as er}from"@thi.ng/memoize";import{TLRUCache as tr}from"@thi.ng/cache";var et=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var ne=class{client;constructor(e){this.client=e.getWsProvider()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.client.readContract({abi:et,address:e,functionName:"latestRoundData"}),this.client.readContract({abi:et,address:e,functionName:"decimals"}),this.client.getBlock()]),[n,o,a,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),u=Number(c);return{price:o,decimals:s,updatedAt:u<0?0:u}}};var D=class extends H{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new tr(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=er(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new ne(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(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();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=[],t=[],r=[],s=[];for(let o of this.augmentedPools){let{address:a,tokens:l}=o;l.filter(c=>c.id==="0").forEach(()=>{e.push(a)}),l.filter(c=>c.type==="Token"&&c.id!=="0"&&c.id!==o.id).forEach(c=>{t.push([a,c.id])}),l.filter(c=>c.type==="Erc20").forEach(c=>{r.push([a,c.id])})}let i=o=>{o.forEach(([a,l])=>{let c=this.pools.find(u=>u.address===a);if(c){let u=c.tokens.findIndex(g=>g.id==="0");c.tokens[u].balance=l.toString()}})},n=o=>{o.forEach(([a,l])=>{let[c,u]=a,g=this.pools.find(h=>h.address===c);if(g){let h=g.tokens.findIndex(d=>d.id===u);g.tokens[h].balance=l.toString()}})};if(e.length>0){let o=await this.subscribeSystemBalances(e,i);s.push(o)}if(t.length>0){let o=await this.subscribeTokenBalances(t,n);s.push(o)}if(r.length>0){let o=await this.subscribeErc20Balances(r,n);s.push(o)}return()=>{for(let o of s)try{o()}catch(a){console.warn("Balance unsub failed",a)}}}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}};function Ce(p,e){let t=[];return JSON.stringify(p,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Ba(p,e,t){let r;return JSON.stringify(p,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var xa=(p,e)=>typeof e=="bigint"?e.toString():e;var ar=["Supply","Withdraw","Repay","Borrow"],ke=class extends D{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return rr(sr(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?Ce(e.location,"accountKey20").accountKey20.key:X.fromAssetId(e.id)}isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,n]=r.data.toJSON();this.pools.filter(o=>o.tokens.some(a=>a.id===i.toString()||a.id===n.toString())).forEach(o=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${n}`),this.updatePoolState(o)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:o}=ir({abi:we,topics:i.topics,data:i.data});if(ar.includes(n)){let a=o.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===a}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${n} ${a}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(n=>{let o=n.id===t.id?s.toString():i.toString();return{...n,balance:o}})}};import{calculate_in_given_out as nr,calculate_out_given_in as or,calculate_linear_weights as lr,calculate_pool_trade_fee as cr,get_spot_price as ur}from"@galacticcouncil/math-lbp";var U=class{static getSpotPrice(e,t,r,s,i){return ur(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return nr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return or(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return lr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return cr(e,t,r)}};var y=class p{static toPct(e){let[t,r]=e;return p.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return p.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var _e=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new p(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(s.balance),o=m(i.balance);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(n)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let o=this.calculateTradeFee(t,r),a=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(o),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let o=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:o,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let n=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(n)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let o=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:o,feePct:0,errors:i}}else{let o=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(o,r),l=y.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=o.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:o,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=U.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=U.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=U.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),O(N,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=U.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),O(N,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=U.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var De=class extends D{MAX_FINAL_WEIGHT=O(m(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:i,assets:n,initialWeight:o,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=U.calculateLinearWeights(s.toString(),i.toString(),o.toString(),a.toString(),r),[g,h]=n,d=g.toString(),b=m(u),P=h.toString(),x=this.MAX_FINAL_WEIGHT.minus(m(b)),[f,w,I]=await Promise.all([this.isRepayFeeApplied(d,l.toString(),c.toString()),this.getBalance(e,d),this.getBalance(e,P)]);return{repayFeeApply:f,tokens:[{id:d,weight:b,balance:w.toString()},{id:P,weight:x,balance:I.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t>=r&&t<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,n])=>this.isActivePool(n.unwrap(),r.toNumber())).map(async([{args:[i]},n])=>{let o=n.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,o,r.toString());this.poolsData.set(i.toString(),o);let[c,u]=o.fee;return{address:a,type:"Lbp",fee:y.fromRate(c.toNumber(),u.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let n=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,n)}else{let n=this.pools.findIndex(o=>o.address==r.address);this.pools.splice(n,1)}})})}};import{calculate_in_given_out as mr,calculate_lrna_in_given_out as pr,calculate_out_given_in as dr,calculate_out_given_lrna_in as gr,calculate_spot_price as hr,calculate_lrna_spot_price as yr,calculate_shares as br,calculate_liquidity_out as Pr,calculate_liquidity_lrna_out as fr,calculate_liquidity_hub_in as Sr,is_sell_allowed as Br,is_buy_allowed as xr,is_add_liquidity_allowed as vr,is_remove_liquidity_allowed as wr,recalculate_asset_fee as Tr,recalculate_protocol_fee as Or,verify_asset_cap as Ir}from"@galacticcouncil/math-omnipool";var F=class{static calculateSpotPrice(e,t,r,s){return hr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return yr(e,t)}static calculateInGivenOut(e,t,r,s,i,n,o,a,l){return mr(e,t,r,s,i,n,o,a,l)}static calculateLrnaInGivenOut(e,t,r,s,i){return pr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i,n,o,a,l){return dr(e,t,r,s,i,n,o,a,l)}static calculateOutGivenLrnaIn(e,t,r,s,i){return gr(e,t,r,s,i)}static calculateShares(e,t,r,s){return br(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,n,o,a){return Pr(e,t,r,s,i,n,o,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,n,o,a){return fr(e,t,r,s,i,n,o,a)}static calculateCapDifference(e,t,r,s){let i=B(t),n=B(e),o=B(s),l=B(r).shiftedBy(-18);if(i.div(o).lt(l)){let u=l.times(o).minus(i).times(n),g=i.times(B(1).minus(l));return u.div(g).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return Sr(e,t,r,s)}static isSellAllowed(e){return Br(e)}static isBuyAllowed(e){return xr(e)}static isAddLiquidityAllowed(e){return vr(e)}static isRemoveLiquidityAllowed(e){return wr(e)}static recalculateAssetFee(e,t,r,s,i,n,o,a,l,c,u){return Tr(e,t,r,s,i,n,o,a,l,c,u)}static recalculateProtocolFee(e,t,r,s,i,n,o,a,l,c,u){return Or(e,t,r,s,i,n,o,a,l,c,u)}static verifyAssetCap(e,t,r,s){return Ir(e,t,r,s)}};var Me=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new p(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(s.balance),o=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let g=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(g)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let g=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(g)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=F.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=m(s);return i.isNegative()?S:i}calculateLrnaInGivenOut(e,t,r){let s=F.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=m(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=F.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString(),r?y.toRaw(r.protocolFee).toString():S.toString()),i=m(s);return i.isNegative()?S:i}calculateOutGivenLrnaIn(e,t,r){let s=F.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?y.toRaw(r.assetFee).toString():S.toString()),i=m(s);return i.isNegative()?S:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=F.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=F.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=F.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=F.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Ar}from"@polkadot/util-crypto";import{stringToU8a as Fr}from"@polkadot/util";import{memoize1 as tt}from"@thi.ng/memoize";import{TLRUCache as Nr}from"@thi.ng/cache";var vt="omnipool",wt="Short",Le=class extends D{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new Nr(null,{ttl:6*1e3});memOracleQuery=tt(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(vt,t,wt)},this.memQueryCache);memFeesQuery=tt(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=tt(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return Ar(Fr("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),n=r.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:g,cap:h,protocolShares:d}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:g.bits.toNumber(),balance:b.toString(),cap:m(h.toString()),protocolShares:m(d.toString())}}),o=await Promise.all(n);return o.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:o,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,n;if(this.isAssetConfigSupported()&&(n=await this.getDynamicFeesConfiguration(s).then(f=>f.unwrapOr(null))),n?.isFixed){let f=n.asFixed.assetFee.toNumber(),w=n.asFixed.protocolFee.toNumber();return{assetFee:y.fromPermill(f),protocolFee:y.fromPermill(w)}}let[o,a,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[c,u,g]=this.getAssetFee(t,e,o,a,n?.isDynamic?n.asDynamic.assetFeeParams:void 0),[h,d,b]=i==="1"?[0,0,0]:this.getProtocolFee(t,e,o,l,n?.isDynamic?n.asDynamic.protocolFeeParams:void 0),P=c+h,x=g+b;return{assetFee:y.fromPermill(u),protocolFee:y.fromPermill(d),min:y.fromPermill(P),max:y.fromPermill(x)}}getAssetFee(e,t,r,s,i){let{assetOut:n,balanceOut:o}=e,{minFee:a,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.assetFeeParameters,g=y.fromPermill(a.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[d]=s.unwrap(),{assetFee:b,timestamp:P}=r.unwrap(),x=Math.max(1,t-P.toNumber()),f=d.volume.bIn.toString(),w=d.volume.bOut.toString(),I=d.liquidity.b.toString();n==="0"&&(f=d.volume.aIn.toString(),w=d.volume.aOut.toString(),I=d.liquidity.a.toString());let A=y.fromPermill(b.toNumber()),T=F.recalculateAssetFee(f,w,I,"9",o.toString(),y.toRaw(A).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),c.toString(),u.toString());return[a.toNumber(),Number(T)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:n,balanceIn:o}=e,{minFee:a,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.protocolFeeParameters,g=y.fromPermill(a.toNumber()),h=y.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[d]=s.unwrap(),{protocolFee:b,timestamp:P}=r.unwrap(),x=Math.max(1,t-P.toNumber()),f=d.volume.bIn.toString(),w=d.volume.bOut.toString(),I=d.liquidity.b.toString();n==="0"&&(f=d.volume.aIn.toString(),w=d.volume.aOut.toString(),I=d.liquidity.a.toString());let A=y.fromPermill(b.toNumber()),T=F.recalculateProtocolFee(f,w,I,"9",o.toString(),y.toRaw(A).toString(),x.toString(),y.toRaw(g).toString(),y.toRaw(h).toString(),c.toString(),u.toString());return[a.toNumber(),Number(T)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let g=l.unwrap();return this.updateTokenState(u,g)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});if(r.push(i),this.isAssetConfigSupported()){let a=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,u)=>{let g=t[u];this.dynamicFeesConfiguration.set(g,c)})});r.push(a)}let n=t.map(a=>{let l=this.getOracleKey(a);return[vt,l,wt]}),o=await this.api.query.emaOracle.oracles.multi(n,a=>{a.forEach(async(l,c)=>{let u=n[c],[g,h,d]=u;this.oracles.set(h.join(":"),l)})});return r.push(o),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:n,protocolShares:o}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(n.toString()),protocolShares:m(o.toString()),tradeable:i.bits.toNumber()}}};import{calculate_in_given_out as Rr,calculate_out_given_in as Er,calculate_pool_trade_fee as Cr,get_spot_price as kr,calculate_liquidity_in as _r,calculate_shares as Dr,calculate_spot_price as Mr,calculate_spot_price_with_fee as Lr,calculate_liquidity_out_asset_a as Hr,calculate_liquidity_out_asset_b as Gr}from"@galacticcouncil/math-xyk";var V=class{static getSpotPrice(e,t,r){return kr(e,t,r)}static calculateInGivenOut(e,t,r){return Rr(e,t,r)}static calculateOutGivenIn(e,t,r){return Er(e,t,r)}static calculatePoolTradeFee(e,t,r){return Cr(e,t,r)}static calculateLiquidityIn(e,t,r){return _r(e,t,r)}static calculateSpotPrice(e,t){return Mr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return Lr(e,t,r,s)}static calculateShares(e,t,r){return Dr(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Hr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Gr(e,t,r,s)}};var He=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new p(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(s.balance),o=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:n,balanceOut:o,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return o.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:o,calculatedIn:s,amountOut:t,feePct:n,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),n=y.toPct(r.exchangeFee),o=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return o.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:o,feePct:n,errors:a}}calculateInGivenOut(e,t){let r=V.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}calculateOutGivenIn(e,t){let r=V.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?S:s}spotPriceInGivenOut(e){let t=V.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=O(N,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=V.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=O(N,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=V.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var Ge=class extends D{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[n,o]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(i,n.toString()),this.getBalance(i,o.toString())]);return{address:i,type:"Xyk",tokens:[{id:n.toString(),balance:a.toString()},{id:o.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return y.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};import{calculate_in_given_out as Ur,calculate_out_given_in as qr,calculate_amplification as Wr,calculate_add_one_asset as Xr,calculate_liquidity_out_one_asset as Yr,calculate_shares as Vr,calculate_shares_for_amount as Kr,calculate_spot_price_with_fee as $r,pool_account_name as Qr,recalculate_peg as jr}from"@galacticcouncil/math-stableswap";var k=class{static getPoolAddress(e){return Qr(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return Wr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,n,o){return Ur(e,t,r,s,i,n,o)}static calculateAddOneAsset(e,t,r,s,i,n,o){return Xr(e,t,r,s,i,n,o)}static calculateSharesForAmount(e,t,r,s,i,n,o){return Kr(e,t,r,s,i,n,o)}static calculateOutGivenIn(e,t,r,s,i,n,o){return qr(e,t,r,s,i,n,o)}static calculateLiquidityOutOneAsset(e,t,r,s,i,n,o){return Yr(e,t,r,s,i,n,o)}static calculateShares(e,t,r,s,i,n){return Vr(e,t,r,s,i,n)}static calculateSpotPriceWithFee(e,t,r,s,i,n,o,a){return $r(e,t,r,s,i,n,o,a)}static recalculatePegs(e,t,r,s,i){let n=jr(e,t,r,s,i);return JSON.parse(n)}};var J=class p{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new p(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let n=m(s.balance),o=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:n,balanceOut:o,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),n=i.minus(s),o=s===S?S:n.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:o.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),o=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:o.toNumber(),errors:a}}calculateIn(e,t,r){let s=k.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateAddOneAsset(e,t,r){let s=k.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateSharesForAmount(e,t,r){let s=k.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=O(N,e.decimalsIn-e.decimalsOut);return m(t).div(s).decimalPlaces(0,1)}let r=O(N,18-e.decimalsIn);return m(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=k.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateWithdrawOneAsset(e,t,r){let s=k.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateShares(e,t,r){let s=k.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?y.toRaw(r.fee).toString():S.toString(),this.getPegs()),i=m(s);return i.isNegative()?S:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=O(N,e.decimalsOut-e.decimalsIn);return m(t).div(s).decimalPlaces(0,1)}let r=O(N,18-e.decimalsOut);return m(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as zr,encodeAddress as Jr}from"@polkadot/util-crypto";var Ue=class extends D{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=k.getPoolAddress(t);return Jr(zr(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:n,finalBlock:o}=t,a=k.calculateAmplification(s.toString(),i.toString(),n.toString(),o.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async n=>{let[o,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,n.toString()),this.getBalance(e,n.toString())]);return{id:n.toString(),tradeable:o.bits.toNumber(),balance:a.toString()}});return Promise.all(i)}isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[n]},o])=>{try{let a=o.unwrap(),l=n.toString(),c=this.getPoolAddress(l),[u,g,h]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(c,l,a),this.getPoolPegs(l,a,r.toString())]);return g.push({id:l,tradeable:15,balance:u.totalIssuance}),this.poolsData.set(c,a),{address:c,id:l,type:"Stableswap",fee:y.fromPermill(a.fee.toNumber()),tokens:g,...u,...h,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${n.toString()}
|
|
2
|
+
`,String(a)),null}});return(await Promise.all(s)).filter(n=>n!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let i=s.unwrap(),n=await this.getLatestPegs(t,i,r),o=this.getRecentPegs(i),a=y.fromPermill(i.maxPegUpdate.toNumber()),l=y.fromPermill(t.fee.toNumber()),[c,u]=k.recalculatePegs(JSON.stringify(o),JSON.stringify(n),r,y.toRaw(a).toString(),y.toRaw(l).toString()),g=Number(c)*1e6;return{pegsFee:y.fromPermill(g),pegs:u}}getDefaultPegs(e){let t=e.fee,r=k.defaultPegs(e.assets.length);return{pegsFee:y.fromPermill(t.toNumber()),pegs:r}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([o,a])=>a.toString()),n=s.map(async(o,a)=>{if(o.isOracle){let[l,c,u]=o.asOracle,g=[u.toString(),i[a]].map(f=>Number(f)).sort((f,w)=>f-w),h=await this.api.query.emaOracle.oracles(l,g,c),[{price:d,updatedAt:b}]=h.unwrap(),P=d.n.toString(),x=d.d.toString();return u.toString()===g[0].toString()?[[P,x],b.toString()]:[[x,P],b.toString()]}else if(o.isMmOracle){let l=o.asMmOracle,{price:c,decimals:u,updatedAt:g}=await this.mmOracle.getData(l.toString()),h=10**u;return[[c.toString(),h.toString()],g.toString()]}else{if(o.isValue)return[o.asValue.map(l=>l.toString()),r];throw Error(o.type+" is not supported")}});return Promise.all(n)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[i,n]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),o=r.tokens.map(a=>a.id===r.id?{...a,balance:i.totalIssuance}:a);Object.assign(r,{tokens:o},i,n)}})})}};import{calculate_collateral_in_given_hollar_out as Zr,calculate_collateral_out_given_hollar_in as es,calculate_hollar_in_given_collateral_out as ts,calculate_hollar_out_given_collateral_in as rs,calculate_imbalance as ss,calculate_max_price as is,calculate_buyback_limit as as,calculate_buyback_price_with_fee as ns}from"@galacticcouncil/math-hsm";var q=class{static calculateCollateralInGivenHollarOut(e,t,r){return Zr(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return es(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return rs(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return ts(e,t,r)}static calculateImbalance(e,t,r){return ss(e,t,r)}static calculateBuybackLimit(e,t){return as(e,t)}static calculateBuybackPriceWithFee(e,t,r){return ns(e,t,r)}static calculateMaxPrice(e,t){return is(e,t)}};var qe=class p extends J{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new p(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let n=this.calculateBuyPrice(e,t,r),o=this.calculateMaxPrice(e);return n.gt(o)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=q.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return m(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=q.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return m(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=q.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),y.toRaw(this.buyBackFee).toString());return m(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=q.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),y.toRaw(this.purchaseFee).toString());return m(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=q.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return m(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=q.calculateBuybackLimit(t.toString(),y.toRaw(this.buyBackRate).toString());return m(r)}calculateBuyPrice(e,t,r){let s=t.dividedBy(m(10).pow(e.decimalsIn));return r.dividedBy(m(10).pow(e.decimalsOut)).dividedBy(s)}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=q.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return m(s).div(m(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=O(N,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=O(N,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[O(N,18).toString(),O(N,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};import{stringToU8a as Tt}from"@polkadot/util";import{encodeAddress as Ot}from"@polkadot/util-crypto";import{decodeEventLog as os}from"viem";var oe=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var le=class{client;constructor(e){this.client=e.getWsProvider()}async getFacilitatorCapacity(e,t){let[r,s]=await this.client.readContract({abi:oe,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var ls=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],We=class extends D{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new le(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return Ot(Tt(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return Ot(Tt("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return Ce(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),n=W.fromAny(i),o=this.getHollarAddress(t.unwrap()),a=await this.ghoTokenClient.getFacilitatorCapacity(o,n),l=r.map(async([{args:[u]},g])=>{let h=g.unwrap(),d=u.toString(),{poolId:b,maxBuyPriceCoefficient:P,maxInHolding:x,purchaseFee:f,buyBackFee:w,buybackRate:I}=h,A=s.find(T=>T.id===b.toString());if(A){let T=this.getPoolId(b.toString()),C=await this.getBalance(i,d);return{...A,address:T,type:"Hsm",tokens:A.tokens.filter(M=>M.id!==b.toString()),hsmAddress:i,hsmMintCapacity:m(a),hollarId:e,hollarH160:o,collateralId:d,collateralBalance:C,maxBuyPriceCoefficient:m(P.toString()),maxInHolding:m(x.unwrap().toString()),purchaseFee:y.fromPermill(f.toNumber()),buyBackFee:y.fromPermill(w.toNumber()),buyBackRate:y.fromPerbill(I.toNumber())}}});return(await Promise.all(l)).filter(u=>u!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:n,args:o}=os({abi:oe,topics:i.topics,data:i.data}),[a]=this.pools,{hsmAddress:l,hollarH160:c}=a,u=W.fromAny(l),g=u.toLowerCase()===o.facilitatorAddress.toLowerCase();if(ls.includes(n)&&g){let h=await this.ghoTokenClient.getFacilitatorCapacity(c,u);this.log(`Sync HSM facilitator via [evm:Log] :: ${n} ${h}`),this.pools.forEach(d=>{Object.assign(d,{hsmMintCapacity:h})})}}catch{}}})}async subscribeBalances(){let e=[],t=[],r=[];for(let i of this.pools){let{tokens:n,hsmAddress:o,collateralId:a}=i;n.find(c=>c.id===a).type==="Erc20"?t.push([o,a]):e.push([o,a])}let s=i=>{i.forEach(([n,o])=>{let[a,l]=n,c=this.pools.find(u=>u.tokens.some(g=>g.id===l));c&&Object.assign(c,{collateralBalance:o})})};if(e.length>0){let i=await this.subscribeTokenBalances(e,s);r.push(i)}if(t.length>0){let i=await this.subscribeErc20Balances(t,s);r.push(i)}return()=>{for(let i of r)try{i()}catch(n){console.warn("Balance unsub failed",n)}}}async subscribeUpdates(){return()=>{}}};var ce=class extends _{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=cs(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new Q(this.api),this.aaveClient=new ke(this.api,t),this.xykClient=new Ge(this.api,t),this.omniClient=new Le(this.api,t),this.lbpClient=new De(this.api,t),this.stableClient=new Ue(this.api,t),this.hsmClient=new We(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Fe(t.type)}}};var ue=class extends ce{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var me=class{static get(e){switch(e.type){case"Aave":return Ee.fromPool(e);case"Xyk":return He.fromPool(e);case"Omnipool":return Me.fromPool(e);case"Lbp":return _e.fromPool(e);case"Stableswap":return J.fromPool(e);case"Hsm":return qe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as us}from"@noble/hashes/sha256";import{bytesToHex as ms}from"@noble/hashes/utils";function It(p){let e=p.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=us(t);return ms(r)}var pe=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 ps=8,de=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new pe,n=[];for(n.push([t,""]),i.enqueue(n);i.size()>0;){let o=i.dequeue();if(!o||o.length>ps)continue;let a=o[o.length-1];(r===null||a[0]===r)&&s.push(o),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,o)){let u=[...o];u.push(c),i.enqueue(u)}})}return s}findShortestPaths(e,t,r){let s=[],i=new pe,n=[];n.push([t,""]),i.enqueue(n);let o=1/0;for(;i.size()>0;){let a=i.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<o?(o=a.length,s.length=0,s.push(a)):a.length===o&&s.push(a);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,a)&&i.enqueue([...a,u])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,n]of t){let o=parseInt(i),a=parseInt(n);r.get(o)?.push([a,s])}return r}};function rt(p){let e={};for(let t of p){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let n=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(n)}}}return e}var ge=class{getProposals(e,t,r){let s=r.filter(f=>f.type==="Xyk"),i=r.filter(f=>f.type!=="Xyk"),n=parseInt(e),o=parseInt(t),a=new Set(i.map(f=>f.tokens).flat().map(f=>f.id)),l=a.has(e),c=a.has(t),u=new de,g=f=>{let w=rt(f),I=Object.keys(w),A=I.flatMap(T=>w[T]);return u.buildAndPopulateGraph(I,A)};if(!l&&!c){let f=s.filter(A=>A.tokens.find(T=>T.id===e)||A.tokens.find(T=>T.id===t)),w=g(f),I=u.findPaths(w,n,o);return this.parsePaths(I)}if(l&&c){let f=g(i),w=u.findPaths(f,n,o);return this.parsePaths(w)}let h=l?t:e,d=s.filter(f=>f.tokens.some(w=>w.id===h)),b=[...i,...d],P=g(b),x=u.findPaths(P,n,o);return this.parsePaths(x)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let n=r[i],o=r[i+1];if(o==null)break;s.push(this.toEdge(n,o))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var he=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new ge,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}async getPools(){return await this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(o=>this.validPath(o,s)).map(o=>this.toHops(o,s))}getProposals(e,t,r){let s=`${e}->${t}::${It(r)}`;if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,me.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let n=t.get(r);return{poolAddress:r,poolId:n?.id,pool:n?.type,assetIn:s,assetOut:i}})}};var ds=m("100");function Iu(p,e){return p.minus(e).abs().div(p.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function ye(p,e){return p.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function At(p,e){return N.minus(e.div(p)).multipliedBy(100).decimalPlaces(4)}function Ft(p,e){return e.div(p).minus(N).multipliedBy(100).decimalPlaces(4)}function z(p,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),p.div(ds).multipliedBy(e).decimalPlaces(0,1)}var st=(t=>(t.Buy="Buy",t.Sell="Sell",t))(st||{}),it=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(it||{}),Nt=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Nt||{});var be=class extends he{async loadRouteContext(e,t){let r=await super.getPools(),s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(i.length===0)throw new Ne(e,t);return{paths:i,pools:r,poolsMap:s}}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,n=s[s.length-1].amountOut;return i.isGreaterThan(n)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[r,s]}}getPoolFeeRange(e){let t=e.min?y.toPct(e.min):void 0,r=e.max?y.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toSellSwaps(r,s,n);else{let a=i.map(async c=>await this.toSellSwaps(r,c,n)),l=await Promise.all(a);o=this.findBestSellRoute(l)}return this.buildSell(n,o)}async getSellTrades(e,t,r){let{paths:s,poolsMap:i}=await this.loadRouteContext(e,t),n=s.map(async a=>await this.toSellSwaps(r,a,i));return(await Promise.all(n)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildSell(i,a)).sort((a,l)=>a.amountOut.isGreaterThan(l.amountOut)?-1:1)}buildSell(e,t){let r=t[0],s=t[t.length-1],i=this.isDirectTrade(t),n=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetOutDecimals)).reduce((b,P)=>b.multipliedBy(P)),o=O(n,s.assetOutDecimals),a=i?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,c=i?s.tradeFeePct:At(a,l).toNumber(),u=a.minus(l),g=this.getRouteFeeRange(t),h=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(o),d=ye(a,h);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:o,tradeFee:u,tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:v(r.amountIn,r.assetInDecimals),amountOut:v(s.amountOut,s.assetOutDecimals),spotPrice:v(o,s.assetOutDecimals),tradeFee:v(u,s.assetOutDecimals),tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d.toNumber(),swaps:t.map(b=>b.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1]:l=e;let c=o.calculateOutGivenIn(a,l);s.push(c)}return s[s.length-1]}async toSellSwaps(e,t,r){let s=[];for(let i=0;i<t.length;i++){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i>0?l=s[i-1].amountOut:l=O(m(e),a.decimalsIn).decimalPlaces(0,1);let c=await this.poolService.getPoolFees(a,o),{amountOut:u,calculatedOut:g,feePct:h,errors:d}=o.validateAndSell(a,l,c),b=this.getPoolFeeRange(c),P=o.spotPriceOutGivenIn(a),x=l.shiftedBy(-1*a.decimalsIn).multipliedBy(P),f=ye(g,x);s.push({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:l,amountOut:u,calculatedOut:g,spotPrice:P,tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:v(l,a.decimalsIn),amountOut:v(u,a.decimalsOut),calculatedOut:v(g,a.decimalsOut),spotPrice:v(P,a.decimalsOut),tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f.toNumber(),errors:d}}})}return s}async getMostLiquidRoute(e,t){let{paths:r,pools:s,poolsMap:i}=await this.loadRouteContext(e,t),l=s.filter(h=>h.tokens.some(d=>d.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(d=>d.id===e)).map(h=>h.map(d=>m(d.balance).shiftedBy(-1*d.decimals)).reduce((d,b)=>d.plus(b))).sort((h,d)=>d.isLessThan(h)?-1:1)[0].div(100).multipliedBy(.1),c=r.map(async h=>await this.toSellSwaps(l,h,i)),u=await Promise.all(c);return this.findBestSellRoute(u).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut}))}async getBestSpotPrice(e,t){let r;try{r=await this.loadRouteContext(e,t)}catch{return Promise.resolve(void 0)}let{poolsMap:s}=r,i=await this.getMostLiquidRoute(e,t),n=await this.toSellSwaps("1",i,s),o=n.map(c=>c.spotPrice.shiftedBy(-1*c.assetOutDecimals)).reduce((c,u)=>c.multipliedBy(u)),a=n[n.length-1].assetOutDecimals;return{amount:O(o,a),decimals:a}}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,n=s[0].amountIn;return i.isGreaterThan(n)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){let{paths:i,poolsMap:n}=await this.loadRouteContext(e,t),o;if(s)o=await this.toBuySwaps(r,s,n);else{let a=i.map(async c=>await this.toBuySwaps(r,c,n)),l=await Promise.all(a);o=this.findBestBuyRoute(l)}return this.buildBuy(n,o)}async getBuyTrades(e,t,r){let{paths:s,poolsMap:i}=await this.loadRouteContext(e,t),n=s.map(async a=>await this.toBuySwaps(r,a,i));return(await Promise.all(n)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildBuy(i,a)).sort((a,l)=>a.amountIn.isGreaterThan(l.amountIn)?1:-1)}buildBuy(e,t){let r=t[t.length-1],s=t[0],i=this.isDirectTrade(t),n=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetInDecimals)).reduce((b,P)=>b.multipliedBy(P)),o=O(n,s.assetInDecimals),a=i?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,c=i?s.tradeFeePct:Ft(a,l).toNumber(),u=l.minus(a),g=this.getRouteFeeRange(t),h=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(o),d;return a.isZero()?d=-100:d=ye(h,a).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:o,tradeFee:u,tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d,swaps:t,toHuman(){return{type:"Buy",amountOut:v(r.amountOut,r.assetOutDecimals),amountIn:v(s.amountIn,s.assetInDecimals),spotPrice:v(o,s.assetInDecimals),tradeFee:v(u,s.assetInDecimals),tradeFeePct:c,tradeFeeRange:g,priceImpactPct:d,swaps:t.map(b=>b.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=e:l=s[0];let c=o.calculateInGivenOut(a,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let n=t[i],o=r.get(n.poolAddress);if(o==null)throw new Error("Pool does not exit");let a=o.parsePair(n.assetIn,n.assetOut),l;i==t.length-1?l=O(m(e),a.decimalsOut).decimalPlaces(0,1):l=s[0].amountIn;let c=await this.poolService.getPoolFees(a,o),{amountIn:u,calculatedIn:g,feePct:h,errors:d}=o.validateAndBuy(a,l,c),b=this.getPoolFeeRange(c),P=o.spotPriceInGivenOut(a),x=l.shiftedBy(-1*a.decimalsOut).multipliedBy(P),f;g.isZero()?f=-100:f=ye(x,g).toNumber(),s.unshift({...n,assetInDecimals:a.decimalsIn,assetOutDecimals:a.decimalsOut,amountIn:u,amountOut:l,calculatedIn:g,spotPrice:P,tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f,errors:d,isSupply(){return o.type==="Aave"&&o.tokens[0].id===n.assetIn},isWithdraw(){return o.type==="Aave"&&o.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:v(u,a.decimalsIn),amountOut:v(l,a.decimalsOut),calculatedIn:v(g,a.decimalsIn),spotPrice:v(P,a.decimalsIn),tradeFeePct:h,tradeFeeRange:b,priceImpactPct:f,errors:d}}})}return s}};var Rt=6e3,Et=m(1e15),Pe=6,at=-5,nt=360*60*1e3,Ku=3,Ct=6;var G=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var fe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Rt,minBudgetInNative:t.minBudgetInNative??Et})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[n,o]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:c}=o,u=l[0],g=l[l.length-1],{assetInDecimals:h}=u,{assetOutDecimals:d}=g,b=Math.abs(c),P=this.getMinimumTradeCount(a,n),x=this.getOptimalTradeCount(b),f=i?Math.round(s/i):x,w=Math.ceil(s/P),I=Math.round(s/x),A=Math.round(s/f),T=a.dividedBy(f).decimalPlaces(0,1),C=await this.router.getBestSell(e,t,v(T,h)),M=a.isLessThan(n),Be=[];M&&Be.push("OrderTooSmall");let xe=C.amountOut.multipliedBy(f),Ve=this.toBlockPeriod(A),Ke=C.tradeFee.multipliedBy(f),$e=G.build(l),ve={assetIn:e,assetOut:t,errors:Be,frequencyMin:w,frequencyOpt:I,frequency:A,tradeCount:f,tradeFee:Ke,tradeImpactPct:C.priceImpactPct,tradePeriod:Ve,tradeRoute:$e,type:"Dca"};return{...ve,amountIn:a,amountOut:xe,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...ve,amountIn:v(a,h),amountOut:v(xe,d),tradeAmountIn:v(C.amountIn,h),tradeAmountOut:v(C.amountOut,d)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:n,swaps:o,priceImpactPct:a}=i,l=o[0],c=o[o.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,h=Math.abs(a),d=this.getTwapTradeCount(h),b=n.dividedBy(d).decimalPlaces(0,1),P=await this.router.getBestSell(l.assetIn,c.assetOut,v(b,u)),x=d===1,f=n.isLessThan(s),w=P.priceImpactPct<at,I=[];f||x?I.push("OrderTooSmall"):w&&I.push("OrderImpactTooBig");let A=P.amountOut.multipliedBy(d),T=P.tradeFee.multipliedBy(d),C=G.build(o),M={assetIn:e,assetOut:t,errors:I,tradeCount:d,tradeImpactPct:P.priceImpactPct,tradePeriod:Pe,tradeRoute:C,type:"TwapSell"};return{...M,amountIn:n,amountOut:A,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:T,toHuman(){return{...M,amountIn:v(n,u),amountOut:v(A,g),tradeAmountIn:v(P.amountIn,u),tradeAmountOut:v(P.amountOut,g),tradeFee:v(T,g)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:n,swaps:o,priceImpactPct:a}=i,l=o[0],c=o[o.length-1],{assetInDecimals:u}=l,{assetOutDecimals:g}=c,h=Math.abs(a),d=this.getTwapTradeCount(h),b=n.dividedBy(d).decimalPlaces(0,1),P=await this.router.getBestBuy(l.assetIn,c.assetOut,v(b,g)),x=P.amountIn.multipliedBy(d),f=d===1,w=x.isLessThan(s),I=P.priceImpactPct<at,A=[];w||f?A.push("OrderTooSmall"):I&&A.push("OrderImpactTooBig");let T=P.tradeFee.multipliedBy(d),C=G.build(o),M={assetIn:e,assetOut:t,errors:A,tradeCount:d,tradeImpactPct:P.priceImpactPct,tradePeriod:Pe,tradeRoute:C,type:"TwapBuy"};return{...M,amountIn:x,amountOut:n,tradeAmountIn:P.amountIn,tradeAmountOut:P.amountOut,tradeFee:T,toHuman(){return{...M,amountIn:v(x,u),amountOut:v(n,g),tradeAmountIn:v(P.amountIn,u),tradeAmountOut:v(P.amountOut,g),tradeFee:v(T,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>nt){let s=nt/(this.blockTime*Pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,Ct)}};var Z=class extends _{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new H(e),this.aaveUtils=new $(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r;try{r=await this.api.call.dryRunApi.dryRunCall({System:{Signed:e}},t.inner.toHex())}catch(s){throw console.error(s),new Error("Dry run execution failed!")}if(r.isOk)return r.asOk;throw console.log(r.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),ee)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Xe=class extends Z{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:n}=s,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,n)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=z(e,this.slippagePct),o=s.assetIn,a=i.assetOut,l=e.plus(n),c;return this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,o,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(o,a,t.toFixed(),l.toFixed(),G.build(r)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],n=z(t,this.slippagePct),o=s.assetIn,a=i.assetOut,l=t.minus(n),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(o,a,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(o,a,e.toFixed(),l.toFixed(),G.build(r)),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let g=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSellAll",g,ee)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=z(e,this.slippagePct),n=r.assetIn,o=s.assetOut,a=e.minus(i),l=this.api.tx.router.sellAll(n,o,a.toFixed(),G.build(t));if(r.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,ee)}return this.wrapTx("RouterSellAll",l)}};var Ye=class extends Z{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:n}=this.order,o=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:n}}},null);return this.wrapTx("DcaSchedule",o)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=z(i,this.slippagePct),l=i.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:n,tradeRoute:o}=this.order,a=z(s,this.slippagePct),l=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:n,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:o}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var Se=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new Xe(this.api,this.evm).setTrade(e)}order(e){return new Ye(this.api,this.evm).setOrder(e)}};var gs={router:{}};function Xm(p,e=gs){let t=new ae(p),r=new Re(p),s=new ue(p,r),i=new $(r),n=new be(s,e.router),o=new fe(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:n,scheduler:o},client:{asset:new Q(p),balance:new H(p),balanceV2:new ie(p)},ctx:{pool:s},evm:r,tx:new Se(p,r),destroy:()=>{s.destroy()}}}export{te as AaveClient,Ee as AavePool,ke as AavePoolClient,$ as AaveUtils,Q as AssetClient,yt as AssetNotFound,Os as BASILISK_PARACHAIN_ID,H as BalanceClient,ie as BalanceClientV2,B as BigNumber,ue as CachingPoolService,ae as ChainParams,Yt as DECIMAL_PLACES,Rt as DEFAULT_BLOCK_TIME,Et as DEFAULT_MIN_BUDGET,X as ERC20,Re as EvmClient,Ze as FarmClient,W as H160,Te as HUB_ASSET_ID,Is as HYDRADX_PARACHAIN_ID,L as HYDRADX_SS58_PREFIX,Ms as INFINITY,U as LbpMath,_e as LbpPool,De as LbpPoolClient,N as ONE,Ct as ORDER_MIN_BLOCK_PERIOD,F as OmniMath,Me as OmniPool,Le as OmniPoolClient,lt as PERBILL_DENOMINATOR,K as PERMILL_DENOMINATOR,_ as PolkadotApiClient,ht as PoolConfigNotFound,j as PoolError,me as PoolFactory,Fe as PoolNotFound,ce as PoolService,E as PoolType,ft as ProviderConfigNotFound,re as RUNTIME_DECIMALS,Ne as RouteNotFound,he as Router,ct as SYSTEM_ASSET_DECIMALS,R as SYSTEM_ASSET_ID,k as StableMath,J as StableSwap,Ue as StableSwapClient,bt as StorageConfigNotFound,Pt as SubscriptionNotSupported,se as TRADEABLE_DEFAULT,Pe as TWAP_BLOCK_PERIOD,nt as TWAP_MAX_DURATION,at as TWAP_MAX_PRICE_IMPACT,Ku as TWAP_TX_MULTIPLIER,Nt as TradeOrderError,it as TradeOrderType,G as TradeRouteBuilder,be as TradeRouter,fe as TradeScheduler,st as TradeType,Se as TxBuilderFactory,V as XykMath,He as XykPool,Ge as XykPoolClient,S as ZERO,xa as bnFormatter,m as bnum,Ft as calculateBuyFee,Iu as calculateDiffToAvg,ye as calculateDiffToRef,At as calculateSellFee,St as createChain,Xm as createSdkContext,Ce as findNestedKey,Ba as findNestedObj,z as getFraction,It as hashPools,qt as isEvmAccount,Wt as isEvmAddress,Xt as isSs58Address,O as scale,Ls as toBn,v as toDecimals};
|
|
@@ -9,8 +9,11 @@ export declare class BalanceClient extends PolkadotApiClient {
|
|
|
9
9
|
getTokenBalance(account: string, assetId: string): Promise<BigNumber>;
|
|
10
10
|
getErc20Balance(account: string, assetId: string): Promise<BigNumber>;
|
|
11
11
|
subscribeSystemBalance(address: string, onChange: (token: string, balance: BigNumber) => void): UnsubscribePromise;
|
|
12
|
+
subscribeSystemBalances(queries: string[], onChange: (balances: [string, BigNumber][]) => void): UnsubscribePromise;
|
|
12
13
|
subscribeTokenBalance(address: string, onChange: (balances: [string, BigNumber][]) => void, assets?: string[]): UnsubscribePromise;
|
|
14
|
+
subscribeTokenBalances(queries: string[][], onChange: (balances: [string[], BigNumber][]) => void): UnsubscribePromise;
|
|
13
15
|
subscribeErc20Balance(address: string, onChange: (balances: [string, BigNumber][]) => void, assets?: string[]): UnsubscribePromise;
|
|
16
|
+
subscribeErc20Balances(queries: string[][], onChange: (balances: [string[], BigNumber][]) => void): UnsubscribePromise;
|
|
14
17
|
getTokenBalanceData(account: string, assetId: string): Promise<OrmlTokensAccountData>;
|
|
15
18
|
protected calculateFreeBalance(data: PalletBalancesAccountData | OrmlTokensAccountData): BigNumber;
|
|
16
19
|
}
|
|
@@ -36,13 +36,7 @@ export declare abstract class PoolClient extends BalanceClient {
|
|
|
36
36
|
getPoolsMem(): Promise<PoolBase[]>;
|
|
37
37
|
getPools(): Promise<PoolBase[]>;
|
|
38
38
|
protected subscribeBalances(): UnsubscribePromise;
|
|
39
|
-
private hasSystemAsset;
|
|
40
|
-
private hasErc20Asset;
|
|
41
39
|
unsubscribe(): void;
|
|
42
|
-
private subscribeLog;
|
|
43
|
-
private subscribeSystemPoolBalance;
|
|
44
|
-
private subscribeTokensPoolBalance;
|
|
45
|
-
private subscribeErc20PoolBalance;
|
|
46
40
|
/**
|
|
47
41
|
* Check if pool valid. Only XYK pools are being verified as those are
|
|
48
42
|
* considered permissionless.
|
|
@@ -58,6 +52,4 @@ export declare abstract class PoolClient extends BalanceClient {
|
|
|
58
52
|
* @returns asset pool with augmented tokens
|
|
59
53
|
*/
|
|
60
54
|
private withMetadata;
|
|
61
|
-
private updateBalancesCallback;
|
|
62
|
-
private updateBalanceCallback;
|
|
63
55
|
}
|
package/package.json
CHANGED