@galacticcouncil/sdk-next 0.13.0 → 0.14.0-pr220-de485c9
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 +1 -1
- package/build/index.mjs +1 -1
- package/build/types/aave/AaveUtils.d.ts +5 -0
- package/package.json +2 -2
package/build/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var ai=Object.defineProperty;var v=(m,t)=>{for(var e in t)ai(m,e,{get:t[e],enumerable:!0})};import ri from"buffer";typeof window<"u"&&(window.Buffer=ri.Buffer);var en={};v(en,{Papi:()=>E,getWs:()=>mi});import{hydration as si}from"@galacticcouncil/descriptors";function tn(m){switch(m){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var E=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(si)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");tn(n)&&console.log(t,...e)}};import{createClient as oi}from"polkadot-api";import{withLogsRecorder as li}from"polkadot-api/logs-provider";import{withLegacy as ci}from"@polkadot-api/legacy-provider";import{getWsProvider as ui}from"polkadot-api/ws-provider";var mi=async m=>{let t=typeof m=="string"?m.split(","):m,e=ui(t,{innerEnhancer:ci()}),n=li(i=>console.log(i),e);return oi(e)};var un={};v(un,{AAVE_GAS_LIMIT:()=>Te,AAVE_LENDING_POOL_ADDRESS:()=>se,AAVE_POOL_ABI:()=>Se,AAVE_POOL_DATA_PROVIDER:()=>re,AAVE_POOL_DATA_PROVIDER_ABI:()=>ae,AAVE_POOL_PROXY:()=>xe,AAVE_ROUNDING_THRESHOLD:()=>Ds,AAVE_UINT_256_MAX:()=>pi,AaveClient:()=>At,AaveUtils:()=>it});var Se=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var ae=[{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 xe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",re="0x112b087b60C1a166130d59266363C45F8aa99db0",se="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Te=1000000n,Ds=5,pi=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var At=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:ae,address:re,args:[se],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:ae,address:re,args:[se,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:Se,address:xe,args:[t],functionName:"getUserAccountData"})}};import N from"big.js";var P={};v(P,{asBigInt:()=>hi,toBigInt:()=>gi,toDecimal:()=>di});import nt from"big.js";nt.NE=-18;function di(m,t,e=6,n){let i=nt(m.toString()),a=nt(10).pow(t);return i.div(a).round(e,n).toString()}function gi(m,t){let e=nt(10).pow(t),i=nt(m).mul(e).toFixed(0,nt.roundDown);return BigInt(i)}function hi(m){return BigInt(m.round(0,nt.roundDown).toFixed(0))}var rt={};v(rt,{ERC20:()=>ve});var ve=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var w={};v(w,{FeeUtils:()=>Ae,shiftNeg:()=>Pi});import fi from"big.js";var nn={};v(nn,{HUB_ASSET_ID:()=>Ot,HYDRATION_OMNIPOOL_ADDRESS:()=>yi,HYDRATION_PARACHAIN_ID:()=>bi,HYDRATION_SS58_PREFIX:()=>k,PERBILL_DENOMINATOR:()=>we,PERMILL_DENOMINATOR:()=>st,RUNTIME_DECIMALS:()=>_,SYSTEM_ASSET_DECIMALS:()=>Ie,SYSTEM_ASSET_ID:()=>F,TRADEABLE_DEFAULT:()=>ot});var _=18,st=1e6,we=1e9,F=0,Ie=12,bi=2034,k=63,yi="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Ot=1,ot=15;var Ae=class m{static toPct(t){let[e,n]=t;return m.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return m.safeDivide(e,n)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,n=12){let i=10**n;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Pi(m,t){let e=fi(typeof m=="bigint"?m.toString():m);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var lt={};v(lt,{H160:()=>Be,isEvmAccount:()=>rn,isEvmAddress:()=>sn,isSs58Address:()=>on});import{AccountId as Bt}from"polkadot-api";import{toHex as an}from"@polkadot-api/utils";import{Buffer as Q}from"buffer";var Oe="ETH\0";function rn(m){if(!m)return!1;try{let t=Bt().enc(m),e=Q.from(Oe);return Q.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function sn(m){return!!/^0x[a-fA-F0-9]{40}$/.test(m)}function on(m){try{return Bt(63).enc(m),!0}catch{return!1}}var Be=class m{static toAccount=t=>{let e=Q.from(t.slice(2),"hex"),n=Q.from(Oe),i=Uint8Array.from(Q.concat([n,e,Q.alloc(8)])),a=an(i);return Bt(63).dec(a)};static fromAccount=t=>{let e=Bt().enc(t),n=Q.from(Oe),i=e.slice(n.length,-8);return"0x"+Q.from(i).toString("hex")};static fromSS58=t=>{let n=Bt().enc(t).slice(0,20);return an(n)};static fromAny=t=>{if(sn(t))return t;if(rn(t))return m.fromAccount(t);if(on(t))return m.fromSS58(t);throw new Error("Unknown address type")}};var _t={};v(_t,{findNestedKey:()=>Si,findNestedObj:()=>xi,jsonFormatter:()=>Ti});var Si=(m,t)=>{let e=[];return JSON.stringify(m,(n,i)=>(i&&i[t]&&e.push(i),i)),e[0]},xi=(m,t,e)=>{let n;return JSON.stringify(m,(i,a)=>(a&&a[t]===e&&(n=a),a)),n},Ti=(m,t)=>typeof t=="bigint"?t.toString():t;var B={};v(B,{calculateBuyFee:()=>Ai,calculateDiffToAvg:()=>vi,calculateDiffToRef:()=>wi,calculateSellFee:()=>Ii,getFraction:()=>Oi});import z from"big.js";function vi(m,t){let e=z(m.toString()),n=z(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function wi(m,t){if(t===0n)return 0;let e=z(m.toString()),n=z(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function Ii(m,t){if(m===0n)return 0;let e=z(m.toString()),n=z(t.toString());return z(1).minus(n.div(e)).mul(100).round(2).toNumber()}function Ai(m,t){if(m===0n)return 0;let e=z(m.toString());return z(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Oi(m,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),i=BigInt(t*n);return m*i/BigInt(100*n)}var ln={};v(ln,{convertToId:()=>_i});import{Buffer as Bi}from"buffer";function _i(m){let e=Bi.from(m.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}import{TLRUCache as cn}from"@thi.ng/cache";var oe=class{debug;constructor(t){this.debug=t||!1}log(t,e,n){this.debug&&console.log(t,e,n)}scope(t,e,n,i){let a=new Map,r=i!==void 0?new cn(null,{ttl:i}):new cn;return{get:(...c)=>{let u=n(...c);if(a.has(u)){this.log("[live]",t,u);let d=a.get(u);return Promise.resolve(d)}if(r.has(u))return this.log("[memo]",t,u),r.get(u);this.log("[fetch]",t,u);let p=e(...c).catch(d=>{throw r.delete(u),d});return r.set(u,p),p},set:(c,...u)=>{let p=n(...u);this.log("[set-live]",t,p),a.set(p,c)},clear:()=>{this.log("[clear]",t),a.clear(),r.release()}}}};var{ERC20:ct}=rt,{H160:_e}=lt,Fi=1.01,Ri=31536000n,le=10n**27n,it=class{client;constructor(t){this.client=new At(t)}async getSummary(t){let e=_e.fromAny(t),[n,i,a,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[s]=n,[o,l]=i,[c,u,p,d,g,b]=a,h=P.toDecimal(b,18),y=[];for(let f of o){let S=f.underlyingAsset.toLowerCase(),x=s.find(({underlyingAsset:Pe})=>Pe.toLowerCase()===S);if(!x)throw new Error("Missing pool reserve for "+S);let T=f.scaledATokenBalance,A=x.liquidityIndex,O=x.liquidityRate,D=x.availableLiquidity,U=x.priceInMarketReferenceCurrency,K=r+6,H=this.calculateLinearInterest(O,x.lastUpdateTimestamp,K),W=A*H/le,tt=T*W/le,ee=Number(l!==0&&l===x.eModeCategoryId?x.eModeLiquidationThreshold:x.reserveLiquidationThreshold)/1e4,ne=x.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,ie=ct.toAssetId(S);y.push({aTokenBalance:tt,availableLiquidity:D,decimals:Number(x.decimals),isCollateral:ne,priceInRef:U,reserveId:ie,reserveAsset:S,reserveLiquidationThreshold:ee})}return{healthFactor:Number(h),totalCollateral:c,totalDebt:u,reserves:y}}async hasBorrowPositions(t){let e=_e.fromAny(t),n=await this.client.getUserAccountData(e),[i,a]=n;return a>0n}async getHealthFactor(t){let e=_e.fromAny(t),n=await this.client.getUserAccountData(e),[i,a,r,s,o,l]=n,c=P.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:i,totalDebt:a,reserves:r}=await this.getSummary(t),s=ct.fromAssetId(e),o=r.find(y=>y.reserveAsset===s);if(!o)throw new Error("Missing reserve ctx for "+s);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:p}=o,d=P.toBigInt(n,l),g=c?d*u/10n**BigInt(l):0n,b=i-g;if(b<=0n)return 0;let h=N(b.toString()).mul(p).div(a.toString()).toFixed(6,N.roundDown);return Number(h)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:i,totalDebt:a,reserves:r}=await this.getSummary(t),s=ct.fromAssetId(e),o=r.find(h=>h.reserveAsset===s);if(!o)throw new Error("Missing reserve ctx for "+s);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=o,d=P.toBigInt(n,l)*c/10n**BigInt(l),g=i+d;if(g<=0n)return 0;let b=N(g.toString()).mul(u).div(a.toString()).toFixed(6,N.roundDown);return Number(b)}async getHealthFactorAfterSwap(t,e,n,i,a){let{totalDebt:r,reserves:s,healthFactor:o}=await this.getSummary(t),l=ct.fromAssetId(n),c=ct.fromAssetId(a),u=s.find(A=>A.reserveAsset===l),p=s.find(A=>A.reserveAsset===c);if(!u)throw new Error(`Missing reserve ctx for ${l}`);if(!p)throw new Error(`Missing reserve ctx for ${p}`);let d=P.toBigInt(e,u.decimals),g=P.toBigInt(i,p.decimals),b=d*u.priceInRef/10n**BigInt(u.decimals),h=g*p.priceInRef/10n**BigInt(p.decimals),y=u.isCollateral?N(b.toString()).mul(u.reserveLiquidationThreshold):N(0),x=N(h.toString()).mul(p.reserveLiquidationThreshold).minus(y).div(r.toString()),T=N(o).plus(x).toFixed(6,N.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:n,reserves:i,healthFactor:a}=await this.getSummary(t),r=ct.fromAssetId(e),s=i.find(o=>o.reserveAsset===r);if(!s)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(s,n,a)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:n,healthFactor:i}=await this.getSummary(t),a={};for(let r of n){let s=this.calculateWithdrawMax(r,e,i);r.reserveId&&(a[r.reserveId]=s)}return a}calculateWithdrawMax(t,e,n){let{aTokenBalance:i,availableLiquidity:a,decimals:r,priceInRef:s,reserveLiquidationThreshold:o,isCollateral:l}=t,c=i;if(l&&e>0n){let p=n-Fi;if(p>0){let d=N(p).mul(e.toString()).div(o).toFixed(0,N.roundDown),g=N(d).div(s.toString()).mul(10**r).toFixed(0,N.roundDown);c=i<BigInt(g)?i:BigInt(g)}else c=0n}return{amount:c<a?c:a,decimals:r}}calculateLinearInterest(t,e,n){let i=n-e;if(i<=0)return le;let a=t*BigInt(i)/Ri;return le+a}};var pn={};v(pn,{AssetClient:()=>ut,BalanceClient:()=>$,ChainParams:()=>pt});var ut=class extends E{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:i}=n;return this.SUPPORTED_TYPES.includes(i.type)}).map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async mapToken(t,e,n,i){let{name:a,asset_type:r,is_sufficient:s,existential_deposit:o}=e,{symbol:l,decimals:c}=n.get(t)??{};return{id:t,name:a?.asText(),symbol:l,decimals:c,icon:l,type:r.type,isSufficient:s,location:i,existentialDeposit:o}}async mapBond(t,e,n,i){let[a,r]=i,{asset_type:s,is_sufficient:o,existential_deposit:l}=e,{symbol:c,decimals:u}=await this.mapToken(a,e,n),p=Number(r),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(p)].join(" ");return{id:t,name:g,symbol:c+"b",decimals:u,icon:c,type:s.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:p}}async mapShares(t,e,n,i){let{assets:a}=i,{name:r,symbol:s,asset_type:o,is_sufficient:l,existential_deposit:c}=e,u=await Promise.all(a.map(async g=>{let{symbol:b}=await this.mapToken(g,e,n);return[g,b]})),p=Object.fromEntries(u),d=Object.values(p);return{id:t,name:d.join(", "),symbol:s?.asText()||r?.asText(),decimals:18,icon:d.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:p}}async mapExternal(t,e,n,i){let a=await this.mapToken(t,e,new Map,i),r=n?.find(s=>s.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,i,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),s=this.parseMetadata(n),o=[];for(let[l,c]of Array.from(n)){let u=i.get(l),{asset_type:p}=c,d;switch(p.type){case"Bond":let g=r.get(l);d=await this.mapBond(l,c,s,g);break;case"StableSwap":let b=a.get(l);d=await this.mapShares(l,c,s,b);break;case"External":d=await this.mapExternal(l,c,e,u);break;default:d=await this.mapToken(l,c,s,u)}o.push(d)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{Subject as Ci,bufferCount as Ei,combineLatest as ki,debounceTime as Mi,distinctUntilChanged as mn,finalize as Di,map as mt,pairwise as Li,shareReplay as qi,startWith as Hi}from"rxjs";var $=class extends E{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:n}=await e.getValue(t,{at:"best"});return this.calculateBalance(n)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.calculateBalance(i)}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),i=this.subscribeErc20Balance(t);return ki([e,n,i]).pipe(Mi(250),mt(a=>a.flat()),Hi([]),Ei(2,1),mt(([a,r],s)=>s===0?r:this.getDeltas(a,r)))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(mt(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(mt(i=>({id:e,balance:this.calculateBalance(i)})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(mn((n,i)=>!i.deltas),mt(({deltas:n})=>{let i=[];return n?.deleted.forEach(a=>{let[r,s]=a.args;i.push({id:s,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(a=>{let[r,s]=a.args;i.push({id:s,balance:this.calculateBalance(a.value)})}),i}))}subscribeErc20Balance(t,e){let n=new Ci,i=n.pipe(qi(1)),a=async()=>(await this.api.query.AssetRegistry.Assets.getEntries({at:"best"})).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),r=async()=>{let o=e||await a(),l=async()=>{let p=(await Promise.all(o.map(async d=>{let g=await this.getTokenBalanceData(t,d);return[d,g]}))).map(([d,g])=>({id:d,balance:g}));n.next(p)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},s;return r().then(o=>s=o),i.pipe(Di(()=>s?.()),Li(),mt(([o,l],c)=>c===0?l.filter(u=>u.balance.transferable>0n):this.getDeltas(o,l)),mn((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.calculateBalance(n)}calculateBalance(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,n=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:n,transferable:e}}getDeltas(t,e){let n=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,i=t.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return e.filter(a=>!n(a.balance,i.get(a.id)))}};var pt=class extends E{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var dn={};v(dn,{AssetNotFound:()=>Fe,PoolNotFound:()=>Ft,RouteNotFound:()=>Rt});var Fe=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Ft=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Rt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var yn={};v(yn,{EvmClient:()=>Et,EvmRpcAdapter:()=>Ct,createChain:()=>Re});import{Binary as Ni,CompatibilityLevel as Gi,FixedSizeBinary as gn}from"polkadot-api";import{hydration as Vi}from"@galacticcouncil/descriptors";import{encodeFunctionData as Ui,decodeFunctionResult as Wi}from"viem";var Yi=10000000n,Ct=class{api;constructor(t){this.api=t.getTypedApi(Vi)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,n=e.timestamp/1000n,[i]=e.number;return{timestamp:n,number:i}}readContract=(async t=>{let{abi:e,address:n,functionName:i,args:a}=t,r=Ui({abi:e,functionName:i,args:a}),s=this.api.apis.EthereumRuntimeRPCApi.call,o=await this.api.compatibilityToken,l=s.isCompatible(Gi.BackwardsCompatible,o);console.log(l);let c=await this.api.apis.EthereumRuntimeRPCApi.call(gn.fromText(""),gn.fromHex(n),Ni.fromHex(r),[0n,0n,0n,0n],[Yi,0n,0n,0n],void 0,void 0,void 0,!1,[]);if(console.log(c),!c.success)throw console.error(i,c.value.type),new Error("Contract read failure");let{exit_reason:u,value:p,used_gas:d}=c.value;if(console.log(d),u.type==="Succeed")return Wi({abi:e,functionName:i,data:p.asHex()});throw console.log(i,u.type,u.value.type),new Error("Contract read error")})};import{defineChain as Xi}from"viem";var Ki=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Re=()=>Xi({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Ki}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as hn,createWalletClient as $i,custom as bn,http as zi}from"viem";var Et=class{client;chain;constructor(t){this.client=t,this.chain=Re()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return hn({chain:this.chain,transport:zi()})}getWsProvider(){return hn({transport:bn({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return $i({account:t,chain:this.chain,transport:bn(window.ethereum)})}getRPCAdapter(){return new Ct(this.client)}};var vn={};v(vn,{LiquidityMiningApi:()=>kt,LiquidityMiningClient:()=>Mt});import{AccountId as ea}from"polkadot-api";import L from"big.js";import{fixed_from_rational as Tn}from"@galacticcouncil/math-liquidity-mining";var ce=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let n=0;n<t.length;++n){let[i,a]=t[n];this.result.set(this.getKey(a,i),e[n].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,n,i){let a=this.getKey(t,e),r=this.getKey(t,n),s=this.result.get(a)??0n,o=this.result.get(r)??0n;if(s<i)throw new Error("Attempting to transfer more than is present");this.result.set(a,s+i),this.result.set(r,o+i)}};import at from"big.js";import{calculate_accumulated_rps as ji,calculate_global_farm_rewards as Qi,calculate_loyalty_multiplier as Ji,calculate_user_reward as xn,calculate_yield_farm_delta_rpvs as Zi}from"@galacticcouncil/math-liquidity-mining";import fn from"big.js";var Ce=fn(10).pow(18),Pn=BigInt(fn(1).pow(18).toString()),Sn=6e3;var ta="1000000000000000000",ue=class{constructor(t,e,n){this.getAccount=t;this.getAsset=e;this.multiCurrency=n}async syncGlobalFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let i=await this.getAsset(t.reward_currency),a=e-t.updated_at,r=this.getAccount(t.id),s=i?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,r),l=at(s.toString()),c=at(o.toString()).minus(l.lt(o.toString())?s.toString():o.toString()),u=at(Qi(t.total_shares_z.toString(),n.toString(),at(t.yield_per_period.toString()).mul(Ce).round(0,at.roundDown).toFixed(),t.max_reward_per_period.toString(),a.toFixed()));if(c.lt(u)&&(u=c),u.eq(0))return t;let p=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,r,p,BigInt(u.toFixed())),{...t,accumulated_rpz:BigInt(ji(t.accumulated_rpz.toString(),t.total_shares_z.toString(),u.toFixed()))}}syncYieldFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===n)return null;if(t.total_valued_shares===0n)return{...t,updated_at:n};let i=Zi(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:n}}getLoyaltyMultiplier(t,e){let n=at(1).mul(Ce).round(0,at.roundDown).toString();if(!e)return n;let{initial_reward_percentage:i,scale_coef:a}=e;return Ji(t.toFixed(),i.toString(),a.toFixed())}async claimRewards(t,e,n,i,a){if(e.state.type==="Terminated")return null;let r=Math.floor(i/t.blocks_per_period);if(n.updated_at===r)return null;let s=await this.syncGlobalFarm(t,r,a);if(!s)return null;let o=this.syncYieldFarm(e,s,r);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,u=this.getLoyaltyMultiplier(c,o.loyalty_curve),p=BigInt(xn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),u)),d=BigInt(xn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),ta));return{reward:p,maxReward:d,assetId:s.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var na=L(365.2425).times(24).times(60).times(60),kt=class{client;balanceClient;options;constructor(t,e,n={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:n.blockTime??Sn})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let n=[t,e].sort((a,r)=>a-r);if(t===e)return Pn;let i=await this.client.getOraclePrice(n);if(i){let{n:a,d:r}=i[0].price,s;return t<e?s=Tn(a.toString(),r.toString()):s=Tn(r.toString(),a.toString()),BigInt(s)}}getFarmAddress=(t,e)=>{let n=Buffer.from("modl","utf-8"),i=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),a=Buffer.from([t]),r=Buffer.concat([n,i,a]),o="0x"+Buffer.concat([r,Buffer.alloc(32-r.length)]).toString("hex");return ea(63).dec(o)};getGlobalRewardPerPeriod(t,e,n,i){let a=L(i).times(t.toString()).times(e.toString()).div(18);return a.gte(n.toString())?n.toString():a.toString()}getPoolYieldPerPeriod(t,e,n,i){let a=L(t.toString()).times(e),r=L(n.toString()).times(i);return a.div(r.toString()).toString()}farmData(t,e,n){let{yieldFarm:i,globalFarm:a,priceAdjustment:r,balance:s,id:o}=t,{multiplier:l,loyalty_curve:c}=i,{blocks_per_period:u,yield_per_period:p,total_shares_z:d,max_reward_per_period:g,pending_rewards:b,accumulated_paid_rewards:h,planned_yielding_periods:y,updated_at:f,incentivized_asset:S,reward_currency:x,price_adjustment:T,min_deposit:A}=a,O=w.shiftNeg(r??T,18),D=w.shiftNeg(l,18),U=w.shiftNeg(c?.initial_reward_percentage??0,18),K=na.div(L(this.blockTime).div(1e3).times(u)).toString(),H;if(d<=0)H=L(D).times(p.toString()).times(K).toString();else{let ni=this.getGlobalRewardPerPeriod(d,p,g,O),ii=this.getPoolYieldPerPeriod(ni,D,d,O);H=L(ii).times(K).toString()}let W=b+h,tt=g*BigInt(y),et=s.transferable+W,Je=et-W,ee=L(Je.toString()).div(g.toString()),ne=L(e).div(u.toString()).toString(),ie=(d>=0?ee.plus(f):ee.plus(ne)).toString(),Pe=L(ie).times(u).toString(),ti=L(d.toString()).div(L(g.toString()).div(p.toString())).div(Math.pow(10,18)).times(100).times(O).toFixed(2),Ze=L(W.toString()).div(et.toString()).gte(.999);H=Ze?"0":L(H).div(n?2:1).times(100).toString();let ei=U?L(H).times(U).toString():void 0;return{apr:H,minApr:ei,isDistributed:Ze,estimatedEndPeriod:ie,estimatedEndBlock:Pe,maxRewards:tt,incentivizedAsset:S,rewardCurrency:x,loyaltyCurve:c,currentPeriod:ne,potMaxRewards:et,fullness:ti,yieldFarmId:i.id,globalFarmId:a.id,poolId:o,distributedRewards:W,plannedYieldingPeriods:y,minDeposit:A}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((i,a)=>i.includes(a.keyArgs[0].toString())?i:[...i,a.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async i=>{let a=await this.getOmnipoolFarms(i);if(a)return[i,a]}));return Object.fromEntries(n.filter(i=>!!i))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),n=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:a,value:r})=>{let[,s]=a,o=r,l=await this.client.getOmnipoolGlobalFarm(s),c=await this.client.getOmnipoolYieldFarm(Number(t),s,o);if(!l||!c)return;let u=l.reward_currency,p=l.incentivized_asset,d=this.getFarmAddress(s),g=await this.getOraclePrice(u,p),b=await this.balanceClient.getBalance(d,u);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b}}));return n?i.map(a=>a?this.farmData(a,n):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((i,a)=>i.includes(a.keyArgs[0].toString())?i:[...i,a.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async i=>{let a=await this.getIsolatedFarms(i);if(a)return[i,a]}));return Object.fromEntries(n.filter(i=>!!i))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),n=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:a,value:r})=>{let[,s]=a,o=r,l=await this.client.getIsolatedGlobalFarm(s),c=await this.client.getIsolatedYieldFarm(t,s,o);if(!l||!c)return;let u=l.reward_currency,p=l.incentivized_asset,d=this.getFarmAddress(s,!0),g=await this.getOraclePrice(u,p),b=await this.balanceClient.getBalance(d,u);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b,farmAddress:d}}));return n?i.map(a=>a?this.farmData(a,n,!0):void 0):[]}async getDepositReward(t,e,n,i){let a=e.global_farm_id,r=e.yield_farm_id,s=n?await this.client.getIsolatedYieldFarm(t,a,r):await this.client.getOmnipoolYieldFarm(Number(t),a,r),o=n?await this.client.getIsolatedGlobalFarm(a):await this.client.getOmnipoolGlobalFarm(a);if(!o||!s)return;let l=o.reward_currency,c=o.incentivized_asset,u=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],p=await this.getAccountAssetBalances(u),d=await this.getOraclePrice(l,c),g=new ce(u,p),h=await new ue(f=>this.getFarmAddress(f),f=>this.client.getAsset(f),g).claimRewards(o,s,e,i,d??o.price_adjustment);if(!h)return;let y=await this.client.getAsset(h.assetId);if(y&&!(h.reward<=y.existential_deposit))return h}async getAccountAssetBalances(t){let[e,n]=await Promise.all([Promise.all(t.filter(([a,r])=>r!==0).map(([a,r])=>this.balanceClient.getTokenBalance(a,r))),Promise.all(t.filter(([a,r])=>r===0).map(([a])=>this.balanceClient.getSystemBalance(a)))]),i=[];for(let a=0,r=0;a+r<t.length;){let s=a+r,[,o]=t[s];o===0?(i.push(n[r]),r+=1):(i.push(e[a]),a+=1)}return i}};import{Binary as ia,Enum as aa}from"polkadot-api";var Mt=class extends E{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(ia.fromText("omnipool"),t,aa("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t)}async getOmnipoolYieldFarm(t,e,n){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,n)}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t)}async getIsolatedYieldFarm(t,e,n){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,n)}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var qn={};v(qn,{PoolContextProvider:()=>St,PoolError:()=>J,PoolFactory:()=>ft,PoolType:()=>R,aave:()=>Ne,hsm:()=>We,lbp:()=>Ee,omni:()=>Me,stable:()=>Le,xyk:()=>qe});var Ee={};v(Ee,{LbpMath:()=>Y,LbpPool:()=>Dt,LbpPoolClient:()=>Lt});import{calculate_in_given_out as ra,calculate_out_given_in as sa,calculate_linear_weights as oa,calculate_pool_trade_fee as la,get_spot_price as ca}from"@galacticcouncil/math-lbp";var Y=class{static getSpotPrice(t,e,n,i,a){return ca(t,e,n,i,a)}static calculateInGivenOut(t,e,n,i,a){return ra(t,e,n,i,a)}static calculateOutGivenIn(t,e,n,i,a){return sa(t,e,n,i,a)}static calculateLinearWeights(t,e,n,i,a){return oa(t,e,n,i,a)}static calculatePoolTradeFee(t,e,n){return la(t,e,n)}};var R=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r.HSM="HSM",r))(R||{}),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{FeeUtils:wn}=w,Dt=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new m(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:a.balance,decimalsIn:i.decimals,decimalsOut:a.decimals,weightIn:i.weight,weightOut:a.weight}}validateAndBuy(t,e,n){let i=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&a.push("MaxOutRatioExceeded"),i===t.assetOut){let s=this.calculateTradeFee(e,n),o=wn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+s,c=this.calculateInGivenOut(t,l),u=t.balanceIn/this.maxInRatio;return c>u&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:a}}else{let s=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return s>o&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}}validateAndSell(t,e,n){let i=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&a.push("MaxInRatioExceeded"),i===t.assetIn){let s=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return s>o&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}else{let s=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(s,n),l=wn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=s-o,u=t.balanceOut/this.maxOutRatio;return c>u&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(t,e){let n=Y.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e){let n=Y.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){let e=Y.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=Y.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=Y.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as _a}from"polkadot-api";import{Subscription as Fa,distinctUntilChanged as Ra,filter as Ca}from"rxjs";import{memoize1 as ma}from"@thi.ng/memoize";import{TLRUCache as pa}from"@thi.ng/cache";import{ReplaySubject as da,Subscription as ga,bufferCount as ha,combineLatest as In,debounceTime as ba,defer as ya,filter as fa,finalize as Pa,from as Sa,map as dt,merge as xa,of as Ta,pairwise as va,skip as wa,share as Ia,startWith as Aa,switchMap as Oa,tap as An,throttleTime as Ba}from"rxjs";import{BehaviorSubject as ua}from"rxjs";var me=class{store$=new ua([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,n=new Map(e.map((s,o)=>[s.address,o])),i=await t(e),a=e.slice(),r=new Set;for(let s of i){let o=n.get(s.address);o===void 0?(n.set(s.address,a.length),a.push(s)):a[o]=s,r.add(s.address)}this.changeset=r,this.store$.next(a)}).catch(console.error)}destroy(){this.store$.complete()}};var q=class extends ${evm;store=new me;shared$;mem=0;memPoolsCache=new pa(null,{ttl:6*1e3});memPools=ma(t=>(this.log(this.getPoolType(),"sync mem pools",t),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe(Aa([]),ha(2,1),dt(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),fa(t=>t.length>0),Ba(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return ya(()=>{let t=new ga;return Sa(this.getMemPools()).pipe(dt(n=>n.filter(i=>this.hasValidAssets(i))),An(n=>this.store.set(n))).pipe(An(()=>{t.add(this.subscribeBalances()),t.add(this.subscribeUpdates())}),Oa(n=>xa(Ta(n),this.store.asObservable().pipe(wa(1)))),Pa(()=>{t.unsubscribe()}))}).pipe(Ia({connector:()=>new da(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:n}=e,i=[this.subscribeTokensBalance(n)];if(this.hasSystemAsset(e)){let a=this.subscribeSystemBalance(n);i.push(a)}if(this.hasErc20Asset(e)){let a=e.tokens.filter(s=>s.type==="Erc20").map(s=>s.id),r=this.subscribeErc20Balance(n,a);i.push(r)}return In(i).pipe(dt(a=>a.flat()),va(),dt(([a,r])=>this.getDeltas(a,r)),dt(a=>[n,a]))});return In(t).pipe(ba(250),dt(e=>new Map(e))).subscribe(e=>this.store.update(n=>this.updateBalances(n,e)))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:n})=>n>0n&&!!e)}updateBalances=(t,e)=>{let n=[],i=new Map(t.map(a=>[a.address,a]));for(let[a,r]of e){let s=i.get(a);if(s){let o=s.tokens.map(l=>{let c=r.find(u=>u.id===l.id);return c&&l.id!==s.id?{...l,balance:c.balance.transferable}:l});n.push({...s,tokens:o})}}return n}};var Lt=class extends q{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}getPoolWeights(t,e){let{start:n,end:i,initial_weight:a,final_weight:r}=t,s=Y.calculateLinearWeights(n?n.toString():"0",i?i.toString():"0",a.toString(),r.toString(),e.toString()),o=BigInt(s),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(_a.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),i=e?.relay_parent_number||0,a=t.filter(({value:r})=>e&&this.isActivePool(r,i)).map(async({keyArgs:r,value:s})=>{let[o]=r,l=o.toString(),c=await this.getPoolDelta(l,s,i);return{address:l,type:"LBP",fee:s.fee,...c,...n}});return Promise.all(a)}async getPoolDelta(t,e,n){let{assets:i,repay_target:a,fee_collector:r}=e,[s,o]=this.getPoolWeights(e,n),[l,c]=i,[u,p,d,g,b]=await Promise.all([this.isRepayFeeApplied(l,a,r.toString()),this.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c)]);return{repayFeeApply:u,tokens:[{id:l,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:p.transferable,weight:s,type:d?.asset_type.type},{id:c,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:i}=t;return n&&i?e>=n&&e<i:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return(await this.getBalance(n,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let n=this.store.pools.find(a=>a.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:n.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe(Ca(t=>t!==void 0),Ra((t,e)=>t.relay_parent_number===e.relay_parent_number)).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let n=[];for(let i of e){let a=this.poolsData.get(i.address);if(a){let{assets:r,repay_target:s,fee_collector:o}=a,[l]=r,[c,u]=this.getPoolWeights(a,t),[p,d]=i.tokens,g=[{...p,weight:c},{...d,weight:u}],b=await this.isRepayFeeApplied(l,s,o.toString());n.push({...i,tokens:g,repayFeeApply:b})}}return n})})}subscribeUpdates(){let t=new Fa;return t.add(this.subscribeValidationData()),t}};var Me={};v(Me,{OmniMath:()=>I,OmniPool:()=>qt,OmniPoolClient:()=>Ht});import{calculate_in_given_out as Ea,calculate_lrna_in_given_out as ka,calculate_out_given_in as Ma,calculate_out_given_lrna_in as Da,calculate_spot_price as La,calculate_lrna_spot_price as qa,calculate_shares as Ha,calculate_liquidity_out as Na,calculate_liquidity_lrna_out as Ga,verify_asset_cap as Va,calculate_liquidity_hub_in as Ua,is_sell_allowed as Wa,is_buy_allowed as Ya,is_add_liquidity_allowed as Xa,is_remove_liquidity_allowed as Ka,recalculate_asset_fee as $a,recalculate_protocol_fee as za}from"@galacticcouncil/math-omnipool";import gt from"big.js";var I=class{static calculateSpotPrice(t,e,n,i){return La(t,e,n,i)}static calculateLrnaSpotPrice(t,e){return qa(t,e)}static calculateInGivenOut(t,e,n,i,a,r,s,o,l){return Ea(t,e,n,i,a,r,s,o,l)}static calculateLrnaInGivenOut(t,e,n,i,a){return ka(t,e,n,i,a)}static calculateOutGivenIn(t,e,n,i,a,r,s,o,l){return Ma(t,e,n,i,a,r,s,o,l)}static calculateOutGivenLrnaIn(t,e,n,i,a){return Da(t,e,n,i,a)}static calculateShares(t,e,n,i){return Ha(t,e,n,i)}static calculateLiquidityOut(t,e,n,i,a,r,s,o){return Na(t,e,n,i,a,r,s,o)}static calculateLiquidityLRNAOut(t,e,n,i,a,r,s,o){return Ga(t,e,n,i,a,r,s,o)}static calculateCapDifference(t,e,n,i){let a=gt(e),r=gt(t),s=gt(i),o=gt(n),l=gt(10).pow(18),c=o.div(l);if(a.div(s).lt(c)){let p=c.times(s).minus(a).times(r),d=a.times(gt(1).minus(c));return p.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,n,i){return Ua(t,e,n,i)}static isSellAllowed(t){return Wa(t)}static isBuyAllowed(t){return Ya(t)}static isAddLiquidityAllowed(t){return Xa(t)}static isRemoveLiquidityAllowed(t){return Ka(t)}static recalculateAssetFee(t,e,n,i,a,r,s,o,l,c,u){return $a(t,e,n,i,a,r,s,o,l,c,u)}static recalculateProtocolFee(t,e,n,i,a,r,s,o,l,c,u){return za(t,e,n,i,a,r,s,o,l,c,u)}static verifyAssetCap(t,e,n,i){return Va(t,e,n,i)}};var{FeeUtils:ht}=w,qt=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new m(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:i.hubReserves,hubReservesOut:a.hubReserves,sharesIn:i.shares,sharesOut:a.shares,decimalsIn:i.decimals,decimalsOut:a.decimals,balanceIn:i.balance,balanceOut:a.balance,tradeableIn:i.tradeable,tradeableOut:a.tradeable,assetInEd:i.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=i===0n?0:B.calculateDiffToRef(a,i),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&s.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&s.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&s.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:i,amountOut:e,feePct:r,errors:s}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=B.calculateDiffToRef(i,a),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&s.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&s.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:a,feePct:r,errors:s}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let i=I.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0",n?ht.toRaw(n.protocolFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}calculateLrnaInGivenOut(t,e,n){let i=I.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let i=I.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0",n?ht.toRaw(n.protocolFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}calculateOutGivenLrnaIn(t,e,n){let i=I.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=I.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=I.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=I.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=I.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as ja,Binary as Qa,CompatibilityLevel as Ja,Enum as Za}from"polkadot-api";import{toHex as tr}from"@polkadot-api/utils";import{Subscription as er,distinctUntilChanged as ke,filter as nr,finalize as bt,map as ir,merge as ar}from"rxjs";var{FeeUtils:C}=w,On=Qa.fromText("omnipool"),Bn=Za("Short"),Ht=class extends q{queryBus=new oe;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:"best"}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:"best"}),t=>String(t),6*1e3);emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(On,t,Bn,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=tr(e);return ja(63).dec(n)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Ja.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,i,a,r,s]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:c,value:u})=>{let[p]=c,{hub_reserve:d,shares:g,tradable:b,cap:h,protocol_shares:y}=u,[f,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:S.transferable,cap:h,hubReserves:d,protocolShares:y,shares:g,tradeable:b,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r.transferable,tradeable:i,type:a?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...s}]}async getPoolFees(t){let e=t.assetOut,n=t.assetIn,i=await this.dynamicFeesConfig.get(e);if(i?.type==="Fixed"){let{asset_fee:f,protocol_fee:S}=i.value;return{assetFee:C.fromPermill(f),protocolFee:C.fromPermill(S)}}let a=this.getOraclePair(e),r=this.getOraclePair(n),[s,o,l]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(a),this.emaOracles.get(r)]),[c,u,p]=await this.getAssetFee(t,this.block,s,o,i?.value.asset_fee_params),[d,g,b]=n===1?[0,0,0]:await this.getProtocolFee(t,this.block,s,l,i?.value.protocol_fee_params),h=c+d,y=p+b;return{assetFee:C.fromPermill(u),protocolFee:C.fromPermill(g),min:C.fromPermill(h),max:C.fromPermill(y)}}async getAssetFee(t,e,n,i,a){let{assetOut:r,balanceOut:s}=t,{min_fee:o,max_fee:l,decay:c,amplification:u}=a||await this.api.constants.DynamicFees.AssetFeeParameters();if(!n||!i)return[o,o,l];let p=C.fromPermill(o),d=C.fromPermill(l),[g]=i,{asset_fee:b,timestamp:h}=n,y=Math.max(1,e-h),f=g.volume.b_in.toString(),S=g.volume.b_out.toString(),x=g.liquidity.b.toString();r===0&&(f=g.volume.a_in.toString(),S=g.volume.a_out.toString(),x=g.liquidity.a.toString());let T=C.fromPermill(b),A=I.recalculateAssetFee(f,S,x,"9",s.toString(),C.toRaw(T).toString(),y.toString(),C.toRaw(p).toString(),C.toRaw(d).toString(),c.toString(),u.toString());return[o,Number(A)*1e6,l]}async getProtocolFee(t,e,n,i,a){let{assetIn:r,balanceIn:s}=t,{min_fee:o,max_fee:l,decay:c,amplification:u}=a||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!n||!i)return[o,o,l];let p=C.fromPermill(o),d=C.fromPermill(l),[g]=i,{protocol_fee:b,timestamp:h}=n,y=Math.max(1,e-h),f=g.volume.b_in.toString(),S=g.volume.b_out.toString(),x=g.liquidity.b.toString();r===0&&(f=g.volume.a_in.toString(),S=g.volume.a_out.toString(),x=g.liquidity.a.toString());let T=C.fromPermill(b),A=I.recalculateProtocolFee(f,S,x,"9",s.toString(),C.toRaw(T).toString(),y.toString(),C.toRaw(p).toString(),C.toRaw(d).toString(),c.toString(),u.toString());return[o,Number(A)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,n=t.tokens.map(i=>i.id).map(i=>this.getOraclePair(i)).map(i=>this.api.query.EmaOracle.Oracles.watchValue(On,i,Bn,"best").pipe(nr(a=>a!==void 0),ir(a=>({pair:i,value:a}))));return ar(...n).pipe(bt(()=>{this.log(this.getPoolType(),"unsub ema oracles"),this.emaOracles.clear()})).subscribe(i=>{let{pair:a,value:r}=i;this.emaOracles.set(r,a)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe(ke((t,e)=>!e.deltas),bt(()=>{bt(()=>{this.log(this.getPoolType(),"unsub dyn fees"),this.dynamicFees.clear()})})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFees.set(e.value,n)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe(ke((t,e)=>!e.deltas),bt(()=>{this.log(this.getPoolType(),"unsub dyn fees config"),this.dynamicFeesConfig.clear()})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFeesConfig.set(e.value,n)})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe(bt(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(ke((t,e)=>!e.deltas),bt(()=>{this.log(this.getPoolType(),"unsub assets")})).subscribe(({deltas:t})=>{this.store.update(([e])=>{let n=t?.upserted.reduce((a,r)=>{let[s]=r.args;return a.set(s,r.value),a},new Map),i=e.tokens.map(a=>{let r=n?.get(a.id);return r?this.updateTokenState(a,r):a});return[{...e,tokens:i}]})})}subscribeUpdates(){let t=new er;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:n,shares:i,tradable:a,cap:r,protocol_shares:s}=e;return{...t,cap:r,hubReserves:n,protocolShares:s,shares:i,tradeable:a}}};var Le={};v(Le,{StableMath:()=>M,StableSwap:()=>Z,StableSwapClient:()=>Nt});import{calculate_in_given_out as rr,calculate_out_given_in as sr,calculate_amplification as or,calculate_add_one_asset as lr,calculate_liquidity_out_one_asset as cr,calculate_shares as ur,calculate_shares_for_amount as mr,calculate_spot_price_with_fee as pr,pool_account_name as dr,recalculate_peg as gr}from"@galacticcouncil/math-stableswap";var M=class{static getPoolAddress(t){return dr(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,i,a){return or(t,e,n,i,a)}static calculateInGivenOut(t,e,n,i,a,r,s){return rr(t,e,n,i,a,r,s)}static calculateAddOneAsset(t,e,n,i,a,r,s){return lr(t,e,n,i,a,r,s)}static calculateSharesForAmount(t,e,n,i,a,r,s){return mr(t,e,n,i,a,r,s)}static calculateOutGivenIn(t,e,n,i,a,r,s){return sr(t,e,n,i,a,r,s)}static calculateLiquidityOutOneAsset(t,e,n,i,a,r,s){return cr(t,e,n,i,a,r,s)}static calculateShares(t,e,n,i,a,r){return ur(t,e,n,i,a,r)}static calculateSpotPriceWithFee(t,e,n,i,a,r,s,o){return pr(t,e,n,i,a,r,s,o)}static recalculatePegs(t,e,n,i,a){let r=gr(t,e,n,i,a);return JSON.parse(r)}};var{FeeUtils:yt}=w,Z=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new m(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:a.balance,decimalsIn:i.decimals,decimalsOut:a.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:a.tradeable,assetInEd:i.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=i===0n?0:B.calculateDiffToRef(a,i),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&s.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:i,amountOut:e,feePct:r,errors:s}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=B.calculateDiffToRef(i,a),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&s.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:a,feePct:r,errors:s}}calculateIn(t,e,n){let i=M.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateAddOneAsset(t,e,n){let i=M.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateSharesForAmount(t,e,n){let i=M.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateInGivenOut(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=M.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let i=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(i)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let i=M.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateWithdrawOneAsset(t,e,n){let i=M.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateShares(t,e,n){let i=M.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=M.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let i=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(i)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:i})=>({asset_id:e,amount:n,decimals:i}));return JSON.stringify(t,_t.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],_t.jsonFormatter)}};import{AccountId as hr,CompatibilityLevel as br}from"polkadot-api";import{toHex as yr}from"@polkadot-api/utils";import{blake2b as fr}from"@noble/hashes/blake2b";import{Subscription as Pr,distinctUntilChanged as Sr,finalize as De,map as xr,merge as Tr}from"rxjs";var{FeeUtils:vr}=w,Nt=class extends q{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=M.getPoolAddress(t),n=fr(e,{dkLen:32}),i=yr(n);return hr(63).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:n,final_amplification:i,initial_block:a,final_block:r}=t,s=M.calculateAmplification(n.toString(),i.toString(),a.toString(),r.toString(),e.toString()),o=Number(s)<i;return{amplification:BigInt(s),isRampPeriod:o}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),i=e.assets.map(async a=>{let[r,s,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:o.transferable,tradeable:r,type:s?.asset_type.type}});return Promise.all(i)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(br.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),i=t.map(async({keyArgs:a,value:r})=>{let[s]=a,o=this.getPoolAddress(s),[l,c,u]=await Promise.all([this.getPoolTokens(s,r),this.api.query.Stableswap.PoolPegs.getValue(s,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(s,{at:"best"})]),p=this.getPoolAmplification(r,e),d=c?this.getRecentPegs(c):this.getDefaultPegs(r);return l.push({id:s,tradeable:15,balance:u,decimals:18}),this.poolsData.set(s,r),{address:o,id:s,type:"Stableswap",fee:vr.fromPermill(r.fee),tokens:l,totalIssuance:u,pegs:d,...n,...p}});return Promise.all(i)}async getPoolFees(t,e){return{fee:this.store.pools.find(i=>i.address===e).fee}}getDefaultPegs(t){return M.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,i])=>i.map(a=>a.toString()))}subscribeIssuance(){let e=this.store.pools.map(n=>n.id).map(n=>this.api.query.Tokens.TotalIssuance.watchValue(n,"best").pipe(xr(i=>({id:n,value:i}))));return Tr(...e).pipe(De(()=>{this.log(this.getPoolType(),"unsub total issuance")})).subscribe(n=>{let{id:i,value:a}=n;this.store.update(r=>{let s=[];return r.filter(o=>o.id===i).forEach(o=>{let l=o.tokens.map(c=>c.id===i?{...c,balance:a}:c);s.push({...o,tokens:l,totalIssuance:a})}),s})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe(Sr((t,e)=>!e.deltas),De(()=>{this.log(this.getPoolType(),"unsub pool pegs")})).subscribe(({deltas:t})=>{this.store.update(e=>{let n=[],i=new Map(e.map(a=>[a.id,a]));return t?.upserted.forEach(({args:a,value:r})=>{let[s]=a,o=i.get(s);if(o){let l=this.getRecentPegs(r);n.push({...o,pegs:l})}}),n})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe(De(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.store.update(e=>{let n=[];return e.filter(i=>i.isRampPeriod).forEach(i=>{let a=this.poolsData.get(i.id);if(a){let r=this.getPoolAmplification(a,t);n.push({...i,...r})}}),n})})}subscribeUpdates(){let t=new Pr;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var qe={};v(qe,{XykMath:()=>j,XykPool:()=>Gt,XykPoolClient:()=>Vt});import{calculate_in_given_out as wr,calculate_out_given_in as Ir,calculate_pool_trade_fee as Ar,get_spot_price as Or,calculate_liquidity_in as Br,calculate_shares as _r,calculate_spot_price as Fr,calculate_spot_price_with_fee as Rr,calculate_liquidity_out_asset_a as Cr,calculate_liquidity_out_asset_b as Er}from"@galacticcouncil/math-xyk";var j=class{static getSpotPrice(t,e,n){return Or(t,e,n)}static calculateInGivenOut(t,e,n){return wr(t,e,n)}static calculateOutGivenIn(t,e,n){return Ir(t,e,n)}static calculatePoolTradeFee(t,e,n){return Ar(t,e,n)}static calculateLiquidityIn(t,e,n){return Br(t,e,n)}static calculateSpotPrice(t,e){return Fr(t,e)}static calculateSpotPriceWithFee(t,e,n,i){return Rr(t,e,n,i)}static calculateShares(t,e,n){return _r(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,i){return Cr(t,e,n,i)}static calculateLiquidityOutAssetB(t,e,n,i){return Er(t,e,n,i)}};var{FeeUtils:_n}=w,Gt=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new m(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:a.decimals,balanceIn:i.balance,balanceOut:a.balance,assetInEd:i.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=this.calculateTradeFee(i,n),r=_n.toPct(n.exchangeFee),s=i+a,o=[];(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return s>c&&o.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=this.calculateTradeFee(i,n),r=_n.toPct(n.exchangeFee),s=i-a,o=[];(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return s>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:r,errors:o}}calculateInGivenOut(t,e){let n=j.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e){let n=j.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){let e=j.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=j.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=j.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as kr}from"polkadot-api";import{Subscription as Mr}from"rxjs";var Vt=class extends q{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(kr.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),n=t.map(async({keyArgs:i,value:a})=>{let[r]=i,[s,o]=a,[l,c,u,p]=await Promise.all([this.getBalance(r,s),this.api.query.AssetRegistry.Assets.getValue(s),this.getBalance(r,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:r,type:"XYK",tokens:[{id:s,decimals:c?.decimals||this.decimals.get(s),existentialDeposit:c?.existential_deposit,balance:l.transferable,type:c?.asset_type.type},{id:o,decimals:p?.decimals||this.decimals.get(o),existentialDeposit:p?.existential_deposit,balance:u.transferable,type:p?.asset_type.type}],...e}});return Promise.all(n)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Mr.EMPTY}};var Ne={};v(Ne,{AavePool:()=>Ut,AavePoolClient:()=>Wt});var Ut=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new m(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:a.balance,decimalsIn:i.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=[];return e>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=[];return i>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:a}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};import{AccountId as Dr}from"polkadot-api";import{toHex as Lr}from"@polkadot-api/utils";import{Subscription as Rn,filter as He,finalize as Cn,map as En}from"rxjs";import{decodeEventLog as qr}from"viem";var Fn=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var{ERC20:Hr}=rt,Nr=["Supply","Withdraw","Repay","Borrow"],Wt=class extends q{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let n=t+"/"+e,i=new TextEncoder().encode(n.padEnd(32,"\0")),a=Lr(i);return Dr(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:n,atoken:i,liqudity_in:a,liqudity_out:r})=>{let[s,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i)]);return{address:this.getPoolId(n,i),type:"Aave",tokens:[{id:n,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:a,location:o,type:s?.asset_type.type},{id:i,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:i,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id,{at:"best"});return t.tokens.map(r=>{let s=r.id===e.id?i:a;return{...r,balance:s}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:n}=e.value;return n.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return Hr.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:n}=t;return{assetIn:e,assetOut:n,key:`${e}:${n}`}}parseEvmLog(t){let{topics:e,data:n}=t.log,i=e.map(r=>r.asHex()),a=n.asHex();try{let{eventName:r,args:s}=qr({abi:Fn,topics:i,data:a}),o=s.reserve.toLowerCase();return{eventName:r,reserve:o,key:`${r}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(n=>n.tokens).map(([n,i])=>i).map(n=>n.id);return this.api.event.Router.Executed.watch().pipe(En(({payload:n})=>this.parseRouterLog(n)),He(({assetIn:n,assetOut:i})=>e.includes(n)||e.includes(i)),Cn(()=>{this.log(this.getPoolType(),"unsub router executed")})).subscribe(({assetIn:n,assetOut:i,key:a})=>{this.log(this.getPoolType(),"[router:Executed]",a),this.store.update(async r=>{let s=[];for(let o of r){let[l,c]=o.tokens;if(c.id===n||c.id===i){let p=await this.getPoolDelta(o);s.push({...o,tokens:p})}}return s})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(En(({payload:t})=>this.parseEvmLog(t)),He(t=>t!==void 0),He(({eventName:t})=>Nr.includes(t)),Cn(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({reserve:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async n=>{let i=[];for(let a of n){let[r]=a.tokens;if(this.getReserveH160Id(r).toLowerCase()===t){let o=await this.getPoolDelta(a);i.push({...a,tokens:o})}}return i})})}subscribeBalances(){return Rn.EMPTY}subscribeUpdates(){let t=new Rn;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var ft=class{static get(t){switch(t.type){case"Aave":return Ut.fromPool(t);case"XYK":return Gt.fromPool(t);case"Omnipool":return qt.fromPool(t);case"LBP":return Dt.fromPool(t);case"Stableswap":return Z.fromPool(t);case"HSM":return Z.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as ns,Subscription as Pt,takeUntil as is}from"rxjs";var We={};v(We,{HsmMath:()=>X,HsmPool:()=>Ge,HsmPoolClient:()=>$t});import{calculate_collateral_in_given_hollar_out as Gr,calculate_collateral_out_given_hollar_in as Vr,calculate_hollar_in_given_collateral_out as Ur,calculate_hollar_out_given_collateral_in as Wr,calculate_imbalance as Yr,calculate_max_price as Xr,calculate_buyback_limit as Kr,calculate_buyback_price_with_fee as $r}from"@galacticcouncil/math-hsm";var X=class{static calculateCollateralInGivenHollarOut(t,e,n){return Gr(t,e,n)}static calculateCollateralOutGivenHollarIn(t,e,n){return Vr(t,e,n)}static calculateHollarOutGivenCollateralIn(t,e,n){return Wr(t,e,n)}static calculateHollarInGivenCollateralOut(t,e,n){return Ur(t,e,n)}static calculateImbalance(t,e,n){return Yr(t,e,n)}static calculateBuybackLimit(t,e){return Kr(t,e)}static calculateBuybackPriceWithFee(t,e,n){return $r(t,e,n)}static calculateMaxPrice(t,e){return Xr(t,e)}};var{FeeUtils:Yt}=w,Ge=class m extends Z{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new m(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,n,i){let a=this.calculateBuybackLimit(t);e>a&&i.push("MaxBuyBackExceeded");let r=this.calculateBuyPrice(t,e,n),s=this.calculateMaxPrice(t);return r>s&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,n){return this.collateralBalance+t>this.maxInHolding&&n.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&n.push("FacilitatorCapacityExceeded"),n}validateTradeConstraints(t,e,n){let i=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,n,i):this.validateTradeHollarOut(e,n,i)}validateAndBuy(t,e){let n=this.calculateInGivenOut(t,e),i=this.validateTradeConstraints(t,n,e);return{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e){let n=this.calculateOutGivenIn(t,e),i=this.validateTradeConstraints(t,e,n);return{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:i}}calculateHollarInGivenCollateralOut(t,e){let n=super.calculateInGivenOut(t,e,{fee:this.fee}),i=X.calculateHollarInGivenCollateralOut(e.toString(),n.toString(),Yt.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),n=X.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),Yt.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let n=super.calculateOutGivenIn(t,e,{fee:this.fee}),i=X.calculateCollateralOutGivenHollarIn(e.toString(),n.toString(),Yt.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),n=X.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),Yt.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),n=X.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(n)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),n=X.calculateBuybackLimit(e.toString(),Yt.toRaw(this.buyBackRate).toString());return BigInt(n)}calculateBuyPrice(t,e,n){let i=n*10n**BigInt(t.decimalsIn);return e*10n**BigInt(t.decimalsOut)/i}calculateMaxPrice(t){let e=this.getCollateralPeg(),n=X.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[i,a]=JSON.parse(n),r=10n**BigInt(18-t.decimalsOut);return BigInt(i)*r/BigInt(a)}spotPriceInGivenOut(t){let e=P.toBigInt(1,t.decimalsOut);return this.calculateInGivenOut(t,e)}spotPriceOutGivenIn(t){let e=P.toBigInt(1,t.decimalsIn);return this.calculateOutGivenIn(t,e)}getCollateralPeg(){let t=this.tokens.findIndex(i=>i.id!==this.hollarId),e=this.pegs[t],n=this.tokens[t].decimals;return this.isDefaultPeg(e)?[P.toBigInt(1,18).toString(),P.toBigInt(1,n).toString()]:e}isDefaultPeg(t){let[e,n]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&n==="1"}};import{AccountId as zr,CompatibilityLevel as jr}from"polkadot-api";import{toHex as Qr}from"@polkadot-api/utils";import{Subscription as kn,combineLatest as Jr,filter as Mn,finalize as Dn,map as Ve,pairwise as Zr}from"rxjs";import{decodeEventLog as ts}from"viem";var Xt=[{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 Kt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[n,i]=await this.client.readContract({abi:Xt,address:t,functionName:"getFacilitatorBucket",args:[e]});return n-i}};var{FeeUtils:Ue}=w,{H160:Ln}=lt,es=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],$t=class extends q{ghoClient;stableClient;constructor(t,e,n){super(t,e),this.stableClient=n,this.ghoClient=new Kt(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:n}=e.value;return n.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),n=new TextEncoder().encode(e),i=Qr(n);return zr(63).dec(i)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(jr.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,n,i]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(n.length===0)return[];let a=this.getFacilitatorAddress(),r=Ln.fromAny(a),s=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(s,r),l=n.map(async({keyArgs:u,value:p})=>{let[d]=u,{pool_id:g,max_buy_price_coefficient:b,max_in_holding:h,purchase_fee:y,buy_back_fee:f,buyback_rate:S}=p,x=i.find(T=>T.id===g);if(x){let T=this.getPoolId(g),A=await this.getBalance(a,d);return{...x,address:T,type:"HSM",tokens:x.tokens.filter(O=>O.id!==g),hsmAddress:a,hsmMintCapacity:o,hollarId:t,hollarH160:s,collateralId:d,collateralBalance:A.transferable,maxBuyPriceCoefficient:b,maxInHolding:h,purchaseFee:Ue.fromPermill(y),buyBackFee:Ue.fromPermill(f),buyBackRate:Ue.fromPerbill(S)}}});return(await Promise.all(l)).filter(u=>u!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:n}=t.log,i=e.map(r=>r.asHex()),a=n.asHex();try{let{eventName:r,args:s}=ts({abi:Xt,topics:i,data:a}),o=s.facilitatorAddress.toLowerCase();return{eventName:r,facilitator:o,key:`${r}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Ve(({payload:t})=>this.parseEvmLog(t)),Mn(t=>t!==void 0),Mn(({eventName:t})=>es.includes(t)),Dn(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({facilitator:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async n=>{let i=[],[{hsmAddress:a,hollarH160:r}]=n,s=Ln.fromAny(a);if(s.toLowerCase()===t){let l=await this.ghoClient.getFacilitatorCapacity(r,s);for(let c of n)i.push({...c,hsmMintCapacity:l})}return i})})}subscribeBalances(){let t=[],e=[];this.store.pools.forEach(a=>{let{tokens:r,collateralId:s}=a;r.find(l=>l.id===s).type==="Erc20"?e.push(s):t.push(s)});let[{hsmAddress:n}]=this.store.pools,i=[];if(t.length>0){let a=this.subscribeTokensBalance(n);i.push(a)}if(e.length>0){let a=this.subscribeErc20Balance(n,e);i.push(a)}return i.length>0?Jr(i).pipe(Ve(a=>a.flat()),Zr(),Ve(([a,r])=>this.getDeltas(a,r)),Dn(()=>{this.log(this.getPoolType(),"unsub collateral balance")})).subscribe(a=>{this.store.update(r=>{let s=[],o=new Map(r.map(l=>[l.collateralId,l]));return a.forEach(({id:l,balance:c})=>{let u=o.get(l);u&&(this.log(this.getPoolType(),"[collateral:Balance]",l,c.transferable),s.push({...u,collateralBalance:c.transferable}))}),s})}):kn.EMPTY}subscribeUpdates(){let t=new kn;return t.add(this.subscribeEvmLog()),t}};var St=class extends E{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=Pt.EMPTY;omniSub=Pt.EMPTY;stableSub=Pt.EMPTY;hsmSub=Pt.EMPTY;xykSub=Pt.EMPTY;lbpSub=Pt.EMPTY;isReady=!1;isDestroyed=new ns;constructor(t,e){super(t),this.evm=e,this.aave=new Wt(t,e),this.omnipool=new Ht(t,e),this.stableswap=new Nt(t,e),this.hsm=new $t(t,e,this.stableswap),this.xyk=new Vt(t,e),this.lbp=new Lt(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe(is(this.isDestroyed)).subscribe(e=>{e.forEach(n=>{this.pools.set(n.address,n)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(i=>i.getPoolType()===e.type);if(n)return n.getPoolFees(t,e.address);throw new Ft(e.type)}};var Un={};v(Un,{DEFAULT_BLOCK_TIME:()=>Nn,DEFAULT_MIN_BUDGET:()=>Ke,ORDER_MIN_BLOCK_PERIOD:()=>Gn,Router:()=>xt,TWAP_BLOCK_PERIOD:()=>Jt,TWAP_MAX_DURATION:()=>ze,TWAP_MAX_PRICE_IMPACT:()=>$e,TWAP_TX_MULTIPLIER:()=>Cg,TradeOrderError:()=>Xe,TradeOrderType:()=>de,TradeRouteBuilder:()=>G,TradeRouter:()=>Tt,TradeScheduler:()=>vt,TradeType:()=>pe});var zt=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var as=10,jt=class{isNotVisited(t,e){let n=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let i=[],a=new zt,r=[];for(r.push([e,""]),a.enqueue(r);a.size()>0;){let s=a.dequeue();if(!s||s.length>as)continue;let o=s[s.length-1];(n===null||o[0]===n)&&i.push(s),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,s)){let u=[...s];u.push(c),a.enqueue(u)}})}return i}findShortestPaths(t,e,n){let i=[],a=new zt,r=[];r.push([e,""]),a.enqueue(r);let s=1/0;for(;a.size()>0;){let o=a.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<s?(s=o.length,i.length=0,i.push(o)):o.length===s&&i.push(o);continue}let c=t.get(l[0]);for(let u of c??[])this.isNotVisited(u,o)&&a.enqueue([...o,u])}return i}buildAndPopulateGraph(t,e){let n=new Map;for(let i of t)n.set(parseInt(i),[]);for(let[i,a,r]of e)n.get(a)?.push([r,i]);return n}};function Ye(m){let t={};for(let e of m){let n=e.tokens.length;for(let i=0;i<n;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let a=0;a<n;a++){if(i==a)continue;let r=[e.address,e.tokens[i].id,e.tokens[a].id];t[e.tokens[i].id].push(r)}}}return t}var Qt=class{getProposals(t,e,n){let i=n.filter(h=>h.type==="XYK"),a=n.filter(h=>h.type!=="XYK"),r=new Set(a.map(h=>h.tokens).flat().map(h=>h.id)),s=r.has(t),o=r.has(e),l=new jt,c=h=>{let y=Ye(h),f=Object.keys(y),S=f.flatMap(x=>y[x]);return l.buildAndPopulateGraph(f,S)};if(!s&&!o){let h=i.filter(S=>S.tokens.find(x=>x.id===t)||S.tokens.find(x=>x.id===e)),y=c(h),f=l.findPaths(y,t,e);return this.parsePaths(f)}if(s&&o){let h=c(a),y=l.findPaths(h,t,e);return this.parsePaths(y)}let u=s?e:t,p=i.filter(h=>h.tokens.some(y=>y.id===u));if(p.length===0)return[];let d=[...a,...p],g=c(d),b=l.findPaths(g,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let n of t){let i=[];for(let a=0;a<n.length;a++){let r=n[a],s=n[a+1];if(s==null)break;i.push(this.toEdge(r,s))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var xt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Qt,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:n=[]}=this.filter,i=new Set(e),a=new Set(n);return t.filter(r=>a.has(r.type)?!1:i.size>0?i.has(r.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(i=>i!==t).map(i=>this.getRoutes(i,t)))).filter(i=>i.length>0).map(([i])=>i[0].assetIn).sort()}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(n);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(i=>i.id)).flat().sort((n,i)=>n>i?1:-1);return new Set(e)}getPaths(t,e,n){let i=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(r=>this.validPath(r,i)).map(r=>this.toHops(r,i))}getProposals(t,e,n){let i=this.buildRouteKey(t,e,n);if(this.routeProposals.has(i))return this.routeProposals.get(i);let a=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(i,a),a}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,i)=>n&&i)}validEdge([t,e,n],i){return i.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,ft.get(e)]))}toHops(t,e){return t.map(([n,i,a])=>{let r=e.get(n);return{poolAddress:n,poolId:r?.id,pool:r?.type,assetIn:i,assetOut:a}})}};var pe=(e=>(e.Buy="Buy",e.Sell="Sell",e))(pe||{}),de=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(de||{}),Xe=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Xe||{});var{FeeUtils:Hn}=w,Tt=class extends xt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,n){let i=super.validateInput(t,e,n),a=super.getPaths(t,e,n);if(!a.length)throw new Rt(t,e);return{paths:a,pools:n,poolsMap:i}}async withCtx(t,e,n){let i=await super.getPools(),a=this.buildCtxSync(t,e,i);return n(a)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,i)=>{let a=n[n.length-1].amountOut,r=i[i.length-1].amountOut;return a>r?-1:1});return e.find(n=>n.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(a=>a.tradeFeeRange?.[0]??a.tradeFeePct).reduce((a,r)=>a+r),i=t.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,r)=>a+r);return[n,i]}}getPoolFeeRange(t){let e=t.min?Hn.toPct(t.min):void 0,n=t.max?Hn.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(s=>s.assetOutDecimals).reduce((s,o)=>s+o),i=t.map(s=>s.spotPrice).reduce((s,o)=>s*o),a=n-e.assetOutDecimals,r=Math.pow(10,a);return i/BigInt(r)}async getSell(t,e,n,i){return this.withCtx(t,e,async({paths:a,poolsMap:r})=>{let s;if(i)s=await this.toSellSwaps(n,i,r);else{let o=a.map(c=>this.toSellSwaps(n,c,r)),l=await Promise.all(o);s=this.findBestSellRoute(l)}return this.buildSell(r,s)})}async getSells(t,e,n){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let r=i.map(o=>this.toSellSwaps(n,o,a));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(a,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let n=e[0],i=e[e.length-1],a=this.isDirectTrade(e),r=this.getSellSpot(e),s=i.amountOut,o=a?i.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-s,c=this.getRouteFeeRange(e),u=a?i.tradeFeePct:B.calculateSellFee(o,s),p=Math.pow(10,n.assetInDecimals),d=n.amountIn*r/BigInt(p),g=B.calculateDiffToRef(o,d);return{type:"Sell",amountIn:n.amountIn,amountOut:i.amountOut,spotPrice:r,tradeFee:l,tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Sell",amountIn:P.toDecimal(n.amountIn,n.assetInDecimals),amountOut:P.toDecimal(i.amountOut,i.assetOutDecimals),spotPrice:P.toDecimal(r,i.assetOutDecimals),tradeFee:P.toDecimal(l,i.assetOutDecimals),tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0Y(t,e,n){let i=[];for(let a=0;a<e.length;a++){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a>0?l=i[a-1]:l=t;let c=s.calculateOutGivenIn(o,l);i.push(c)}return i[i.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:i,pools:a,poolsMap:r}=n,l=a.filter(b=>b.tokens.some(h=>h.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(h=>h.id===t)).map(b=>b.map(h=>h.balance).reduce((h,y)=>h+y)).sort((b,h)=>h<b?-1:1)[0],c=B.getFraction(l,.1),u=await Promise.all(i.map(b=>this.toSellSwaps(c,b,r))),d=this.findBestSellRoute(u).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),g=this.buildRouteKey(t,e,a);return this.mlr.set(g,d),d}async toSellSwaps(t,e,n){let i=[];for(let a=0;a<e.length;a++){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a>0?l=i[a-1].amountOut:l=typeof t=="string"?P.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,s),{amountOut:u,calculatedOut:p,feePct:d,errors:g}=s.validateAndSell(o,l,c),b=this.getPoolFeeRange(c),h=s.spotPriceOutGivenIn(o),y=Math.pow(10,o.decimalsIn),f=l*h/BigInt(y),S=B.calculateDiffToRef(p,f);i.push({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:u,calculatedOut:p,spotPrice:h,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g,isSupply(){return s.type==="Aave"&&s.tokens[0].id===r.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===r.assetIn},toHuman(){return{...r,amountIn:P.toDecimal(l,o.decimalsIn),amountOut:P.toDecimal(u,o.decimalsOut),calculatedOut:P.toDecimal(p,o.decimalsOut),spotPrice:P.toDecimal(h,o.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g}}})}return i}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let i=this.buildRouteKey(t,e,n.pools),a=this.mlr.get(i);return a||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:i,poolsMap:a}=n,r=this.buildRouteKey(t,e,i),s=this.mlr.get(r);s||(s=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",s,a),l=this.getSellSpot(o),c=o[o.length-1].assetOutDecimals;return{amount:l,decimals:c}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((n,i)=>{let a=n[0].amountIn,r=i[0].amountIn;return a>r?1:-1});return e.find(n=>n.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(s=>s.assetInDecimals).reduce((s,o)=>s+o),i=t.map(s=>s.spotPrice).reduce((s,o)=>s*o),a=n-e.assetInDecimals,r=Math.pow(10,a);return i/BigInt(r)}async getBuy(t,e,n,i){return this.withCtx(t,e,async({paths:a,poolsMap:r})=>{let s;if(i)s=await this.toBuySwaps(n,i,r);else{let o=a.map(c=>this.toBuySwaps(n,c,r)),l=await Promise.all(o);s=this.findBestBuyRoute(l)}return this.buildBuy(r,s)})}async getBuys(t,e,n){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let r=i.map(o=>this.toBuySwaps(n,o,a));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(a,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let n=e[e.length-1],i=e[0],a=this.isDirectTrade(e),r=this.getBuySpot(e),s=i.amountIn,o=a?i.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=s-o,c=this.getRouteFeeRange(e),u=a?i.tradeFeePct:B.calculateBuyFee(o,s),p=Math.pow(10,n.assetOutDecimals),d=n.amountOut*r/BigInt(p),g;return o===0n?g=-100:g=B.calculateDiffToRef(d,o),{type:"Buy",amountOut:n.amountOut,amountIn:i.amountIn,spotPrice:r,tradeFee:l,tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Buy",amountOut:P.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:P.toDecimal(i.amountIn,i.assetInDecimals),spotPrice:P.toDecimal(r,i.assetInDecimals),tradeFee:P.toDecimal(l,i.assetInDecimals),tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0X(t,e,n){let i=[];for(let a=e.length-1;a>=0;a--){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=t:l=i[0];let c=s.calculateInGivenOut(o,l);i.unshift(c)}return i[0]}async toBuySwaps(t,e,n){let i=[];for(let a=e.length-1;a>=0;a--){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=typeof t=="string"?P.toBigInt(t,o.decimalsOut):t:l=i[0].amountIn;let c=await this.ctx.getPoolFees(o,s),{amountIn:u,calculatedIn:p,feePct:d,errors:g}=s.validateAndBuy(o,l,c),b=this.getPoolFeeRange(c),h=s.spotPriceInGivenOut(o),y=Math.pow(10,o.decimalsOut),f=l*h/BigInt(y),S;p===0n?S=-100:S=B.calculateDiffToRef(f,p),i.unshift({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:u,calculatedIn:p,spotPrice:h,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g,isSupply(){return s.type==="Aave"&&s.tokens[0].id===r.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===r.assetIn},toHuman(){return{...r,amountOut:P.toDecimal(l,o.decimalsOut),amountIn:P.toDecimal(u,o.decimalsIn),calculatedIn:P.toDecimal(p,o.decimalsIn),spotPrice:P.toDecimal(h,o.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g}}})}return i}};var Nn=6e3,Ke=1000000000000000n,Jt=6,$e=-5,ze=216e5,Cg=3,Gn=6;import{Enum as Vn}from"polkadot-api";var G=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:i,poolId:a})=>i==="Stableswap"?{pool:Vn("Stableswap",a),asset_in:e,asset_out:n}:{pool:Vn(i),asset_in:e,asset_out:n})}};var vt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Ke})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,i,a){let[r,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=s,u=l[0],p=l[l.length-1],{assetInDecimals:d}=u,{assetOutDecimals:g}=p,b=Math.abs(c),h=this.getMinimumTradeCount(o,r),y=this.getOptimalTradeCount(b),f=a?Math.round(i/a):y,S=Math.ceil(i/h),x=Math.round(i/y),T=Math.round(i/f),A=o/BigInt(f),O=await this.router.getBestSell(t,e,A),D=o<r,U=[];D&&U.push("OrderTooSmall");let K=O.amountOut*BigInt(f),H=this.toBlockPeriod(T),W=O.tradeFee*BigInt(f),tt=G.build(l),et={assetIn:t,assetOut:e,errors:U,frequencyMin:S,frequencyOpt:x,frequency:T,tradeCount:f,tradeFee:W,tradeImpactPct:O.priceImpactPct,tradePeriod:H,tradeRoute:tt,type:"Dca"};return{...et,amountIn:o,amountOut:K,tradeAmountIn:O.amountIn,tradeAmountOut:O.amountOut,toHuman(){return{...et,amountIn:P.toDecimal(o,d),amountOut:P.toDecimal(K,g),tradeAmountIn:P.toDecimal(O.amountIn,d),tradeAmountOut:P.toDecimal(O.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let i=t+n/2n;return Number(i/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:r,swaps:s,priceImpactPct:o}=a,l=s[0],c=s[s.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,d=Math.abs(o),g=this.getTwapTradeCount(d),b=r/BigInt(g),h=await this.router.getBestSell(l.assetIn,c.assetOut,b),y=g===1,f=r<i,S=h.priceImpactPct<-5,x=[];f||y?x.push("OrderTooSmall"):S&&x.push("OrderImpactTooBig");let T=h.amountOut*BigInt(g),A=h.tradeFee*BigInt(g),O=G.build(s),D={assetIn:t,assetOut:e,errors:x,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:O,type:"TwapSell"};return{...D,amountIn:r,amountOut:T,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:A,toHuman(){return{...D,amountIn:P.toDecimal(r,u),amountOut:P.toDecimal(T,p),tradeAmountIn:P.toDecimal(h.amountIn,u),tradeAmountOut:P.toDecimal(h.amountOut,p),tradeFee:P.toDecimal(A,p)}}}}async getTwapBuyOrder(t,e,n){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:r,swaps:s,priceImpactPct:o}=a,l=s[0],c=s[s.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,d=Math.abs(o),g=this.getTwapTradeCount(d),b=r/BigInt(g),h=await this.router.getBestBuy(l.assetIn,c.assetOut,b),y=h.amountIn*BigInt(g),f=g===1,S=y<i,x=h.priceImpactPct<-5,T=[];S||f?T.push("OrderTooSmall"):x&&T.push("OrderImpactTooBig");let A=h.tradeFee*BigInt(g),O=G.build(s),D={assetIn:t,assetOut:e,errors:T,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:O,type:"TwapBuy"};return{...D,amountIn:y,amountOut:r,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:A,toHuman(){return{...D,amountIn:P.toDecimal(y,u),amountOut:P.toDecimal(r,p),tradeAmountIn:P.toDecimal(h.amountIn,u),tradeAmountOut:P.toDecimal(h.amountOut,p),tradeFee:P.toDecimal(A,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let i=216e5/(this.blockTime*6);return Math.round(i)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var jn={};v(jn,{BIG_10:()=>zn,BIG_BILL:()=>je,StakingApi:()=>Zt,StakingClient:()=>te});import{calculate_accumulated_rps as os,calculate_percentage_amount as ls,calculate_period_number as Xn,calculate_points as Kn,calculate_rewards as cs,sigmoid as $n}from"@galacticcouncil/math-staking";import V from"big.js";var ge={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},Wn=m=>Object.keys(ge).includes(m);import{AccountId as rs}from"polkadot-api";import{toHex as ss}from"@polkadot-api/utils";function Yn(m){let t=("modl"+m).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=ss(e);return rs(63).dec(n)}var he="20000000000000000",be="2000",zn=V(10),je=V(zn.pow(12)),Zt=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getPotBalance(){let t=await this.client.getPalletId(),e=Yn(t);return await this.balanceClient.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let i=e.created_at,a=await n.reduce(async(r,[s,o])=>{let l=await r,c=s,u=o.amount,p=o.conviction.toString().toLowerCase(),d=await this.client.getReferendumInfo(c);return d&&(d.type==="Approved"||d.type==="Rejected")&&Wn(p)&&l.push({id:c,amount:u,conviction:p}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:i,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:a}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,i]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),a=i.find(r=>r)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:a,stakePosition:a?await this.getStakingPosition(a):void 0}}getCurrentActionPoints(t,e,n,i){let a=V(0),r=V(0),s=ge.locked6x,o=V(n.toString()).mul(s),l=100,c=[];t.forEach(d=>{let g=ge[d.conviction],b=i.includes(d.id.toString());b&&c.push(d.id.toString());let h=V(d.amount.toString()).mul(l).div(o);a=a.plus(Math.floor(h.mul(g).toNumber())),r=r.plus(Math.floor(h.mul(b?s:g).toNumber()))});let u=Math.floor(V(n.toString()).mul(s).mul(l).div(o).toNumber());i.forEach(d=>{c.includes(d)||(r=r.plus(u))});let p={democracyVote:1};return a=a.mul(p.democracyVote),a=a.plus(e.toString()||"0"),r=r.mul(p.democracyVote),r=r.plus(e.toString()||"0"),{currentActionPoints:a.toString(),maxActionPoints:r.toString()}}async getRewards(t,e,n){let i=await this.getStake(t),{potReservedBalance:a,accumulatedRewardPerStake:r,totalStake:s,stakePosition:o}=i;if(!o)return;let[l,c,u,p,d,g,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=V(l.transferable.toString()).minus(a.toString()),y=h.gt(0)&&s>0?os(r.toString(),h.toString(),s.toString()):r.toString(),f=Xn(c.toString(),n,b),S=Xn(c.toString(),o.createdAt.toString(),b),x=cs(y,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),A=Kn(S,f,p.toString(),d.toString(),T.currentActionPoints,g.toString(),o.accumulatedSlashPoints.toString()),O=$n(A,he,be),D=(()=>{if(!e.length)return;let tt=Kn(S,f,p.toString(),d.toString(),T.maxActionPoints.toString(),g.toString(),o.accumulatedSlashPoints.toString());return $n(tt,he,be)})(),U=V(x).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if(V(f).minus(S).lte(u.toString()))return{rewards:"0",payablePercentage:O,extraPayablePercentage:D,constants:{a:he,b:be}};let K=ls(U.toString(),O),H=V(o.accumulatedLockedRewards.toString()),W=H.gt(K)?H:V(K);return{rewards:W.div(je).toString(),maxRewards:U.div(je).toString(),allocatedRewardsPercentage:W.div(U).mul(100).toNumber(),payablePercentage:O,extraPayablePercentage:D,constants:{a:he,b:be}}}};var te=class extends E{async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:r})=>{let[s,o,l]=r;return{address:s,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Zn={};v(Zn,{TxBuilderFactory:()=>It});import{Enum as Jn}from"polkadot-api";function Qn(m){let t=[],e=m;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var wt=class extends E{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new $(t),this.aaveUtils=new it(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Te})}async dryRun(t,e){let n=Jn("Signed",t),i=Jn("system",n),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall),s=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(s){let o=Qn(s.value);throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var ye=class extends wt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,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:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],a=await this.balanceClient.getBalance(this.beneficiary,i);return t>=a.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,i=n[0],a=n[n.length-1],r=B.getFraction(t,this.slippagePct),s=i.assetIn,o=a.assetOut,l=t+r,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.buy({asset_in:s,asset_out:o,amount:e,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:s,asset_out:o,amount_out:e,max_amount_in:l,route:G.build(n)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,i=n[0],a=n[n.length-1],r=B.getFraction(e,this.slippagePct),s=i.assetIn,o=a.assetOut,l=e-r,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.sell({asset_in:s,asset_out:o,amount:t,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:s,asset_out:o,amount_in:t,min_amount_out:l,route:G.build(n)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],i=e[e.length-1],a=B.getFraction(t,this.slippagePct),r=n.assetIn,s=i.assetOut,o=t-a,l=this.api.tx.Router.sell_all({asset_in:r,asset_out:s,min_amount_out:o,route:G.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as Qe}from"polkadot-api";var fe=class extends wt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,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:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradePeriod:a,tradeRoute:r}=this.order,s=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Qe("Sell",{asset_in:e,asset_out:n,amount_in:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",s)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradeAmountOut:a,tradePeriod:r,tradeRoute:s}=this.order,o=B.getFraction(a,this.slippagePct),l=a-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Qe("Sell",{asset_in:e,asset_out:n,amount_in:i,min_amount_out:l,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradeAmountOut:a,tradePeriod:r,tradeRoute:s}=this.order,o=B.getFraction(i,this.slippagePct),l=i+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Qe("Buy",{asset_in:e,asset_out:n,amount_out:a,max_amount_in:l,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var It=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new ye(this.client,this.evmClient).setTrade(t)}order(t){return new fe(this.client,this.evmClient).setOrder(t)}};async function cb(m){let t=new pt(m),e=new Et(m),[n,i]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=new St(m,e).withAave().withOmnipool().withStableswap().withXyk(),r=new $(m),s=new te(m),o=new Mt(m),l=new it(e),c=new Tt(a),u=new vt(c,{blockTime:n,minBudgetInNative:i}),p=new Zt(s,r),d=new kt(o,r,{blockTime:n});return{api:{aave:l,router:c,scheduler:u,staking:p,farm:d},client:{asset:new ut(m),balance:r,evm:e},ctx:{pool:a},tx:new It(m,e),destroy:()=>{a.destroy()}}}export{oe as QueryBus,un as aave,en as api,P as big,pn as client,nn as const,cb as createSdkContext,rt as erc20,dn as error,yn as evm,vn as farm,w as fmt,lt as h160,_t as json,B as math,qn as pool,Un as sor,jn as staking,Zn as tx,ln as xc};
|
|
1
|
+
var ai=Object.defineProperty;var v=(m,t)=>{for(var e in t)ai(m,e,{get:t[e],enumerable:!0})};import ri from"buffer";typeof window<"u"&&(window.Buffer=ri.Buffer);var en={};v(en,{Papi:()=>E,getWs:()=>mi});import{hydration as si}from"@galacticcouncil/descriptors";function tn(m){switch(m){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var E=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(si)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");tn(n)&&console.log(t,...e)}};import{createClient as oi}from"polkadot-api";import{withLogsRecorder as li}from"polkadot-api/logs-provider";import{withLegacy as ci}from"@polkadot-api/legacy-provider";import{getWsProvider as ui}from"polkadot-api/ws-provider";var mi=async m=>{let t=typeof m=="string"?m.split(","):m,e=ui(t,{innerEnhancer:ci()}),n=li(i=>console.log(i),e);return oi(e)};var un={};v(un,{AAVE_GAS_LIMIT:()=>Te,AAVE_LENDING_POOL_ADDRESS:()=>se,AAVE_POOL_ABI:()=>Se,AAVE_POOL_DATA_PROVIDER:()=>re,AAVE_POOL_DATA_PROVIDER_ABI:()=>ae,AAVE_POOL_PROXY:()=>xe,AAVE_ROUNDING_THRESHOLD:()=>qs,AAVE_UINT_256_MAX:()=>pi,AaveClient:()=>At,AaveUtils:()=>it});var Se=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var ae=[{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 xe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",re="0x112b087b60C1a166130d59266363C45F8aa99db0",se="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Te=1000000n,qs=5,pi=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var At=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:ae,address:re,args:[se],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:ae,address:re,args:[se,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:Se,address:xe,args:[t],functionName:"getUserAccountData"})}};import N from"big.js";var P={};v(P,{asBigInt:()=>hi,toBigInt:()=>gi,toDecimal:()=>di});import nt from"big.js";nt.NE=-18;function di(m,t,e=6,n){let i=nt(m.toString()),a=nt(10).pow(t);return i.div(a).round(e,n).toString()}function gi(m,t){let e=nt(10).pow(t),i=nt(m).mul(e).toFixed(0,nt.roundDown);return BigInt(i)}function hi(m){return BigInt(m.round(0,nt.roundDown).toFixed(0))}var rt={};v(rt,{ERC20:()=>ve});var ve=class{static fromAssetId(t){let e=Buffer.alloc(20,0);return e[15]=1,e.writeUInt32BE(t,16),"0x"+e.toString("hex")}static toAssetId(t){let e=Buffer.from(t.replace("0x",""),"hex");return e.length!==20||!this.isAssetAddress(t)?null:e.readUInt32BE(16)}static isAssetAddress(t){let e=Buffer.from("0000000000000000000000000000000100000000","hex"),n=Buffer.from(t.replace("0x",""),"hex");return n.length!==20?!1:n.subarray(0,16).equals(e.subarray(0,16))}};var w={};v(w,{FeeUtils:()=>Ae,shiftNeg:()=>Pi});import fi from"big.js";var nn={};v(nn,{HUB_ASSET_ID:()=>Ot,HYDRATION_OMNIPOOL_ADDRESS:()=>yi,HYDRATION_PARACHAIN_ID:()=>bi,HYDRATION_SS58_PREFIX:()=>k,PERBILL_DENOMINATOR:()=>we,PERMILL_DENOMINATOR:()=>st,RUNTIME_DECIMALS:()=>_,SYSTEM_ASSET_DECIMALS:()=>Ie,SYSTEM_ASSET_ID:()=>F,TRADEABLE_DEFAULT:()=>ot});var _=18,st=1e6,we=1e9,F=0,Ie=12,bi=2034,k=63,yi="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Ot=1,ot=15;var Ae=class m{static toPct(t){let[e,n]=t;return m.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return m.safeDivide(e,n)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,n=12){let i=10**n;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Pi(m,t){let e=fi(typeof m=="bigint"?m.toString():m);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var lt={};v(lt,{H160:()=>Be,isEvmAccount:()=>rn,isEvmAddress:()=>sn,isSs58Address:()=>on});import{AccountId as Bt}from"polkadot-api";import{toHex as an}from"@polkadot-api/utils";import{Buffer as Q}from"buffer";var Oe="ETH\0";function rn(m){if(!m)return!1;try{let t=Bt().enc(m),e=Q.from(Oe);return Q.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function sn(m){return!!/^0x[a-fA-F0-9]{40}$/.test(m)}function on(m){try{return Bt(63).enc(m),!0}catch{return!1}}var Be=class m{static toAccount=t=>{let e=Q.from(t.slice(2),"hex"),n=Q.from(Oe),i=Uint8Array.from(Q.concat([n,e,Q.alloc(8)])),a=an(i);return Bt(63).dec(a)};static fromAccount=t=>{let e=Bt().enc(t),n=Q.from(Oe),i=e.slice(n.length,-8);return"0x"+Q.from(i).toString("hex")};static fromSS58=t=>{let n=Bt().enc(t).slice(0,20);return an(n)};static fromAny=t=>{if(sn(t))return t;if(rn(t))return m.fromAccount(t);if(on(t))return m.fromSS58(t);throw new Error("Unknown address type")}};var _t={};v(_t,{findNestedKey:()=>Si,findNestedObj:()=>xi,jsonFormatter:()=>Ti});var Si=(m,t)=>{let e=[];return JSON.stringify(m,(n,i)=>(i&&i[t]&&e.push(i),i)),e[0]},xi=(m,t,e)=>{let n;return JSON.stringify(m,(i,a)=>(a&&a[t]===e&&(n=a),a)),n},Ti=(m,t)=>typeof t=="bigint"?t.toString():t;var B={};v(B,{calculateBuyFee:()=>Ai,calculateDiffToAvg:()=>vi,calculateDiffToRef:()=>wi,calculateSellFee:()=>Ii,getFraction:()=>Oi});import z from"big.js";function vi(m,t){let e=z(m.toString()),n=z(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function wi(m,t){if(t===0n)return 0;let e=z(m.toString()),n=z(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function Ii(m,t){if(m===0n)return 0;let e=z(m.toString()),n=z(t.toString());return z(1).minus(n.div(e)).mul(100).round(2).toNumber()}function Ai(m,t){if(m===0n)return 0;let e=z(m.toString());return z(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function Oi(m,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),i=BigInt(t*n);return m*i/BigInt(100*n)}var ln={};v(ln,{convertToId:()=>_i});import{Buffer as Bi}from"buffer";function _i(m){let e=Bi.from(m.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}import{TLRUCache as cn}from"@thi.ng/cache";var oe=class{debug;constructor(t){this.debug=t||!1}log(t,e,n){this.debug&&console.log(t,e,n)}scope(t,e,n,i){let a=new Map,r=i!==void 0?new cn(null,{ttl:i}):new cn;return{get:(...c)=>{let u=n(...c);if(a.has(u)){this.log("[live]",t,u);let d=a.get(u);return Promise.resolve(d)}if(r.has(u))return this.log("[memo]",t,u),r.get(u);this.log("[fetch]",t,u);let p=e(...c).catch(d=>{throw r.delete(u),d});return r.set(u,p),p},set:(c,...u)=>{let p=n(...u);this.log("[set-live]",t,p),a.set(p,c)},clear:()=>{this.log("[clear]",t),a.clear(),r.release()}}}};var{ERC20:ct}=rt,{H160:_e}=lt,Fi=1.01,Ri=31536000n,Ci=4,Ei=-1,le=10n**27n,it=class{client;constructor(t){this.client=new At(t)}async getSummary(t){let e=_e.fromAny(t),[n,i,a,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[s]=n,[o,l]=i,[c,u,p,d,g,b]=a,h=P.toDecimal(b,18),y=[];for(let f of o){let S=f.underlyingAsset.toLowerCase(),x=s.find(({underlyingAsset:Pe})=>Pe.toLowerCase()===S);if(!x)throw new Error("Missing pool reserve for "+S);let T=f.scaledATokenBalance,A=x.liquidityIndex,O=x.liquidityRate,D=x.availableLiquidity,U=x.priceInMarketReferenceCurrency,K=r+6,H=this.calculateLinearInterest(O,x.lastUpdateTimestamp,K),W=A*H/le,tt=T*W/le,ee=Number(l!==0&&l===x.eModeCategoryId?x.eModeLiquidationThreshold:x.reserveLiquidationThreshold)/1e4,ne=x.usageAsCollateralEnabled&&f.usageAsCollateralEnabledOnUser&&f.scaledATokenBalance>0n,ie=ct.toAssetId(S);y.push({aTokenBalance:tt,availableLiquidity:D,decimals:Number(x.decimals),isCollateral:ne,priceInRef:U,reserveId:ie,reserveAsset:S,reserveLiquidationThreshold:ee})}return{healthFactor:Number(h),totalCollateral:c,totalDebt:u,reserves:y}}async hasBorrowPositions(t){let e=_e.fromAny(t),n=await this.client.getUserAccountData(e),[i,a]=n;return a>0n}async getHealthFactor(t){let e=_e.fromAny(t),n=await this.client.getUserAccountData(e),[i,a,r,s,o,l]=n;return this.calculateHealthFactorFromBalances(a,i,s)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:i,totalDebt:a,reserves:r}=await this.getSummary(t),s=ct.fromAssetId(e),o=r.find(y=>y.reserveAsset===s);if(!o)throw new Error("Missing reserve ctx for "+s);let{decimals:l,isCollateral:c,priceInRef:u,reserveLiquidationThreshold:p}=o,d=P.toBigInt(n,l),g=c?d*u/10n**BigInt(l):0n,b=i-g;if(b<=0n)return 0;let h=N(b.toString()).mul(p).div(a.toString()).toFixed(6,N.roundDown);return Number(h)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:i,totalDebt:a,reserves:r}=await this.getSummary(t),s=ct.fromAssetId(e),o=r.find(h=>h.reserveAsset===s);if(!o)throw new Error("Missing reserve ctx for "+s);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:u}=o,d=P.toBigInt(n,l)*c/10n**BigInt(l),g=i+d;if(g<=0n)return 0;let b=N(g.toString()).mul(u).div(a.toString()).toFixed(6,N.roundDown);return Number(b)}async getHealthFactorAfterSwap(t,e,n,i,a){let{totalDebt:r,reserves:s,healthFactor:o}=await this.getSummary(t),l=ct.fromAssetId(n),c=ct.fromAssetId(a),u=s.find(A=>A.reserveAsset===l),p=s.find(A=>A.reserveAsset===c);if(!u)throw new Error(`Missing reserve ctx for ${l}`);if(!p)throw new Error(`Missing reserve ctx for ${p}`);let d=P.toBigInt(e,u.decimals),g=P.toBigInt(i,p.decimals),b=d*u.priceInRef/10n**BigInt(u.decimals),h=g*p.priceInRef/10n**BigInt(p.decimals),y=u.isCollateral?N(b.toString()).mul(u.reserveLiquidationThreshold):N(0),x=N(h.toString()).mul(p.reserveLiquidationThreshold).minus(y).div(r.toString()),T=N(o).plus(x).toFixed(6,N.roundDown);return Number(T)}async getMaxWithdraw(t,e){let{totalDebt:n,reserves:i,healthFactor:a}=await this.getSummary(t),r=ct.fromAssetId(e),s=i.find(o=>o.reserveAsset===r);if(!s)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(s,n,a)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:n,healthFactor:i}=await this.getSummary(t),a={};for(let r of n){let s=this.calculateWithdrawMax(r,e,i);r.reserveId&&(a[r.reserveId]=s)}return a}calculateWithdrawMax(t,e,n){let{aTokenBalance:i,availableLiquidity:a,decimals:r,priceInRef:s,reserveLiquidationThreshold:o,isCollateral:l}=t,c=i;if(l&&e>0n){let p=n-Fi;if(p>0){let d=N(p).mul(e.toString()).div(o).toFixed(0,N.roundDown),g=N(d).div(s.toString()).mul(10**r).toFixed(0,N.roundDown);c=i<BigInt(g)?i:BigInt(g)}else c=0n}return{amount:c<a?c:a,decimals:r}}calculateLinearInterest(t,e,n){let i=n-e;if(i<=0)return le;let a=t*BigInt(i)/Ri;return le+a}calculateHealthFactorFromBalances(t,e,n){if(t===0n)return Ei;let i=e*n/t,a=P.toDecimal(i,Ci);return Number(a)}};var pn={};v(pn,{AssetClient:()=>ut,BalanceClient:()=>$,ChainParams:()=>pt});var ut=class extends E{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:i}=n;return this.SUPPORTED_TYPES.includes(i.type)}).map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[a]=n;return[a,i]}))}async mapToken(t,e,n,i){let{name:a,asset_type:r,is_sufficient:s,existential_deposit:o}=e,{symbol:l,decimals:c}=n.get(t)??{};return{id:t,name:a?.asText(),symbol:l,decimals:c,icon:l,type:r.type,isSufficient:s,location:i,existentialDeposit:o}}async mapBond(t,e,n,i){let[a,r]=i,{asset_type:s,is_sufficient:o,existential_deposit:l}=e,{symbol:c,decimals:u}=await this.mapToken(a,e,n),p=Number(r),d=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",d.format(p)].join(" ");return{id:t,name:g,symbol:c+"b",decimals:u,icon:c,type:s.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:p}}async mapShares(t,e,n,i){let{assets:a}=i,{name:r,symbol:s,asset_type:o,is_sufficient:l,existential_deposit:c}=e,u=await Promise.all(a.map(async g=>{let{symbol:b}=await this.mapToken(g,e,n);return[g,b]})),p=Object.fromEntries(u),d=Object.values(p);return{id:t,name:d.join(", "),symbol:s?.asText()||r?.asText(),decimals:18,icon:d.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:p}}async mapExternal(t,e,n,i){let a=await this.mapToken(t,e,new Map,i),r=n?.find(s=>s.internalId===a.id);return r?{...a,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:a}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,i,a,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),s=this.parseMetadata(n),o=[];for(let[l,c]of Array.from(n)){let u=i.get(l),{asset_type:p}=c,d;switch(p.type){case"Bond":let g=r.get(l);d=await this.mapBond(l,c,s,g);break;case"StableSwap":let b=a.get(l);d=await this.mapShares(l,c,s,b);break;case"External":d=await this.mapExternal(l,c,e,u);break;default:d=await this.mapToken(l,c,s,u)}o.push(d)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};import{Subject as ki,bufferCount as Mi,combineLatest as Di,debounceTime as Li,distinctUntilChanged as mn,finalize as qi,map as mt,pairwise as Hi,shareReplay as Ni,startWith as Gi}from"rxjs";var $=class extends E{constructor(t){super(t)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getTokenBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:n}=await e.getValue(t,{at:"best"});return this.calculateBalance(n)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.calculateBalance(i)}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),i=this.subscribeErc20Balance(t);return Di([e,n,i]).pipe(Li(250),mt(a=>a.flat()),Gi([]),Mi(2,1),mt(([a,r],s)=>s===0?r:this.getDeltas(a,r)))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(mt(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(mt(i=>({id:e,balance:this.calculateBalance(i)})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(mn((n,i)=>!i.deltas),mt(({deltas:n})=>{let i=[];return n?.deleted.forEach(a=>{let[r,s]=a.args;i.push({id:s,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(a=>{let[r,s]=a.args;i.push({id:s,balance:this.calculateBalance(a.value)})}),i}))}subscribeErc20Balance(t,e){let n=new ki,i=n.pipe(Ni(1)),a=async()=>(await this.api.query.AssetRegistry.Assets.getEntries({at:"best"})).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),r=async()=>{let o=e||await a(),l=async()=>{let p=(await Promise.all(o.map(async d=>{let g=await this.getTokenBalanceData(t,d);return[d,g]}))).map(([d,g])=>({id:d,balance:g}));n.next(p)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},s;return r().then(o=>s=o),i.pipe(qi(()=>s?.()),Hi(),mt(([o,l],c)=>c===0?l.filter(u=>u.balance.transferable>0n):this.getDeltas(o,l)),mn((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.calculateBalance(n)}calculateBalance(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,n=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:n,transferable:e}}getDeltas(t,e){let n=(a,r)=>a!==void 0&&r!==void 0&&a.transferable===r.transferable&&a.total===r.total,i=t.reduce((a,r)=>(a.set(r.id,r.balance),a),new Map);return e.filter(a=>!n(a.balance,i.get(a.id)))}};var pt=class extends E{_minOrderBudget;_blockTime;constructor(t){super(t)}async getBlockTime(){if(this._blockTime===void 0){let t=await this.api.constants.Aura.SlotDuration();this._blockTime=Number(t)}return this._blockTime}async getMinOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=await this.api.constants.DCA.MinBudgetInNativeCurrency()),this._minOrderBudget}};var dn={};v(dn,{AssetNotFound:()=>Fe,PoolNotFound:()=>Ft,RouteNotFound:()=>Rt});var Fe=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Ft=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Rt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var yn={};v(yn,{EvmClient:()=>Et,EvmRpcAdapter:()=>Ct,createChain:()=>Re});import{Binary as Vi,CompatibilityLevel as Ui,FixedSizeBinary as gn}from"polkadot-api";import{hydration as Wi}from"@galacticcouncil/descriptors";import{encodeFunctionData as Yi,decodeFunctionResult as Xi}from"viem";var Ki=10000000n,Ct=class{api;constructor(t){this.api=t.getTypedApi(Wi)}async getBlock(){let t=await this.api.query.Ethereum.CurrentBlock.getValue({at:"best"}),{header:e}=t,n=e.timestamp/1000n,[i]=e.number;return{timestamp:n,number:i}}readContract=(async t=>{let{abi:e,address:n,functionName:i,args:a}=t,r=Yi({abi:e,functionName:i,args:a}),s=this.api.apis.EthereumRuntimeRPCApi.call,o=await this.api.compatibilityToken,l=s.isCompatible(Ui.BackwardsCompatible,o);console.log(l);let c=await this.api.apis.EthereumRuntimeRPCApi.call(gn.fromText(""),gn.fromHex(n),Vi.fromHex(r),[0n,0n,0n,0n],[Ki,0n,0n,0n],void 0,void 0,void 0,!1,[]);if(console.log(c),!c.success)throw console.error(i,c.value.type),new Error("Contract read failure");let{exit_reason:u,value:p,used_gas:d}=c.value;if(console.log(d),u.type==="Succeed")return Xi({abi:e,functionName:i,data:p.asHex()});throw console.log(i,u.type,u.value.type),new Error("Contract read error")})};import{defineChain as $i}from"viem";var zi=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],Re=()=>$i({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:zi}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as hn,createWalletClient as ji,custom as bn,http as Qi}from"viem";var Et=class{client;chain;constructor(t){this.client=t,this.chain=Re()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return hn({chain:this.chain,transport:Qi()})}getWsProvider(){return hn({transport:bn({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return ji({account:t,chain:this.chain,transport:bn(window.ethereum)})}getRPCAdapter(){return new Ct(this.client)}};var vn={};v(vn,{LiquidityMiningApi:()=>kt,LiquidityMiningClient:()=>Mt});import{AccountId as ia}from"polkadot-api";import L from"big.js";import{fixed_from_rational as Tn}from"@galacticcouncil/math-liquidity-mining";var ce=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let n=0;n<t.length;++n){let[i,a]=t[n];this.result.set(this.getKey(a,i),e[n].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,n,i){let a=this.getKey(t,e),r=this.getKey(t,n),s=this.result.get(a)??0n,o=this.result.get(r)??0n;if(s<i)throw new Error("Attempting to transfer more than is present");this.result.set(a,s+i),this.result.set(r,o+i)}};import at from"big.js";import{calculate_accumulated_rps as Ji,calculate_global_farm_rewards as Zi,calculate_loyalty_multiplier as ta,calculate_user_reward as xn,calculate_yield_farm_delta_rpvs as ea}from"@galacticcouncil/math-liquidity-mining";import fn from"big.js";var Ce=fn(10).pow(18),Pn=BigInt(fn(1).pow(18).toString()),Sn=6e3;var na="1000000000000000000",ue=class{constructor(t,e,n){this.getAccount=t;this.getAsset=e;this.multiCurrency=n}async syncGlobalFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let i=await this.getAsset(t.reward_currency),a=e-t.updated_at,r=this.getAccount(t.id),s=i?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,r),l=at(s.toString()),c=at(o.toString()).minus(l.lt(o.toString())?s.toString():o.toString()),u=at(Zi(t.total_shares_z.toString(),n.toString(),at(t.yield_per_period.toString()).mul(Ce).round(0,at.roundDown).toFixed(),t.max_reward_per_period.toString(),a.toFixed()));if(c.lt(u)&&(u=c),u.eq(0))return t;let p=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,r,p,BigInt(u.toFixed())),{...t,accumulated_rpz:BigInt(Ji(t.accumulated_rpz.toString(),t.total_shares_z.toString(),u.toFixed()))}}syncYieldFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===n)return null;if(t.total_valued_shares===0n)return{...t,updated_at:n};let i=ea(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:n}}getLoyaltyMultiplier(t,e){let n=at(1).mul(Ce).round(0,at.roundDown).toString();if(!e)return n;let{initial_reward_percentage:i,scale_coef:a}=e;return ta(t.toFixed(),i.toString(),a.toFixed())}async claimRewards(t,e,n,i,a){if(e.state.type==="Terminated")return null;let r=Math.floor(i/t.blocks_per_period);if(n.updated_at===r)return null;let s=await this.syncGlobalFarm(t,r,a);if(!s)return null;let o=this.syncYieldFarm(e,s,r);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,u=this.getLoyaltyMultiplier(c,o.loyalty_curve),p=BigInt(xn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),u)),d=BigInt(xn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),na));return{reward:p,maxReward:d,assetId:s.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var aa=L(365.2425).times(24).times(60).times(60),kt=class{client;balanceClient;options;constructor(t,e,n={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:n.blockTime??Sn})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let n=[t,e].sort((a,r)=>a-r);if(t===e)return Pn;let i=await this.client.getOraclePrice(n);if(i){let{n:a,d:r}=i[0].price,s;return t<e?s=Tn(a.toString(),r.toString()):s=Tn(r.toString(),a.toString()),BigInt(s)}}getFarmAddress=(t,e)=>{let n=Buffer.from("modl","utf-8"),i=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),a=Buffer.from([t]),r=Buffer.concat([n,i,a]),o="0x"+Buffer.concat([r,Buffer.alloc(32-r.length)]).toString("hex");return ia(63).dec(o)};getGlobalRewardPerPeriod(t,e,n,i){let a=L(i).times(t.toString()).times(e.toString()).div(18);return a.gte(n.toString())?n.toString():a.toString()}getPoolYieldPerPeriod(t,e,n,i){let a=L(t.toString()).times(e),r=L(n.toString()).times(i);return a.div(r.toString()).toString()}farmData(t,e,n){let{yieldFarm:i,globalFarm:a,priceAdjustment:r,balance:s,id:o}=t,{multiplier:l,loyalty_curve:c}=i,{blocks_per_period:u,yield_per_period:p,total_shares_z:d,max_reward_per_period:g,pending_rewards:b,accumulated_paid_rewards:h,planned_yielding_periods:y,updated_at:f,incentivized_asset:S,reward_currency:x,price_adjustment:T,min_deposit:A}=a,O=w.shiftNeg(r??T,18),D=w.shiftNeg(l,18),U=w.shiftNeg(c?.initial_reward_percentage??0,18),K=aa.div(L(this.blockTime).div(1e3).times(u)).toString(),H;if(d<=0)H=L(D).times(p.toString()).times(K).toString();else{let ni=this.getGlobalRewardPerPeriod(d,p,g,O),ii=this.getPoolYieldPerPeriod(ni,D,d,O);H=L(ii).times(K).toString()}let W=b+h,tt=g*BigInt(y),et=s.transferable+W,Je=et-W,ee=L(Je.toString()).div(g.toString()),ne=L(e).div(u.toString()).toString(),ie=(d>=0?ee.plus(f):ee.plus(ne)).toString(),Pe=L(ie).times(u).toString(),ti=L(d.toString()).div(L(g.toString()).div(p.toString())).div(Math.pow(10,18)).times(100).times(O).toFixed(2),Ze=L(W.toString()).div(et.toString()).gte(.999);H=Ze?"0":L(H).div(n?2:1).times(100).toString();let ei=U?L(H).times(U).toString():void 0;return{apr:H,minApr:ei,isDistributed:Ze,estimatedEndPeriod:ie,estimatedEndBlock:Pe,maxRewards:tt,incentivizedAsset:S,rewardCurrency:x,loyaltyCurve:c,currentPeriod:ne,potMaxRewards:et,fullness:ti,yieldFarmId:i.id,globalFarmId:a.id,poolId:o,distributedRewards:W,plannedYieldingPeriods:y,minDeposit:A}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((i,a)=>i.includes(a.keyArgs[0].toString())?i:[...i,a.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async i=>{let a=await this.getOmnipoolFarms(i);if(a)return[i,a]}));return Object.fromEntries(n.filter(i=>!!i))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),n=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:a,value:r})=>{let[,s]=a,o=r,l=await this.client.getOmnipoolGlobalFarm(s),c=await this.client.getOmnipoolYieldFarm(Number(t),s,o);if(!l||!c)return;let u=l.reward_currency,p=l.incentivized_asset,d=this.getFarmAddress(s),g=await this.getOraclePrice(u,p),b=await this.balanceClient.getBalance(d,u);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b}}));return n?i.map(a=>a?this.farmData(a,n):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((i,a)=>i.includes(a.keyArgs[0].toString())?i:[...i,a.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async i=>{let a=await this.getIsolatedFarms(i);if(a)return[i,a]}));return Object.fromEntries(n.filter(i=>!!i))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),n=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:a,value:r})=>{let[,s]=a,o=r,l=await this.client.getIsolatedGlobalFarm(s),c=await this.client.getIsolatedYieldFarm(t,s,o);if(!l||!c)return;let u=l.reward_currency,p=l.incentivized_asset,d=this.getFarmAddress(s,!0),g=await this.getOraclePrice(u,p),b=await this.balanceClient.getBalance(d,u);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b,farmAddress:d}}));return n?i.map(a=>a?this.farmData(a,n,!0):void 0):[]}async getDepositReward(t,e,n,i){let a=e.global_farm_id,r=e.yield_farm_id,s=n?await this.client.getIsolatedYieldFarm(t,a,r):await this.client.getOmnipoolYieldFarm(Number(t),a,r),o=n?await this.client.getIsolatedGlobalFarm(a):await this.client.getOmnipoolGlobalFarm(a);if(!o||!s)return;let l=o.reward_currency,c=o.incentivized_asset,u=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],p=await this.getAccountAssetBalances(u),d=await this.getOraclePrice(l,c),g=new ce(u,p),h=await new ue(f=>this.getFarmAddress(f),f=>this.client.getAsset(f),g).claimRewards(o,s,e,i,d??o.price_adjustment);if(!h)return;let y=await this.client.getAsset(h.assetId);if(y&&!(h.reward<=y.existential_deposit))return h}async getAccountAssetBalances(t){let[e,n]=await Promise.all([Promise.all(t.filter(([a,r])=>r!==0).map(([a,r])=>this.balanceClient.getTokenBalance(a,r))),Promise.all(t.filter(([a,r])=>r===0).map(([a])=>this.balanceClient.getSystemBalance(a)))]),i=[];for(let a=0,r=0;a+r<t.length;){let s=a+r,[,o]=t[s];o===0?(i.push(n[r]),r+=1):(i.push(e[a]),a+=1)}return i}};import{Binary as ra,Enum as sa}from"polkadot-api";var Mt=class extends E{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(ra.fromText("omnipool"),t,sa("TenMinutes"))}async getRelayBlockNumber(){return(await this.api.query.ParachainSystem.ValidationData.getValue())?.relay_parent_number}async getAllOmnipooFarms(){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries()}async getOmnipooFarms(t){return this.api.query.OmnipoolWarehouseLM.ActiveYieldFarm.getEntries(t)}async getOmnipoolGlobalFarm(t){return this.api.query.OmnipoolWarehouseLM.GlobalFarm.getValue(t)}async getOmnipoolYieldFarm(t,e,n){return this.api.query.OmnipoolWarehouseLM.YieldFarm.getValue(t,e,n)}async getAllIsolatedFarms(){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries()}async getIsolatedFarms(t){return this.api.query.XYKWarehouseLM.ActiveYieldFarm.getEntries(t)}async getIsolatedGlobalFarm(t){return this.api.query.XYKWarehouseLM.GlobalFarm.getValue(t)}async getIsolatedYieldFarm(t,e,n){return this.api.query.XYKWarehouseLM.YieldFarm.getValue(t,e,n)}async getAsset(t){return this.api.query.AssetRegistry.Assets.getValue(t)}};var qn={};v(qn,{PoolContextProvider:()=>St,PoolError:()=>J,PoolFactory:()=>ft,PoolType:()=>R,aave:()=>Ne,hsm:()=>We,lbp:()=>Ee,omni:()=>Me,stable:()=>Le,xyk:()=>qe});var Ee={};v(Ee,{LbpMath:()=>Y,LbpPool:()=>Dt,LbpPoolClient:()=>Lt});import{calculate_in_given_out as oa,calculate_out_given_in as la,calculate_linear_weights as ca,calculate_pool_trade_fee as ua,get_spot_price as ma}from"@galacticcouncil/math-lbp";var Y=class{static getSpotPrice(t,e,n,i,a){return ma(t,e,n,i,a)}static calculateInGivenOut(t,e,n,i,a){return oa(t,e,n,i,a)}static calculateOutGivenIn(t,e,n,i,a){return la(t,e,n,i,a)}static calculateLinearWeights(t,e,n,i,a){return ca(t,e,n,i,a)}static calculatePoolTradeFee(t,e,n){return ua(t,e,n)}};var R=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r.HSM="HSM",r))(R||{}),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{FeeUtils:wn}=w,Dt=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new m(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:a.balance,decimalsIn:i.decimals,decimalsOut:a.decimals,weightIn:i.weight,weightOut:a.weight}}validateAndBuy(t,e,n){let i=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&a.push("MaxOutRatioExceeded"),i===t.assetOut){let s=this.calculateTradeFee(e,n),o=wn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+s,c=this.calculateInGivenOut(t,l),u=t.balanceIn/this.maxInRatio;return c>u&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:a}}else{let s=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return s>o&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}}validateAndSell(t,e,n){let i=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&a.push("MaxInRatioExceeded"),i===t.assetIn){let s=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return s>o&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}else{let s=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(s,n),l=wn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=s-o,u=t.balanceOut/this.maxOutRatio;return c>u&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(t,e){let n=Y.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e){let n=Y.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){let e=Y.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=Y.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=Y.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Ra}from"polkadot-api";import{Subscription as Ca,distinctUntilChanged as Ea,filter as ka}from"rxjs";import{memoize1 as da}from"@thi.ng/memoize";import{TLRUCache as ga}from"@thi.ng/cache";import{ReplaySubject as ha,Subscription as ba,bufferCount as ya,combineLatest as In,debounceTime as fa,defer as Pa,filter as Sa,finalize as xa,from as Ta,map as dt,merge as va,of as wa,pairwise as Ia,skip as Aa,share as Oa,startWith as Ba,switchMap as _a,tap as An,throttleTime as Fa}from"rxjs";import{BehaviorSubject as pa}from"rxjs";var me=class{store$=new pa([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,n=new Map(e.map((s,o)=>[s.address,o])),i=await t(e),a=e.slice(),r=new Set;for(let s of i){let o=n.get(s.address);o===void 0?(n.set(s.address,a.length),a.push(s)):a[o]=s,r.add(s.address)}this.changeset=r,this.store$.next(a)}).catch(console.error)}destroy(){this.store$.complete()}};var q=class extends ${evm;store=new me;shared$;mem=0;memPoolsCache=new ga(null,{ttl:6*1e3});memPools=da(t=>(this.log(this.getPoolType(),"sync mem pools",t),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe(Ba([]),ya(2,1),dt(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),Sa(t=>t.length>0),Fa(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return Pa(()=>{let t=new ba;return Ta(this.getMemPools()).pipe(dt(n=>n.filter(i=>this.hasValidAssets(i))),An(n=>this.store.set(n))).pipe(An(()=>{t.add(this.subscribeBalances()),t.add(this.subscribeUpdates())}),_a(n=>va(wa(n),this.store.asObservable().pipe(Aa(1)))),xa(()=>{t.unsubscribe()}))}).pipe(Oa({connector:()=>new ha(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:n}=e,i=[this.subscribeTokensBalance(n)];if(this.hasSystemAsset(e)){let a=this.subscribeSystemBalance(n);i.push(a)}if(this.hasErc20Asset(e)){let a=e.tokens.filter(s=>s.type==="Erc20").map(s=>s.id),r=this.subscribeErc20Balance(n,a);i.push(r)}return In(i).pipe(dt(a=>a.flat()),Ia(),dt(([a,r])=>this.getDeltas(a,r)),dt(a=>[n,a]))});return In(t).pipe(fa(250),dt(e=>new Map(e))).subscribe(e=>this.store.update(n=>this.updateBalances(n,e)))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:n})=>n>0n&&!!e)}updateBalances=(t,e)=>{let n=[],i=new Map(t.map(a=>[a.address,a]));for(let[a,r]of e){let s=i.get(a);if(s){let o=s.tokens.map(l=>{let c=r.find(u=>u.id===l.id);return c&&l.id!==s.id?{...l,balance:c.balance.transferable}:l});n.push({...s,tokens:o})}}return n}};var Lt=class extends q{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}getPoolWeights(t,e){let{start:n,end:i,initial_weight:a,final_weight:r}=t,s=Y.calculateLinearWeights(n?n.toString():"0",i?i.toString():"0",a.toString(),r.toString(),e.toString()),o=BigInt(s),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Ra.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:"best"}),this.api.query.ParachainSystem.ValidationData.getValue({at:"best"}),this.getPoolLimits()]),i=e?.relay_parent_number||0,a=t.filter(({value:r})=>e&&this.isActivePool(r,i)).map(async({keyArgs:r,value:s})=>{let[o]=r,l=o.toString(),c=await this.getPoolDelta(l,s,i);return{address:l,type:"LBP",fee:s.fee,...c,...n}});return Promise.all(a)}async getPoolDelta(t,e,n){let{assets:i,repay_target:a,fee_collector:r}=e,[s,o]=this.getPoolWeights(e,n),[l,c]=i,[u,p,d,g,b]=await Promise.all([this.isRepayFeeApplied(l,a,r.toString()),this.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c)]);return{repayFeeApply:u,tokens:[{id:l,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:p.transferable,weight:s,type:d?.asset_type.type},{id:c,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:i}=t;return n&&i?e>=n&&e<i:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return(await this.getBalance(n,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let n=this.store.pools.find(a=>a.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:n.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe(ka(t=>t!==void 0),Ea((t,e)=>t.relay_parent_number===e.relay_parent_number)).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let n=[];for(let i of e){let a=this.poolsData.get(i.address);if(a){let{assets:r,repay_target:s,fee_collector:o}=a,[l]=r,[c,u]=this.getPoolWeights(a,t),[p,d]=i.tokens,g=[{...p,weight:c},{...d,weight:u}],b=await this.isRepayFeeApplied(l,s,o.toString());n.push({...i,tokens:g,repayFeeApply:b})}}return n})})}subscribeUpdates(){let t=new Ca;return t.add(this.subscribeValidationData()),t}};var Me={};v(Me,{OmniMath:()=>I,OmniPool:()=>qt,OmniPoolClient:()=>Ht});import{calculate_in_given_out as Ma,calculate_lrna_in_given_out as Da,calculate_out_given_in as La,calculate_out_given_lrna_in as qa,calculate_spot_price as Ha,calculate_lrna_spot_price as Na,calculate_shares as Ga,calculate_liquidity_out as Va,calculate_liquidity_lrna_out as Ua,verify_asset_cap as Wa,calculate_liquidity_hub_in as Ya,is_sell_allowed as Xa,is_buy_allowed as Ka,is_add_liquidity_allowed as $a,is_remove_liquidity_allowed as za,recalculate_asset_fee as ja,recalculate_protocol_fee as Qa}from"@galacticcouncil/math-omnipool";import gt from"big.js";var I=class{static calculateSpotPrice(t,e,n,i){return Ha(t,e,n,i)}static calculateLrnaSpotPrice(t,e){return Na(t,e)}static calculateInGivenOut(t,e,n,i,a,r,s,o,l){return Ma(t,e,n,i,a,r,s,o,l)}static calculateLrnaInGivenOut(t,e,n,i,a){return Da(t,e,n,i,a)}static calculateOutGivenIn(t,e,n,i,a,r,s,o,l){return La(t,e,n,i,a,r,s,o,l)}static calculateOutGivenLrnaIn(t,e,n,i,a){return qa(t,e,n,i,a)}static calculateShares(t,e,n,i){return Ga(t,e,n,i)}static calculateLiquidityOut(t,e,n,i,a,r,s,o){return Va(t,e,n,i,a,r,s,o)}static calculateLiquidityLRNAOut(t,e,n,i,a,r,s,o){return Ua(t,e,n,i,a,r,s,o)}static calculateCapDifference(t,e,n,i){let a=gt(e),r=gt(t),s=gt(i),o=gt(n),l=gt(10).pow(18),c=o.div(l);if(a.div(s).lt(c)){let p=c.times(s).minus(a).times(r),d=a.times(gt(1).minus(c));return p.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,n,i){return Ya(t,e,n,i)}static isSellAllowed(t){return Xa(t)}static isBuyAllowed(t){return Ka(t)}static isAddLiquidityAllowed(t){return $a(t)}static isRemoveLiquidityAllowed(t){return za(t)}static recalculateAssetFee(t,e,n,i,a,r,s,o,l,c,u){return ja(t,e,n,i,a,r,s,o,l,c,u)}static recalculateProtocolFee(t,e,n,i,a,r,s,o,l,c,u){return Qa(t,e,n,i,a,r,s,o,l,c,u)}static verifyAssetCap(t,e,n,i){return Wa(t,e,n,i)}};var{FeeUtils:ht}=w,qt=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new m(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:i.hubReserves,hubReservesOut:a.hubReserves,sharesIn:i.shares,sharesOut:a.shares,decimalsIn:i.decimals,decimalsOut:a.decimals,balanceIn:i.balance,balanceOut:a.balance,tradeableIn:i.tradeable,tradeableOut:a.tradeable,assetInEd:i.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=i===0n?0:B.calculateDiffToRef(a,i),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&s.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&s.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&s.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:i,amountOut:e,feePct:r,errors:s}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=B.calculateDiffToRef(i,a),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&s.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&s.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:a,feePct:r,errors:s}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let i=I.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0",n?ht.toRaw(n.protocolFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}calculateLrnaInGivenOut(t,e,n){let i=I.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let i=I.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0",n?ht.toRaw(n.protocolFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}calculateOutGivenLrnaIn(t,e,n){let i=I.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ht.toRaw(n.assetFee).toString():"0"),a=BigInt(i);return a<0n?0n:a}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=I.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceLrnaInGivenOut(t){let e=I.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=I.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}spotPriceOutGivenLrnaIn(t){let e=I.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as Ja,Binary as Za,CompatibilityLevel as tr,Enum as er}from"polkadot-api";import{toHex as nr}from"@polkadot-api/utils";import{Subscription as ir,distinctUntilChanged as ke,filter as ar,finalize as bt,map as rr,merge as sr}from"rxjs";var{FeeUtils:C}=w,On=Za.fromText("omnipool"),Bn=er("Short"),Ht=class extends q{queryBus=new oe;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t,{at:"best"}),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t,{at:"best"}),t=>String(t),6*1e3);emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(On,t,Bn,{at:"best"}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=nr(e);return Ja(63).dec(n)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(tr.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,i,a,r,s]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:"best"}),this.api.query.Omnipool.HubAssetTradability.getValue(),this.api.query.AssetRegistry.Assets.getValue(t),this.getBalance(e,t),this.getPoolLimits()]),o=n.map(async({keyArgs:c,value:u})=>{let[p]=c,{hub_reserve:d,shares:g,tradable:b,cap:h,protocol_shares:y}=u,[f,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p),this.getBalance(e,p)]);return{id:p,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:S.transferable,cap:h,hubReserves:d,protocolShares:y,shares:g,tradeable:b,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:r.transferable,tradeable:i,type:a?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...s}]}async getPoolFees(t){let e=t.assetOut,n=t.assetIn,i=await this.dynamicFeesConfig.get(e);if(i?.type==="Fixed"){let{asset_fee:f,protocol_fee:S}=i.value;return{assetFee:C.fromPermill(f),protocolFee:C.fromPermill(S)}}let a=this.getOraclePair(e),r=this.getOraclePair(n),[s,o,l]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(a),this.emaOracles.get(r)]),[c,u,p]=await this.getAssetFee(t,this.block,s,o,i?.value.asset_fee_params),[d,g,b]=n===1?[0,0,0]:await this.getProtocolFee(t,this.block,s,l,i?.value.protocol_fee_params),h=c+d,y=p+b;return{assetFee:C.fromPermill(u),protocolFee:C.fromPermill(g),min:C.fromPermill(h),max:C.fromPermill(y)}}async getAssetFee(t,e,n,i,a){let{assetOut:r,balanceOut:s}=t,{min_fee:o,max_fee:l,decay:c,amplification:u}=a||await this.api.constants.DynamicFees.AssetFeeParameters();if(!n||!i)return[o,o,l];let p=C.fromPermill(o),d=C.fromPermill(l),[g]=i,{asset_fee:b,timestamp:h}=n,y=Math.max(1,e-h),f=g.volume.b_in.toString(),S=g.volume.b_out.toString(),x=g.liquidity.b.toString();r===0&&(f=g.volume.a_in.toString(),S=g.volume.a_out.toString(),x=g.liquidity.a.toString());let T=C.fromPermill(b),A=I.recalculateAssetFee(f,S,x,"9",s.toString(),C.toRaw(T).toString(),y.toString(),C.toRaw(p).toString(),C.toRaw(d).toString(),c.toString(),u.toString());return[o,Number(A)*1e6,l]}async getProtocolFee(t,e,n,i,a){let{assetIn:r,balanceIn:s}=t,{min_fee:o,max_fee:l,decay:c,amplification:u}=a||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!n||!i)return[o,o,l];let p=C.fromPermill(o),d=C.fromPermill(l),[g]=i,{protocol_fee:b,timestamp:h}=n,y=Math.max(1,e-h),f=g.volume.b_in.toString(),S=g.volume.b_out.toString(),x=g.liquidity.b.toString();r===0&&(f=g.volume.a_in.toString(),S=g.volume.a_out.toString(),x=g.liquidity.a.toString());let T=C.fromPermill(b),A=I.recalculateProtocolFee(f,S,x,"9",s.toString(),C.toRaw(T).toString(),y.toString(),C.toRaw(p).toString(),C.toRaw(d).toString(),c.toString(),u.toString());return[o,Number(A)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,n=t.tokens.map(i=>i.id).map(i=>this.getOraclePair(i)).map(i=>this.api.query.EmaOracle.Oracles.watchValue(On,i,Bn,"best").pipe(ar(a=>a!==void 0),rr(a=>({pair:i,value:a}))));return sr(...n).pipe(bt(()=>{this.log(this.getPoolType(),"unsub ema oracles"),this.emaOracles.clear()})).subscribe(i=>{let{pair:a,value:r}=i;this.emaOracles.set(r,a)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe(ke((t,e)=>!e.deltas),bt(()=>{bt(()=>{this.log(this.getPoolType(),"unsub dyn fees"),this.dynamicFees.clear()})})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFees.set(e.value,n)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe(ke((t,e)=>!e.deltas),bt(()=>{this.log(this.getPoolType(),"unsub dyn fees config"),this.dynamicFeesConfig.clear()})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFeesConfig.set(e.value,n)})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe(bt(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(ke((t,e)=>!e.deltas),bt(()=>{this.log(this.getPoolType(),"unsub assets")})).subscribe(({deltas:t})=>{this.store.update(([e])=>{let n=t?.upserted.reduce((a,r)=>{let[s]=r.args;return a.set(s,r.value),a},new Map),i=e.tokens.map(a=>{let r=n?.get(a.id);return r?this.updateTokenState(a,r):a});return[{...e,tokens:i}]})})}subscribeUpdates(){let t=new ir;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:n,shares:i,tradable:a,cap:r,protocol_shares:s}=e;return{...t,cap:r,hubReserves:n,protocolShares:s,shares:i,tradeable:a}}};var Le={};v(Le,{StableMath:()=>M,StableSwap:()=>Z,StableSwapClient:()=>Nt});import{calculate_in_given_out as or,calculate_out_given_in as lr,calculate_amplification as cr,calculate_add_one_asset as ur,calculate_liquidity_out_one_asset as mr,calculate_shares as pr,calculate_shares_for_amount as dr,calculate_spot_price_with_fee as gr,pool_account_name as hr,recalculate_peg as br}from"@galacticcouncil/math-stableswap";var M=class{static getPoolAddress(t){return hr(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,i,a){return cr(t,e,n,i,a)}static calculateInGivenOut(t,e,n,i,a,r,s){return or(t,e,n,i,a,r,s)}static calculateAddOneAsset(t,e,n,i,a,r,s){return ur(t,e,n,i,a,r,s)}static calculateSharesForAmount(t,e,n,i,a,r,s){return dr(t,e,n,i,a,r,s)}static calculateOutGivenIn(t,e,n,i,a,r,s){return lr(t,e,n,i,a,r,s)}static calculateLiquidityOutOneAsset(t,e,n,i,a,r,s){return mr(t,e,n,i,a,r,s)}static calculateShares(t,e,n,i,a,r){return pr(t,e,n,i,a,r)}static calculateSpotPriceWithFee(t,e,n,i,a,r,s,o){return gr(t,e,n,i,a,r,s,o)}static recalculatePegs(t,e,n,i,a){let r=br(t,e,n,i,a);return JSON.parse(r)}};var{FeeUtils:yt}=w,Z=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new m(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:a.balance,decimalsIn:i.decimals,decimalsOut:a.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:a.tradeable,assetInEd:i.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),r=i===0n?0:B.calculateDiffToRef(a,i),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&s.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:i,amountOut:e,feePct:r,errors:s}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),r=B.calculateDiffToRef(i,a),s=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&s.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:a,feePct:r,errors:s}}calculateIn(t,e,n){let i=M.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateAddOneAsset(t,e,n){let i=M.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateSharesForAmount(t,e,n){let i=M.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateInGivenOut(t,e,n){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,n):t.assetIn==this.id?this.calculateSharesForAmount(t,e,n):this.calculateIn(t,e,n)}spotPriceInGivenOut(t){let e=M.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let i=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(i)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let i=M.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateWithdrawOneAsset(t,e,n){let i=M.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateShares(t,e,n){let i=M.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?yt.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(i);return a<0n?0n:a}calculateOutGivenIn(t,e,n){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,n):t.assetOut==this.id?this.calculateShares(t,e,n):this.calculateOut(t,e,n)}spotPriceOutGivenIn(t){let e=M.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let i=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(i)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:i})=>({asset_id:e,amount:n,decimals:i}));return JSON.stringify(t,_t.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],_t.jsonFormatter)}};import{AccountId as yr,CompatibilityLevel as fr}from"polkadot-api";import{toHex as Pr}from"@polkadot-api/utils";import{blake2b as Sr}from"@noble/hashes/blake2b";import{Subscription as xr,distinctUntilChanged as Tr,finalize as De,map as vr,merge as wr}from"rxjs";var{FeeUtils:Ir}=w,Nt=class extends q{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=M.getPoolAddress(t),n=Sr(e,{dkLen:32}),i=Pr(n);return yr(63).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:n,final_amplification:i,initial_block:a,final_block:r}=t,s=M.calculateAmplification(n.toString(),i.toString(),a.toString(),r.toString(),e.toString()),o=Number(s)<i;return{amplification:BigInt(s),isRampPeriod:o}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),i=e.assets.map(async a=>{let[r,s,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,a),this.api.query.AssetRegistry.Assets.getValue(a),this.getBalance(n,a)]);return{id:a,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:o.transferable,tradeable:r,type:s?.asset_type.type}});return Promise.all(i)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(fr.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:"best"}),this.api.query.System.Number.getValue({at:"best"}),this.getPoolLimits()]),i=t.map(async({keyArgs:a,value:r})=>{let[s]=a,o=this.getPoolAddress(s),[l,c,u]=await Promise.all([this.getPoolTokens(s,r),this.api.query.Stableswap.PoolPegs.getValue(s,{at:"best"}),this.api.query.Tokens.TotalIssuance.getValue(s,{at:"best"})]),p=this.getPoolAmplification(r,e),d=c?this.getRecentPegs(c):this.getDefaultPegs(r);return l.push({id:s,tradeable:15,balance:u,decimals:18}),this.poolsData.set(s,r),{address:o,id:s,type:"Stableswap",fee:Ir.fromPermill(r.fee),tokens:l,totalIssuance:u,pegs:d,...n,...p}});return Promise.all(i)}async getPoolFees(t,e){return{fee:this.store.pools.find(i=>i.address===e).fee}}getDefaultPegs(t){return M.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,i])=>i.map(a=>a.toString()))}subscribeIssuance(){let e=this.store.pools.map(n=>n.id).map(n=>this.api.query.Tokens.TotalIssuance.watchValue(n,"best").pipe(vr(i=>({id:n,value:i}))));return wr(...e).pipe(De(()=>{this.log(this.getPoolType(),"unsub total issuance")})).subscribe(n=>{let{id:i,value:a}=n;this.store.update(r=>{let s=[];return r.filter(o=>o.id===i).forEach(o=>{let l=o.tokens.map(c=>c.id===i?{...c,balance:a}:c);s.push({...o,tokens:l,totalIssuance:a})}),s})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe(Tr((t,e)=>!e.deltas),De(()=>{this.log(this.getPoolType(),"unsub pool pegs")})).subscribe(({deltas:t})=>{this.store.update(e=>{let n=[],i=new Map(e.map(a=>[a.id,a]));return t?.upserted.forEach(({args:a,value:r})=>{let[s]=a,o=i.get(s);if(o){let l=this.getRecentPegs(r);n.push({...o,pegs:l})}}),n})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe(De(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.store.update(e=>{let n=[];return e.filter(i=>i.isRampPeriod).forEach(i=>{let a=this.poolsData.get(i.id);if(a){let r=this.getPoolAmplification(a,t);n.push({...i,...r})}}),n})})}subscribeUpdates(){let t=new xr;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var qe={};v(qe,{XykMath:()=>j,XykPool:()=>Gt,XykPoolClient:()=>Vt});import{calculate_in_given_out as Ar,calculate_out_given_in as Or,calculate_pool_trade_fee as Br,get_spot_price as _r,calculate_liquidity_in as Fr,calculate_shares as Rr,calculate_spot_price as Cr,calculate_spot_price_with_fee as Er,calculate_liquidity_out_asset_a as kr,calculate_liquidity_out_asset_b as Mr}from"@galacticcouncil/math-xyk";var j=class{static getSpotPrice(t,e,n){return _r(t,e,n)}static calculateInGivenOut(t,e,n){return Ar(t,e,n)}static calculateOutGivenIn(t,e,n){return Or(t,e,n)}static calculatePoolTradeFee(t,e,n){return Br(t,e,n)}static calculateLiquidityIn(t,e,n){return Fr(t,e,n)}static calculateSpotPrice(t,e){return Cr(t,e)}static calculateSpotPriceWithFee(t,e,n,i){return Er(t,e,n,i)}static calculateShares(t,e,n){return Rr(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,i){return kr(t,e,n,i)}static calculateLiquidityOutAssetB(t,e,n,i){return Mr(t,e,n,i)}};var{FeeUtils:_n}=w,Gt=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new m(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:a.decimals,balanceIn:i.balance,balanceOut:a.balance,assetInEd:i.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=this.calculateTradeFee(i,n),r=_n.toPct(n.exchangeFee),s=i+a,o=[];(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return s>c&&o.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=this.calculateTradeFee(i,n),r=_n.toPct(n.exchangeFee),s=i-a,o=[];(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return s>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:r,errors:o}}calculateInGivenOut(t,e){let n=j.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e){let n=j.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){let e=j.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=j.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=j.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Dr}from"polkadot-api";import{Subscription as Lr}from"rxjs";var Vt=class extends q{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Dr.BackwardsCompatible,e)}async loadPools(){let[t,e]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries(),this.getPoolLimits()]),n=t.map(async({keyArgs:i,value:a})=>{let[r]=i,[s,o]=a,[l,c,u,p]=await Promise.all([this.getBalance(r,s),this.api.query.AssetRegistry.Assets.getValue(s),this.getBalance(r,o),this.api.query.AssetRegistry.Assets.getValue(o)]);return{address:r,type:"XYK",tokens:[{id:s,decimals:c?.decimals||this.decimals.get(s),existentialDeposit:c?.existential_deposit,balance:l.transferable,type:c?.asset_type.type},{id:o,decimals:p?.decimals||this.decimals.get(o),existentialDeposit:p?.existential_deposit,balance:u.transferable,type:p?.asset_type.type}],...e}});return Promise.all(n)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Lr.EMPTY}};var Ne={};v(Ne,{AavePool:()=>Ut,AavePoolClient:()=>Wt});var Ut=class m{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new m(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),a=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(a==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:a.balance,decimalsIn:i.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),a=[];return e>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),a=[];return i>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:a}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){let e=Math.pow(10,t.decimalsOut);return BigInt(e)}spotPriceOutGivenIn(t){let e=Math.pow(10,t.decimalsIn);return BigInt(e)}calculateTradeFee(t,e){return 0n}};import{AccountId as qr}from"polkadot-api";import{toHex as Hr}from"@polkadot-api/utils";import{Subscription as Rn,filter as He,finalize as Cn,map as En}from"rxjs";import{decodeEventLog as Nr}from"viem";var Fn=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"}];var{ERC20:Gr}=rt,Vr=["Supply","Withdraw","Repay","Borrow"],Wt=class extends q{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let n=t+"/"+e,i=new TextEncoder().encode(n.padEnd(32,"\0")),a=Hr(i);return qr(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools({at:"best"})).map(async({reserve:n,atoken:i,liqudity_in:a,liqudity_out:r})=>{let[s,o,l,c]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i)]);return{address:this.getPoolId(n,i),type:"Aave",tokens:[{id:n,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:a,location:o,type:s?.asset_type.type},{id:i,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:i,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id,{at:"best"});return t.tokens.map(r=>{let s=r.id===e.id?i:a;return{...r,balance:s}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:n}=e.value;return n.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return Gr.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:n}=t;return{assetIn:e,assetOut:n,key:`${e}:${n}`}}parseEvmLog(t){let{topics:e,data:n}=t.log,i=e.map(r=>r.asHex()),a=n.asHex();try{let{eventName:r,args:s}=Nr({abi:Fn,topics:i,data:a}),o=s.reserve.toLowerCase();return{eventName:r,reserve:o,key:`${r}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(n=>n.tokens).map(([n,i])=>i).map(n=>n.id);return this.api.event.Router.Executed.watch().pipe(En(({payload:n})=>this.parseRouterLog(n)),He(({assetIn:n,assetOut:i})=>e.includes(n)||e.includes(i)),Cn(()=>{this.log(this.getPoolType(),"unsub router executed")})).subscribe(({assetIn:n,assetOut:i,key:a})=>{this.log(this.getPoolType(),"[router:Executed]",a),this.store.update(async r=>{let s=[];for(let o of r){let[l,c]=o.tokens;if(c.id===n||c.id===i){let p=await this.getPoolDelta(o);s.push({...o,tokens:p})}}return s})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(En(({payload:t})=>this.parseEvmLog(t)),He(t=>t!==void 0),He(({eventName:t})=>Vr.includes(t)),Cn(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({reserve:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async n=>{let i=[];for(let a of n){let[r]=a.tokens;if(this.getReserveH160Id(r).toLowerCase()===t){let o=await this.getPoolDelta(a);i.push({...a,tokens:o})}}return i})})}subscribeBalances(){return Rn.EMPTY}subscribeUpdates(){let t=new Rn;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var ft=class{static get(t){switch(t.type){case"Aave":return Ut.fromPool(t);case"XYK":return Gt.fromPool(t);case"Omnipool":return qt.fromPool(t);case"LBP":return Dt.fromPool(t);case"Stableswap":return Z.fromPool(t);case"HSM":return Z.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as as,Subscription as Pt,takeUntil as rs}from"rxjs";var We={};v(We,{HsmMath:()=>X,HsmPool:()=>Ge,HsmPoolClient:()=>$t});import{calculate_collateral_in_given_hollar_out as Ur,calculate_collateral_out_given_hollar_in as Wr,calculate_hollar_in_given_collateral_out as Yr,calculate_hollar_out_given_collateral_in as Xr,calculate_imbalance as Kr,calculate_max_price as $r,calculate_buyback_limit as zr,calculate_buyback_price_with_fee as jr}from"@galacticcouncil/math-hsm";var X=class{static calculateCollateralInGivenHollarOut(t,e,n){return Ur(t,e,n)}static calculateCollateralOutGivenHollarIn(t,e,n){return Wr(t,e,n)}static calculateHollarOutGivenCollateralIn(t,e,n){return Xr(t,e,n)}static calculateHollarInGivenCollateralOut(t,e,n){return Yr(t,e,n)}static calculateImbalance(t,e,n){return Kr(t,e,n)}static calculateBuybackLimit(t,e){return zr(t,e)}static calculateBuybackPriceWithFee(t,e,n){return jr(t,e,n)}static calculateMaxPrice(t,e){return $r(t,e)}};var{FeeUtils:Yt}=w,Ge=class m extends Z{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new m(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,n,i){let a=this.calculateBuybackLimit(t);e>a&&i.push("MaxBuyBackExceeded");let r=this.calculateBuyPrice(t,e,n),s=this.calculateMaxPrice(t);return r>s&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,n){return this.collateralBalance+t>this.maxInHolding&&n.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&n.push("FacilitatorCapacityExceeded"),n}validateTradeConstraints(t,e,n){let i=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,n,i):this.validateTradeHollarOut(e,n,i)}validateAndBuy(t,e){let n=this.calculateInGivenOut(t,e),i=this.validateTradeConstraints(t,n,e);return{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e){let n=this.calculateOutGivenIn(t,e),i=this.validateTradeConstraints(t,e,n);return{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:i}}calculateHollarInGivenCollateralOut(t,e){let n=super.calculateInGivenOut(t,e,{fee:this.fee}),i=X.calculateHollarInGivenCollateralOut(e.toString(),n.toString(),Yt.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),n=X.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),Yt.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let n=super.calculateOutGivenIn(t,e,{fee:this.fee}),i=X.calculateCollateralOutGivenHollarIn(e.toString(),n.toString(),Yt.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),n=X.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),Yt.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),n=X.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(n)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),n=X.calculateBuybackLimit(e.toString(),Yt.toRaw(this.buyBackRate).toString());return BigInt(n)}calculateBuyPrice(t,e,n){let i=n*10n**BigInt(t.decimalsIn);return e*10n**BigInt(t.decimalsOut)/i}calculateMaxPrice(t){let e=this.getCollateralPeg(),n=X.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[i,a]=JSON.parse(n),r=10n**BigInt(18-t.decimalsOut);return BigInt(i)*r/BigInt(a)}spotPriceInGivenOut(t){let e=P.toBigInt(1,t.decimalsOut);return this.calculateInGivenOut(t,e)}spotPriceOutGivenIn(t){let e=P.toBigInt(1,t.decimalsIn);return this.calculateOutGivenIn(t,e)}getCollateralPeg(){let t=this.tokens.findIndex(i=>i.id!==this.hollarId),e=this.pegs[t],n=this.tokens[t].decimals;return this.isDefaultPeg(e)?[P.toBigInt(1,18).toString(),P.toBigInt(1,n).toString()]:e}isDefaultPeg(t){let[e,n]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&n==="1"}};import{AccountId as Qr,CompatibilityLevel as Jr}from"polkadot-api";import{toHex as Zr}from"@polkadot-api/utils";import{Subscription as kn,combineLatest as ts,filter as Mn,finalize as Dn,map as Ve,pairwise as es}from"rxjs";import{decodeEventLog as ns}from"viem";var Xt=[{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 Kt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[n,i]=await this.client.readContract({abi:Xt,address:t,functionName:"getFacilitatorBucket",args:[e]});return n-i}};var{FeeUtils:Ue}=w,{H160:Ln}=lt,is=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],$t=class extends q{ghoClient;stableClient;constructor(t,e,n){super(t,e),this.stableClient=n,this.ghoClient=new Kt(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:n}=e.value;return n.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),n=new TextEncoder().encode(e),i=Zr(n);return Qr(63).dec(i)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(Jr.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,n,i]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries({at:"best"}),this.stableClient.getPools()]);if(n.length===0)return[];let a=this.getFacilitatorAddress(),r=Ln.fromAny(a),s=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(s,r),l=n.map(async({keyArgs:u,value:p})=>{let[d]=u,{pool_id:g,max_buy_price_coefficient:b,max_in_holding:h,purchase_fee:y,buy_back_fee:f,buyback_rate:S}=p,x=i.find(T=>T.id===g);if(x){let T=this.getPoolId(g),A=await this.getBalance(a,d);return{...x,address:T,type:"HSM",tokens:x.tokens.filter(O=>O.id!==g),hsmAddress:a,hsmMintCapacity:o,hollarId:t,hollarH160:s,collateralId:d,collateralBalance:A.transferable,maxBuyPriceCoefficient:b,maxInHolding:h,purchaseFee:Ue.fromPermill(y),buyBackFee:Ue.fromPermill(f),buyBackRate:Ue.fromPerbill(S)}}});return(await Promise.all(l)).filter(u=>u!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:n}=t.log,i=e.map(r=>r.asHex()),a=n.asHex();try{let{eventName:r,args:s}=ns({abi:Xt,topics:i,data:a}),o=s.facilitatorAddress.toLowerCase();return{eventName:r,facilitator:o,key:`${r}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Ve(({payload:t})=>this.parseEvmLog(t)),Mn(t=>t!==void 0),Mn(({eventName:t})=>is.includes(t)),Dn(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({facilitator:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async n=>{let i=[],[{hsmAddress:a,hollarH160:r}]=n,s=Ln.fromAny(a);if(s.toLowerCase()===t){let l=await this.ghoClient.getFacilitatorCapacity(r,s);for(let c of n)i.push({...c,hsmMintCapacity:l})}return i})})}subscribeBalances(){let t=[],e=[];this.store.pools.forEach(a=>{let{tokens:r,collateralId:s}=a;r.find(l=>l.id===s).type==="Erc20"?e.push(s):t.push(s)});let[{hsmAddress:n}]=this.store.pools,i=[];if(t.length>0){let a=this.subscribeTokensBalance(n);i.push(a)}if(e.length>0){let a=this.subscribeErc20Balance(n,e);i.push(a)}return i.length>0?ts(i).pipe(Ve(a=>a.flat()),es(),Ve(([a,r])=>this.getDeltas(a,r)),Dn(()=>{this.log(this.getPoolType(),"unsub collateral balance")})).subscribe(a=>{this.store.update(r=>{let s=[],o=new Map(r.map(l=>[l.collateralId,l]));return a.forEach(({id:l,balance:c})=>{let u=o.get(l);u&&(this.log(this.getPoolType(),"[collateral:Balance]",l,c.transferable),s.push({...u,collateralBalance:c.transferable}))}),s})}):kn.EMPTY}subscribeUpdates(){let t=new kn;return t.add(this.subscribeEvmLog()),t}};var St=class extends E{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=Pt.EMPTY;omniSub=Pt.EMPTY;stableSub=Pt.EMPTY;hsmSub=Pt.EMPTY;xykSub=Pt.EMPTY;lbpSub=Pt.EMPTY;isReady=!1;isDestroyed=new as;constructor(t,e){super(t),this.evm=e,this.aave=new Wt(t,e),this.omnipool=new Ht(t,e),this.stableswap=new Nt(t,e),this.hsm=new $t(t,e,this.stableswap),this.xyk=new Vt(t,e),this.lbp=new Lt(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe(rs(this.isDestroyed)).subscribe(e=>{e.forEach(n=>{this.pools.set(n.address,n)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(i=>i.getPoolType()===e.type);if(n)return n.getPoolFees(t,e.address);throw new Ft(e.type)}};var Un={};v(Un,{DEFAULT_BLOCK_TIME:()=>Nn,DEFAULT_MIN_BUDGET:()=>Ke,ORDER_MIN_BLOCK_PERIOD:()=>Gn,Router:()=>xt,TWAP_BLOCK_PERIOD:()=>Jt,TWAP_MAX_DURATION:()=>ze,TWAP_MAX_PRICE_IMPACT:()=>$e,TWAP_TX_MULTIPLIER:()=>kg,TradeOrderError:()=>Xe,TradeOrderType:()=>de,TradeRouteBuilder:()=>G,TradeRouter:()=>Tt,TradeScheduler:()=>vt,TradeType:()=>pe});var zt=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var ss=10,jt=class{isNotVisited(t,e){let n=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let i=[],a=new zt,r=[];for(r.push([e,""]),a.enqueue(r);a.size()>0;){let s=a.dequeue();if(!s||s.length>ss)continue;let o=s[s.length-1];(n===null||o[0]===n)&&i.push(s),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,s)){let u=[...s];u.push(c),a.enqueue(u)}})}return i}findShortestPaths(t,e,n){let i=[],a=new zt,r=[];r.push([e,""]),a.enqueue(r);let s=1/0;for(;a.size()>0;){let o=a.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<s?(s=o.length,i.length=0,i.push(o)):o.length===s&&i.push(o);continue}let c=t.get(l[0]);for(let u of c??[])this.isNotVisited(u,o)&&a.enqueue([...o,u])}return i}buildAndPopulateGraph(t,e){let n=new Map;for(let i of t)n.set(parseInt(i),[]);for(let[i,a,r]of e)n.get(a)?.push([r,i]);return n}};function Ye(m){let t={};for(let e of m){let n=e.tokens.length;for(let i=0;i<n;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let a=0;a<n;a++){if(i==a)continue;let r=[e.address,e.tokens[i].id,e.tokens[a].id];t[e.tokens[i].id].push(r)}}}return t}var Qt=class{getProposals(t,e,n){let i=n.filter(h=>h.type==="XYK"),a=n.filter(h=>h.type!=="XYK"),r=new Set(a.map(h=>h.tokens).flat().map(h=>h.id)),s=r.has(t),o=r.has(e),l=new jt,c=h=>{let y=Ye(h),f=Object.keys(y),S=f.flatMap(x=>y[x]);return l.buildAndPopulateGraph(f,S)};if(!s&&!o){let h=i.filter(S=>S.tokens.find(x=>x.id===t)||S.tokens.find(x=>x.id===e)),y=c(h),f=l.findPaths(y,t,e);return this.parsePaths(f)}if(s&&o){let h=c(a),y=l.findPaths(h,t,e);return this.parsePaths(y)}let u=s?e:t,p=i.filter(h=>h.tokens.some(y=>y.id===u));if(p.length===0)return[];let d=[...a,...p],g=c(d),b=l.findPaths(g,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let n of t){let i=[];for(let a=0;a<n.length;a++){let r=n[a],s=n[a+1];if(s==null)break;i.push(this.toEdge(r,s))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var xt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Qt,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:n=[]}=this.filter,i=new Set(e),a=new Set(n);return t.filter(r=>a.has(r.type)?!1:i.size>0?i.has(r.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(i=>i!==t).map(i=>this.getRoutes(i,t)))).filter(i=>i.length>0).map(([i])=>i[0].assetIn).sort()}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(n);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(i=>i.id)).flat().sort((n,i)=>n>i?1:-1);return new Set(e)}getPaths(t,e,n){let i=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(r=>this.validPath(r,i)).map(r=>this.toHops(r,i))}getProposals(t,e,n){let i=this.buildRouteKey(t,e,n);if(this.routeProposals.has(i))return this.routeProposals.get(i);let a=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(i,a),a}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,i)=>n&&i)}validEdge([t,e,n],i){return i.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,ft.get(e)]))}toHops(t,e){return t.map(([n,i,a])=>{let r=e.get(n);return{poolAddress:n,poolId:r?.id,pool:r?.type,assetIn:i,assetOut:a}})}};var pe=(e=>(e.Buy="Buy",e.Sell="Sell",e))(pe||{}),de=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(de||{}),Xe=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Xe||{});var{FeeUtils:Hn}=w,Tt=class extends xt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,n){let i=super.validateInput(t,e,n),a=super.getPaths(t,e,n);if(!a.length)throw new Rt(t,e);return{paths:a,pools:n,poolsMap:i}}async withCtx(t,e,n){let i=await super.getPools(),a=this.buildCtxSync(t,e,i);return n(a)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,i)=>{let a=n[n.length-1].amountOut,r=i[i.length-1].amountOut;return a>r?-1:1});return e.find(n=>n.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(a=>a.tradeFeeRange?.[0]??a.tradeFeePct).reduce((a,r)=>a+r),i=t.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,r)=>a+r);return[n,i]}}getPoolFeeRange(t){let e=t.min?Hn.toPct(t.min):void 0,n=t.max?Hn.toPct(t.max):void 0;if(e&&n)return[e,n]}async getBestSell(t,e,n){return this.getSell(t,e,n)}getSellSpot(t){let e=t[t.length-1];if(t.length===1)return e.spotPrice;let n=t.map(s=>s.assetOutDecimals).reduce((s,o)=>s+o),i=t.map(s=>s.spotPrice).reduce((s,o)=>s*o),a=n-e.assetOutDecimals,r=Math.pow(10,a);return i/BigInt(r)}async getSell(t,e,n,i){return this.withCtx(t,e,async({paths:a,poolsMap:r})=>{let s;if(i)s=await this.toSellSwaps(n,i,r);else{let o=a.map(c=>this.toSellSwaps(n,c,r)),l=await Promise.all(o);s=this.findBestSellRoute(l)}return this.buildSell(r,s)})}async getSells(t,e,n){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let r=i.map(o=>this.toSellSwaps(n,o,a));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(a,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let n=e[0],i=e[e.length-1],a=this.isDirectTrade(e),r=this.getSellSpot(e),s=i.amountOut,o=a?i.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-s,c=this.getRouteFeeRange(e),u=a?i.tradeFeePct:B.calculateSellFee(o,s),p=Math.pow(10,n.assetInDecimals),d=n.amountIn*r/BigInt(p),g=B.calculateDiffToRef(o,d);return{type:"Sell",amountIn:n.amountIn,amountOut:i.amountOut,spotPrice:r,tradeFee:l,tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Sell",amountIn:P.toDecimal(n.amountIn,n.assetInDecimals),amountOut:P.toDecimal(i.amountOut,i.assetOutDecimals),spotPrice:P.toDecimal(r,i.assetOutDecimals),tradeFee:P.toDecimal(l,i.assetOutDecimals),tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0Y(t,e,n){let i=[];for(let a=0;a<e.length;a++){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a>0?l=i[a-1]:l=t;let c=s.calculateOutGivenIn(o,l);i.push(c)}return i[i.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:i,pools:a,poolsMap:r}=n,l=a.filter(b=>b.tokens.some(h=>h.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(h=>h.id===t)).map(b=>b.map(h=>h.balance).reduce((h,y)=>h+y)).sort((b,h)=>h<b?-1:1)[0],c=B.getFraction(l,.1),u=await Promise.all(i.map(b=>this.toSellSwaps(c,b,r))),d=this.findBestSellRoute(u).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),g=this.buildRouteKey(t,e,a);return this.mlr.set(g,d),d}async toSellSwaps(t,e,n){let i=[];for(let a=0;a<e.length;a++){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a>0?l=i[a-1].amountOut:l=typeof t=="string"?P.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,s),{amountOut:u,calculatedOut:p,feePct:d,errors:g}=s.validateAndSell(o,l,c),b=this.getPoolFeeRange(c),h=s.spotPriceOutGivenIn(o),y=Math.pow(10,o.decimalsIn),f=l*h/BigInt(y),S=B.calculateDiffToRef(p,f);i.push({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:u,calculatedOut:p,spotPrice:h,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g,isSupply(){return s.type==="Aave"&&s.tokens[0].id===r.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===r.assetIn},toHuman(){return{...r,amountIn:P.toDecimal(l,o.decimalsIn),amountOut:P.toDecimal(u,o.decimalsOut),calculatedOut:P.toDecimal(p,o.decimalsOut),spotPrice:P.toDecimal(h,o.decimalsOut),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g}}})}return i}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let i=this.buildRouteKey(t,e,n.pools),a=this.mlr.get(i);return a||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:i,poolsMap:a}=n,r=this.buildRouteKey(t,e,i),s=this.mlr.get(r);s||(s=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",s,a),l=this.getSellSpot(o),c=o[o.length-1].assetOutDecimals;return{amount:l,decimals:c}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((n,i)=>{let a=n[0].amountIn,r=i[0].amountIn;return a>r?1:-1});return e.find(n=>n.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(s=>s.assetInDecimals).reduce((s,o)=>s+o),i=t.map(s=>s.spotPrice).reduce((s,o)=>s*o),a=n-e.assetInDecimals,r=Math.pow(10,a);return i/BigInt(r)}async getBuy(t,e,n,i){return this.withCtx(t,e,async({paths:a,poolsMap:r})=>{let s;if(i)s=await this.toBuySwaps(n,i,r);else{let o=a.map(c=>this.toBuySwaps(n,c,r)),l=await Promise.all(o);s=this.findBestBuyRoute(l)}return this.buildBuy(r,s)})}async getBuys(t,e,n){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let r=i.map(o=>this.toBuySwaps(n,o,a));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(a,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let n=e[e.length-1],i=e[0],a=this.isDirectTrade(e),r=this.getBuySpot(e),s=i.amountIn,o=a?i.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=s-o,c=this.getRouteFeeRange(e),u=a?i.tradeFeePct:B.calculateBuyFee(o,s),p=Math.pow(10,n.assetOutDecimals),d=n.amountOut*r/BigInt(p),g;return o===0n?g=-100:g=B.calculateDiffToRef(d,o),{type:"Buy",amountOut:n.amountOut,amountIn:i.amountIn,spotPrice:r,tradeFee:l,tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Buy",amountOut:P.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:P.toDecimal(i.amountIn,i.assetInDecimals),spotPrice:P.toDecimal(r,i.assetInDecimals),tradeFee:P.toDecimal(l,i.assetInDecimals),tradeFeePct:u,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0X(t,e,n){let i=[];for(let a=e.length-1;a>=0;a--){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=t:l=i[0];let c=s.calculateInGivenOut(o,l);i.unshift(c)}return i[0]}async toBuySwaps(t,e,n){let i=[];for(let a=e.length-1;a>=0;a--){let r=e[a],s=n.get(r.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(r.assetIn,r.assetOut),l;a==e.length-1?l=typeof t=="string"?P.toBigInt(t,o.decimalsOut):t:l=i[0].amountIn;let c=await this.ctx.getPoolFees(o,s),{amountIn:u,calculatedIn:p,feePct:d,errors:g}=s.validateAndBuy(o,l,c),b=this.getPoolFeeRange(c),h=s.spotPriceInGivenOut(o),y=Math.pow(10,o.decimalsOut),f=l*h/BigInt(y),S;p===0n?S=-100:S=B.calculateDiffToRef(f,p),i.unshift({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:u,calculatedIn:p,spotPrice:h,tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g,isSupply(){return s.type==="Aave"&&s.tokens[0].id===r.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===r.assetIn},toHuman(){return{...r,amountOut:P.toDecimal(l,o.decimalsOut),amountIn:P.toDecimal(u,o.decimalsIn),calculatedIn:P.toDecimal(p,o.decimalsIn),spotPrice:P.toDecimal(h,o.decimalsIn),tradeFeePct:d,tradeFeeRange:b,priceImpactPct:S,errors:g}}})}return i}};var Nn=6e3,Ke=1000000000000000n,Jt=6,$e=-5,ze=216e5,kg=3,Gn=6;import{Enum as Vn}from"polkadot-api";var G=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:i,poolId:a})=>i==="Stableswap"?{pool:Vn("Stableswap",a),asset_in:e,asset_out:n}:{pool:Vn(i),asset_in:e,asset_out:n})}};var vt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Ke})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,i,a){let[r,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=s,u=l[0],p=l[l.length-1],{assetInDecimals:d}=u,{assetOutDecimals:g}=p,b=Math.abs(c),h=this.getMinimumTradeCount(o,r),y=this.getOptimalTradeCount(b),f=a?Math.round(i/a):y,S=Math.ceil(i/h),x=Math.round(i/y),T=Math.round(i/f),A=o/BigInt(f),O=await this.router.getBestSell(t,e,A),D=o<r,U=[];D&&U.push("OrderTooSmall");let K=O.amountOut*BigInt(f),H=this.toBlockPeriod(T),W=O.tradeFee*BigInt(f),tt=G.build(l),et={assetIn:t,assetOut:e,errors:U,frequencyMin:S,frequencyOpt:x,frequency:T,tradeCount:f,tradeFee:W,tradeImpactPct:O.priceImpactPct,tradePeriod:H,tradeRoute:tt,type:"Dca"};return{...et,amountIn:o,amountOut:K,tradeAmountIn:O.amountIn,tradeAmountOut:O.amountOut,toHuman(){return{...et,amountIn:P.toDecimal(o,d),amountOut:P.toDecimal(K,g),tradeAmountIn:P.toDecimal(O.amountIn,d),tradeAmountOut:P.toDecimal(O.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let i=t+n/2n;return Number(i/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:r,swaps:s,priceImpactPct:o}=a,l=s[0],c=s[s.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,d=Math.abs(o),g=this.getTwapTradeCount(d),b=r/BigInt(g),h=await this.router.getBestSell(l.assetIn,c.assetOut,b),y=g===1,f=r<i,S=h.priceImpactPct<-5,x=[];f||y?x.push("OrderTooSmall"):S&&x.push("OrderImpactTooBig");let T=h.amountOut*BigInt(g),A=h.tradeFee*BigInt(g),O=G.build(s),D={assetIn:t,assetOut:e,errors:x,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:O,type:"TwapSell"};return{...D,amountIn:r,amountOut:T,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:A,toHuman(){return{...D,amountIn:P.toDecimal(r,u),amountOut:P.toDecimal(T,p),tradeAmountIn:P.toDecimal(h.amountIn,u),tradeAmountOut:P.toDecimal(h.amountOut,p),tradeFee:P.toDecimal(A,p)}}}}async getTwapBuyOrder(t,e,n){let[i,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:r,swaps:s,priceImpactPct:o}=a,l=s[0],c=s[s.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,d=Math.abs(o),g=this.getTwapTradeCount(d),b=r/BigInt(g),h=await this.router.getBestBuy(l.assetIn,c.assetOut,b),y=h.amountIn*BigInt(g),f=g===1,S=y<i,x=h.priceImpactPct<-5,T=[];S||f?T.push("OrderTooSmall"):x&&T.push("OrderImpactTooBig");let A=h.tradeFee*BigInt(g),O=G.build(s),D={assetIn:t,assetOut:e,errors:T,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:O,type:"TwapBuy"};return{...D,amountIn:y,amountOut:r,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:A,toHuman(){return{...D,amountIn:P.toDecimal(y,u),amountOut:P.toDecimal(r,p),tradeAmountIn:P.toDecimal(h.amountIn,u),tradeAmountOut:P.toDecimal(h.amountOut,p),tradeFee:P.toDecimal(A,u)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let i=216e5/(this.blockTime*6);return Math.round(i)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var jn={};v(jn,{BIG_10:()=>zn,BIG_BILL:()=>je,StakingApi:()=>Zt,StakingClient:()=>te});import{calculate_accumulated_rps as cs,calculate_percentage_amount as us,calculate_period_number as Xn,calculate_points as Kn,calculate_rewards as ms,sigmoid as $n}from"@galacticcouncil/math-staking";import V from"big.js";var ge={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},Wn=m=>Object.keys(ge).includes(m);import{AccountId as os}from"polkadot-api";import{toHex as ls}from"@polkadot-api/utils";function Yn(m){let t=("modl"+m).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=ls(e);return os(63).dec(n)}var he="20000000000000000",be="2000",zn=V(10),je=V(zn.pow(12)),Zt=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getPotBalance(){let t=await this.client.getPalletId(),e=Yn(t);return await this.balanceClient.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let i=e.created_at,a=await n.reduce(async(r,[s,o])=>{let l=await r,c=s,u=o.amount,p=o.conviction.toString().toLowerCase(),d=await this.client.getReferendumInfo(c);return d&&(d.type==="Approved"||d.type==="Rejected")&&Wn(p)&&l.push({id:c,amount:u,conviction:p}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:i,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:a}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,i]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),a=i.find(r=>r)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:a,stakePosition:a?await this.getStakingPosition(a):void 0}}getCurrentActionPoints(t,e,n,i){let a=V(0),r=V(0),s=ge.locked6x,o=V(n.toString()).mul(s),l=100,c=[];t.forEach(d=>{let g=ge[d.conviction],b=i.includes(d.id.toString());b&&c.push(d.id.toString());let h=V(d.amount.toString()).mul(l).div(o);a=a.plus(Math.floor(h.mul(g).toNumber())),r=r.plus(Math.floor(h.mul(b?s:g).toNumber()))});let u=Math.floor(V(n.toString()).mul(s).mul(l).div(o).toNumber());i.forEach(d=>{c.includes(d)||(r=r.plus(u))});let p={democracyVote:1};return a=a.mul(p.democracyVote),a=a.plus(e.toString()||"0"),r=r.mul(p.democracyVote),r=r.plus(e.toString()||"0"),{currentActionPoints:a.toString(),maxActionPoints:r.toString()}}async getRewards(t,e,n){let i=await this.getStake(t),{potReservedBalance:a,accumulatedRewardPerStake:r,totalStake:s,stakePosition:o}=i;if(!o)return;let[l,c,u,p,d,g,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=V(l.transferable.toString()).minus(a.toString()),y=h.gt(0)&&s>0?cs(r.toString(),h.toString(),s.toString()):r.toString(),f=Xn(c.toString(),n,b),S=Xn(c.toString(),o.createdAt.toString(),b),x=ms(y,o.rewardPerStake.toString(),o.stake.toString()),T=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),A=Kn(S,f,p.toString(),d.toString(),T.currentActionPoints,g.toString(),o.accumulatedSlashPoints.toString()),O=$n(A,he,be),D=(()=>{if(!e.length)return;let tt=Kn(S,f,p.toString(),d.toString(),T.maxActionPoints.toString(),g.toString(),o.accumulatedSlashPoints.toString());return $n(tt,he,be)})(),U=V(x).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if(V(f).minus(S).lte(u.toString()))return{rewards:"0",payablePercentage:O,extraPayablePercentage:D,constants:{a:he,b:be}};let K=us(U.toString(),O),H=V(o.accumulatedLockedRewards.toString()),W=H.gt(K)?H:V(K);return{rewards:W.div(je).toString(),maxRewards:U.div(je).toString(),allocatedRewardsPercentage:W.div(U).mul(100).toNumber(),payablePercentage:O,extraPayablePercentage:D,constants:{a:he,b:be}}}};var te=class extends E{async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:r})=>{let[s,o,l]=r;return{address:s,collectionId:o,itemId:l}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var Zn={};v(Zn,{TxBuilderFactory:()=>It});import{Enum as Jn}from"polkadot-api";function Qn(m){let t=[],e=m;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var wt=class extends E{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new $(t),this.aaveUtils=new it(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:n=>this.dryRun(n,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Te})}async dryRun(t,e){let n=Jn("Signed",t),i=Jn("system",n),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall),s=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(s){let o=Qn(s.value);throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var ye=class extends wt{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,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:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],a=await this.balanceClient.getBalance(this.beneficiary,i);return t>=a.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,i=n[0],a=n[n.length-1],r=B.getFraction(t,this.slippagePct),s=i.assetIn,o=a.assetOut,l=t+r,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.buy({asset_in:s,asset_out:o,amount:e,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:s,asset_out:o,amount_out:e,max_amount_in:l,route:G.build(n)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,i=n[0],a=n[n.length-1],r=B.getFraction(e,this.slippagePct),s=i.assetIn,o=a.assetOut,l=e-r,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.sell({asset_in:s,asset_out:o,amount:t,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:s,asset_out:o,amount_in:t,min_amount_out:l,route:G.build(n)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],i=e[e.length-1],a=B.getFraction(t,this.slippagePct),r=n.assetIn,s=i.assetOut,o=t-a,l=this.api.tx.Router.sell_all({asset_in:r,asset_out:s,min_amount_out:o,route:G.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as Qe}from"polkadot-api";var fe=class extends wt{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,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:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradePeriod:a,tradeRoute:r}=this.order,s=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:a,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Qe("Sell",{asset_in:e,asset_out:n,amount_in:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",s)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradeAmountOut:a,tradePeriod:r,tradeRoute:s}=this.order,o=B.getFraction(a,this.slippagePct),l=a-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Qe("Sell",{asset_in:e,asset_out:n,amount_in:i,min_amount_out:l,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradeAmountOut:a,tradePeriod:r,tradeRoute:s}=this.order,o=B.getFraction(i,this.slippagePct),l=i+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Qe("Buy",{asset_in:e,asset_out:n,amount_out:a,max_amount_in:l,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var It=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new ye(this.client,this.evmClient).setTrade(t)}order(t){return new fe(this.client,this.evmClient).setOrder(t)}};async function mb(m){let t=new pt(m),e=new Et(m),[n,i]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=new St(m,e).withAave().withOmnipool().withStableswap().withXyk(),r=new $(m),s=new te(m),o=new Mt(m),l=new it(e),c=new Tt(a),u=new vt(c,{blockTime:n,minBudgetInNative:i}),p=new Zt(s,r),d=new kt(o,r,{blockTime:n});return{api:{aave:l,router:c,scheduler:u,staking:p,farm:d},client:{asset:new ut(m),balance:r,evm:e},ctx:{pool:a},tx:new It(m,e),destroy:()=>{a.destroy()}}}export{oe as QueryBus,un as aave,en as api,P as big,pn as client,nn as const,mb as createSdkContext,rt as erc20,dn as error,yn as evm,vn as farm,w as fmt,lt as h160,_t as json,B as math,qn as pool,Un as sor,jn as staking,Zn as tx,ln as xc};
|