@galacticcouncil/sdk-next 0.7.1-pr199-9b2819e → 0.8.0-pr203-91dcafe
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/AaveClient.d.ts +1 -0
- package/build/types/aave/AaveUtils.d.ts +6 -2
- package/build/types/aave/types.d.ts +1 -0
- package/build/types/farm/const.d.ts +1 -1
- package/build/types/farm/types.d.ts +0 -3
- package/build/types/staking/StakingApi.d.ts +46 -26
- package/build/types/staking/StakingClient.d.ts +3 -0
- package/package.json +1 -1
package/build/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Bn=Object.defineProperty;var T=(u,t)=>{for(var e in t)Bn(u,e,{get:t[e],enumerable:!0})};var Ce={};T(Ce,{Papi:()=>_,getWs:()=>En});import{hydration as _n}from"@galacticcouncil/descriptors";function Ee(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var _=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(_n)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Ee(n)&&console.log(t,...e)}};import{createClient as Rn}from"polkadot-api";import{withPolkadotSdkCompat as Fn}from"polkadot-api/polkadot-sdk-compat";var En=async u=>{let t=typeof u=="string"?u.split(","):u,r=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return Rn(Fn(r))};var Ge={};T(Ge,{AAVE_GAS_LIMIT:()=>ae,AAVE_LENDING_POOL_ADDRESS:()=>Kt,AAVE_POOL_ABI:()=>ne,AAVE_POOL_DATA_PROVIDER:()=>Xt,AAVE_POOL_DATA_PROVIDER_ABI:()=>Yt,AAVE_POOL_PROXY:()=>re,AAVE_ROUNDING_THRESHOLD:()=>li,AAVE_UINT_256_MAX:()=>Cn,AaveClient:()=>Pt,AaveUtils:()=>Q});var ne=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{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 Yt=[{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 re="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Xt="0x112b087b60C1a166130d59266363C45F8aa99db0",Kt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ae=1000000n,li=5,Cn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Pt=class{client;constructor(t){this.client=t.getWsProvider()}async getReservesData(){return await this.client.readContract({abi:Yt,address:Xt,args:[Kt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Yt,address:Xt,args:[Kt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ne,address:re,args:[t],functionName:"getUserAccountData"})}};var h={};T(h,{asBigInt:()=>Mn,toBigInt:()=>Dn,toDecimal:()=>kn});import j from"big.js";j.NE=-18;function kn(u,t,e=6,n){let r=j(u.toString()),a=j(10).pow(t);return r.div(a).round(e,n).toString()}function Dn(u,t){let e=j(10).pow(t),r=j(u).mul(e).toFixed(0,j.roundDown);return BigInt(r)}function Mn(u){return BigInt(u.round(0,j.roundDown).toFixed(0))}var et={};T(et,{ERC20:()=>ie});var ie=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 v={};T(v,{FeeUtils:()=>ce,shiftNeg:()=>Gn});import Nn from"big.js";var ke={};T(ke,{HUB_ASSET_ID:()=>le,HYDRATION_OMNIPOOL_ADDRESS:()=>qn,HYDRATION_PARACHAIN_ID:()=>Ln,HYDRATION_SS58_PREFIX:()=>C,PERBILL_DENOMINATOR:()=>se,PERMILL_DENOMINATOR:()=>ft,RUNTIME_DECIMALS:()=>I,SYSTEM_ASSET_DECIMALS:()=>oe,SYSTEM_ASSET_ID:()=>F,TRADEABLE_DEFAULT:()=>nt});var I=18,ft=1e6,se=1e9,F=0,oe=12,Ln=2034,C=63,qn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",le=1,nt=15;var ce=class u{static toPct(t){let[e,n]=t;return u.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return u.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 r=10**n;return Math.round(t*r/e)/r}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Gn(u,t){let e=Nn(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var zt={};T(zt,{H160:()=>me,isEvmAccount:()=>Me,isEvmAddress:()=>Le,isSs58Address:()=>qe});import{AccountId as St}from"polkadot-api";import{toHex as De}from"@polkadot-api/utils";import{Buffer as Y}from"buffer";var ue="ETH\0";function Me(u){if(!u)return!1;try{let t=St().enc(u),e=Y.from(ue);return Y.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function Le(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function qe(u){try{return St(63).enc(u),!0}catch{return!1}}var me=class u{static toAccount=t=>{let e=Y.from(t.slice(2),"hex"),n=Y.from(ue),r=Uint8Array.from(Y.concat([n,e,Y.alloc(8)])),a=De(r);return St(63).dec(a)};static fromAccount=t=>{let e=St().enc(t),n=Y.from(ue),r=e.slice(n.length,-8);return"0x"+Y.from(r).toString("hex")};static fromSS58=t=>{let n=St().enc(t).slice(0,20);return De(n)};static fromAny=t=>{if(Le(t))return t;if(Me(t))return u.fromAccount(t);if(qe(t))return u.fromSS58(t);throw new Error("Unknown address type")}};var $={};T($,{findNestedKey:()=>Un,findNestedObj:()=>Hn,jsonFormatter:()=>Vn});var Un=(u,t)=>{let e=[];return JSON.stringify(u,(n,r)=>(r&&r[t]&&e.push(r),r)),e[0]},Hn=(u,t,e)=>{let n;return JSON.stringify(u,(r,a)=>(a&&a[t]===e&&(n=a),a)),n},Vn=(u,t)=>typeof t=="bigint"?t.toString():t;var O={};T(O,{calculateBuyFee:()=>Kn,calculateDiffToAvg:()=>Wn,calculateDiffToRef:()=>Yn,calculateSellFee:()=>Xn,getFraction:()=>zn});import H from"big.js";function Wn(u,t){let e=H(u.toString()),n=H(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function Yn(u,t){if(t===0n)return 0;let e=H(u.toString()),n=H(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function Xn(u,t){let e=H(u.toString()),n=H(t.toString());return H(1).minus(n.div(e)).mul(100).round(2).toNumber()}function Kn(u,t){let e=H(u.toString());return H(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function zn(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),r=BigInt(t*n);return u*r/BigInt(100*n)}var Ne={};T(Ne,{convertToId:()=>$n});import{Buffer as jn}from"buffer";function $n(u){let e=jn.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:jt}=et,{H160:pe}=zt,Qn=1.01,Jn=99999,Zn=10n**27n,tr=10n**18n,Q=class{client;constructor(t){this.client=new Pt(t)}async getSummary(t){let e=pe.fromAny(t),[n,r,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e)]),[s]=n,[i,o]=r,[l,c,m,d,p,g]=a,y=h.toDecimal(g,18),b=[];for(let P of i){let f=P.underlyingAsset.toLowerCase(),S=s.find(({underlyingAsset:yt})=>yt.toLowerCase()===f);if(!S)throw new Error("Missing pool reserve for "+f);let w=P.scaledATokenBalance,k=S.liquidityIndex,D=S.priceInMarketReferenceCurrency,R=w*k/Zn,z=Number(o===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,N=S.usageAsCollateralEnabled&&P.usageAsCollateralEnabledOnUser&&P.scaledATokenBalance>0n,W=jt.toAssetId(f);b.push({aTokenBalance:R,decimals:Number(S.decimals),isCollateral:N,priceInRef:D,reserveId:W,reserveAsset:f,reserveLiquidationThreshold:z})}return{healthFactor:Number(y),totalCollateral:l,totalDebt:c,reserves:b}}async hasBorrowPositions(t){let e=pe.fromAny(t),n=await this.client.getUserAccountData(e),[r,a]=n;return a>0n}async getHealthFactor(t){let e=pe.fromAny(t),n=await this.client.getUserAccountData(e),[r,a,s,i,o,l]=n,c=h.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(t),i=jt.fromAssetId(e),o=s.find(b=>b.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:d}=o,p=h.toBigInt(n,l),g=c?p*m/10n**BigInt(l):0n,y=r-g;return y<=0n?0:this.calculateHealthFactor(y,d,a)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:r,totalDebt:a,reserves:s}=await this.getSummary(t),i=jt.fromAssetId(e),o=s.find(y=>y.reserveAsset===i);if(!o)throw new Error("Missing reserve ctx for "+i);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=o,p=h.toBigInt(n,l)*c/10n**BigInt(l),g=r+p;return g<=0n?0:this.calculateHealthFactor(g,m,a)}async getMaxWithdraw(t,e){let{totalCollateral:n,totalDebt:r,reserves:a}=await this.getSummary(t),s=jt.fromAssetId(e),i=a.find(o=>o.reserveAsset===s);if(!i)throw new Error("Missing reserve ctx for "+s);return this.calculateWithdrawMax(i,n,r)}async getMaxWithdrawAll(t){let{totalCollateral:e,totalDebt:n,reserves:r}=await this.getSummary(t),a={};for(let s of r){let i=this.calculateWithdrawMax(s,e,n);s.reserveId&&(a[s.reserveId]=i)}return a}calculateHealthFactor(t,e,n){if(n===0n)return Jn;let r=10n**6n,a=h.toBigInt(e,18),s=t*a*r,i=n*tr,o=s/i;return Number(o)/1e6}calculateRequiredCollateral(t,e,n){let r=h.toBigInt(t,18),a=h.toBigInt(e,18);return(r*n+a-1n)/a}calculateWithdrawMax(t,e,n){let{aTokenBalance:r,decimals:a,priceInRef:s,reserveLiquidationThreshold:i}=t,o=this.calculateRequiredCollateral(Qn,i,n),l=e-o;if(l<=0n)return{amount:0n,decimals:a};let c=l*10n**BigInt(a)/s;return{amount:r<c?r:c,decimals:a}}};var Ve={};T(Ve,{AssetClient:()=>rt,BalanceClient:()=>U,ChainParams:()=>it});var rt=class extends _{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:r})=>{let[a]=n;return[a,r]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:r})=>{let[a]=n;return[a,r]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:r}=n;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:n,value:r})=>{let[a]=n;return[a,r]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:r})=>{let[a]=n;return[a,r]}))}async mapToken(t,e,n,r){let{name:a,asset_type:s,is_sufficient:i,existential_deposit:o}=e,{symbol:l,decimals:c}=n.get(t)??{};return{id:t,name:a?.asText(),symbol:l,decimals:c,icon:l,type:s.type,isSufficient:i,location:r,existentialDeposit:o}}async mapBond(t,e,n,r){let[a,s]=r,{asset_type:i,is_sufficient:o,existential_deposit:l}=e,{symbol:c,decimals:m}=await this.mapToken(a,e,n),d=Number(s),p=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",p.format(d)].join(" ");return{id:t,name:g,symbol:c+"b",decimals:m,icon:c,type:i.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:a,maturity:d}}async mapShares(t,e,n,r){let{assets:a}=r,{name:s,symbol:i,asset_type:o,is_sufficient:l,existential_deposit:c}=e,m=await Promise.all(a.map(async g=>{let{symbol:y}=await this.mapToken(g,e,n);return[g,y]})),d=Object.fromEntries(m),p=Object.values(d);return{id:t,name:p.join(", "),symbol:i?.asText()||s?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:d}}async mapExternal(t,e,n,r){let a=await this.mapToken(t,e,new Map,r),s=n?.find(i=>i.internalId===a.id);return s?{...a,decimals:s.decimals,name:s.name,symbol:s.symbol,icon:s.symbol,isWhiteListed:s.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,r,a,s]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),i=this.parseMetadata(n),o=[];for(let[l,c]of Array.from(n)){let m=r.get(l),{asset_type:d}=c,p;switch(d.type){case"Bond":let g=s.get(l);p=await this.mapBond(l,c,i,g);break;case"StableSwap":let y=a.get(l);p=await this.mapShares(l,c,i,y);break;case"External":p=await this.mapExternal(l,c,e,m);break;default:p=await this.mapToken(l,c,i,m)}o.push(p)}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 er,bufferCount as nr,combineLatest as rr,debounceTime as ar,distinctUntilChanged as Ue,finalize as ir,map as at,pairwise as sr,shareReplay as or,startWith as lr}from"rxjs";var U=class extends _{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);return this.calculateBalance(n)}async getTokenBalance(t,e){let r=await this.api.query.Tokens.Accounts.getValue(t,e);return this.calculateBalance(r)}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}}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),r=this.subscribeErc20Balance(t);return rr([e,n,r]).pipe(ar(250),at(a=>a.flat()),lr([]),nr(2,1),at(([a,s],i)=>{if(i===0)return s;let o=a.reduce((c,m)=>(c.set(m.id,m.balance),c),new Map);return s.filter(c=>!He(c.balance,o.get(c.id)))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(at(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(at(r=>({id:e,balance:r})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(Ue((n,r)=>!r.deltas),at(({deltas:n})=>{let r=[];return n?.deleted.forEach(a=>{let[s,i]=a.args;r.push({id:i,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(a=>{let[s,i]=a.args;r.push({id:i,balance:this.calculateBalance(a.value)})}),r}))}subscribeErc20Balance(t,e){let n=new er,r=n.pipe(or(1)),a=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),s=async()=>{let o=e||await a(),l=async()=>{let d=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(t,p);return[p,g]}))).map(([p,g])=>({id:p,balance:g}));n.next(d)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},i;return s().then(o=>i=o),r.pipe(ir(()=>i?.()),sr(),at(([o,l],c)=>{if(c===0)return l;let m=o.reduce((p,g)=>(p.set(g.id,g.balance),p),new Map);return l.filter(p=>!He(p.balance,m.get(p.id)))}),Ue((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t);return this.calculateBalance(n)}},He=(u,t)=>u!==void 0&&t!==void 0&&u.transferable===t.transferable&&u.total===t.total;var it=class extends _{_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 We={};T(We,{AssetNotFound:()=>de,PoolNotFound:()=>Tt,RouteNotFound:()=>wt});var de=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},Tt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},wt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Ke={};T(Ke,{EvmClient:()=>xt,createChain:()=>ge});import{defineChain as cr}from"viem";var ur=["https://hydration-rpc.n.dwellir.com","https://hydration.dotters.network","https://rpc.helikon.io/hydradx","https://hydration.ibp.network","https://rpc.cay.hydration.cloud","https://rpc.parm.hydration.cloud","https://rpc.roach.hydration.cloud","https://rpc.zipp.hydration.cloud","https://rpc.sin.hydration.cloud","https://rpc.coke.hydration.cloud"],ge=()=>cr({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:ur}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as Ye,createWalletClient as mr,custom as Xe,http as pr}from"viem";var xt=class{client;chain;constructor(t){this.client=t,this.chain=ge()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return Ye({chain:this.chain,transport:pr()})}getWsProvider(){return Ye({transport:Xe({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return mr({account:t,chain:this.chain,transport:Xe(window.ethereum)})}};var Ze={};T(Ze,{LiquidityMiningApi:()=>It,LiquidityMiningClient:()=>vt});import{AccountId as Pr}from"polkadot-api";import E from"big.js";import{fixed_from_rational as Je}from"@galacticcouncil/math-liquidity-mining";var $t=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let n=0;n<t.length;++n){let[r,a]=t[n];this.result.set(this.getKey(a,r),e[n].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,n,r){let a=this.getKey(t,e),s=this.getKey(t,n),i=this.result.get(a)??0n,o=this.result.get(s)??0n;if(i<r)throw new Error("Attempting to transfer more than is present");this.result.set(a,i+r),this.result.set(s,o+r)}};import J from"big.js";import{calculate_accumulated_rps as dr,calculate_global_farm_rewards as gr,calculate_loyalty_multiplier as br,calculate_user_reward as Qe,calculate_yield_farm_delta_rpvs as yr}from"@galacticcouncil/math-liquidity-mining";import ze from"big.js";var be=ze(10).pow(18),je=BigInt(ze(1).pow(18).toString()),$e=6e3;var hr="1000000000000000000",Qt=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 r=await this.getAsset(t.reward_currency),a=e-t.updated_at,s=this.getAccount(t.id),i=r?.existential_deposit;if(!i)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,s),l=J(i.toString()),c=J(o.toString()).minus(l.lt(o.toString())?i.toString():o.toString()),m=J(gr(t.total_shares_z.toString(),n.toString(),J(t.yield_per_period.toString()).mul(be).round(0,J.roundDown).toFixed(),t.max_reward_per_period.toString(),a.toFixed()));if(c.lt(m)&&(m=c),m.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,s,d,BigInt(m.toFixed())),{...t,accumulated_rpz:BigInt(dr(t.accumulated_rpz.toString(),t.total_shares_z.toString(),m.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 r=yr(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(r),updated_at:n}}getLoyaltyMultiplier(t,e){let n=J(1).mul(be).round(0,J.roundDown).toString();if(!e)return n;let{initial_reward_percentage:r,scale_coef:a}=e;return br(t.toFixed(),r.toString(),a.toFixed())}async claimRewards(t,e,n,r,a){if(e.state.type==="Terminated")return null;let s=Math.floor(r/t.blocks_per_period);if(n.updated_at===s)return null;let i=await this.syncGlobalFarm(t,s,a);if(!i)return null;let o=this.syncYieldFarm(e,i,s);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,m=this.getLoyaltyMultiplier(c,o.loyalty_curve),d=BigInt(Qe(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),m)),p=BigInt(Qe(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),hr));return{reward:d,maxReward:p,assetId:i.reward_currency}}};var fr=E(365.2425).times(24).times(60).times(60),It=class{client;balanceClient;options;constructor(t,e,n={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:n.blockTime??$e})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let n=[t,e].sort((a,s)=>a-s);if(t===e)return je;let r=await this.client.getOraclePrice(n);if(r){let{n:a,d:s}=r[0].price,i;return t<e?i=Je(a.toString(),s.toString()):i=Je(s.toString(),a.toString()),BigInt(i)}}getFarmAddress=(t,e)=>{let n=Buffer.from("modl","utf-8"),r=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),a=Buffer.from([t]),s=Buffer.concat([n,r,a]),o="0x"+Buffer.concat([s,Buffer.alloc(32-s.length)]).toString("hex");return Pr(63).dec(o)};getGlobalRewardPerPeriod(t,e,n,r){let a=E(r).times(t.toString()).times(e.toString()).div(18);return a.gte(n.toString())?n.toString():a.toString()}getPoolYieldPerPeriod(t,e,n,r){let a=E(t.toString()).times(e),s=E(n.toString()).times(r);return a.div(s.toString()).toString()}farmData(t,e,n){let{yieldFarm:r,globalFarm:a,priceAdjustment:s,balance:i,id:o}=t,{multiplier:l,loyalty_curve:c}=r,{blocks_per_period:m,yield_per_period:d,total_shares_z:p,max_reward_per_period:g,pending_rewards:y,accumulated_paid_rewards:b,planned_yielding_periods:P,updated_at:f,incentivized_asset:S,reward_currency:w,price_adjustment:k}=a,D=v.shiftNeg(s??k,18),R=v.shiftNeg(l,18),q=v.shiftNeg(c?.initial_reward_percentage??0,18),z=fr.div(E(this.blockTime).div(1e3).times(m)).toString(),N;if(p<=0)N=E(R).times(d.toString()).times(z).toString();else{let On=this.getGlobalRewardPerPeriod(p,d,g,D),An=this.getPoolYieldPerPeriod(On,R,p,D);N=E(An).times(z).toString()}let W=y+b,yt=g*BigInt(P),ht=i.transferable+W,Wt=ht-W,Be=E(Wt.toString()).div(g.toString()),_e=E(e).div(m.toString()).toString(),Re=(p>=0?Be.plus(f):Be.plus(_e)).toString(),xn=E(Re).times(m).toString(),In=E(p.toString()).div(E(g.toString()).div(d.toString())).div(Math.pow(10,18)).times(100).times(D).toFixed(2),Fe=E(W.toString()).div(ht.toString()).gte(.999);N=Fe?"0":E(N).div(n?2:1).times(100).toString();let vn=q?E(N).times(q).toString():void 0;return{apr:N,minApr:vn,isDistributed:Fe,estimatedEndPeriod:Re,estimatedEndBlock:xn,maxRewards:yt,incentivizedAsset:S,rewardCurrency:w,loyaltyCurve:c,currentPeriod:_e,potMaxRewards:ht,fullness:In,yieldFarmId:r.id,globalFarmId:a.id,poolId:o,distributedRewards:W,plannedYieldingPeriods:P}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((r,a)=>r.includes(a.keyArgs[0].toString())?r:[...r,a.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async r=>{let a=await this.getOmnipoolFarms(r);if(a)return[r,a]}));return Object.fromEntries(n.filter(r=>!!r))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),n=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:a,value:s})=>{let[,i]=a,o=s,l=await this.client.getOmnipoolGlobalFarm(i),c=await this.client.getOmnipoolYieldFarm(Number(t),i,o);if(!l||!c)return;let m=l.reward_currency,d=l.incentivized_asset,p=this.getFarmAddress(i),g=await this.getOraclePrice(m,d),y=await this.balanceClient.getBalance(p,m);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:y}}));return n?r.map(a=>a?this.farmData(a,n):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((r,a)=>r.includes(a.keyArgs[0].toString())?r:[...r,a.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async r=>{let a=await this.getIsolatedFarms(r);if(a)return[r,a]}));return Object.fromEntries(n.filter(r=>!!r))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),n=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:a,value:s})=>{let[,i]=a,o=s,l=await this.client.getIsolatedGlobalFarm(i),c=await this.client.getIsolatedYieldFarm(t,i,o);if(!l||!c)return;let m=l.reward_currency,d=l.incentivized_asset,p=this.getFarmAddress(i,!0),g=await this.getOraclePrice(m,d),y=await this.balanceClient.getBalance(p,m);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:y,farmAddress:p}}));return n?r.map(a=>a?this.farmData(a,n,!0):void 0):[]}async getDepositReward(t,e,n,r){let a=e.global_farm_id,s=e.yield_farm_id,i=n?await this.client.getIsolatedYieldFarm(t,a,s):await this.client.getOmnipoolYieldFarm(Number(t),a,s),o=n?await this.client.getIsolatedGlobalFarm(a):await this.client.getOmnipoolGlobalFarm(a);if(!o||!i)return;let l=o.reward_currency,c=o.incentivized_asset,m=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await this.getAccountAssetBalances(m),p=await this.getOraclePrice(l,c),g=new $t(m,d),b=await new Qt(f=>this.getFarmAddress(f),f=>this.client.getAsset(f),g).claimRewards(o,i,e,r,p??o.price_adjustment);if(!b)return;let P=await this.client.getAsset(b.assetId);if(P&&!(b.reward<=P.existential_deposit))return b}async getAccountAssetBalances(t){let[e,n]=await Promise.all([Promise.all(t.filter(([a,s])=>s!==0).map(([a,s])=>this.balanceClient.getTokenBalance(a,s))),Promise.all(t.filter(([a,s])=>s===0).map(([a])=>this.balanceClient.getSystemBalance(a)))]),r=[];for(let a=0,s=0;a+s<t.length;){let i=a+s,[,o]=t[i];o===0?(r.push(n[s]),s+=1):(r.push(e[a]),a+=1)}return r}};import{Binary as Sr,Enum as Tr}from"polkadot-api";var vt=class extends _{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Sr.fromText("omnipool"),t,Tr("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 un={};T(un,{PoolContextProvider:()=>ct,PoolError:()=>Z,PoolFactory:()=>lt,PoolType:()=>A,aave:()=>Te,lbp:()=>he,omni:()=>Pe,stable:()=>fe,xyk:()=>Se});var he={};T(he,{LbpMath:()=>G,LbpPool:()=>Ot,LbpPoolClient:()=>Bt});import{calculate_in_given_out as wr,calculate_out_given_in as xr,calculate_linear_weights as Ir,calculate_pool_trade_fee as vr,get_spot_price as Or}from"@galacticcouncil/math-lbp";var G=class{static getSpotPrice(t,e,n,r,a){return Or(t,e,n,r,a)}static calculateInGivenOut(t,e,n,r,a){return wr(t,e,n,r,a)}static calculateOutGivenIn(t,e,n,r,a){return xr(t,e,n,r,a)}static calculateLinearWeights(t,e,n,r,a){return Ir(t,e,n,r,a)}static calculatePoolTradeFee(t,e,n){return vr(t,e,n)}};var A=(a=>(a.Aave="Aave",a.LBP="LBP",a.Omni="Omnipool",a.Stable="Stableswap",a.XYK="XYK",a))(A||{}),Z=(a=>(a.InsufficientTradingAmount="InsufficientTradingAmount",a.MaxInRatioExceeded="MaxInRatioExceeded",a.MaxOutRatioExceeded="MaxOutRatioExceeded",a.TradeNotAllowed="TradeNotAllowed",a.UnknownError="UnknownError",a))(Z||{});var{FeeUtils:tn}=v,Ot=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,r,a,s,i){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a,this.fee=s,this.repayFeeApply=i}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(t),a=n.get(e);if(r==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:r.balance,balanceOut:a.balance,decimalsIn:r.decimals,decimalsOut:a.decimals,weightIn:r.weight,weightOut:a.weight}}validateAndBuy(t,e,n){let r=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let s=t.balanceOut/this.maxOutRatio;if(e>s&&a.push("MaxOutRatioExceeded"),r===t.assetOut){let i=this.calculateTradeFee(e,n),o=tn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+i,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&a.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:a}}else{let i=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return i>o&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:a}}}validateAndSell(t,e,n){let r=this.tokens[0].id,a=[];e<this.minTradingLimit&&a.push("InsufficientTradingAmount");let s=t.balanceIn/this.maxInRatio;if(e>s&&a.push("MaxInRatioExceeded"),r===t.assetIn){let i=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return i>o&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:a}}else{let i=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(i,n),l=tn.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=i-o,m=t.balanceOut/this.maxOutRatio;return c>m&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:c,feePct:l,errors:a}}}calculateInGivenOut(t,e){let n=G.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(t,e){let n=G.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(t){let e=G.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=G.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=G.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 Cr}from"polkadot-api";import{map as kr,of as sn,switchMap as Dr}from"rxjs";import{memoize1 as Ar}from"@thi.ng/memoize";import{combineLatest as en,combineLatestAll as Br,debounceTime as _r,firstValueFrom as Rr,from as nn,map as rn,mergeAll as Fr,of as Er,switchMap as an}from"rxjs";var ye=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var At=class{client;constructor(t){this.client=t.getWsProvider()}async getData(t,e=6){let[n,r,a]=await Promise.all([this.client.readContract({abi:ye,address:t,functionName:"latestRoundData"}),this.client.readContract({abi:ye,address:t,functionName:"decimals"}),this.client.getBlock()]),[s,i,o,l]=n,c=a.number-(a.timestamp-l)/BigInt(e),m=Number(c);return{price:i,decimals:r,updatedAt:m<0?0:m}}};var M=class extends U{evm;mmOracle;override=[];mem=0;memPools=Ar(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t,e){super(t),this.evm=e,this.mmOracle=new At(e)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=nn(this.getPoolsMem()).pipe(an(e=>this.subscribe(e)),Br());return Rr(t)}getSubscriber(){return nn(this.getPoolsMem()).pipe(an(t=>this.subscribe(t)),Fr())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>en([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(_r(250),rn(([n,r])=>this.updatePool(n,r))))}subscribePoolBalance(t){if(t.type==="Aave")return Er([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),r=this.subscribeErc20Balance(t.address,n);e.push(r)}return en(e).pipe(rn(n=>n.map(r=>Array.isArray(r)?r:[r]).flat()))}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(({id:e,decimals:n,balance:r})=>{let a=this.override.find(i=>i.id===e),s=!!n||!!a?.decimals;return r>0n&&s})}updatePool=(t,e)=>{let n=t.tokens.map(r=>{let a=e.find(i=>i.id===r.id),s=this.override.find(i=>i.id===r.id);return a?{...r,balance:a.balance.transferable,decimals:r.decimals||s?.decimals}:{...r,decimals:r.decimals||s?.decimals}});return{...t,tokens:n}}};var Bt=class extends M{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),r=e?.relay_parent_number||0,a=t.filter(({value:s})=>e&&this.isActivePool(s,r)).map(async({keyArgs:s,value:i})=>{let[o]=s,l=o.toString(),c=await this.getPoolDelta(l,i,r);return{address:l,type:"LBP",fee:i.fee,...c,...n}});return Promise.all(a)}async getPoolDelta(t,e,n){let{start:r,end:a,assets:s,initial_weight:i,final_weight:o,repay_target:l,fee_collector:c}=e,m=G.calculateLinearWeights(r?r.toString():"0",a?a.toString():"0",i.toString(),o.toString(),n.toString()),[d,p]=s,g=BigInt(m),y=this.MAX_FINAL_WEIGHT-BigInt(g),[b,P,f,S,w]=await Promise.all([this.isRepayFeeApplied(d,l,c.toString()),this.getBalance(t,d),this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:b,tokens:[{id:d,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:P.transferable,weight:g,type:f?.asset_type.type},{id:p,decimals:w?.decimals,existentialDeposit:w?.existential_deposit,balance:S.transferable,weight:y,type:w?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:r}=t;return n&&r?e>=n&&e<r:!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 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}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Cr.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe(Dr(r=>r?this.getPoolDelta(t.address,n,r.relay_parent_number):sn(t)),kr(r=>Object.assign({},t,r))):sn(t)}};var Pe={};T(Pe,{OmniMath:()=>x,OmniPool:()=>_t,OmniPoolClient:()=>Rt});import{calculate_in_given_out as Mr,calculate_lrna_in_given_out as Lr,calculate_out_given_in as qr,calculate_out_given_lrna_in as Nr,calculate_spot_price as Gr,calculate_lrna_spot_price as Ur,calculate_shares as Hr,calculate_liquidity_out as Vr,calculate_liquidity_lrna_out as Wr,verify_asset_cap as Yr,calculate_liquidity_hub_in as Xr,is_sell_allowed as Kr,is_buy_allowed as zr,is_add_liquidity_allowed as jr,is_remove_liquidity_allowed as $r}from"@galacticcouncil/math-omnipool";import st from"big.js";var x=class{static calculateSpotPrice(t,e,n,r){return Gr(t,e,n,r)}static calculateLrnaSpotPrice(t,e){return Ur(t,e)}static calculateInGivenOut(t,e,n,r,a,s,i,o,l){return Mr(t,e,n,r,a,s,i,o,l)}static calculateLrnaInGivenOut(t,e,n,r,a){return Lr(t,e,n,r,a)}static calculateOutGivenIn(t,e,n,r,a,s,i,o,l){return qr(t,e,n,r,a,s,i,o,l)}static calculateOutGivenLrnaIn(t,e,n,r,a){return Nr(t,e,n,r,a)}static calculateShares(t,e,n,r){return Hr(t,e,n,r)}static calculateLiquidityOut(t,e,n,r,a,s,i,o){return Vr(t,e,n,r,a,s,i,o)}static calculateLiquidityLRNAOut(t,e,n,r,a,s,i,o){return Wr(t,e,n,r,a,s,i,o)}static calculateCapDifference(t,e,n,r){let a=st(e),s=st(t),i=st(r),o=st(n),l=st(10).pow(18),c=o.div(l);if(a.div(i).lt(c)){let d=c.times(i).minus(a).times(s),p=a.times(st(1).minus(c));return d.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,r){return Yr(t,e,n,r)}static calculateLimitHubIn(t,e,n,r){return Xr(t,e,n,r)}static isSellAllowed(t){return Kr(t)}static isBuyAllowed(t){return zr(t)}static isAddLiquidityAllowed(t){return jr(t)}static isRemoveLiquidityAllowed(t){return $r(t)}};var{FeeUtils:ot}=v,_t=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,r,a,s){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a,this.hubAssetId=s}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(t),a=n.get(e);if(r==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:r.hubReserves,hubReservesOut:a.hubReserves,sharesIn:r.shares,sharesOut:a.shares,decimalsIn:r.decimals,decimalsOut:a.decimals,balanceIn:r.balance,balanceOut:a.balance,tradeableIn:r.tradeable,tradeableOut:a.tradeable,assetInEd:r.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),s=r===0n?0:O.calculateDiffToRef(a,r),i=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&i.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&i.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return a>m&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:r,amountOut:e,feePct:s,errors:i}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),s=O.calculateDiffToRef(r,a),i=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&i.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&i.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return a>m&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:a,feePct:s,errors:i}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let r=x.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ot.toRaw(n.assetFee).toString():"0",n?ot.toRaw(n.protocolFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}calculateLrnaInGivenOut(t,e,n){let r=x.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ot.toRaw(n.assetFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let r=x.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ot.toRaw(n.assetFee).toString():"0",n?ot.toRaw(n.protocolFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}calculateOutGivenLrnaIn(t,e,n){let r=x.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?ot.toRaw(n.assetFee).toString():"0"),a=BigInt(r);return a<0n?0n:a}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=x.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=x.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=x.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=x.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as Qr,CompatibilityLevel as Jr}from"polkadot-api";import{toHex as Zr}from"@polkadot-api/utils";import{distinctUntilChanged as ta,map as on}from"rxjs";var{FeeUtils:X}=v,Rt=class extends M{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,r,a,s,i]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),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:m})=>{let[d]=c,{hub_reserve:p,shares:g,tradable:y,cap:b,protocol_shares:P}=m,[f,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,d)]);return{id:d,decimals:f?.decimals,existentialDeposit:f?.existential_deposit,balance:S.transferable,cap:b,hubReserves:p,protocolShares:P,shares:g,tradeable:y,type:f?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:s.transferable,tradeable:r,type:a?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...i}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=Zr(e);return Qr(63).dec(n)}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 getPoolFees(t,e){let[n,r,a]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),s=n.min_fee+r.min_fee,i=n.max_fee+r.max_fee;if(a){let{asset_fee:o,protocol_fee:l}=a;return{assetFee:X.fromPermill(o),protocolFee:X.fromPermill(l),min:X.fromPermill(s),max:X.fromPermill(i)}}else return{assetFee:X.fromPermill(n.min_fee),protocolFee:X.fromPermill(r.min_fee),min:X.fromPermill(s),max:X.fromPermill(i)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Jr.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(ta((n,r)=>!r.deltas),on(({entries:n})=>n.map(r=>{let[a]=r.args,{hub_reserve:s,shares:i,tradable:o,cap:l,protocol_shares:c}=r.value,m=t.tokens.findIndex(p=>p.id===a);return{...t.tokens[m],cap:l,hubReserves:s,protocolShares:c,shares:i,tradeable:o}})),on(n=>{let r=t.tokens.find(a=>a.id===1);return{...t,tokens:[...n,r]}}))}};var fe={};T(fe,{StableMath:()=>B,StableSwap:()=>Ft,StableSwapClient:()=>Et});import{calculate_in_given_out as ea,calculate_out_given_in as na,calculate_amplification as ra,calculate_add_one_asset as aa,calculate_liquidity_out_one_asset as ia,calculate_shares as sa,calculate_shares_for_amount as oa,calculate_spot_price_with_fee as la,pool_account_name as ca,recalculate_peg as ua}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return ca(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,r,a){return ra(t,e,n,r,a)}static calculateInGivenOut(t,e,n,r,a,s,i){return ea(t,e,n,r,a,s,i)}static calculateAddOneAsset(t,e,n,r,a,s,i){return aa(t,e,n,r,a,s,i)}static calculateSharesForAmount(t,e,n,r,a,s,i){return oa(t,e,n,r,a,s,i)}static calculateOutGivenIn(t,e,n,r,a,s,i){return na(t,e,n,r,a,s,i)}static calculateLiquidityOutOneAsset(t,e,n,r,a,s,i){return ia(t,e,n,r,a,s,i)}static calculateShares(t,e,n,r,a,s){return sa(t,e,n,r,a,s)}static calculateSpotPriceWithFee(t,e,n,r,a,s,i,o){return la(t,e,n,r,a,s,i,o)}static recalculatePegs(t,e,n,r,a){let s=ua(t,e,n,r,a);return JSON.parse(s)}};var{FeeUtils:K}=v,Ft=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,r,a,s,i,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a,this.amplification=s,this.id=i,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(t),a=n.get(e);if(r==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:r.balance,balanceOut:a.balance,decimalsIn:r.decimals,decimalsOut:a.decimals,tradeableIn:this.id===t?15:r.tradeable,tradeableOut:this.id===e?15:a.tradeable,assetInEd:r.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),a=this.calculateInGivenOut(t,e,n),s=K.toPct(n.fee),i=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&i.push("InsufficientTradingAmount"),{amountIn:a,calculatedIn:r,amountOut:e,feePct:s,errors:i}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),a=this.calculateOutGivenIn(t,e,n),s=K.toPct(n.fee),i=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!o||!l)&&i.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&i.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:r,amountOut:a,feePct:s,errors:i}}calculateIn(t,e,n){let r=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?K.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateAddOneAsset(t,e,n){let r=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?K.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateSharesForAmount(t,e,n){let r=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?K.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(r);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=B.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 r=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(r)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let r=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?K.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateWithdrawOneAsset(t,e,n){let r=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?K.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(r);return a<0n?0n:a}calculateShares(t,e,n){let r=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?K.toRaw(n.fee).toString():"0",this.getPegs()),a=BigInt(r);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=B.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 r=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(r)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){let t=B.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:r})=>({asset_id:e,amount:n,decimals:r}));return JSON.stringify(t,$.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],$.jsonFormatter)}};import{AccountId as ma,CompatibilityLevel as pa}from"polkadot-api";import{toHex as da}from"@polkadot-api/utils";import{blake2b as ga}from"@noble/hashes/blake2b";import{map as ba,of as ya,switchMap as ha}from"rxjs";var{FeeUtils:tt}=v,Et=class extends M{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=B.getPoolAddress(t),n=ga(e,{dkLen:32}),r=da(n);return ma(63).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolDelta(t,e,n){let{initial_amplification:r,final_amplification:a,initial_block:s,final_block:i}=e,o=B.calculateAmplification(r.toString(),a.toString(),s.toString(),i.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),r=e.assets.map(async a=>{let[s,i,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:i?.decimals,existentialDeposit:i?.existential_deposit,balance:o.transferable,tradeable:s,type:i?.asset_type.type}});return Promise.all(r)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(pa.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),r=t.map(async({keyArgs:a,value:s})=>{let[i]=a,o=this.getPoolAddress(i),[l,c,m]=await Promise.all([this.getPoolDelta(i,s,e),this.getPoolTokens(i,s),this.getPoolPegs(i,s,e)]);return c.push({id:i,tradeable:15,balance:l.totalIssuance,decimals:18}),this.poolsData.set(o,s),{address:o,id:i,type:"Stableswap",fee:tt.fromPermill(s.fee),tokens:c,...l,...m,...n}});return Promise.all(r)}async getPoolFees(t){return{fee:t.fee}}async getPoolPegs(t,e,n){let r=await this.api.query.Stableswap.PoolPegs.getValue(t);if(!r)return this.getDefaultPegs(e);let a=await this.getLatestPegs(e,r,n),s=this.getRecentPegs(r),i=tt.fromPermill(r.max_peg_update),o=tt.fromPermill(e.fee),[l,c]=B.recalculatePegs(JSON.stringify(s),JSON.stringify(a),n.toString(),tt.toRaw(i).toString(),tt.toRaw(o).toString()),m=Number(l)*1e6;return{pegsFee:tt.fromPermill(m),pegs:c}}getDefaultPegs(t){let e=t.fee,n=B.defaultPegs(t.assets.length);return{pegsFee:tt.fromPermill(e),pegs:n}}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,r])=>r.map(a=>a.toString()))}async getLatestPegs(t,e,n){let{source:r}=e,a=Array.from(t.assets.entries()).map(([i,o])=>o),s=r.map(async(i,o)=>{if(i.type==="Oracle"){let[l,c,m]=i.value,d=[m,a[o]].sort((f,S)=>f-S),p=await this.api.query.EmaOracle.Oracles.getValue(l,d,c);if(!p)return;let[{price:g,updated_at:y}]=p,b=g.n.toString(),P=g.d.toString();return m.toString()===d[0].toString()?[[b,P],y.toString()]:[[P,b],y.toString()]}else if(i.type==="MMOracle"){let l=i.value.asHex(),{price:c,decimals:m,updatedAt:d}=await this.mmOracle.getData(l),p=10**m;return[[c.toString(),p.toString()],d.toString()]}else return[i.value.map(l=>l.toString()),n.toString()]});return Promise.all(s)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?ya(t):e.watchValue("best").pipe(ha(r=>Promise.all([this.getPoolDelta(t.id,n,r),this.getPoolPegs(t.id,n,r)])),ba(([r,a])=>{let s=t.tokens.map(i=>i.id===t.id?{...i,balance:r.totalIssuance}:i);return Object.assign(t,{tokens:s},r,a)}))}};var Se={};T(Se,{XykMath:()=>V,XykPool:()=>Ct,XykPoolClient:()=>kt});import{calculate_in_given_out as Pa,calculate_out_given_in as fa,calculate_pool_trade_fee as Sa,get_spot_price as Ta,calculate_liquidity_in as wa,calculate_shares as xa,calculate_spot_price as Ia,calculate_spot_price_with_fee as va,calculate_liquidity_out_asset_a as Oa,calculate_liquidity_out_asset_b as Aa}from"@galacticcouncil/math-xyk";var V=class{static getSpotPrice(t,e,n){return Ta(t,e,n)}static calculateInGivenOut(t,e,n){return Pa(t,e,n)}static calculateOutGivenIn(t,e,n){return fa(t,e,n)}static calculatePoolTradeFee(t,e,n){return Sa(t,e,n)}static calculateLiquidityIn(t,e,n){return wa(t,e,n)}static calculateSpotPrice(t,e){return Ia(t,e)}static calculateSpotPriceWithFee(t,e,n,r){return va(t,e,n,r)}static calculateShares(t,e,n){return xa(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,r){return Oa(t,e,n,r)}static calculateLiquidityOutAssetB(t,e,n,r){return Aa(t,e,n,r)}};var{FeeUtils:ln}=v,Ct=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,r,a){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(t),a=n.get(e);if(r==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:r.decimals,decimalsOut:a.decimals,balanceIn:r.balance,balanceOut:a.balance,assetInEd:r.existentialDeposit,assetOutEd:a.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),a=this.calculateTradeFee(r,n),s=ln.toPct(n.exchangeFee),i=r+a,o=[];(e<this.minTradingLimit||r<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return i>c&&o.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:e,feePct:s,errors:o}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),a=this.calculateTradeFee(r,n),s=ln.toPct(n.exchangeFee),i=r-a,o=[];(e<this.minTradingLimit||r<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return i>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:i,feePct:s,errors:o}}calculateInGivenOut(t,e){let n=V.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(t,e){let n=V.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(t){let e=V.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=V.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=V.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Ba}from"polkadot-api";import{of as _a}from"rxjs";var kt=class extends M{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),r=e.map(async({keyArgs:a,value:s})=>{let[i]=a,[o,l]=s,[c,m,d,p]=await Promise.all([this.getBalance(i,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(i,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:i,type:"XYK",tokens:[{id:o,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:c.transferable,type:m?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:d.transferable,type:p?.asset_type.type}],...n}});return Promise.all(r)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}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 getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Ba.BackwardsCompatible,e)}subscribePoolChange(t){return _a(t)}};var Te={};T(Te,{AavePool:()=>Dt,AavePoolClient:()=>Mt});var Dt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,r,a){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(s=>[s.id,s])),r=n.get(t),a=n.get(e);if(r==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:r.balance,balanceOut:a.balance,decimalsIn:r.decimals,decimalsOut:a.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),a=[];return e>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),a=[];return r>t.balanceOut&&a.push("TradeNotAllowed"),{amountIn:e,calculatedOut:r,amountOut:r,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 Ra}from"polkadot-api";import{toHex as Fa}from"@polkadot-api/utils";import{map as Ea,merge as Ca,switchMap as ka}from"rxjs";import{decodeEventLog as Da}from"viem";var cn=[{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:Ma}=et,La=["Supply","Withdraw","Repay","Borrow"],Mt=class extends M{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:r,liqudity_in:a,liqudity_out:s})=>{let[i,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(r),this.api.query.AssetRegistry.AssetLocations.getValue(r)]);return{address:this.getPoolId(n,r),type:"Aave",tokens:[{id:n,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a,location:o,type:i?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:s,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:r,liqudity_out:a}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(s=>{let i=s.id===e.id?r:a;return{...s,balance:i}})}getPoolId(t,e){let n=t+"/"+e,r=new TextEncoder().encode(n.padEnd(32,"\0")),a=Fa(r);return Ra(63).dec(a)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,r=this.getReserveH160Id(e),a=this.api.event.Router.Executed.watch(({asset_in:i,asset_out:o})=>i===n.id||o===n.id),s=this.api.event.EVM.Log.watch(({log:i})=>{let{topics:o,data:l}=i,c=o.map(g=>g.asHex()),m=l.asHex(),{eventName:d,args:p}=Da({abi:cn,topics:c,data:m});return La.includes(d)&&p.reserve.toLowerCase()===r.toLowerCase()});return Ca([a,s]).pipe(ka(()=>this.getPoolDelta(t)),Ea(i=>({...t,tokens:[...i]})))}getReserveH160Id(t){return t.type==="Erc20"?$.findNestedKey(t.location,"AccountKey20").AccountKey20.key:Ma.fromAssetId(t.id)}};var lt=class{static get(t){switch(t.type){case"Aave":return Dt.fromPool(t);case"XYK":return Ct.fromPool(t);case"Omnipool":return _t.fromPool(t);case"LBP":return Ot.fromPool(t);case"Stableswap":return Ft.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as qa,Subscription as Lt,takeUntil as Na}from"rxjs";var ct=class extends _{evm;lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=Lt.EMPTY;omniSub=Lt.EMPTY;stableSub=Lt.EMPTY;xykSub=Lt.EMPTY;aaveSub=Lt.EMPTY;isReady=!1;isDestroyed=new qa;constructor(t,e){super(t),this.evm=e,this.lbpClient=new Bt(t,e),this.omniClient=new Rt(t,e),this.stableClient=new Et(t,e),this.xykClient=new kt(t,e),this.aaveClient=new Mt(t,e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe(Na(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(t={}){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let{useOnly:e=[],exclude:n=[]}=t,r=new Set(e),a=new Set(n),s=async i=>{let o=i.getPoolType();return r.size>0?r.has(o):a.size>0?!a.has(o):i.isSupported()};return this.getFilteredPools(s)}async getFilteredPools(t){let e=await Promise.all(this.clients.map(t)),n=this.clients.filter((a,s)=>e[s]);return(await Promise.all(n.map(a=>a.getPoolsMem()))).flat()}async getPoolFees(t,e){let n=this.clients.find(r=>r.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new Tt(t.type)}};var bn={};T(bn,{DEFAULT_BLOCK_TIME:()=>pn,DEFAULT_MIN_BUDGET:()=>Ie,ORDER_MIN_BLOCK_PERIOD:()=>dn,Router:()=>ut,TWAP_BLOCK_PERIOD:()=>Ut,TWAP_MAX_DURATION:()=>Oe,TWAP_MAX_PRICE_IMPACT:()=>ve,TWAP_TX_MULTIPLIER:()=>Wu,TradeOrderError:()=>xe,TradeOrderType:()=>Zt,TradeRouteBuilder:()=>L,TradeRouter:()=>mt,TradeScheduler:()=>pt,TradeType:()=>Jt});var qt=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 Ga=8,Nt=class{isNotVisited(t,e){let n=!0;return e.forEach(r=>{(r[0]===t[0]||r[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let r=[],a=new qt,s=[];for(s.push([e,""]),a.enqueue(s);a.size()>0;){let i=a.dequeue();if(!i||i.length>Ga)continue;let o=i[i.length-1];(n===null||o[0]===n)&&r.push(i),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,i)){let m=[...i];m.push(c),a.enqueue(m)}})}return r}findShortestPaths(t,e,n){let r=[],a=new qt,s=[];s.push([e,""]),a.enqueue(s);let i=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<i?(i=o.length,r.length=0,r.push(o)):o.length===i&&r.push(o);continue}let c=t.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&a.enqueue([...o,m])}return r}buildAndPopulateGraph(t,e){let n=new Map;for(let r of t)n.set(parseInt(r),[]);for(let[r,a,s]of e)n.get(a)?.push([s,r]);return n}};function we(u){let t={};for(let e of u){let n=e.tokens.length;for(let r=0;r<n;r++){t[e.tokens[r].id]||(t[e.tokens[r].id]=[]);for(let a=0;a<n;a++){if(r==a)continue;let s=[e.address,e.tokens[r].id,e.tokens[a].id];t[e.tokens[r].id].push(s)}}}return t}var Gt=class{getProposals(t,e,n){let r=n.filter(b=>b.type==="XYK"),a=n.filter(b=>b.type!=="XYK"),s=new Set(a.map(b=>b.tokens).flat().map(b=>b.id)),i=s.has(t),o=s.has(e),l=new Nt,c=b=>{let P=we(b),f=Object.keys(P),S=f.flatMap(w=>P[w]);return l.buildAndPopulateGraph(f,S)};if(!i&&!o){let b=r.filter(S=>S.tokens.find(w=>w.id===t)||S.tokens.find(w=>w.id===e)),P=c(b),f=l.findPaths(P,t,e);return this.parsePaths(f)}if(i&&o){let b=c(a),P=l.findPaths(b,t,e);return this.parsePaths(P)}let m=i?e:t,d=r.filter(b=>b.tokens.some(P=>P.id===m));if(d.length===0)return[];let p=[...a,...d],g=c(p),y=l.findPaths(g,t,e);return this.parsePaths(y)}parsePaths(t){let e=[];for(let n of t){let r=[];for(let a=0;a<n.length;a++){let s=n[a],i=n[a+1];if(i==null)break;r.push(this.toEdge(s,i))}e.push(r)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var ut=class{routeSuggester;routeProposals;routerOptions;ctx;constructor(t,e={}){this.ctx=t,this.routeSuggester=new Gt,this.routeProposals=new Map,this.routerOptions=Object.freeze(e)}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}async getPools(){return this.ctx.getPools(this.routerOptions)}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(r=>r!==t).map(r=>this.getRoutes(r,t)))).filter(r=>r.length>0).map(([r])=>r[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 r=this.getAssets(n);if(!r.has(t))throw new Error(t+" is not supported asset");if(!r.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(r=>r.id)).flat().sort((n,r)=>n>r?1:-1);return new Set(e)}getPaths(t,e,n){let r=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(s=>this.validPath(s,r)).map(s=>this.toHops(s,r))}getProposals(t,e,n){let r=this.buildRouteKey(t,e,n);if(this.routeProposals.has(r))return this.routeProposals.get(r);let a=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(r,a),a}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,r)=>n&&r)}validEdge([t,e,n],r){return r.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,lt.get(e)]))}toHops(t,e){return t.map(([n,r,a])=>{let s=e.get(n);return{poolAddress:n,poolId:s?.id,pool:s?.type,assetIn:r,assetOut:a}})}};var Jt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Jt||{}),Zt=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Zt||{}),xe=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(xe||{});var{FeeUtils:mn}=v,mt=class extends ut{mlr;poolsSnapshot;constructor(t,e={}){super(t,e),this.mlr=new Map}buildCtxSync(t,e){let n=this.poolsSnapshot,r=super.validateInput(t,e,n),a=super.getPaths(t,e,n);if(!a.length)throw new wt(t,e);return{paths:a,pools:n,poolsMap:r}}async withCtx(t,e,n){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let r=this.buildCtxSync(t,e);return n(r)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,r)=>{let a=n[n.length-1].amountOut,s=r[r.length-1].amountOut;return a>s?-1:1});return e.find(n=>n.every(r=>r.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,s)=>a+s),r=t.map(a=>a.tradeFeeRange?.[1]??a.tradeFeePct).reduce((a,s)=>a+s);return[n,r]}}getPoolFeeRange(t){let e=t.min?mn.toPct(t.min):void 0,n=t.max?mn.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(i=>i.assetOutDecimals).reduce((i,o)=>i+o),r=t.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-e.assetOutDecimals,s=Math.pow(10,a);return r/BigInt(s)}async getSell(t,e,n,r){return this.withCtx(t,e,async({paths:a,poolsMap:s})=>{let i;if(r)i=await this.toSellSwaps(n,r,s);else{let o=a.map(c=>this.toSellSwaps(n,c,s)),l=await Promise.all(o);i=this.findBestSellRoute(l)}return this.buildSell(s,i)})}buildSell(t,e){let n=e[0],r=e[e.length-1],a=this.isDirectTrade(e),s=this.getSellSpot(e),i=r.amountOut,o=a?r.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-i,c=this.getRouteFeeRange(e),m=a?r.tradeFeePct:O.calculateSellFee(o,i),d=Math.pow(10,n.assetInDecimals),p=n.amountIn*s/BigInt(d),g=O.calculateDiffToRef(o,p);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:s,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Sell",amountIn:h.toDecimal(n.amountIn,n.assetInDecimals),amountOut:h.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:h.toDecimal(s,r.assetOutDecimals),tradeFee:h.toDecimal(l,r.assetOutDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0Y(t,e,n){let r=[];for(let a=0;a<e.length;a++){let s=e[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a>0?l=r[a-1]:l=t;let c=i.calculateOutGivenIn(o,l);r.push(c)}return r[r.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:r,pools:a,poolsMap:s}=n,l=a.filter(y=>y.tokens.some(b=>b.id===t)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(b=>b.id===t)).map(y=>y.map(b=>b.balance).reduce((b,P)=>b+P)).sort((y,b)=>b<y?-1:1)[0],c=O.getFraction(l,.1),m=await Promise.all(r.map(y=>this.toSellSwaps(c,y,s))),p=this.findBestSellRoute(m).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),g=this.buildRouteKey(t,e,a);return this.mlr.set(g,p),p}async toSellSwaps(t,e,n){let r=[];for(let a=0;a<e.length;a++){let s=e[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a>0?l=r[a-1].amountOut:l=typeof t=="string"?h.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountOut:m,calculatedOut:d,feePct:p,errors:g}=i.validateAndSell(o,l,c),y=this.getPoolFeeRange(c),b=i.spotPriceOutGivenIn(o),P=Math.pow(10,o.decimalsIn),f=l*b/BigInt(P),S=O.calculateDiffToRef(d,f);r.push({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:d,spotPrice:b,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:S,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===s.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===s.assetIn},toHuman(){return{...s,amountIn:h.toDecimal(l,o.decimalsIn),amountOut:h.toDecimal(m,o.decimalsOut),calculatedOut:h.toDecimal(d,o.decimalsOut),spotPrice:h.toDecimal(b,o.decimalsOut),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:S,errors:g}}})}return r}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let r=this.buildRouteKey(t,e,n.pools),a=this.mlr.get(r);return a||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:r,poolsMap:a}=n,s=this.buildRouteKey(t,e,r),i=this.mlr.get(s);i||(i=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",i,a),l=this.getSellSpot(o),c=o[o.length-1].assetOutDecimals;return{amount:l,decimals:c}})}findBestBuyRoute(t){let e=t.sort((n,r)=>{let a=n[0].amountIn,s=r[0].amountIn;return a>s?1:-1});return e.find(n=>n.every(r=>r.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(i=>i.assetInDecimals).reduce((i,o)=>i+o),r=t.map(i=>i.spotPrice).reduce((i,o)=>i*o),a=n-e.assetInDecimals,s=Math.pow(10,a);return r/BigInt(s)}async getBuy(t,e,n,r){return this.withCtx(t,e,async({paths:a,poolsMap:s})=>{let i;if(r)i=await this.toBuySwaps(n,r,s);else{let o=a.map(c=>this.toBuySwaps(n,c,s)),l=await Promise.all(o);i=this.findBestBuyRoute(l)}return this.buildBuy(s,i)})}buildBuy(t,e){let n=e[e.length-1],r=e[0],a=this.isDirectTrade(e),s=this.getBuySpot(e),i=r.amountIn,o=a?r.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=i-o,c=this.getRouteFeeRange(e),m=a?r.tradeFeePct:O.calculateBuyFee(o,i),d=Math.pow(10,n.assetOutDecimals),p=n.amountOut*s/BigInt(d),g;return o===0n?g=-100:g=O.calculateDiffToRef(p,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:s,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Buy",amountOut:h.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:h.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:h.toDecimal(s,r.assetInDecimals),tradeFee:h.toDecimal(l,r.assetInDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0X(t,e,n){let r=[];for(let a=e.length-1;a>=0;a--){let s=e[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a==e.length-1?l=t:l=r[0];let c=i.calculateInGivenOut(o,l);r.unshift(c)}return r[0]}async toBuySwaps(t,e,n){let r=[];for(let a=e.length-1;a>=0;a--){let s=e[a],i=n.get(s.poolAddress);if(i==null)throw new Error("Pool does not exit");let o=i.parsePair(s.assetIn,s.assetOut),l;a==e.length-1?l=typeof t=="string"?h.toBigInt(t,o.decimalsOut):t:l=r[0].amountIn;let c=await this.ctx.getPoolFees(i,o.assetOut),{amountIn:m,calculatedIn:d,feePct:p,errors:g}=i.validateAndBuy(o,l,c),y=this.getPoolFeeRange(c),b=i.spotPriceInGivenOut(o),P=Math.pow(10,o.decimalsOut),f=l*b/BigInt(P),S;d===0n?S=-100:S=O.calculateDiffToRef(f,d),r.unshift({...s,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:m,calculatedIn:d,spotPrice:b,tradeFeePct:p,tradeFeeRange:y,priceImpactPct:S,errors:g,isSupply(){return i.type==="Aave"&&i.tokens[0].id===s.assetIn},isWithdraw(){return i.type==="Aave"&&i.tokens[1].id===s.assetIn},toHuman(){return{...s,amountOut:h.toDecimal(l,o.decimalsOut),amountIn:h.toDecimal(m,o.decimalsIn),calculatedIn:h.toDecimal(d,o.decimalsIn),spotPrice:h.toDecimal(b,o.decimalsIn),tradeFeePct:p,tradeFeeRange:y,priceImpactPct:S,errors:g}}})}return r}};var pn=6e3,Ie=1000000000000000n,Ut=6,ve=-5,Oe=216e5,Wu=3,dn=6;import{Enum as gn}from"polkadot-api";var L=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:r,poolId:a})=>r==="Stableswap"?{pool:gn("Stableswap",a),asset_in:e,asset_out:n}:{pool:gn(r),asset_in:e,asset_out:n})}};var pt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Ie})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,r,a){let[s,i]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=i,m=l[0],d=l[l.length-1],{assetInDecimals:p}=m,{assetOutDecimals:g}=d,y=Math.abs(c),b=this.getMinimumTradeCount(o,s),P=this.getOptimalTradeCount(y),f=a?Math.round(r/a):P,S=Math.ceil(r/b),w=Math.round(r/P),k=Math.round(r/f),D=o/BigInt(f),R=await this.router.getBestSell(t,e,D),q=o<s,z=[];q&&z.push("OrderTooSmall");let N=R.amountOut*BigInt(f),W=this.toBlockPeriod(k),yt=R.tradeFee*BigInt(f),ht=L.build(l),Wt={assetIn:t,assetOut:e,errors:z,frequencyMin:S,frequencyOpt:w,frequency:k,tradeCount:f,tradeFee:yt,tradeImpactPct:R.priceImpactPct,tradePeriod:W,tradeRoute:ht,type:"Dca"};return{...Wt,amountIn:o,amountOut:N,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...Wt,amountIn:h.toDecimal(o,p),amountOut:h.toDecimal(N,g),tradeAmountIn:h.toDecimal(R.amountIn,p),tradeAmountOut:h.toDecimal(R.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 r=t+n/2n;return Number(r/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[r,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:s,swaps:i,priceImpactPct:o}=a,l=i[0],c=i[i.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,p=Math.abs(o),g=this.getTwapTradeCount(p),y=s/BigInt(g),b=await this.router.getBestSell(l.assetIn,c.assetOut,y),P=g===1,f=s<r,S=b.priceImpactPct<-5,w=[];f||P?w.push("OrderTooSmall"):S&&w.push("OrderImpactTooBig");let k=b.amountOut*BigInt(g),D=b.tradeFee*BigInt(g),R=L.build(i),q={assetIn:t,assetOut:e,errors:w,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...q,amountIn:s,amountOut:k,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:D,toHuman(){return{...q,amountIn:h.toDecimal(s,m),amountOut:h.toDecimal(k,d),tradeAmountIn:h.toDecimal(b.amountIn,m),tradeAmountOut:h.toDecimal(b.amountOut,d),tradeFee:h.toDecimal(D,d)}}}}async getTwapBuyOrder(t,e,n){let[r,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:s,swaps:i,priceImpactPct:o}=a,l=i[0],c=i[i.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,p=Math.abs(o),g=this.getTwapTradeCount(p),y=s/BigInt(g),b=await this.router.getBestBuy(l.assetIn,c.assetOut,y),P=b.amountIn*BigInt(g),f=g===1,S=P<r,w=b.priceImpactPct<-5,k=[];S||f?k.push("OrderTooSmall"):w&&k.push("OrderImpactTooBig");let D=b.tradeFee*BigInt(g),R=L.build(i),q={assetIn:t,assetOut:e,errors:k,tradeCount:g,tradeImpactPct:b.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...q,amountIn:P,amountOut:s,tradeAmountIn:b.amountIn,tradeAmountOut:b.amountOut,tradeFee:D,toHuman(){return{...q,amountIn:h.toDecimal(P,m),amountOut:h.toDecimal(s,d),tradeAmountIn:h.toDecimal(b.amountIn,m),tradeAmountOut:h.toDecimal(b.amountOut,d),tradeFee:h.toDecimal(D,m)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}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 fn={};T(fn,{BIG_10:()=>hn,BIG_BILL:()=>Pn,StakingApi:()=>Ht,StakingClient:()=>Vt});import{encodeAddress as Ua}from"@polkadot/util-crypto";import{stringToU8a as Ha}from"@polkadot/util";import{calculate_accumulated_rps as Va,calculate_period_number as yn,calculate_rewards as Wa}from"@galacticcouncil/math-staking";import dt from"big.js";var hn=dt(10),Pn=dt(hn.pow(12));function Ya(u){return Ua(Ha(("modl"+u).padEnd(32,"\0")),63)}var Ht=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getFreePotBalance(){let t=await this.client.getPalletId(),e=Ya(t);return(await this.balanceClient.getBalance(e,0)).transferable}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]),r=e?.created_at,a=await n.reduce(async(s,[i,o])=>{let l=await s,c=i,m=o.amount,d=o.conviction.toString(),p=await this.client.getReferendumInfo(c);return p&&(p.type==="Approved"||p.type==="Rejected")&&l.push({id:c,amount:m,conviction:d}),l},Promise.resolve([]));return{stake:e?.stake,rewardPerStake:e?.reward_per_stake,createdAt:r,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,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),a=r.find(s=>s)?.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}}async getRewards(t,e){let n=await this.getStake(t),{potReservedBalance:r,accumulatedRewardPerStake:a,totalStake:s,stakePosition:i}=n;if(!i)return;let[o,l,c,m]=await Promise.all([this.getFreePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getSixBlockSince()]),d=dt(o.toString()).minus(r.toString()),p=a.toString(),g=dt(e).plus(1).toString();d.gt(0)&&s>0&&(p=Va(a.toString(),d.toString(),s.toString()));let y=yn(l.toString(),e,m??g),b=yn(l.toString(),i.createdAt?.toString()??"",m??g),P=Wa(p,i.rewardPerStake?.toString()??"",i.stake?.toString()??""),f=dt(P).plus(i.accumulatedUnpaidRewards?.toString()||"0").plus(i.accumulatedLockedRewards?.toString()||"0");if(!dt(y).minus(b).lte(c.toString()))return f.div(Pn).toString()}};var Vt=class extends _{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:s})=>{let[i,o,l]=s;return{address:i,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 getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};var wn={};T(wn,{TxBuilderFactory:()=>bt});import{Enum as Tn}from"polkadot-api";function Sn(u){let t=[],e=u;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var gt=class extends _{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new U(t),this.aaveUtils=new Q(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:ae})}async dryRun(t,e){let n=Tn("Signed",t),r=Tn("system",n),s=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,e.decodedCall),i=s.success&&!s.value.execution_result.success?s.value.execution_result.value.error:null;if(i){let o=Sn(i.value);throw new Error("Dry run execution error!",{cause:o})}return s}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var te=class extends gt{_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:r}=e[0],a=await this.balanceClient.getBalance(this.beneficiary,r);return t>=a.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,r=n[0],a=n[n.length-1],s=O.getFraction(t,this.slippagePct),i=r.assetIn,o=a.assetOut,l=t+s,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.buy({asset_in:i,asset_out:o,amount:e,max_sell_amount:l}):c=this.api.tx.Router.buy({asset_in:i,asset_out:o,amount_out:e,max_amount_in:l,route:L.build(n)}),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,r=n[0],a=n[n.length-1],s=O.getFraction(e,this.slippagePct),i=r.assetIn,o=a.assetOut,l=e-s,c;return this.isDirectOmnipoolTrade(n)?c=this.api.tx.Omnipool.sell({asset_in:i,asset_out:o,amount:t,min_buy_amount:l}):c=this.api.tx.Router.sell({asset_in:i,asset_out:o,amount_in:t,min_amount_out:l,route:L.build(n)}),r.isWithdraw()&&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],r=e[e.length-1],a=O.getFraction(t,this.slippagePct),s=n.assetIn,i=r.assetOut,o=t-a,l=this.api.tx.Router.sell_all({asset_in:s,asset_out:i,min_amount_out:o,route:L.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as Ae}from"polkadot-api";var ee=class extends gt{_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:r,tradePeriod:a,tradeRoute:s}=this.order,i=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:Ae("Sell",{asset_in:e,asset_out:n,amount_in:r,min_amount_out:0n,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",i)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:r,tradeAmountOut:a,tradePeriod:s,tradeRoute:i}=this.order,o=O.getFraction(a,this.slippagePct),l=a-o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Ae("Sell",{asset_in:e,asset_out:n,amount_in:r,min_amount_out:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:r,tradeAmountOut:a,tradePeriod:s,tradeRoute:i}=this.order,o=O.getFraction(r,this.slippagePct),l=r+o,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Ae("Buy",{asset_in:e,asset_out:n,amount_out:a,max_amount_in:l,route:i})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var bt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new te(this.client,this.evmClient).setTrade(t)}order(t){return new ee(this.client,this.evmClient).setOrder(t)}};async function Zm(u){let t=new it(u),e=new xt(u),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),a=new ct(u,e).withAave().withOmnipool().withStableswap().withXyk(),s=new U(u),i=new Vt(u),o=new vt(u),l=new Q(e),c=new mt(a),m=new pt(c,{blockTime:n,minBudgetInNative:r}),d=new Ht(i,s),p=new It(o,s,{blockTime:n});return{api:{aave:l,router:c,scheduler:m,staking:d,farm:p},client:{asset:new rt(u),balance:s,evm:e},ctx:{pool:a},tx:new bt(u,e),destroy:()=>{a.destroy()}}}export{Ge as aave,Ce as api,h as big,Ve as client,ke as const,Zm as createSdkContext,et as erc20,We as error,Ke as evm,Ze as farm,v as fmt,zt as h160,$ as json,O as math,un as pool,bn as sor,fn as staking,wn as tx,Ne as xc};
|
|
1
|
+
var Rn=Object.defineProperty;var w=(u,t)=>{for(var e in t)Rn(u,e,{get:t[e],enumerable:!0})};var qe={};w(qe,{Papi:()=>R,getWs:()=>Cn});import{hydration as Fn}from"@galacticcouncil/descriptors";function Le(u){switch(u){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var R=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(Fn)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");Le(n)&&console.log(t,...e)}};import{createClient as kn}from"polkadot-api";import{withPolkadotSdkCompat as En}from"polkadot-api/polkadot-sdk-compat";var Cn=async u=>{let t=typeof u=="string"?u.split(","):u,r=(typeof window>"u"?(await import("polkadot-api/ws-provider/node")).getWsProvider:(await import("polkadot-api/ws-provider/web")).getWsProvider)(t);return kn(En(r))};var Ye={};w(Ye,{AAVE_GAS_LIMIT:()=>me,AAVE_LENDING_POOL_ADDRESS:()=>$t,AAVE_POOL_ABI:()=>ce,AAVE_POOL_DATA_PROVIDER:()=>jt,AAVE_POOL_DATA_PROVIDER_ABI:()=>zt,AAVE_POOL_PROXY:()=>ue,AAVE_ROUNDING_THRESHOLD:()=>gs,AAVE_UINT_256_MAX:()=>Dn,AaveClient:()=>St,AaveUtils:()=>et});var ce=[{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 zt=[{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 ue="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",jt="0x112b087b60C1a166130d59266363C45F8aa99db0",$t="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",me=1000000n,gs=5,Dn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var St=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:zt,address:jt,args:[$t],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:zt,address:jt,args:[$t,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ce,address:ue,args:[t],functionName:"getUserAccountData"})}};import j from"big.js";var f={};w(f,{asBigInt:()=>qn,toBigInt:()=>Ln,toDecimal:()=>Mn});import Z from"big.js";Z.NE=-18;function Mn(u,t,e=6,n){let r=Z(u.toString()),i=Z(10).pow(t);return r.div(i).round(e,n).toString()}function Ln(u,t){let e=Z(10).pow(t),r=Z(u).mul(e).toFixed(0,Z.roundDown);return BigInt(r)}function qn(u){return BigInt(u.round(0,Z.roundDown).toFixed(0))}var st={};w(st,{ERC20:()=>pe});var pe=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 v={};w(v,{FeeUtils:()=>be,shiftNeg:()=>Vn});import Un from"big.js";var Ne={};w(Ne,{HUB_ASSET_ID:()=>ye,HYDRATION_OMNIPOOL_ADDRESS:()=>Gn,HYDRATION_PARACHAIN_ID:()=>Nn,HYDRATION_SS58_PREFIX:()=>M,PERBILL_DENOMINATOR:()=>de,PERMILL_DENOMINATOR:()=>Tt,RUNTIME_DECIMALS:()=>I,SYSTEM_ASSET_DECIMALS:()=>ge,SYSTEM_ASSET_ID:()=>E,TRADEABLE_DEFAULT:()=>at});var I=18,Tt=1e6,de=1e9,E=0,ge=12,Nn=2034,M=63,Gn="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",ye=1,at=15;var be=class u{static toPct(t){let[e,n]=t;return u.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return u.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 r=10**n;return Math.round(t*r/e)/r}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Vn(u,t){let e=Un(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Qt={};w(Qt,{H160:()=>Pe,isEvmAccount:()=>Ue,isEvmAddress:()=>Ve,isSs58Address:()=>We});import{AccountId as wt}from"polkadot-api";import{toHex as Ge}from"@polkadot-api/utils";import{Buffer as z}from"buffer";var he="ETH\0";function Ue(u){if(!u)return!1;try{let t=wt().enc(u),e=z.from(he);return z.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function Ve(u){return!!/^0x[a-fA-F0-9]{40}$/.test(u)}function We(u){try{return wt(63).enc(u),!0}catch{return!1}}var Pe=class u{static toAccount=t=>{let e=z.from(t.slice(2),"hex"),n=z.from(he),r=Uint8Array.from(z.concat([n,e,z.alloc(8)])),i=Ge(r);return wt(63).dec(i)};static fromAccount=t=>{let e=wt().enc(t),n=z.from(he),r=e.slice(n.length,-8);return"0x"+z.from(r).toString("hex")};static fromSS58=t=>{let n=wt().enc(t).slice(0,20);return Ge(n)};static fromAny=t=>{if(Ve(t))return t;if(Ue(t))return u.fromAccount(t);if(We(t))return u.fromSS58(t);throw new Error("Unknown address type")}};var tt={};w(tt,{findNestedKey:()=>Wn,findNestedObj:()=>Hn,jsonFormatter:()=>Yn});var Wn=(u,t)=>{let e=[];return JSON.stringify(u,(n,r)=>(r&&r[t]&&e.push(r),r)),e[0]},Hn=(u,t,e)=>{let n;return JSON.stringify(u,(r,i)=>(i&&i[t]===e&&(n=i),i)),n},Yn=(u,t)=>typeof t=="bigint"?t.toString():t;var O={};w(O,{calculateBuyFee:()=>jn,calculateDiffToAvg:()=>Xn,calculateDiffToRef:()=>Kn,calculateSellFee:()=>zn,getFraction:()=>$n});import Y from"big.js";function Xn(u,t){let e=Y(u.toString()),n=Y(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function Kn(u,t){if(t===0n)return 0;let e=Y(u.toString()),n=Y(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function zn(u,t){let e=Y(u.toString()),n=Y(t.toString());return Y(1).minus(n.div(e)).mul(100).round(2).toNumber()}function jn(u,t){let e=Y(u.toString());return Y(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function $n(u,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),r=BigInt(t*n);return u*r/BigInt(100*n)}var He={};w(He,{convertToId:()=>Jn});import{Buffer as Qn}from"buffer";function Jn(u){let e=Qn.from(u.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var{ERC20:Jt}=st,{H160:fe}=Qt,Zn=1.01,tr=31536000n,Zt=10n**27n,et=class{client;constructor(t){this.client=new St(t)}async getSummary(t){let e=fe.fromAny(t),[n,r,i,a]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[s]=n,[o,l]=r,[c,m,d,p,g,b]=i,y=f.toDecimal(b,18),h=[];for(let P of o){let S=P.underlyingAsset.toLowerCase(),T=s.find(({underlyingAsset:Kt})=>Kt.toLowerCase()===S);if(!T)throw new Error("Missing pool reserve for "+S);let F=P.scaledATokenBalance,k=T.liquidityIndex,B=T.liquidityRate,C=T.availableLiquidity,U=T.priceInMarketReferenceCurrency,D=a+6,W=this.calculateLinearInterest(B,T.lastUpdateTimestamp,D),K=k*W/Zt,J=F*K/Zt,Xt=Number(l!==0&&l===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,oe=T.usageAsCollateralEnabled&&P.usageAsCollateralEnabledOnUser&&P.scaledATokenBalance>0n,le=Jt.toAssetId(S);h.push({aTokenBalance:J,availableLiquidity:C,decimals:Number(T.decimals),isCollateral:oe,priceInRef:U,reserveId:le,reserveAsset:S,reserveLiquidationThreshold:Xt})}return{healthFactor:Number(y),totalCollateral:c,totalDebt:m,reserves:h}}async hasBorrowPositions(t){let e=fe.fromAny(t),n=await this.client.getUserAccountData(e),[r,i]=n;return i>0n}async getHealthFactor(t){let e=fe.fromAny(t),n=await this.client.getUserAccountData(e),[r,i,a,s,o,l]=n,c=f.toDecimal(l,18);return Number(c)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:r,totalDebt:i,reserves:a}=await this.getSummary(t),s=Jt.fromAssetId(e),o=a.find(h=>h.reserveAsset===s);if(!o)throw new Error("Missing reserve ctx for "+s);let{decimals:l,isCollateral:c,priceInRef:m,reserveLiquidationThreshold:d}=o,p=f.toBigInt(n,l),g=c?p*m/10n**BigInt(l):0n,b=r-g;if(b<=0n)return 0;let y=j(b.toString()).mul(d).div(i.toString()).toFixed(6,j.roundDown);return Number(y)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:r,totalDebt:i,reserves:a}=await this.getSummary(t),s=Jt.fromAssetId(e),o=a.find(y=>y.reserveAsset===s);if(!o)throw new Error("Missing reserve ctx for "+s);let{decimals:l,priceInRef:c,reserveLiquidationThreshold:m}=o,p=f.toBigInt(n,l)*c/10n**BigInt(l),g=r+p;if(g<=0n)return 0;let b=j(g.toString()).mul(m).div(i.toString()).toFixed(6,j.roundDown);return Number(b)}async getMaxWithdraw(t,e){let{totalDebt:n,reserves:r,healthFactor:i}=await this.getSummary(t),a=Jt.fromAssetId(e),s=r.find(o=>o.reserveAsset===a);if(!s)throw new Error("Missing reserve ctx for "+a);return this.calculateWithdrawMax(s,n,i)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:n,healthFactor:r}=await this.getSummary(t),i={};for(let a of n){let s=this.calculateWithdrawMax(a,e,r);a.reserveId&&(i[a.reserveId]=s)}return i}calculateWithdrawMax(t,e,n){let{aTokenBalance:r,availableLiquidity:i,decimals:a,priceInRef:s,reserveLiquidationThreshold:o,isCollateral:l}=t,c=r;if(l&&e>0n){let d=n-Zn;if(d>0){let p=j(d).mul(e.toString()).div(o).toFixed(0,j.roundDown),g=j(p).div(s.toString()).mul(10**a).toFixed(0,j.roundDown);c=r<BigInt(g)?r:BigInt(g)}else c=0n}return{amount:c<i?c:i,decimals:a}}calculateLinearInterest(t,e,n){let r=n-e;if(r<=0)return Zt;let i=t*BigInt(r)/tr;return Zt+i}};var ze={};w(ze,{AssetClient:()=>ot,BalanceClient:()=>H,ChainParams:()=>ct});var ot=class extends R{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:r})=>{let[i]=n;return[i,r]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:r})=>{let[i]=n;return[i,r]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:r}=n;return this.SUPPORTED_TYPES.includes(r.type)}).map(({keyArgs:n,value:r})=>{let[i]=n;return[i,r]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:r})=>{let[i]=n;return[i,r]}))}async mapToken(t,e,n,r){let{name:i,asset_type:a,is_sufficient:s,existential_deposit:o}=e,{symbol:l,decimals:c}=n.get(t)??{};return{id:t,name:i?.asText(),symbol:l,decimals:c,icon:l,type:a.type,isSufficient:s,location:r,existentialDeposit:o}}async mapBond(t,e,n,r){let[i,a]=r,{asset_type:s,is_sufficient:o,existential_deposit:l}=e,{symbol:c,decimals:m}=await this.mapToken(i,e,n),d=Number(a),p=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",p.format(d)].join(" ");return{id:t,name:g,symbol:c+"b",decimals:m,icon:c,type:s.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:i,maturity:d}}async mapShares(t,e,n,r){let{assets:i}=r,{name:a,symbol:s,asset_type:o,is_sufficient:l,existential_deposit:c}=e,m=await Promise.all(i.map(async g=>{let{symbol:b}=await this.mapToken(g,e,n);return[g,b]})),d=Object.fromEntries(m),p=Object.values(d);return{id:t,name:p.join(", "),symbol:s?.asText()||a?.asText(),decimals:18,icon:p.join("/"),type:o.type,isSufficient:l,existentialDeposit:c,meta:d}}async mapExternal(t,e,n,r){let i=await this.mapToken(t,e,new Map,r),a=n?.find(s=>s.internalId===i.id);return a?{...i,decimals:a.decimals,name:a.name,symbol:a.symbol,icon:a.symbol,isWhiteListed:a.isWhiteListed}:i}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,r,i,a]=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 m=r.get(l),{asset_type:d}=c,p;switch(d.type){case"Bond":let g=a.get(l);p=await this.mapBond(l,c,s,g);break;case"StableSwap":let b=i.get(l);p=await this.mapShares(l,c,s,b);break;case"External":p=await this.mapExternal(l,c,e,m);break;default:p=await this.mapToken(l,c,s,m)}o.push(p)}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 er,bufferCount as nr,combineLatest as rr,debounceTime as ir,distinctUntilChanged as Xe,finalize as sr,map as lt,pairwise as ar,shareReplay as or,startWith as lr}from"rxjs";var H=class extends R{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);return this.calculateBalance(n)}async getTokenBalance(t,e){let r=await this.api.query.Tokens.Accounts.getValue(t,e);return this.calculateBalance(r)}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}}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),r=this.subscribeErc20Balance(t);return rr([e,n,r]).pipe(ir(250),lt(i=>i.flat()),lr([]),nr(2,1),lt(([i,a],s)=>{if(s===0)return a;let o=i.reduce((c,m)=>(c.set(m.id,m.balance),c),new Map);return a.filter(c=>!Ke(c.balance,o.get(c.id)))}))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe(lt(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe(lt(r=>({id:e,balance:r})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe(Xe((n,r)=>!r.deltas),lt(({deltas:n})=>{let r=[];return n?.deleted.forEach(i=>{let[a,s]=i.args;r.push({id:s,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(i=>{let[a,s]=i.args;r.push({id:s,balance:this.calculateBalance(i.value)})}),r}))}subscribeErc20Balance(t,e){let n=new er,r=n.pipe(or(1)),i=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:c}=l;return c.type==="Erc20"}).map(({keyArgs:l})=>{let[c]=l;return c}),a=async()=>{let o=e||await i(),l=async()=>{let d=(await Promise.all(o.map(async p=>{let g=await this.getTokenBalanceData(t,p);return[p,g]}))).map(([p,g])=>({id:p,balance:g}));n.next(d)};await l();let c=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>c.unsubscribe()},s;return a().then(o=>s=o),r.pipe(sr(()=>s?.()),ar(),lt(([o,l],c)=>{if(c===0)return l;let m=o.reduce((p,g)=>(p.set(g.id,g.balance),p),new Map);return l.filter(p=>!Ke(p.balance,m.get(p.id)))}),Xe((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t);return this.calculateBalance(n)}},Ke=(u,t)=>u!==void 0&&t!==void 0&&u.transferable===t.transferable&&u.total===t.total;var ct=class extends R{_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 je={};w(je,{AssetNotFound:()=>Se,PoolNotFound:()=>xt,RouteNotFound:()=>It});var Se=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},xt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},It=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Je={};w(Je,{EvmClient:()=>vt,createChain:()=>Te});import{defineChain as cr}from"viem";var ur=["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"],Te=()=>cr({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:ur}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});import{createPublicClient as $e,createWalletClient as mr,custom as Qe,http as pr}from"viem";var vt=class{client;chain;constructor(t){this.client=t,this.chain=Te()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return $e({chain:this.chain,transport:pr()})}getWsProvider(){return $e({transport:Qe({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return mr({account:t,chain:this.chain,transport:Qe(window.ethereum)})}};var sn={};w(sn,{LiquidityMiningApi:()=>Ot,LiquidityMiningClient:()=>At});import{AccountId as Pr}from"polkadot-api";import L from"big.js";import{fixed_from_rational as rn}from"@galacticcouncil/math-liquidity-mining";var te=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let n=0;n<t.length;++n){let[r,i]=t[n];this.result.set(this.getKey(i,r),e[n].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,n,r){let i=this.getKey(t,e),a=this.getKey(t,n),s=this.result.get(i)??0n,o=this.result.get(a)??0n;if(s<r)throw new Error("Attempting to transfer more than is present");this.result.set(i,s+r),this.result.set(a,o+r)}};import nt from"big.js";import{calculate_accumulated_rps as dr,calculate_global_farm_rewards as gr,calculate_loyalty_multiplier as yr,calculate_user_reward as nn,calculate_yield_farm_delta_rpvs as br}from"@galacticcouncil/math-liquidity-mining";import Ze from"big.js";var we=Ze(10).pow(18),tn=BigInt(Ze(1).pow(18).toString()),en=6;var hr="1000000000000000000",ee=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 r=await this.getAsset(t.reward_currency),i=e-t.updated_at,a=this.getAccount(t.id),s=r?.existential_deposit;if(!s)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,a),l=nt(s.toString()),c=nt(o.toString()).minus(l.lt(o.toString())?s.toString():o.toString()),m=nt(gr(t.total_shares_z.toString(),n.toString(),nt(t.yield_per_period.toString()).mul(we).round(0,nt.roundDown).toFixed(),t.max_reward_per_period.toString(),i.toFixed()));if(c.lt(m)&&(m=c),m.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,a,d,BigInt(m.toFixed())),{...t,accumulated_rpz:BigInt(dr(t.accumulated_rpz.toString(),t.total_shares_z.toString(),m.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 r=br(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(r),updated_at:n}}getLoyaltyMultiplier(t,e){let n=nt(1).mul(we).round(0,nt.roundDown).toString();if(!e)return n;let{initial_reward_percentage:r,scale_coef:i}=e;return yr(t.toFixed(),r.toString(),i.toFixed())}async claimRewards(t,e,n,r,i){if(e.state.type==="Terminated")return null;let a=Math.floor(r/t.blocks_per_period);if(n.updated_at===a)return null;let s=await this.syncGlobalFarm(t,a,i);if(!s)return null;let o=this.syncYieldFarm(e,s,a);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,c=o.updated_at-n.entered_at-l,m=this.getLoyaltyMultiplier(c,o.loyalty_curve),d=BigInt(nn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),m)),p=BigInt(nn(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),hr));return{reward:d,maxReward:p,assetId:s.reward_currency}}};var fr=L(365.2425).times(24).times(60).times(60),Ot=class{client;balanceClient;options;constructor(t,e,n={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:n.blockTime??en})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let n=[t,e].sort((i,a)=>i-a);if(t===e)return tn;let r=await this.client.getOraclePrice(n);if(r){let{n:i,d:a}=r[0].price,s;return t<e?s=rn(i.toString(),a.toString()):s=rn(a.toString(),i.toString()),BigInt(s)}}getFarmAddress=(t,e)=>{let n=Buffer.from("modl","utf-8"),r=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),i=Buffer.from([t]),a=Buffer.concat([n,r,i]),o="0x"+Buffer.concat([a,Buffer.alloc(32-a.length)]).toString("hex");return Pr(63).dec(o)};getGlobalRewardPerPeriod(t,e,n,r){let i=L(r).times(t.toString()).times(e.toString()).div(18);return i.gte(n.toString())?n.toString():i.toString()}getPoolYieldPerPeriod(t,e,n,r){let i=L(t.toString()).times(e),a=L(n.toString()).times(r);return i.div(a.toString()).toString()}farmData(t,e,n){let{yieldFarm:r,globalFarm:i,priceAdjustment:a,balance:s,id:o}=t,{multiplier:l,loyalty_curve:c}=r,{blocks_per_period:m,yield_per_period:d,total_shares_z:p,max_reward_per_period:g,pending_rewards:b,accumulated_paid_rewards:y,planned_yielding_periods:h,updated_at:P,incentivized_asset:S,reward_currency:T,price_adjustment:F}=i,k=v.shiftNeg(a??F,18),B=v.shiftNeg(l,18),C=v.shiftNeg(c?.initial_reward_percentage??0,18),U=fr.div(L(this.blockTime).times(m)).toString(),D;if(p<=0)D=L(B).times(d.toString()).times(U).toString();else{let Bn=this.getGlobalRewardPerPeriod(p,d,g,k),_n=this.getPoolYieldPerPeriod(Bn,B,p,k);D=L(_n).times(U).toString()}let W=b+y,K=g*BigInt(h),J=s.transferable+W,ft=J-W,ae=L(ft.toString()).div(g.toString()),Xt=L(e).div(m.toString()).toString(),oe=(p>=0?ae.plus(P):ae.plus(Xt)).toString(),le=L(p.toString()).div(L(g.toString()).div(d.toString())).div(Math.pow(10,18)).times(100).times(k).toFixed(2),Kt=L(W.toString()).div(J.toString()).gte(.999);D=Kt?"0":L(D).div(n?2:1).times(100).toString();let An=C?L(D).times(C).toString():void 0;return{apr:D,minApr:An,isDistributed:Kt,estimatedEndPeriod:oe,maxRewards:K,incentivizedAsset:S,rewardCurrency:T,loyaltyCurve:c,currentPeriod:Xt,potMaxRewards:J,fullness:le,yieldFarmId:r.id,globalFarmId:i.id,poolId:o}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((r,i)=>r.includes(i.keyArgs[0].toString())?r:[...r,i.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async r=>{let i=await this.getOmnipoolFarms(r);if(i)return[r,i]}));return Object.fromEntries(n.filter(r=>!!r))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),n=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:i,value:a})=>{let[,s]=i,o=a,l=await this.client.getOmnipoolGlobalFarm(s),c=await this.client.getOmnipoolYieldFarm(Number(t),s,o);if(!l||!c)return;let m=l.reward_currency,d=l.incentivized_asset,p=this.getFarmAddress(s),g=await this.getOraclePrice(m,d),b=await this.balanceClient.getBalance(p,m);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b}}));return n?r.map(i=>i?this.farmData(i,n):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((r,i)=>r.includes(i.keyArgs[0].toString())?r:[...r,i.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async r=>{let i=await this.getIsolatedFarms(r);if(i)return[r,i]}));return Object.fromEntries(n.filter(r=>!!r))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),n=await this.client.getRelayBlockNumber(),r=await Promise.all(e.map(async({keyArgs:i,value:a})=>{let[,s]=i,o=a,l=await this.client.getIsolatedGlobalFarm(s),c=await this.client.getIsolatedYieldFarm(t,s,o);if(!l||!c)return;let m=l.reward_currency,d=l.incentivized_asset,p=this.getFarmAddress(s,!0),g=await this.getOraclePrice(m,d),b=await this.balanceClient.getBalance(p,m);return{id:t,globalFarm:l,yieldFarm:c,priceAdjustment:g,balance:b,farmAddress:p}}));return n?r.map(i=>i?this.farmData(i,n,!0):void 0):[]}async getDepositReward(t,e,n,r){let i=e.global_farm_id,a=e.yield_farm_id,s=n?await this.client.getIsolatedYieldFarm(t,i,a):await this.client.getOmnipoolYieldFarm(Number(t),i,a),o=n?await this.client.getIsolatedGlobalFarm(i):await this.client.getOmnipoolGlobalFarm(i);if(!o||!s)return;let l=o.reward_currency,c=o.incentivized_asset,m=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await this.getAccountAssetBalances(m),p=await this.getOraclePrice(l,c),g=new te(m,d),y=await new ee(P=>this.getFarmAddress(P),P=>this.client.getAsset(P),g).claimRewards(o,s,e,r,p??o.price_adjustment);if(!y)return;let h=await this.client.getAsset(y.assetId);if(h&&!(y.reward<=h.existential_deposit))return y}async getAccountAssetBalances(t){let[e,n]=await Promise.all([Promise.all(t.filter(([i,a])=>a!==0).map(([i,a])=>this.balanceClient.getTokenBalance(i,a))),Promise.all(t.filter(([i,a])=>a===0).map(([i])=>this.balanceClient.getSystemBalance(i)))]),r=[];for(let i=0,a=0;i+a<t.length;){let s=i+a,[,o]=t[s];o===0?(r.push(n[a]),a+=1):(r.push(e[i]),i+=1)}return r}};import{Binary as Sr,Enum as Tr}from"polkadot-api";var At=class extends R{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(Sr.fromText("omnipool"),t,Tr("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 yn={};w(yn,{PoolContextProvider:()=>dt,PoolError:()=>rt,PoolFactory:()=>pt,PoolType:()=>A,aave:()=>Be,lbp:()=>Ie,omni:()=>ve,stable:()=>Oe,xyk:()=>Ae});var Ie={};w(Ie,{LbpMath:()=>V,LbpPool:()=>Bt,LbpPoolClient:()=>Rt});import{calculate_in_given_out as wr,calculate_out_given_in as xr,calculate_linear_weights as Ir,calculate_pool_trade_fee as vr,get_spot_price as Or}from"@galacticcouncil/math-lbp";var V=class{static getSpotPrice(t,e,n,r,i){return Or(t,e,n,r,i)}static calculateInGivenOut(t,e,n,r,i){return wr(t,e,n,r,i)}static calculateOutGivenIn(t,e,n,r,i){return xr(t,e,n,r,i)}static calculateLinearWeights(t,e,n,r,i){return Ir(t,e,n,r,i)}static calculatePoolTradeFee(t,e,n){return vr(t,e,n)}};var A=(i=>(i.Aave="Aave",i.LBP="LBP",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="XYK",i))(A||{}),rt=(i=>(i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i.UnknownError="UnknownError",i))(rt||{});var{FeeUtils:an}=v,Bt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,r,i,a,s){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=i,this.fee=a,this.repayFeeApply=s}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:i.balance,decimalsIn:r.decimals,decimalsOut:i.decimals,weightIn:r.weight,weightOut:i.weight}}validateAndBuy(t,e,n){let r=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceOut/this.maxOutRatio;if(e>a&&i.push("MaxOutRatioExceeded"),r===t.assetOut){let s=this.calculateTradeFee(e,n),o=an.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+s,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:i}}else{let s=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return s>o&&i.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,n){let r=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let a=t.balanceIn/this.maxInRatio;if(e>a&&i.push("MaxInRatioExceeded"),r===t.assetIn){let s=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return s>o&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:i}}else{let s=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(s,n),l=an.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),c=s-o,m=t.balanceOut/this.maxOutRatio;return c>m&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let n=V.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(t,e){let n=V.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(t){let e=V.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=V.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=V.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 Er}from"polkadot-api";import{map as Cr,of as mn,switchMap as Dr}from"rxjs";import{memoize1 as Ar}from"@thi.ng/memoize";import{combineLatest as on,combineLatestAll as Br,debounceTime as _r,firstValueFrom as Rr,from as ln,map as cn,mergeAll as Fr,of as kr,switchMap as un}from"rxjs";var xe=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var _t=class{client;constructor(t){this.client=t.getWsProvider()}async getData(t,e=6){let[n,r,i]=await Promise.all([this.client.readContract({abi:xe,address:t,functionName:"latestRoundData"}),this.client.readContract({abi:xe,address:t,functionName:"decimals"}),this.client.getBlock()]),[a,s,o,l]=n,c=i.number-(i.timestamp-l)/BigInt(e),m=Number(c);return{price:s,decimals:r,updatedAt:m<0?0:m}}};var N=class extends H{evm;mmOracle;override=[];mem=0;memPools=Ar(t=>(this.log(this.getPoolType(),"mem pools",t,"\u2705"),this.loadPools()));constructor(t,e){super(t),this.evm=e,this.mmOracle=new _t(e)}async withOverride(t){this.override=t||[]}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){let t=ln(this.getPoolsMem()).pipe(un(e=>this.subscribe(e)),Br());return Rr(t)}getSubscriber(){return ln(this.getPoolsMem()).pipe(un(t=>this.subscribe(t)),Fr())}subscribe(t){return t.filter(e=>this.hasValidAssets(e)).map(e=>on([this.subscribePoolChange(e),this.subscribePoolBalance(e)]).pipe(_r(250),cn(([n,r])=>this.updatePool(n,r))))}subscribePoolBalance(t){if(t.type==="Aave")return kr([]);let e=[this.subscribeTokensBalance(t.address)];if(this.hasSystemAsset(t)){let n=this.subscribeSystemBalance(t.address);e.push(n)}if(this.hasErc20Asset(t)){let n=t.tokens.filter(i=>i.type==="Erc20").map(i=>i.id),r=this.subscribeErc20Balance(t.address,n);e.push(r)}return on(e).pipe(cn(n=>n.map(r=>Array.isArray(r)?r:[r]).flat()))}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(({id:e,decimals:n,balance:r})=>{let i=this.override.find(s=>s.id===e),a=!!n||!!i?.decimals;return r>0n&&a})}updatePool=(t,e)=>{let n=t.tokens.map(r=>{let i=e.find(s=>s.id===r.id),a=this.override.find(s=>s.id===r.id);return i?{...r,balance:i.balance.transferable,decimals:r.decimals||a?.decimals}:{...r,decimals:r.decimals||a?.decimals}});return{...t,tokens:n}}};var Rt=class extends N{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),r=e?.relay_parent_number||0,i=t.filter(({value:a})=>e&&this.isActivePool(a,r)).map(async({keyArgs:a,value:s})=>{let[o]=a,l=o.toString(),c=await this.getPoolDelta(l,s,r);return{address:l,type:"LBP",fee:s.fee,...c,...n}});return Promise.all(i)}async getPoolDelta(t,e,n){let{start:r,end:i,assets:a,initial_weight:s,final_weight:o,repay_target:l,fee_collector:c}=e,m=V.calculateLinearWeights(r?r.toString():"0",i?i.toString():"0",s.toString(),o.toString(),n.toString()),[d,p]=a,g=BigInt(m),b=this.MAX_FINAL_WEIGHT-BigInt(g),[y,h,P,S,T]=await Promise.all([this.isRepayFeeApplied(d,l,c.toString()),this.getBalance(t,d),this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(t,p),this.api.query.AssetRegistry.Assets.getValue(p)]);return{repayFeeApply:y,tokens:[{id:d,decimals:P?.decimals,existentialDeposit:P?.existential_deposit,balance:h.transferable,weight:g,type:P?.asset_type.type},{id:p,decimals:T?.decimals,existentialDeposit:T?.existential_deposit,balance:S.transferable,weight:b,type:T?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:r}=t;return n&&r?e>=n&&e<r:!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 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}}async getPoolFees(t){return{repayFee:await this.getRepayFee(),exchangeFee:t.fee}}getPoolType(){return"LBP"}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Er.BackwardsCompatible,e)}subscribePoolChange(t){let e=this.api.query.ParachainSystem.ValidationData,n=this.poolsData.get(t.address);return n?e.watchValue("best").pipe(Dr(r=>r?this.getPoolDelta(t.address,n,r.relay_parent_number):mn(t)),Cr(r=>Object.assign({},t,r))):mn(t)}};var ve={};w(ve,{OmniMath:()=>x,OmniPool:()=>Ft,OmniPoolClient:()=>kt});import{calculate_in_given_out as Mr,calculate_lrna_in_given_out as Lr,calculate_out_given_in as qr,calculate_out_given_lrna_in as Nr,calculate_spot_price as Gr,calculate_lrna_spot_price as Ur,calculate_shares as Vr,calculate_liquidity_out as Wr,calculate_liquidity_lrna_out as Hr,verify_asset_cap as Yr,calculate_liquidity_hub_in as Xr,is_sell_allowed as Kr,is_buy_allowed as zr,is_add_liquidity_allowed as jr,is_remove_liquidity_allowed as $r}from"@galacticcouncil/math-omnipool";import ut from"big.js";var x=class{static calculateSpotPrice(t,e,n,r){return Gr(t,e,n,r)}static calculateLrnaSpotPrice(t,e){return Ur(t,e)}static calculateInGivenOut(t,e,n,r,i,a,s,o,l){return Mr(t,e,n,r,i,a,s,o,l)}static calculateLrnaInGivenOut(t,e,n,r,i){return Lr(t,e,n,r,i)}static calculateOutGivenIn(t,e,n,r,i,a,s,o,l){return qr(t,e,n,r,i,a,s,o,l)}static calculateOutGivenLrnaIn(t,e,n,r,i){return Nr(t,e,n,r,i)}static calculateShares(t,e,n,r){return Vr(t,e,n,r)}static calculateLiquidityOut(t,e,n,r,i,a,s,o){return Wr(t,e,n,r,i,a,s,o)}static calculateLiquidityLRNAOut(t,e,n,r,i,a,s,o){return Hr(t,e,n,r,i,a,s,o)}static calculateCapDifference(t,e,n,r){let i=ut(e),a=ut(t),s=ut(r),o=ut(n),l=ut(10).pow(18),c=o.div(l);if(i.div(s).lt(c)){let d=c.times(s).minus(i).times(a),p=i.times(ut(1).minus(c));return d.div(p).toFixed(0)}else return"0"}static verifyAssetCap(t,e,n,r){return Yr(t,e,n,r)}static calculateLimitHubIn(t,e,n,r){return Xr(t,e,n,r)}static isSellAllowed(t){return Kr(t)}static isBuyAllowed(t){return zr(t)}static isAddLiquidityAllowed(t){return jr(t)}static isRemoveLiquidityAllowed(t){return $r(t)}};var{FeeUtils:mt}=v,Ft=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,r,i,a){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=i,this.hubAssetId=a}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:r.hubReserves,hubReservesOut:i.hubReserves,sharesIn:r.shares,sharesOut:i.shares,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:r.balance,balanceOut:i.balance,tradeableIn:r.tradeable,tradeableOut:i.tradeable,assetInEd:r.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,n),a=r===0n?0:O.calculateDiffToRef(i,r),s=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&s.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&s.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return i>m&&s.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:r,amountOut:e,feePct:a,errors:s}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,n),a=O.calculateDiffToRef(r,i),s=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&s.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&s.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return i>m&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:i,feePct:a,errors:s}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let r=x.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?mt.toRaw(n.assetFee).toString():"0",n?mt.toRaw(n.protocolFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,n){let r=x.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?mt.toRaw(n.assetFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let r=x.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?mt.toRaw(n.assetFee).toString():"0",n?mt.toRaw(n.protocolFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,n){let r=x.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?mt.toRaw(n.assetFee).toString():"0"),i=BigInt(r);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=x.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=x.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=x.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=x.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};import{AccountId as Qr,CompatibilityLevel as Jr}from"polkadot-api";import{toHex as Zr}from"@polkadot-api/utils";import{distinctUntilChanged as ti,map as pn}from"rxjs";var{FeeUtils:$}=v,kt=class extends N{async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,r,i,a,s]=await Promise.all([this.api.query.Omnipool.Assets.getEntries(),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:m})=>{let[d]=c,{hub_reserve:p,shares:g,tradable:b,cap:y,protocol_shares:h}=m,[P,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,d)]);return{id:d,decimals:P?.decimals,existentialDeposit:P?.existential_deposit,balance:S.transferable,cap:y,hubReserves:p,protocolShares:h,shares:g,tradeable:b,type:P?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:a.transferable,tradeable:r,type:i?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...s}]}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=Zr(e);return Qr(63).dec(n)}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 getPoolFees(t,e){let[n,r,i]=await Promise.all([this.api.constants.DynamicFees.AssetFeeParameters(),this.api.constants.DynamicFees.ProtocolFeeParameters(),this.api.query.DynamicFees.AssetFee.getValue(e)]),a=n.min_fee+r.min_fee,s=n.max_fee+r.max_fee;if(i){let{asset_fee:o,protocol_fee:l}=i;return{assetFee:$.fromPermill(o),protocolFee:$.fromPermill(l),min:$.fromPermill(a),max:$.fromPermill(s)}}else return{assetFee:$.fromPermill(n.min_fee),protocolFee:$.fromPermill(r.min_fee),min:$.fromPermill(a),max:$.fromPermill(s)}}getPoolType(){return"Omnipool"}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(Jr.BackwardsCompatible,e)}subscribePoolChange(t){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(ti((n,r)=>!r.deltas),pn(({entries:n})=>n.map(r=>{let[i]=r.args,{hub_reserve:a,shares:s,tradable:o,cap:l,protocol_shares:c}=r.value,m=t.tokens.findIndex(p=>p.id===i);return{...t.tokens[m],cap:l,hubReserves:a,protocolShares:c,shares:s,tradeable:o}})),pn(n=>{let r=t.tokens.find(i=>i.id===1);return{...t,tokens:[...n,r]}}))}};var Oe={};w(Oe,{StableMath:()=>_,StableSwap:()=>Et,StableSwapClient:()=>Ct});import{calculate_in_given_out as ei,calculate_out_given_in as ni,calculate_amplification as ri,calculate_add_one_asset as ii,calculate_liquidity_out_one_asset as si,calculate_shares as ai,calculate_shares_for_amount as oi,calculate_spot_price_with_fee as li,pool_account_name as ci,recalculate_peg as ui}from"@galacticcouncil/math-stableswap";var _=class{static getPoolAddress(t){return ci(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,r,i){return ri(t,e,n,r,i)}static calculateInGivenOut(t,e,n,r,i,a,s){return ei(t,e,n,r,i,a,s)}static calculateAddOneAsset(t,e,n,r,i,a,s){return ii(t,e,n,r,i,a,s)}static calculateSharesForAmount(t,e,n,r,i,a,s){return oi(t,e,n,r,i,a,s)}static calculateOutGivenIn(t,e,n,r,i,a,s){return ni(t,e,n,r,i,a,s)}static calculateLiquidityOutOneAsset(t,e,n,r,i,a,s){return si(t,e,n,r,i,a,s)}static calculateShares(t,e,n,r,i,a){return ai(t,e,n,r,i,a)}static calculateSpotPriceWithFee(t,e,n,r,i,a,s,o){return li(t,e,n,r,i,a,s,o)}static recalculatePegs(t,e,n,r,i){let a=ui(t,e,n,r,i);return JSON.parse(a)}};var{FeeUtils:Q}=v,Et=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.id,t.fee,t.totalIssuance)}constructor(t,e,n,r,i,a,s,o,l){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=i,this.amplification=a,this.id=s,this.fee=o,this.totalIssuance=l}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:i.balance,decimalsIn:r.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:r.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:r.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,n),a=Q.toPct(n.fee),s=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetInEd)&&s.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:r,amountOut:e,feePct:a,errors:s}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,n),a=Q.toPct(n.fee),s=[],o=x.isSellAllowed(t.tradeableIn),l=x.isBuyAllowed(t.tradeableOut);return(!o||!l)&&s.push("TradeNotAllowed"),(e<this.minTradingLimit||r<t.assetOutEd)&&s.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:r,amountOut:i,feePct:a,errors:s}}calculateIn(t,e,n){let r=_.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?Q.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateAddOneAsset(t,e,n){let r=_.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?Q.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateSharesForAmount(t,e,n){let r=_.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?Q.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}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=_.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 r=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(r)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let r=_.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?Q.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,n){let r=_.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?Q.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}calculateShares(t,e,n){let r=_.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?Q.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(r);return i<0n?0n:i}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=_.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 r=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(r)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){let t=_.defaultPegs(this.tokens.length-1);return JSON.stringify(t)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:r})=>({asset_id:e,amount:n,decimals:r}));return JSON.stringify(t,tt.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],tt.jsonFormatter)}};import{AccountId as mi,CompatibilityLevel as pi}from"polkadot-api";import{toHex as di}from"@polkadot-api/utils";import{blake2b as gi}from"@noble/hashes/blake2b";import{map as yi,of as bi,switchMap as hi}from"rxjs";var{FeeUtils:it}=v,Ct=class extends N{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=_.getPoolAddress(t),n=gi(e,{dkLen:32}),r=di(n);return mi(63).dec(r)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}async getPoolDelta(t,e,n){let{initial_amplification:r,final_amplification:i,initial_block:a,final_block:s}=e,o=_.calculateAmplification(r.toString(),i.toString(),a.toString(),s.toString(),n.toString()),l=await this.api.query.Tokens.TotalIssuance.getValue(t);return{amplification:BigInt(o),totalIssuance:l}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),r=e.assets.map(async i=>{let[a,s,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,i),this.api.query.AssetRegistry.Assets.getValue(i),this.getBalance(n,i)]);return{id:i,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:o.transferable,tradeable:a,type:s?.asset_type.type}});return Promise.all(r)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(pi.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.Stableswap.Pools.getEntries(),this.api.query.System.Number.getValue(),this.getPoolLimits()]),r=t.map(async({keyArgs:i,value:a})=>{let[s]=i,o=this.getPoolAddress(s),[l,c,m]=await Promise.all([this.getPoolDelta(s,a,e),this.getPoolTokens(s,a),this.getPoolPegs(s,a,e)]);return c.push({id:s,tradeable:15,balance:l.totalIssuance,decimals:18}),this.poolsData.set(o,a),{address:o,id:s,type:"Stableswap",fee:it.fromPermill(a.fee),tokens:c,...l,...m,...n}});return Promise.all(r)}async getPoolFees(t){return{fee:t.fee}}async getPoolPegs(t,e,n){let r=await this.api.query.Stableswap.PoolPegs.getValue(t);if(!r)return this.getDefaultPegs(e);let i=await this.getLatestPegs(e,r,n),a=this.getRecentPegs(r),s=it.fromPermill(r.max_peg_update),o=it.fromPermill(e.fee),[l,c]=_.recalculatePegs(JSON.stringify(a),JSON.stringify(i),n.toString(),it.toRaw(s).toString(),it.toRaw(o).toString()),m=Number(l)*1e6;return{pegsFee:it.fromPermill(m),pegs:c}}getDefaultPegs(t){let e=t.fee,n=_.defaultPegs(t.assets.length);return{pegsFee:it.fromPermill(e),pegs:n}}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,r])=>r.map(i=>i.toString()))}async getLatestPegs(t,e,n){let{source:r}=e,i=Array.from(t.assets.entries()).map(([s,o])=>o),a=r.map(async(s,o)=>{if(s.type==="Oracle"){let[l,c,m]=s.value,d=[m,i[o]].sort((P,S)=>P-S),p=await this.api.query.EmaOracle.Oracles.getValue(l,d,c);if(!p)return;let[{price:g,updated_at:b}]=p,y=g.n.toString(),h=g.d.toString();return m.toString()===d[0].toString()?[[y,h],b.toString()]:[[h,y],b.toString()]}else if(s.type==="MMOracle"){let l=s.value.asHex(),{price:c,decimals:m,updatedAt:d}=await this.mmOracle.getData(l),p=10**m;return[[c.toString(),p.toString()],d.toString()]}else return[s.value.map(l=>l.toString()),n.toString()]});return Promise.all(a)}subscribePoolChange(t){let e=this.api.query.System.Number,n=this.poolsData.get(t.address);return!n||!t.id?bi(t):e.watchValue("best").pipe(hi(r=>Promise.all([this.getPoolDelta(t.id,n,r),this.getPoolPegs(t.id,n,r)])),yi(([r,i])=>{let a=t.tokens.map(s=>s.id===t.id?{...s,balance:r.totalIssuance}:s);return Object.assign(t,{tokens:a},r,i)}))}};var Ae={};w(Ae,{XykMath:()=>X,XykPool:()=>Dt,XykPoolClient:()=>Mt});import{calculate_in_given_out as Pi,calculate_out_given_in as fi,calculate_pool_trade_fee as Si,get_spot_price as Ti,calculate_liquidity_in as wi,calculate_shares as xi,calculate_spot_price as Ii,calculate_spot_price_with_fee as vi,calculate_liquidity_out_asset_a as Oi,calculate_liquidity_out_asset_b as Ai}from"@galacticcouncil/math-xyk";var X=class{static getSpotPrice(t,e,n){return Ti(t,e,n)}static calculateInGivenOut(t,e,n){return Pi(t,e,n)}static calculateOutGivenIn(t,e,n){return fi(t,e,n)}static calculatePoolTradeFee(t,e,n){return Si(t,e,n)}static calculateLiquidityIn(t,e,n){return wi(t,e,n)}static calculateSpotPrice(t,e){return Ii(t,e)}static calculateSpotPriceWithFee(t,e,n,r){return vi(t,e,n,r)}static calculateShares(t,e,n){return xi(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,r){return Oi(t,e,n,r)}static calculateLiquidityOutAssetB(t,e,n,r){return Ai(t,e,n,r)}};var{FeeUtils:dn}=v,Dt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,r,i){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:r.decimals,decimalsOut:i.decimals,balanceIn:r.balance,balanceOut:i.balance,assetInEd:r.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(r,n),a=dn.toPct(n.exchangeFee),s=r+i,o=[];(e<this.minTradingLimit||r<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:r,amountOut:e,feePct:a,errors:o}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(r,n),a=dn.toPct(n.exchangeFee),s=r-i,o=[];(e<this.minTradingLimit||r<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:r,amountOut:s,feePct:a,errors:o}}calculateInGivenOut(t,e){let n=X.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}calculateOutGivenIn(t,e){let n=X.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),r=BigInt(n);return r<0n?0n:r}spotPriceInGivenOut(t){let e=X.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=X.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=X.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};import{CompatibilityLevel as Bi}from"polkadot-api";import{of as _i}from"rxjs";var Mt=class extends N{async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),r=e.map(async({keyArgs:i,value:a})=>{let[s]=i,[o,l]=a,[c,m,d,p]=await Promise.all([this.getBalance(s,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(s,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:s,type:"XYK",tokens:[{id:o,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:c.transferable,type:m?.asset_type.type},{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:d.transferable,type:p?.asset_type.type}],...n}});return Promise.all(r)}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}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 getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}getPoolType(){return"XYK"}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Bi.BackwardsCompatible,e)}subscribePoolChange(t){return _i(t)}};var Be={};w(Be,{AavePool:()=>Lt,AavePoolClient:()=>qt});var Lt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,r,i){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=r,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(a=>[a.id,a])),r=n.get(t),i=n.get(e);if(r==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:r.balance,balanceOut:i.balance,decimalsIn:r.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let r=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,n){let r=this.calculateOutGivenIn(t,e),i=[];return r>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:i}}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 Ri}from"polkadot-api";import{toHex as Fi}from"@polkadot-api/utils";import{map as ki,merge as Ei,switchMap as Ci}from"rxjs";import{decodeEventLog as Di}from"viem";var gn=[{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:Mi}=st,Li=["Supply","Withdraw","Repay","Borrow"],qt=class extends N{async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:r,liqudity_in:i,liqudity_out:a})=>{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(r),this.api.query.AssetRegistry.AssetLocations.getValue(r)]);return{address:this.getPoolId(n,r),type:"Aave",tokens:[{id:n,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:i,location:o,type:s?.asset_type.type},{id:r,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:a,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:r,liqudity_out:i}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(a=>{let s=a.id===e.id?r:i;return{...a,balance:s}})}getPoolId(t,e){let n=t+"/"+e,r=new TextEncoder().encode(n.padEnd(32,"\0")),i=Fi(r);return Ri(63).dec(i)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async getPoolFees(t,e){return{}}getPoolType(){return"Aave"}async isSupported(){return!0}subscribePoolChange(t){let[e,n]=t.tokens,r=this.getReserveH160Id(e),i=this.api.event.Router.Executed.watch(({asset_in:s,asset_out:o})=>s===n.id||o===n.id),a=this.api.event.EVM.Log.watch(({log:s})=>{let{topics:o,data:l}=s,c=o.map(g=>g.asHex()),m=l.asHex(),{eventName:d,args:p}=Di({abi:gn,topics:c,data:m});return Li.includes(d)&&p.reserve.toLowerCase()===r.toLowerCase()});return Ei([i,a]).pipe(Ci(()=>this.getPoolDelta(t)),ki(s=>({...t,tokens:[...s]})))}getReserveH160Id(t){return t.type==="Erc20"?tt.findNestedKey(t.location,"AccountKey20").AccountKey20.key:Mi.fromAssetId(t.id)}};var pt=class{static get(t){switch(t.type){case"Aave":return Lt.fromPool(t);case"XYK":return Dt.fromPool(t);case"Omnipool":return Ft.fromPool(t);case"LBP":return Bt.fromPool(t);case"Stableswap":return Et.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{Subject as qi,Subscription as Nt,takeUntil as Ni}from"rxjs";var dt=class extends R{evm;lbpClient;omniClient;stableClient;xykClient;aaveClient;active=new Set([]);clients=[];pools=new Map([]);lbpSub=Nt.EMPTY;omniSub=Nt.EMPTY;stableSub=Nt.EMPTY;xykSub=Nt.EMPTY;aaveSub=Nt.EMPTY;isReady=!1;isDestroyed=new qi;constructor(t,e){super(t),this.evm=e,this.lbpClient=new Rt(t,e),this.omniClient=new kt(t,e),this.stableClient=new Ct(t,e),this.xykClient=new Mt(t,e),this.aaveClient=new qt(t,e),this.clients=[this.lbpClient,this.omniClient,this.stableClient,this.xykClient,this.aaveClient]}subscribe(t){return t.getSubscriber().pipe(Ni(this.isDestroyed)).subscribe(e=>{this.pools.set(e.address,e)})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omniClient),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableClient),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbpClient),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aaveClient),this.active.add("Aave"),this}withXyk(t){return this.xykClient.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xykClient),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(t={}){if(this.active.size===0)throw new Error("No pools selected");if(this.isReady)return Array.from(this.pools.values());let{useOnly:e=[],exclude:n=[]}=t,r=new Set(e),i=new Set(n),a=async s=>{let o=s.getPoolType();return r.size>0?r.has(o):i.size>0?!i.has(o):s.isSupported()};return this.getFilteredPools(a)}async getFilteredPools(t){let e=await Promise.all(this.clients.map(t)),n=this.clients.filter((i,a)=>e[a]);return(await Promise.all(n.map(i=>i.getPoolsMem()))).flat()}async getPoolFees(t,e){let n=this.clients.find(r=>r.getPoolType()===t.type);if(n)return n.getPoolFees(t,e);throw new xt(t.type)}};var Sn={};w(Sn,{DEFAULT_BLOCK_TIME:()=>hn,DEFAULT_MIN_BUDGET:()=>Fe,ORDER_MIN_BLOCK_PERIOD:()=>Pn,Router:()=>gt,TWAP_BLOCK_PERIOD:()=>Wt,TWAP_MAX_DURATION:()=>Ee,TWAP_MAX_PRICE_IMPACT:()=>ke,TWAP_TX_MULTIPLIER:()=>Qu,TradeOrderError:()=>Re,TradeOrderType:()=>re,TradeRouteBuilder:()=>G,TradeRouter:()=>yt,TradeScheduler:()=>bt,TradeType:()=>ne});var Gt=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 Gi=8,Ut=class{isNotVisited(t,e){let n=!0;return e.forEach(r=>{(r[0]===t[0]||r[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let r=[],i=new Gt,a=[];for(a.push([e,""]),i.enqueue(a);i.size()>0;){let s=i.dequeue();if(!s||s.length>Gi)continue;let o=s[s.length-1];(n===null||o[0]===n)&&r.push(s),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,s)){let m=[...s];m.push(c),i.enqueue(m)}})}return r}findShortestPaths(t,e,n){let r=[],i=new Gt,a=[];a.push([e,""]),i.enqueue(a);let s=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<s?(s=o.length,r.length=0,r.push(o)):o.length===s&&r.push(o);continue}let c=t.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&i.enqueue([...o,m])}return r}buildAndPopulateGraph(t,e){let n=new Map;for(let r of t)n.set(parseInt(r),[]);for(let[r,i,a]of e)n.get(i)?.push([a,r]);return n}};function _e(u){let t={};for(let e of u){let n=e.tokens.length;for(let r=0;r<n;r++){t[e.tokens[r].id]||(t[e.tokens[r].id]=[]);for(let i=0;i<n;i++){if(r==i)continue;let a=[e.address,e.tokens[r].id,e.tokens[i].id];t[e.tokens[r].id].push(a)}}}return t}var Vt=class{getProposals(t,e,n){let r=n.filter(y=>y.type==="XYK"),i=n.filter(y=>y.type!=="XYK"),a=new Set(i.map(y=>y.tokens).flat().map(y=>y.id)),s=a.has(t),o=a.has(e),l=new Ut,c=y=>{let h=_e(y),P=Object.keys(h),S=P.flatMap(T=>h[T]);return l.buildAndPopulateGraph(P,S)};if(!s&&!o){let y=r.filter(S=>S.tokens.find(T=>T.id===t)||S.tokens.find(T=>T.id===e)),h=c(y),P=l.findPaths(h,t,e);return this.parsePaths(P)}if(s&&o){let y=c(i),h=l.findPaths(y,t,e);return this.parsePaths(h)}let m=s?e:t,d=r.filter(y=>y.tokens.some(h=>h.id===m));if(d.length===0)return[];let p=[...i,...d],g=c(p),b=l.findPaths(g,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let n of t){let r=[];for(let i=0;i<n.length;i++){let a=n[i],s=n[i+1];if(s==null)break;r.push(this.toEdge(a,s))}e.push(r)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var gt=class{routeSuggester;routeProposals;routerOptions;ctx;constructor(t,e={}){this.ctx=t,this.routeSuggester=new Vt,this.routeProposals=new Map,this.routerOptions=Object.freeze(e)}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}async getPools(){return this.ctx.getPools(this.routerOptions)}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(r=>r!==t).map(r=>this.getRoutes(r,t)))).filter(r=>r.length>0).map(([r])=>r[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 r=this.getAssets(n);if(!r.has(t))throw new Error(t+" is not supported asset");if(!r.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(r=>r.id)).flat().sort((n,r)=>n>r?1:-1);return new Set(e)}getPaths(t,e,n){let r=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(a=>this.validPath(a,r)).map(a=>this.toHops(a,r))}getProposals(t,e,n){let r=this.buildRouteKey(t,e,n);if(this.routeProposals.has(r))return this.routeProposals.get(r);let i=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(r,i),i}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,r)=>n&&r)}validEdge([t,e,n],r){return r.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,pt.get(e)]))}toHops(t,e){return t.map(([n,r,i])=>{let a=e.get(n);return{poolAddress:n,poolId:a?.id,pool:a?.type,assetIn:r,assetOut:i}})}};var ne=(e=>(e.Buy="Buy",e.Sell="Sell",e))(ne||{}),re=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(re||{}),Re=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Re||{});var{FeeUtils:bn}=v,yt=class extends gt{mlr;poolsSnapshot;constructor(t,e={}){super(t,e),this.mlr=new Map}buildCtxSync(t,e){let n=this.poolsSnapshot,r=super.validateInput(t,e,n),i=super.getPaths(t,e,n);if(!i.length)throw new It(t,e);return{paths:i,pools:n,poolsMap:r}}async withCtx(t,e,n){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let r=this.buildCtxSync(t,e);return n(r)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,r)=>{let i=n[n.length-1].amountOut,a=r[r.length-1].amountOut;return i>a?-1:1});return e.find(n=>n.every(r=>r.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,a)=>i+a),r=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,a)=>i+a);return[n,r]}}getPoolFeeRange(t){let e=t.min?bn.toPct(t.min):void 0,n=t.max?bn.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),r=t.map(s=>s.spotPrice).reduce((s,o)=>s*o),i=n-e.assetOutDecimals,a=Math.pow(10,i);return r/BigInt(a)}async getSell(t,e,n,r){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let s;if(r)s=await this.toSellSwaps(n,r,a);else{let o=i.map(c=>this.toSellSwaps(n,c,a)),l=await Promise.all(o);s=this.findBestSellRoute(l)}return this.buildSell(a,s)})}buildSell(t,e){let n=e[0],r=e[e.length-1],i=this.isDirectTrade(e),a=this.getSellSpot(e),s=r.amountOut,o=i?r.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-s,c=this.getRouteFeeRange(e),m=i?r.tradeFeePct:O.calculateSellFee(o,s),d=Math.pow(10,n.assetInDecimals),p=n.amountIn*a/BigInt(d),g=O.calculateDiffToRef(o,p);return{type:"Sell",amountIn:n.amountIn,amountOut:r.amountOut,spotPrice:a,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Sell",amountIn:f.toDecimal(n.amountIn,n.assetInDecimals),amountOut:f.toDecimal(r.amountOut,r.assetOutDecimals),spotPrice:f.toDecimal(a,r.assetOutDecimals),tradeFee:f.toDecimal(l,r.assetOutDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0Y(t,e,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i>0?l=r[i-1]:l=t;let c=s.calculateOutGivenIn(o,l);r.push(c)}return r[r.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:r,pools:i,poolsMap:a}=n,l=i.filter(b=>b.tokens.some(y=>y.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(y=>y.id===t)).map(b=>b.map(y=>y.balance).reduce((y,h)=>y+h)).sort((b,y)=>y<b?-1:1)[0],c=O.getFraction(l,.1),m=await Promise.all(r.map(b=>this.toSellSwaps(c,b,a))),p=this.findBestSellRoute(m).map(b=>({poolAddress:b.poolAddress,poolId:b?.poolId,pool:b.pool,assetIn:b.assetIn,assetOut:b.assetOut})),g=this.buildRouteKey(t,e,i);return this.mlr.set(g,p),p}async toSellSwaps(t,e,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i>0?l=r[i-1].amountOut:l=typeof t=="string"?f.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(s,o.assetOut),{amountOut:m,calculatedOut:d,feePct:p,errors:g}=s.validateAndSell(o,l,c),b=this.getPoolFeeRange(c),y=s.spotPriceOutGivenIn(o),h=Math.pow(10,o.decimalsIn),P=l*y/BigInt(h),S=O.calculateDiffToRef(d,P);r.push({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:d,spotPrice:y,tradeFeePct:p,tradeFeeRange:b,priceImpactPct:S,errors:g,isSupply(){return s.type==="Aave"&&s.tokens[0].id===a.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===a.assetIn},toHuman(){return{...a,amountIn:f.toDecimal(l,o.decimalsIn),amountOut:f.toDecimal(m,o.decimalsOut),calculatedOut:f.toDecimal(d,o.decimalsOut),spotPrice:f.toDecimal(y,o.decimalsOut),tradeFeePct:p,tradeFeeRange:b,priceImpactPct:S,errors:g}}})}return r}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let r=this.buildRouteKey(t,e,n.pools),i=this.mlr.get(r);return i||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:r,poolsMap:i}=n,a=this.buildRouteKey(t,e,r),s=this.mlr.get(a);s||(s=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",s,i),l=this.getSellSpot(o),c=o[o.length-1].assetOutDecimals;return{amount:l,decimals:c}})}findBestBuyRoute(t){let e=t.sort((n,r)=>{let i=n[0].amountIn,a=r[0].amountIn;return i>a?1:-1});return e.find(n=>n.every(r=>r.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),r=t.map(s=>s.spotPrice).reduce((s,o)=>s*o),i=n-e.assetInDecimals,a=Math.pow(10,i);return r/BigInt(a)}async getBuy(t,e,n,r){return this.withCtx(t,e,async({paths:i,poolsMap:a})=>{let s;if(r)s=await this.toBuySwaps(n,r,a);else{let o=i.map(c=>this.toBuySwaps(n,c,a)),l=await Promise.all(o);s=this.findBestBuyRoute(l)}return this.buildBuy(a,s)})}buildBuy(t,e){let n=e[e.length-1],r=e[0],i=this.isDirectTrade(e),a=this.getBuySpot(e),s=r.amountIn,o=i?r.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=s-o,c=this.getRouteFeeRange(e),m=i?r.tradeFeePct:O.calculateBuyFee(o,s),d=Math.pow(10,n.assetOutDecimals),p=n.amountOut*a/BigInt(d),g;return o===0n?g=-100:g=O.calculateDiffToRef(p,o),{type:"Buy",amountOut:n.amountOut,amountIn:r.amountIn,spotPrice:a,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e,toHuman(){return{type:"Buy",amountOut:f.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:f.toDecimal(r.amountIn,r.assetInDecimals),spotPrice:f.toDecimal(a,r.assetInDecimals),tradeFee:f.toDecimal(l,r.assetInDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0X(t,e,n){let r=[];for(let i=e.length-1;i>=0;i--){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=t:l=r[0];let c=s.calculateInGivenOut(o,l);r.unshift(c)}return r[0]}async toBuySwaps(t,e,n){let r=[];for(let i=e.length-1;i>=0;i--){let a=e[i],s=n.get(a.poolAddress);if(s==null)throw new Error("Pool does not exit");let o=s.parsePair(a.assetIn,a.assetOut),l;i==e.length-1?l=typeof t=="string"?f.toBigInt(t,o.decimalsOut):t:l=r[0].amountIn;let c=await this.ctx.getPoolFees(s,o.assetOut),{amountIn:m,calculatedIn:d,feePct:p,errors:g}=s.validateAndBuy(o,l,c),b=this.getPoolFeeRange(c),y=s.spotPriceInGivenOut(o),h=Math.pow(10,o.decimalsOut),P=l*y/BigInt(h),S;d===0n?S=-100:S=O.calculateDiffToRef(P,d),r.unshift({...a,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:m,calculatedIn:d,spotPrice:y,tradeFeePct:p,tradeFeeRange:b,priceImpactPct:S,errors:g,isSupply(){return s.type==="Aave"&&s.tokens[0].id===a.assetIn},isWithdraw(){return s.type==="Aave"&&s.tokens[1].id===a.assetIn},toHuman(){return{...a,amountOut:f.toDecimal(l,o.decimalsOut),amountIn:f.toDecimal(m,o.decimalsIn),calculatedIn:f.toDecimal(d,o.decimalsIn),spotPrice:f.toDecimal(y,o.decimalsIn),tradeFeePct:p,tradeFeeRange:b,priceImpactPct:S,errors:g}}})}return r}};var hn=6e3,Fe=1000000000000000n,Wt=6,ke=-5,Ee=216e5,Qu=3,Pn=6;import{Enum as fn}from"polkadot-api";var G=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:r,poolId:i})=>r==="Stableswap"?{pool:fn("Stableswap",i),asset_in:e,asset_out:n}:{pool:fn(r),asset_in:e,asset_out:n})}};var bt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Fe})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,r,i){let[a,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:c}=s,m=l[0],d=l[l.length-1],{assetInDecimals:p}=m,{assetOutDecimals:g}=d,b=Math.abs(c),y=this.getMinimumTradeCount(o,a),h=this.getOptimalTradeCount(b),P=i?Math.round(r/i):h,S=Math.ceil(r/y),T=Math.round(r/h),F=Math.round(r/P),k=o/BigInt(P),B=await this.router.getBestSell(t,e,k),C=o<a,U=[];C&&U.push("OrderTooSmall");let D=B.amountOut*BigInt(P),W=this.toBlockPeriod(F),K=B.tradeFee*BigInt(P),J=G.build(l),ft={assetIn:t,assetOut:e,errors:U,frequencyMin:S,frequencyOpt:T,frequency:F,tradeCount:P,tradeFee:K,tradeImpactPct:B.priceImpactPct,tradePeriod:W,tradeRoute:J,type:"Dca"};return{...ft,amountIn:o,amountOut:D,tradeAmountIn:B.amountIn,tradeAmountOut:B.amountOut,toHuman(){return{...ft,amountIn:f.toDecimal(o,p),amountOut:f.toDecimal(D,g),tradeAmountIn:f.toDecimal(B.amountIn,p),tradeAmountOut:f.toDecimal(B.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 r=t+n/2n;return Number(r/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[r,i]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:a,swaps:s,priceImpactPct:o}=i,l=s[0],c=s[s.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,p=Math.abs(o),g=this.getTwapTradeCount(p),b=a/BigInt(g),y=await this.router.getBestSell(l.assetIn,c.assetOut,b),h=g===1,P=a<r,S=y.priceImpactPct<-5,T=[];P||h?T.push("OrderTooSmall"):S&&T.push("OrderImpactTooBig");let F=y.amountOut*BigInt(g),k=y.tradeFee*BigInt(g),B=G.build(s),C={assetIn:t,assetOut:e,errors:T,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:B,type:"TwapSell"};return{...C,amountIn:a,amountOut:F,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...C,amountIn:f.toDecimal(a,m),amountOut:f.toDecimal(F,d),tradeAmountIn:f.toDecimal(y.amountIn,m),tradeAmountOut:f.toDecimal(y.amountOut,d),tradeFee:f.toDecimal(k,d)}}}}async getTwapBuyOrder(t,e,n){let[r,i]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:a,swaps:s,priceImpactPct:o}=i,l=s[0],c=s[s.length-1],{assetInDecimals:m}=l,{assetOutDecimals:d}=c,p=Math.abs(o),g=this.getTwapTradeCount(p),b=a/BigInt(g),y=await this.router.getBestBuy(l.assetIn,c.assetOut,b),h=y.amountIn*BigInt(g),P=g===1,S=h<r,T=y.priceImpactPct<-5,F=[];S||P?F.push("OrderTooSmall"):T&&F.push("OrderImpactTooBig");let k=y.tradeFee*BigInt(g),B=G.build(s),C={assetIn:t,assetOut:e,errors:F,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:6,tradeRoute:B,type:"TwapBuy"};return{...C,amountIn:h,amountOut:a,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:k,toHuman(){return{...C,amountIn:f.toDecimal(h,m),amountOut:f.toDecimal(a,d),tradeAmountIn:f.toDecimal(y.amountIn,m),tradeAmountOut:f.toDecimal(y.amountOut,d),tradeFee:f.toDecimal(k,m)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let r=216e5/(this.blockTime*6);return Math.round(r)}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 xn={};w(xn,{BIG_10:()=>wn,BIG_BILL:()=>De,StakingApi:()=>Ht,StakingClient:()=>Yt});import{encodeAddress as Ui}from"@polkadot/util-crypto";import{stringToU8a as Vi}from"@polkadot/util";import{calculate_accumulated_rps as Wi,calculate_percentage_amount as Hi,calculate_period_number as Tn,calculate_points as Yi,calculate_rewards as Xi,sigmoid as Ki}from"@galacticcouncil/math-staking";import q from"big.js";var Ce={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},zi=u=>Object.keys(Ce).includes(u),ji="20000000000000000",$i="2000",wn=q(10),De=q(wn.pow(12));function Qi(u){return Ui(Vi(("modl"+u).padEnd(32,"\0")),63)}var Ht=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getFreePotBalance(){let t=await this.client.getPalletId(),e=Qi(t);return(await this.balanceClient.getBalance(e,0)).transferable}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let r=e.created_at,i=await n.reduce(async(a,[s,o])=>{let l=await a,c=s,m=o.amount,d=o.conviction.toString().toLowerCase(),p=await this.client.getReferendumInfo(c);return p&&(p.type==="Approved"||p.type==="Rejected")&&zi(d)&&l.push({id:c,amount:m,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:r,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:i}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,r]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),i=r.find(a=>a)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:i,stakePosition:i?await this.getStakingPosition(i):void 0}}getCurrentActionPoints(t,e,n,r){let i=q(0),a=q(0),s=Ce.locked6x,o=q(n.toString()).mul(s),l=100,c=[];t.forEach(p=>{let g=Ce[p.conviction],b=r.includes(p.id.toString());b&&c.push(p.id.toString());let y=q(p.amount.toString()).mul(l).div(o);i=i.plus(Math.floor(y.mul(g).toNumber())),a=a.plus(Math.floor(y.mul(b?s:g).toNumber()))});let m=Math.floor(q(n.toString()).mul(s).mul(l).div(o).toNumber());r.forEach(p=>{c.includes(p)||(a=a.plus(m))});let d={democracyVote:1};return i=i.mul(d.democracyVote),i=i.plus(e.toString()||"0"),a=a.mul(d.democracyVote),a=a.plus(e.toString()||"0"),{currentActionPoints:i.toString(),maxActionPoints:a.toString()}}async getRewards(t,e,n){let r=await this.getStake(t),{potReservedBalance:i,accumulatedRewardPerStake:a,totalStake:s,stakePosition:o}=r;if(!o)return;let[l,c,m,d,p,g,b]=await Promise.all([this.getFreePotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),y=q(l.toString()).minus(i.toString()),h=y.gt(0)&&s>0?Wi(a.toString(),y.toString(),s.toString()):a.toString(),P=Tn(c.toString(),n,b),S=Tn(c.toString(),o.createdAt.toString(),b),T=Xi(h,o.rewardPerStake.toString(),o.stake.toString()),F=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),k=Yi(S,P,d.toString(),p.toString(),F.currentActionPoints,g.toString(),o.accumulatedSlashPoints.toString()),B=q(k).div(2).toString(),C=Ki(B,ji,$i),U=q(T).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if(q(P).minus(S).lte(m.toString()))return{rewards:"0"};let D=Hi(U.toString(),C),W=q(o.accumulatedLockedRewards.toString()),K=W.gt(D)?W:q(D);return{rewards:K.div(De).toString(),maxRewards:U.div(De).toString(),allocatedRewardsPercentage:K.div(U).mul(100).toNumber()}}};var Yt=class extends R{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:a})=>{let[s,o,l]=a;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 On={};w(On,{TxBuilderFactory:()=>Pt});import{Enum as vn}from"polkadot-api";function In(u){let t=[],e=u;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var ht=class extends R{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new H(t),this.aaveUtils=new et(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:me})}async dryRun(t,e){let n=vn("Signed",t),r=vn("system",n),a=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(r,e.decodedCall),s=a.success&&!a.value.execution_result.success?a.value.execution_result.value.error:null;if(s){let o=In(s.value);throw new Error("Dry run execution error!",{cause:o})}return a}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var ie=class extends ht{_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:r}=e[0],i=await this.balanceClient.getBalance(this.beneficiary,r);return t>=i.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,r=n[0],i=n[n.length-1],a=O.getFraction(t,this.slippagePct),s=r.assetIn,o=i.assetOut,l=t+a,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)}),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,r=n[0],i=n[n.length-1],a=O.getFraction(e,this.slippagePct),s=r.assetIn,o=i.assetOut,l=e-a,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)}),r.isWithdraw()&&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],r=e[e.length-1],i=O.getFraction(t,this.slippagePct),a=n.assetIn,s=r.assetOut,o=t-i,l=this.api.tx.Router.sell_all({asset_in:a,asset_out:s,min_amount_out:o,route:G.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};import{Enum as Me}from"polkadot-api";var se=class extends ht{_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:r,tradePeriod:i,tradeRoute:a}=this.order,s=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:Me("Sell",{asset_in:e,asset_out:n,amount_in:r,min_amount_out:0n,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",s)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:r,tradeAmountOut:i,tradePeriod:a,tradeRoute:s}=this.order,o=O.getFraction(i,this.slippagePct),l=i-o,c=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:Me("Sell",{asset_in:e,asset_out:n,amount_in:r,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:r,tradeAmountOut:i,tradePeriod:a,tradeRoute:s}=this.order,o=O.getFraction(r,this.slippagePct),l=r+o,c=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:Me("Buy",{asset_in:e,asset_out:n,amount_out:i,max_amount_in:l,route:s})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",c)}};var Pt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new ie(this.client,this.evmClient).setTrade(t)}order(t){return new se(this.client,this.evmClient).setOrder(t)}};async function ap(u){let t=new ct(u),e=new vt(u),[n,r]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),i=new dt(u,e).withAave().withOmnipool().withStableswap().withXyk(),a=new H(u),s=new Yt(u),o=new At(u),l=new et(e),c=new yt(i),m=new bt(c,{blockTime:n,minBudgetInNative:r}),d=new Ht(s,a),p=new Ot(o,a,{blockTime:n});return{api:{aave:l,router:c,scheduler:m,staking:d,farm:p},client:{asset:new ot(u),balance:a,evm:e},ctx:{pool:i},tx:new Pt(u,e),destroy:()=>{i.destroy()}}}export{Ye as aave,qe as api,f as big,ze as client,Ne as const,ap as createSdkContext,st as erc20,je as error,Je as evm,sn as farm,v as fmt,Qt as h160,tt as json,O as math,yn as pool,Sn as sor,xn as staking,On as tx,He as xc};
|
|
@@ -52,7 +52,11 @@ export declare class AaveUtils {
|
|
|
52
52
|
* @returns aTokens max withdrawable balances
|
|
53
53
|
*/
|
|
54
54
|
getMaxWithdrawAll(user: string): Promise<Record<number, Amount>>;
|
|
55
|
-
|
|
56
|
-
|
|
55
|
+
/**
|
|
56
|
+
* Calculate maxWithdraw using following formula:
|
|
57
|
+
*
|
|
58
|
+
* maxWithdraw = (HF - 1.01 x totalDebt) / reserveLT
|
|
59
|
+
*/
|
|
57
60
|
private calculateWithdrawMax;
|
|
61
|
+
private calculateLinearInterest;
|
|
58
62
|
}
|
|
@@ -26,7 +26,6 @@ export type Farm = {
|
|
|
26
26
|
minApr: string | undefined;
|
|
27
27
|
isDistributed: boolean;
|
|
28
28
|
estimatedEndPeriod: string;
|
|
29
|
-
estimatedEndBlock: string;
|
|
30
29
|
maxRewards: bigint;
|
|
31
30
|
incentivizedAsset: number;
|
|
32
31
|
rewardCurrency: number;
|
|
@@ -37,6 +36,4 @@ export type Farm = {
|
|
|
37
36
|
yieldFarmId: number;
|
|
38
37
|
globalFarmId: number;
|
|
39
38
|
poolId: string;
|
|
40
|
-
distributedRewards: bigint;
|
|
41
|
-
plannedYieldingPeriods: number;
|
|
42
39
|
};
|