@galacticcouncil/sdk-next 0.10.0-pr206-70b5b04 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/build/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var Ms=Object.create;var ye=Object.defineProperty;var Ls=Object.getOwnPropertyDescriptor;var qs=Object.getOwnPropertyNames;var Ns=Object.getPrototypeOf,Us=Object.prototype.hasOwnProperty;var Ln=(c,t)=>()=>(c&&(t=c(c=0)),t);var I=(c,t)=>{for(var e in t)ye(c,e,{get:t[e],enumerable:!0})},be=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of qs(t))!Us.call(c,s)&&s!==e&&ye(c,s,{get:()=>t[s],enumerable:!(n=Ls(t,s))||n.enumerable});return c},wt=(c,t,e)=>(be(c,t,"default"),e&&be(e,t,"default")),ot=(c,t,e)=>(e=c!=null?Ms(Ns(c)):{},be(t||!c||!c.__esModule?ye(e,"default",{value:c,enumerable:!0}):e,c)),Vs=c=>be(ye({},"__esModule",{value:!0}),c);var Nt={};var Un=Ln(()=>{wt(Nt,require("@polkadot-api/ws-provider/node"))});var Ut={};var Vn=Ln(()=>{wt(Ut,require("@polkadot-api/ws-provider/web"))});var vi={};I(vi,{QueryBus:()=>Yt,aave:()=>ln,api:()=>Ye,big:()=>S,client:()=>cn,const:()=>Je,createSdkContext:()=>Si,erc20:()=>yt,error:()=>pn,evm:()=>dn,farm:()=>yn,fmt:()=>B,h160:()=>Wt,json:()=>mt,math:()=>_,pool:()=>Tn,sor:()=>Rn,staking:()=>En,tx:()=>Cn,xc:()=>sn});module.exports=Vs(vi);var Ye={};I(Ye,{Papi:()=>N,getWs:()=>Gs});var Nn=require("@galacticcouncil/descriptors");function qn(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var N=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi(Nn.hydration)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");qn(n)&&console.log(t,...e)}};var Gn=require("polkadot-api"),Wn=require("polkadot-api/polkadot-sdk-compat"),Gs=async c=>{let t=typeof c=="string"?c.split(","):c,s=(typeof window>"u"?(await Promise.resolve().then(()=>(Un(),Nt))).getWsProvider:(await Promise.resolve().then(()=>(Vn(),Ut))).getWsProvider)(t);return(0,Gn.createClient)((0,Wn.withPolkadotSdkCompat)(s))};var ln={};I(ln,{AAVE_GAS_LIMIT:()=>Ke,AAVE_LENDING_POOL_ADDRESS:()=>Se,AAVE_POOL_ABI:()=>ze,AAVE_POOL_DATA_PROVIDER:()=>Pe,AAVE_POOL_DATA_PROVIDER_ABI:()=>fe,AAVE_POOL_PROXY:()=>Xe,AAVE_ROUNDING_THRESHOLD:()=>Li,AAVE_UINT_256_MAX:()=>Ws,AaveClient:()=>Vt,AaveUtils:()=>Pt});var ze=[{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 fe=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Xe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Pe="0x112b087b60C1a166130d59266363C45F8aa99db0",Se="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ke=1000000n,Li=5,Ws=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var Vt=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:fe,address:Pe,args:[Se],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:fe,address:Pe,args:[Se,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ze,address:Xe,args:[t],functionName:"getUserAccountData"})}};var ct=ot(require("big.js"));var S={};I(S,{asBigInt:()=>zs,toBigInt:()=>Ys,toDecimal:()=>Hs});var pt=ot(require("big.js"));pt.default.NE=-18;function Hs(c,t,e=6,n){let s=(0,pt.default)(c.toString()),i=(0,pt.default)(10).pow(t);return s.div(i).round(e,n).toString()}function Ys(c,t){let e=(0,pt.default)(10).pow(t),s=(0,pt.default)(c).mul(e).toFixed(0,pt.default.roundDown);return BigInt(s)}function zs(c){return BigInt(c.round(0,pt.default.roundDown).toFixed(0))}var yt={};I(yt,{ERC20:()=>je});var je=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 B={};I(B,{FeeUtils:()=>Ze,shiftNeg:()=>js});var Hn=ot(require("big.js"));var Je={};I(Je,{HUB_ASSET_ID:()=>Gt,HYDRATION_OMNIPOOL_ADDRESS:()=>Ks,HYDRATION_PARACHAIN_ID:()=>Xs,HYDRATION_SS58_PREFIX:()=>H,PERBILL_DENOMINATOR:()=>$e,PERMILL_DENOMINATOR:()=>Tt,RUNTIME_DECIMALS:()=>F,SYSTEM_ASSET_DECIMALS:()=>Qe,SYSTEM_ASSET_ID:()=>E,TRADEABLE_DEFAULT:()=>xt});var F=18,Tt=1e6,$e=1e9,E=0,Qe=12,Xs=2034,H=63,Ks="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Gt=1,xt=15;var Ze=class c{static toPct(t){let[e,n]=t;return c.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return c.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 s=10**n;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function js(c,t){let e=(0,Hn.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Wt={};I(Wt,{H160:()=>nn,isEvmAccount:()=>Yn,isEvmAddress:()=>zn,isSs58Address:()=>Xn});var It=require("polkadot-api"),tn=require("@polkadot-api/utils"),lt=require("buffer");var en="ETH\0";function Yn(c){if(!c)return!1;try{let t=(0,It.AccountId)().enc(c),e=lt.Buffer.from(en);return lt.Buffer.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function zn(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function Xn(c){try{return(0,It.AccountId)(63).enc(c),!0}catch{return!1}}var nn=class c{static toAccount=t=>{let e=lt.Buffer.from(t.slice(2),"hex"),n=lt.Buffer.from(en),s=Uint8Array.from(lt.Buffer.concat([n,e,lt.Buffer.alloc(8)])),i=(0,tn.toHex)(s);return(0,It.AccountId)(63).dec(i)};static fromAccount=t=>{let e=(0,It.AccountId)().enc(t),n=lt.Buffer.from(en),s=e.slice(n.length,-8);return"0x"+lt.Buffer.from(s).toString("hex")};static fromSS58=t=>{let n=(0,It.AccountId)().enc(t).slice(0,20);return(0,tn.toHex)(n)};static fromAny=t=>{if(zn(t))return t;if(Yn(t))return c.fromAccount(t);if(Xn(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var mt={};I(mt,{findNestedKey:()=>$s,findNestedObj:()=>Qs,jsonFormatter:()=>Js});var $s=(c,t)=>{let e=[];return JSON.stringify(c,(n,s)=>(s&&s[t]&&e.push(s),s)),e[0]},Qs=(c,t,e)=>{let n;return JSON.stringify(c,(s,i)=>(i&&i[t]===e&&(n=i),i)),n},Js=(c,t)=>typeof t=="bigint"?t.toString():t;var _={};I(_,{calculateBuyFee:()=>ni,calculateDiffToAvg:()=>Zs,calculateDiffToRef:()=>ti,calculateSellFee:()=>ei,getFraction:()=>si});var nt=ot(require("big.js"));function Zs(c,t){let e=(0,nt.default)(c.toString()),n=(0,nt.default)(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function ti(c,t){if(t===0n)return 0;let e=(0,nt.default)(c.toString()),n=(0,nt.default)(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function ei(c,t){let e=(0,nt.default)(c.toString()),n=(0,nt.default)(t.toString());return(0,nt.default)(1).minus(n.div(e)).mul(100).round(2).toNumber()}function ni(c,t){let e=(0,nt.default)(c.toString());return(0,nt.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function si(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),s=BigInt(t*n);return c*s/BigInt(100*n)}var sn={};I(sn,{convertToId:()=>ii});var Kn=require("buffer");function ii(c){let e=Kn.Buffer.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var Ht=(c,t)=>c===t?0:c==null?t==null?0:-1:t==null?c==null?0:1:typeof c.compare=="function"?c.compare(t):typeof t.compare=="function"?-t.compare(c):c<t?-1:c>t?1:0;var ve=(c,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(c(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var ri=ve(()=>"illegal argument(s)"),jn=c=>{throw new ri(c)};var ai=ve(()=>"index out of bounds"),rn=c=>{throw new ai(c)},we=(c,t,e)=>(c<t||c>=e)&&rn(c);var $n=23283064365386963e-26,Te=class{float(t=1){return this.int()*$n*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*$n-.5)*2*t}normMinMax(t,e){let n=this.minmax(t,e);return this.float()<.5?n:-n}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let n=(e|0)-t;return n?t+this.int()%n:t}minmaxUint(t,e){t>>>=0;let n=(e>>>0)-t;return n?t+this.int()%n:t}};var xe=class extends Te{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var Qn=new xe(Math.random);var Jn=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var Zn=Object.getPrototypeOf({}),Ie="function",ts="string",_t=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===Ie)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===Ie)return t.equiv(c)}else return c==t;return typeof c===ts||typeof t===ts?!1:(e=Object.getPrototypeOf(c),(e==null||e===Zn)&&(e=Object.getPrototypeOf(t),e==null||e===Zn)?ui(c,t):typeof c!==Ie&&c.length!==void 0&&typeof t!==Ie&&t.length!==void 0?oi(c,t):c instanceof Set&&t instanceof Set?li(c,t):c instanceof Map&&t instanceof Map?ci(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},oi=(c,t,e=_t)=>{let n=c.length;if(n===t.length)for(;n-- >0&&e(c[n],t[n]););return n<0},li=(c,t,e=_t)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),ci=(c,t,e=_t)=>c.size===t.size&&e([...c].sort(),[...t].sort()),ui=(c,t,e=_t)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let n in c)if(!t.hasOwnProperty(n)||!e(c[n],t[n]))return!1;return!0};var an=class{value;constructor(t){this.value=t}deref(){return this.value}};var es=c=>c instanceof an;var _e=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return ns("next",this._head)}reverseIterator(){return ns("prev",this.tail)}clear(){this.release()}compare(t,e=Ht){let n=this._length;if(n<t._length)return-1;if(n>t._length)return 1;if(n===0)return 0;{let s=this._head,i=t._head,r=0;for(;n-- >0&&r===0;)r=e(s.value,i.value),s=s.next,i=i.next;return r}}concat(...t){let e=this.copy();for(let n of t)e.into(n);return e}equiv(t){if(!(t instanceof c||Jn(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),n=this._head;for(let s=this._length;s-- >0;){if(!_t(n.value,e.next().value))return!1;n=n.next}return!0}filter(t){let e=this.empty();return this.traverse(n=>(t(n.value)&&e.append(n.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||Ht;for(let n=this._head,s=this._length;s-- >0;){if(e(t,n.value)<=0)return this.insertBefore(n,t);n=n.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let n=this.nthCell(t);return n?n.value:e}nthCellUnsafe(t){let e,n;for(t<=this._length>>>1?(e=this._head,n="next"):(e=this.tail,n="prev",t=this._length-t-1);t-- >0&&e;)e=e[n];return e}peek(){return this.tail?.value}$reduce(t,e){let n=this._head;for(let s=this._length;s-- >0&&!es(e);)e=t(e,n.value),n=n.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let n=this._length;n-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,n=(this._length>>>1)+(this._length&1);for(;t&&e&&n>0;){let s=t.value;t.value=e.value,e.value=s,t=t.next,e=e.prev,n--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let n=this.nthCell(t);return!n&&rn(t),n.value=e,n}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let n=t.value;t.value=e.value,e.value=n}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,n){if(!this._head)return;let s=e;do{if(!t(s))break;s=s.next}while(s!==n);return s}_map(t,e){return this.traverse(n=>(t.append(e(n.value)),!0)),t}};function*ns(c,t){for(;t;)yield t.value,t=t[c]}var Ae=class c extends _e{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new c}insertAfter(t,e){let n={value:e,next:t.next,prev:t};return t.next?t.next.prev=n:this._tail=n,t.next=n,this._length++,n}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(we(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let n={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=n:this._head=n,t.prev=n,this._length++,n}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(we(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,t)}nth(t,e){let n=this.nthCell(t);return n?n.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let n=this.nthCell(t),s=this.nthCell(e-1),i=r=>({first(){return r.value},next(){return r!==s&&r.next?i(r.next):void 0}});return n?i(n):void 0}shuffle(t,e=Qn){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let n=this._head;for(;n;){let s=n.next;e.probability(.5)?this.asHead(n):this.asTail(n),n=s}}return this}slice(t=0,e=this.length){let n=t<0?t+this._length:t,s=e<0?e+this._length:e;(n<0||s<0)&&jn("invalid indices: ${from} / ${to}");let i=new c,r=this.nthCell(n);for(;r&&++n<=s;)i.push(r.value),r=r.next;return i}sort(t=Ht){if(!this._length)return this;let e=1;for(;;){let n=this._head;this._head=void 0,this._tail=void 0;let s=0;for(;n;){s++;let i=n,r=0;for(let o=0;o<e&&(r++,i=i.next,!!i);o++);let a=e;for(;r>0||a>0&&i;){let o;r===0?(o=i,i=i.next,a--):!i||a===0||t(n.value,i.value)<=0?(o=n,n=n.next,r--):(o=i,i=i.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}n=i}if(this._tail.next=void 0,s<=1)return this;e*=2}}splice(t,e=0,n){let s;typeof t=="number"?(t<0&&(t+=this._length),we(t,0,this._length),s=this.nthCellUnsafe(t)):s=t;let i=new c;if(e>0)for(;s&&e-- >0;)this.remove(s),i.push(s.value),s=s.next;else s&&(s=s.next);if(n)if(s)for(let r of n)this.insertBefore(s,r);else for(let r of n)this.push(r);return i}};var Oe=class c{map;items;opts;_size;constructor(t,e){let n={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=n.map(),this.items=new Ae,this._size=0,this.opts=n,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let n=this.map.get(t);return n?this.resetEntry(n):e}set(t,e){let n=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),i=Math.max(0,n-(s?s.value.s:0));return this._size+=i,this.ensureSize()?this.doSetEntry(s,t,e,n):this._size-=i,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let n=this.map.get(t);return n?this.resetEntry(n):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:n}=this.opts;for(;this._size>e||this.length>=n;){let s=this.items.drop();if(!s)return!1;this.map.delete(s.k),t?.(s.k,s.v),this._size-=s.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,n,s){t?(this.opts.update?.(e,t.value.v,n),t.value.v=n,t.value.s=s,this.items.asTail(t)):(this.items.push({k:e,v:n,s}),this.map.set(e,this.items.tail))}};var ft=class c extends Oe{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let n=this.map.get(t);if(n){if(n.value.t>=Date.now())return this.resetEntry(n);this.removeEntry(n)}return e}set(t,e,n=this.opts.ttl){let s=this.opts.ksize(t)+this.opts.vsize(e),i=this.map.get(t),r=Math.max(0,s-(i?i.value.s:0));return this._size+=r,this.ensureSize()?this.doSetEntry(i,t,e,s,n):this._size-=r,e}async getSet(t,e,n=this.opts.ttl){let s=this.get(t);return s!==void 0?s:this.set(t,await e(),n)}prune(){let t=Date.now(),e=this.items.head,n=0;for(;e;)e.value.t<t&&(this.removeEntry(e),n++),e=e.next;return n}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,n=Date.now(),s=this.items.head;for(;s&&(this._size>e||this.length>=t);)s.value.t<n&&this.removeEntry(s),s=s.next;return super.ensureSize()}doSetEntry(t,e,n,s,i=this.opts.ttl){let r=Date.now()+i;t?(this.opts.update?.(e,t.value.v,n),t.value.v=n,t.value.s=s,t.value.t=r,this.items.asTail(t)):(this.items.push({k:e,v:n,s,t:r,ttl:i}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var Yt=class{debug;constructor(t){this.debug=t||!1}log(t,e,n){this.debug&&console.log(t,e,n)}scope(t,e,n,s){let i=new Map,r=s!==void 0?new ft(null,{ttl:s}):new ft;return{get:(...u)=>{let p=n(...u);if(i.has(p)){this.log("[live]",t,p);let m=i.get(p);return Promise.resolve(m)}if(r.has(p))return this.log("[memo]",t,p),r.get(p);this.log("[fetch]",t,p);let d=e(...u).catch(m=>{throw r.delete(p),m});return r.set(p,d),d},set:(u,...p)=>{let d=n(...p);this.log("[set-live]",t,d),i.set(d,u)},clear:()=>{this.log("[clear]",t),i.clear(),r.release()}}}};var{ERC20:Be}=yt,{H160:on}=Wt,pi=1.01,mi=31536000n,Re=10n**27n,Pt=class{client;constructor(t){this.client=new Vt(t)}async getSummary(t){let e=on.fromAny(t),[n,s,i,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=n,[o,l]=s,[u,p,d,m,g,b]=i,h=S.toDecimal(b,18),P=[];for(let y of o){let v=y.underlyingAsset.toLowerCase(),w=a.find(({underlyingAsset:He})=>He.toLowerCase()===v);if(!w)throw new Error("Missing pool reserve for "+v);let R=y.scaledATokenBalance,q=w.liquidityIndex,O=w.liquidityRate,G=w.availableLiquidity,Q=w.priceInMarketReferenceCurrency,et=r+6,Y=this.calculateLinearInterest(O,w.lastUpdateTimestamp,et),J=q*Y/Re,ht=R*J/Re,de=Number(l!==0&&l===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold)/1e4,ge=w.usageAsCollateralEnabled&&y.usageAsCollateralEnabledOnUser&&y.scaledATokenBalance>0n,he=Be.toAssetId(v);P.push({aTokenBalance:ht,availableLiquidity:G,decimals:Number(w.decimals),isCollateral:ge,priceInRef:Q,reserveId:he,reserveAsset:v,reserveLiquidationThreshold:de})}return{healthFactor:Number(h),totalCollateral:u,totalDebt:p,reserves:P}}async hasBorrowPositions(t){let e=on.fromAny(t),n=await this.client.getUserAccountData(e),[s,i]=n;return i>0n}async getHealthFactor(t){let e=on.fromAny(t),n=await this.client.getUserAccountData(e),[s,i,r,a,o,l]=n,u=S.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:s,totalDebt:i,reserves:r}=await this.getSummary(t),a=Be.fromAssetId(e),o=r.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:p,reserveLiquidationThreshold:d}=o,m=S.toBigInt(n,l),g=u?m*p/10n**BigInt(l):0n,b=s-g;if(b<=0n)return 0;let h=(0,ct.default)(b.toString()).mul(d).div(i.toString()).toFixed(6,ct.default.roundDown);return Number(h)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:s,totalDebt:i,reserves:r}=await this.getSummary(t),a=Be.fromAssetId(e),o=r.find(h=>h.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:p}=o,m=S.toBigInt(n,l)*u/10n**BigInt(l),g=s+m;if(g<=0n)return 0;let b=(0,ct.default)(g.toString()).mul(p).div(i.toString()).toFixed(6,ct.default.roundDown);return Number(b)}async getMaxWithdraw(t,e){let{totalDebt:n,reserves:s,healthFactor:i}=await this.getSummary(t),r=Be.fromAssetId(e),a=s.find(o=>o.reserveAsset===r);if(!a)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(a,n,i)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:n,healthFactor:s}=await this.getSummary(t),i={};for(let r of n){let a=this.calculateWithdrawMax(r,e,s);r.reserveId&&(i[r.reserveId]=a)}return i}calculateWithdrawMax(t,e,n){let{aTokenBalance:s,availableLiquidity:i,decimals:r,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=s;if(l&&e>0n){let d=n-pi;if(d>0){let m=(0,ct.default)(d).mul(e.toString()).div(o).toFixed(0,ct.default.roundDown),g=(0,ct.default)(m).div(a.toString()).mul(10**r).toFixed(0,ct.default.roundDown);u=s<BigInt(g)?s:BigInt(g)}else u=0n}return{amount:u<i?u:i,decimals:r}}calculateLinearInterest(t,e,n){let s=n-e;if(s<=0)return Re;let i=t*BigInt(s)/mi;return Re+i}};var cn={};I(cn,{AssetClient:()=>At,BalanceClient:()=>st,ChainParams:()=>Ot});var At=class extends N{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:s})=>{let[i]=n;return[i,s]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[i]=n;return[i,s]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:s}=n;return this.SUPPORTED_TYPES.includes(s.type)}).map(({keyArgs:n,value:s})=>{let[i]=n;return[i,s]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:s})=>{let[i]=n;return[i,s]}))}async mapToken(t,e,n,s){let{name:i,asset_type:r,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:i?.asText(),symbol:l,decimals:u,icon:l,type:r.type,isSufficient:a,location:s,existentialDeposit:o}}async mapBond(t,e,n,s){let[i,r]=s,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(i,e,n),d=Number(r),m=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",m.format(d)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:i,maturity:d}}async mapShares(t,e,n,s){let{assets:i}=s,{name:r,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(i.map(async g=>{let{symbol:b}=await this.mapToken(g,e,n);return[g,b]})),d=Object.fromEntries(p),m=Object.values(d);return{id:t,name:m.join(", "),symbol:a?.asText()||r?.asText(),decimals:18,icon:m.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:d}}async mapExternal(t,e,n,s){let i=await this.mapToken(t,e,new Map,s),r=n?.find(a=>a.internalId===i.id);return r?{...i,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.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,s,i,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let p=s.get(l),{asset_type:d}=u,m;switch(d.type){case"Bond":let g=r.get(l);m=await this.mapBond(l,u,a,g);break;case"StableSwap":let b=i.get(l);m=await this.mapShares(l,u,a,b);break;case"External":m=await this.mapExternal(l,u,e,p);break;default:m=await this.mapToken(l,u,a,p)}o.push(m)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var x=require("rxjs");var st=class extends N{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 s=await this.api.query.Tokens.Accounts.getValue(t,e);return this.calculateBalance(s)}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),s=this.subscribeErc20Balance(t);return(0,x.combineLatest)([e,n,s]).pipe((0,x.debounceTime)(250),(0,x.map)(i=>i.flat()),(0,x.startWith)([]),(0,x.bufferCount)(2,1),(0,x.map)(([i,r],a)=>a===0?r:this.getDeltas(i,r)))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,x.map)(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,x.map)(s=>({id:e,balance:s})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,x.distinctUntilChanged)((n,s)=>!s.deltas),(0,x.map)(({deltas:n})=>{let s=[];return n?.deleted.forEach(i=>{let[r,a]=i.args;s.push({id:a,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(i=>{let[r,a]=i.args;s.push({id:a,balance:this.calculateBalance(i.value)})}),s}))}subscribeErc20Balance(t,e){let n=new x.Subject,s=n.pipe((0,x.shareReplay)(1)),i=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),r=async()=>{let o=e||await i(),l=async()=>{let d=(await Promise.all(o.map(async m=>{let g=await this.getTokenBalanceData(t,m);return[m,g]}))).map(([m,g])=>({id:m,balance:g}));n.next(d)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return r().then(o=>a=o),s.pipe((0,x.finalize)(()=>a?.()),(0,x.pairwise)(),(0,x.map)(([o,l],u)=>u===0?l.filter(p=>p.balance.transferable>0n):this.getDeltas(o,l)),(0,x.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t);return this.calculateBalance(n)}calculateBalance(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,n=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:n,transferable:e}}getDeltas(t,e){let n=(i,r)=>i!==void 0&&r!==void 0&&i.transferable===r.transferable&&i.total===r.total,s=t.reduce((i,r)=>(i.set(r.id,r.balance),i),new Map);return e.filter(i=>!n(i.balance,s.get(i.id)))}};var Ot=class extends N{_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 pn={};I(pn,{AssetNotFound:()=>un,PoolNotFound:()=>zt,RouteNotFound:()=>Xt});var un=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},zt=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Xt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var dn={};I(dn,{EvmClient:()=>Kt,createChain:()=>mn});var ss=require("viem"),di=["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"],mn=()=>(0,ss.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:di}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var it=require("viem");var Kt=class{client;chain;constructor(t){this.client=t,this.chain=mn()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,it.createPublicClient)({chain:this.chain,transport:(0,it.http)()})}getWsProvider(){return(0,it.createPublicClient)({transport:(0,it.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,it.createWalletClient)({account:t,chain:this.chain,transport:(0,it.custom)(window.ethereum)})}};var yn={};I(yn,{LiquidityMiningApi:()=>jt,LiquidityMiningClient:()=>$t});var as=require("polkadot-api"),U=ot(require("big.js")),bn=require("@galacticcouncil/math-liquidity-mining");var Fe=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let n=0;n<t.length;++n){let[s,i]=t[n];this.result.set(this.getKey(i,s),e[n].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,n,s){let i=this.getKey(t,e),r=this.getKey(t,n),a=this.result.get(i)??0n,o=this.result.get(r)??0n;if(a<s)throw new Error("Attempting to transfer more than is present");this.result.set(i,a+s),this.result.set(r,o+s)}};var dt=ot(require("big.js")),Z=require("@galacticcouncil/math-liquidity-mining");var gn=ot(require("big.js")),hn=(0,gn.default)(10).pow(18),is=BigInt((0,gn.default)(1).pow(18).toString()),rs=6e3;var gi="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 s=await this.getAsset(t.reward_currency),i=e-t.updated_at,r=this.getAccount(t.id),a=s?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,r),l=(0,dt.default)(a.toString()),u=(0,dt.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,dt.default)((0,Z.calculate_global_farm_rewards)(t.total_shares_z.toString(),n.toString(),(0,dt.default)(t.yield_per_period.toString()).mul(hn).round(0,dt.default.roundDown).toFixed(),t.max_reward_per_period.toString(),i.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let d=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,r,d,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,Z.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.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 s=(0,Z.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(s),updated_at:n}}getLoyaltyMultiplier(t,e){let n=(0,dt.default)(1).mul(hn).round(0,dt.default.roundDown).toString();if(!e)return n;let{initial_reward_percentage:s,scale_coef:i}=e;return(0,Z.calculate_loyalty_multiplier)(t.toFixed(),s.toString(),i.toFixed())}async claimRewards(t,e,n,s,i){if(e.state.type==="Terminated")return null;let r=Math.floor(s/t.blocks_per_period);if(n.updated_at===r)return null;let a=await this.syncGlobalFarm(t,r,i);if(!a)return null;let o=this.syncYieldFarm(e,a,r);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,u=o.updated_at-n.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),d=BigInt((0,Z.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),m=BigInt((0,Z.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),gi));return{reward:d,maxReward:m,assetId:a.reward_currency}}};var hi=(0,U.default)(365.2425).times(24).times(60).times(60),jt=class{client;balanceClient;options;constructor(t,e,n={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:n.blockTime??rs})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let n=[t,e].sort((i,r)=>i-r);if(t===e)return is;let s=await this.client.getOraclePrice(n);if(s){let{n:i,d:r}=s[0].price,a;return t<e?a=(0,bn.fixed_from_rational)(i.toString(),r.toString()):a=(0,bn.fixed_from_rational)(r.toString(),i.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let n=Buffer.from("modl","utf-8"),s=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),i=Buffer.from([t]),r=Buffer.concat([n,s,i]),o="0x"+Buffer.concat([r,Buffer.alloc(32-r.length)]).toString("hex");return(0,as.AccountId)(63).dec(o)};getGlobalRewardPerPeriod(t,e,n,s){let i=(0,U.default)(s).times(t.toString()).times(e.toString()).div(18);return i.gte(n.toString())?n.toString():i.toString()}getPoolYieldPerPeriod(t,e,n,s){let i=(0,U.default)(t.toString()).times(e),r=(0,U.default)(n.toString()).times(s);return i.div(r.toString()).toString()}farmData(t,e,n){let{yieldFarm:s,globalFarm:i,priceAdjustment:r,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=s,{blocks_per_period:p,yield_per_period:d,total_shares_z:m,max_reward_per_period:g,pending_rewards:b,accumulated_paid_rewards:h,planned_yielding_periods:P,updated_at:y,incentivized_asset:v,reward_currency:w,price_adjustment:R,min_deposit:q}=i,O=B.shiftNeg(r??R,18),G=B.shiftNeg(l,18),Q=B.shiftNeg(u?.initial_reward_percentage??0,18),et=hi.div((0,U.default)(this.blockTime).div(1e3).times(p)).toString(),Y;if(m<=0)Y=(0,U.default)(G).times(d.toString()).times(et).toString();else{let Cs=this.getGlobalRewardPerPeriod(m,d,g,O),Ds=this.getPoolYieldPerPeriod(Cs,G,m,O);Y=(0,U.default)(Ds).times(et).toString()}let J=b+h,ht=g*BigInt(P),bt=a.transferable+J,Dn=bt-J,de=(0,U.default)(Dn.toString()).div(g.toString()),ge=(0,U.default)(e).div(p.toString()).toString(),he=(m>=0?de.plus(y):de.plus(ge)).toString(),He=(0,U.default)(he).times(p).toString(),Es=(0,U.default)(m.toString()).div((0,U.default)(g.toString()).div(d.toString())).div(Math.pow(10,18)).times(100).times(O).toFixed(2),Mn=(0,U.default)(J.toString()).div(bt.toString()).gte(.999);Y=Mn?"0":(0,U.default)(Y).div(n?2:1).times(100).toString();let ks=Q?(0,U.default)(Y).times(Q).toString():void 0;return{apr:Y,minApr:ks,isDistributed:Mn,estimatedEndPeriod:he,estimatedEndBlock:He,maxRewards:ht,incentivizedAsset:v,rewardCurrency:w,loyaltyCurve:u,currentPeriod:ge,potMaxRewards:bt,fullness:Es,yieldFarmId:s.id,globalFarmId:i.id,poolId:o,distributedRewards:J,plannedYieldingPeriods:P,minDeposit:q}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((s,i)=>s.includes(i.keyArgs[0].toString())?s:[...s,i.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async s=>{let i=await this.getOmnipoolFarms(s);if(i)return[s,i]}));return Object.fromEntries(n.filter(s=>!!s))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),n=await this.client.getRelayBlockNumber(),s=await Promise.all(e.map(async({keyArgs:i,value:r})=>{let[,a]=i,o=r,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a),g=await this.getOraclePrice(p,d),b=await this.balanceClient.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:g,balance:b}}));return n?s.map(i=>i?this.farmData(i,n):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((s,i)=>s.includes(i.keyArgs[0].toString())?s:[...s,i.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async s=>{let i=await this.getIsolatedFarms(s);if(i)return[s,i]}));return Object.fromEntries(n.filter(s=>!!s))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),n=await this.client.getRelayBlockNumber(),s=await Promise.all(e.map(async({keyArgs:i,value:r})=>{let[,a]=i,o=r,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,d=l.incentivized_asset,m=this.getFarmAddress(a,!0),g=await this.getOraclePrice(p,d),b=await this.balanceClient.getBalance(m,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:g,balance:b,farmAddress:m}}));return n?s.map(i=>i?this.farmData(i,n,!0):void 0):[]}async getDepositReward(t,e,n,s){let i=e.global_farm_id,r=e.yield_farm_id,a=n?await this.client.getIsolatedYieldFarm(t,i,r):await this.client.getOmnipoolYieldFarm(Number(t),i,r),o=n?await this.client.getIsolatedGlobalFarm(i):await this.client.getOmnipoolGlobalFarm(i);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],d=await this.getAccountAssetBalances(p),m=await this.getOraclePrice(l,u),g=new Fe(p,d),h=await new Ee(y=>this.getFarmAddress(y),y=>this.client.getAsset(y),g).claimRewards(o,a,e,s,m??o.price_adjustment);if(!h)return;let P=await this.client.getAsset(h.assetId);if(P&&!(h.reward<=P.existential_deposit))return h}async getAccountAssetBalances(t){let[e,n]=await Promise.all([Promise.all(t.filter(([i,r])=>r!==0).map(([i,r])=>this.balanceClient.getTokenBalance(i,r))),Promise.all(t.filter(([i,r])=>r===0).map(([i])=>this.balanceClient.getSystemBalance(i)))]),s=[];for(let i=0,r=0;i+r<t.length;){let a=i+r,[,o]=t[a];o===0?(s.push(n[r]),r+=1):(s.push(e[i]),i+=1)}return s}};var ke=require("polkadot-api"),$t=class extends N{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(ke.Binary.fromText("omnipool"),t,(0,ke.Enum)("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 Tn={};I(Tn,{PoolContextProvider:()=>kt,PoolError:()=>St,PoolFactory:()=>Et,PoolType:()=>M,aave:()=>wn,lbp:()=>fn,omni:()=>Pn,stable:()=>Sn,xyk:()=>vn});var fn={};I(fn,{LbpMath:()=>tt,LbpPool:()=>Qt,LbpPoolClient:()=>Jt});var rt=require("@galacticcouncil/math-lbp"),tt=class{static getSpotPrice(t,e,n,s,i){return(0,rt.get_spot_price)(t,e,n,s,i)}static calculateInGivenOut(t,e,n,s,i){return(0,rt.calculate_in_given_out)(t,e,n,s,i)}static calculateOutGivenIn(t,e,n,s,i){return(0,rt.calculate_out_given_in)(t,e,n,s,i)}static calculateLinearWeights(t,e,n,s,i){return(0,rt.calculate_linear_weights)(t,e,n,s,i)}static calculatePoolTradeFee(t,e,n){return(0,rt.calculate_pool_trade_fee)(t,e,n)}};var M=(i=>(i.Aave="Aave",i.LBP="LBP",i.Omni="Omnipool",i.Stable="Stableswap",i.XYK="XYK",i))(M||{}),St=(i=>(i.InsufficientTradingAmount="InsufficientTradingAmount",i.MaxInRatioExceeded="MaxInRatioExceeded",i.MaxOutRatioExceeded="MaxOutRatioExceeded",i.TradeNotAllowed="TradeNotAllowed",i.UnknownError="UnknownError",i))(St||{});var{FeeUtils:os}=B,Qt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.fee,t.repayFeeApply)}constructor(t,e,n,s,i,r,a){this.type="LBP",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=i,this.fee=r,this.repayFeeApply=a}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),i=n.get(e);if(s==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:s.balance,balanceOut:i.balance,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(t,e,n){let s=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&i.push("MaxOutRatioExceeded"),s===t.assetOut){let a=this.calculateTradeFee(e,n),o=os.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:i}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&i.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,n){let s=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&i.push("MaxInRatioExceeded"),s===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:i}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,n),l=os.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:i}}}calculateInGivenOut(t,e){let n=tt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=tt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=tt.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=tt.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=tt.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};var us=require("polkadot-api"),Bt=require("rxjs");var ls=(c,t=new Map)=>e=>{let n;return t.has(e)?t.get(e):(t.set(e,n=c(e)),n)};var f=require("rxjs");var cs=require("rxjs"),Ce=class{store$=new cs.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,n=new Map(e.map((a,o)=>[a.address,o])),s=await t(e),i=e.slice(),r=new Set;for(let a of s){let o=n.get(a.address);o===void 0?(n.set(a.address,i.length),i.push(a)):i[o]=a,r.add(a.address)}this.changeset=r,this.store$.next(i)}).catch(console.error)}destroy(){this.store$.complete()}};var K=class extends st{evm;store=new Ce;shared$;mem=0;memPoolsCache=new ft(null,{ttl:6*1e3});memPools=ls(t=>(this.log(this.getPoolType(),"sync mem pools",t),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,f.startWith)([]),(0,f.bufferCount)(2,1),(0,f.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,f.filter)(t=>t.length>0),(0,f.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,f.defer)(()=>{let t=new f.Subscription;return(0,f.from)(this.getMemPools()).pipe((0,f.map)(n=>n.filter(s=>this.hasValidAssets(s))),(0,f.tap)(n=>this.store.set(n))).pipe((0,f.tap)(()=>{t.add(this.subscribeUpdates())}),(0,f.switchMap)(n=>(0,f.merge)((0,f.of)(n),this.store.asObservable().pipe((0,f.skip)(1)))),(0,f.finalize)(()=>{t.unsubscribe()}))}).pipe((0,f.share)({connector:()=>new f.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:n}=e,s=[this.subscribeTokensBalance(n)];if(this.hasSystemAsset(e)){let i=this.subscribeSystemBalance(n);s.push(i)}if(this.hasErc20Asset(e)){let i=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),r=this.subscribeErc20Balance(n,i);s.push(r)}return(0,f.combineLatest)(s).pipe((0,f.map)(i=>i.flat()),(0,f.pairwise)(),(0,f.map)(([i,r])=>this.getDeltas(i,r)),(0,f.map)(i=>[n,i]))});return(0,f.combineLatest)(t).pipe((0,f.debounceTime)(250),(0,f.map)(e=>new Map(e))).subscribe(e=>this.store.update(n=>this.updateBalances(n,e)))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:n})=>n>0n&&!!e)}updateBalances=(t,e)=>{let n=[],s=new Map(t.map(i=>[i.address,i]));for(let[i,r]of e){let a=s.get(i);if(a){let o=a.tokens.map(l=>{let u=r.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});n.push({...a,tokens:o})}}return n}};var Jt=class extends K{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}getPoolWeights(t,e){let{start:n,end:s,initial_weight:i,final_weight:r}=t,a=tt.calculateLinearWeights(n?n.toString():"0",s?s.toString():"0",i.toString(),r.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(us.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),s=e?.relay_parent_number||0,i=t.filter(({value:r})=>e&&this.isActivePool(r,s)).map(async({keyArgs:r,value:a})=>{let[o]=r,l=o.toString(),u=await this.getPoolDelta(l,a,s);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(i)}async getPoolDelta(t,e,n){let{assets:s,repay_target:i,fee_collector:r}=e,[a,o]=this.getPoolWeights(e,n),[l,u]=s,[p,d,m,g,b]=await Promise.all([this.isRepayFeeApplied(l,i,r.toString()),this.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:l,decimals:m?.decimals,existentialDeposit:m?.existential_deposit,balance:d.transferable,weight:a,type:m?.asset_type.type},{id:u,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:s}=t;return n&&s?e>=n&&e<s:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return(await this.getBalance(n,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let n=this.store.pools.find(i=>i.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:n.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,Bt.filter)(t=>t!==void 0),(0,Bt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number)).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let n=[];for(let s of e){let i=this.poolsData.get(s.address);if(i){let{assets:r,repay_target:a,fee_collector:o}=i,[l]=r,[u,p]=this.getPoolWeights(i,t),[d,m]=s.tokens,g=[{...d,weight:u},{...m,weight:p}],b=await this.isRepayFeeApplied(l,a,o.toString());n.push({...s,tokens:g,repayFeeApply:b})}}return n})})}subscribeUpdates(){let t=new Bt.Subscription;return t.add(this.subscribeValidationData()),t}};var Pn={};I(Pn,{OmniMath:()=>A,OmniPool:()=>Zt,OmniPoolClient:()=>te});var T=require("@galacticcouncil/math-omnipool"),vt=ot(require("big.js")),A=class{static calculateSpotPrice(t,e,n,s){return(0,T.calculate_spot_price)(t,e,n,s)}static calculateLrnaSpotPrice(t,e){return(0,T.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,n,s,i,r,a,o,l){return(0,T.calculate_in_given_out)(t,e,n,s,i,r,a,o,l)}static calculateLrnaInGivenOut(t,e,n,s,i){return(0,T.calculate_lrna_in_given_out)(t,e,n,s,i)}static calculateOutGivenIn(t,e,n,s,i,r,a,o,l){return(0,T.calculate_out_given_in)(t,e,n,s,i,r,a,o,l)}static calculateOutGivenLrnaIn(t,e,n,s,i){return(0,T.calculate_out_given_lrna_in)(t,e,n,s,i)}static calculateShares(t,e,n,s){return(0,T.calculate_shares)(t,e,n,s)}static calculateLiquidityOut(t,e,n,s,i,r,a,o){return(0,T.calculate_liquidity_out)(t,e,n,s,i,r,a,o)}static calculateLiquidityLRNAOut(t,e,n,s,i,r,a,o){return(0,T.calculate_liquidity_lrna_out)(t,e,n,s,i,r,a,o)}static calculateCapDifference(t,e,n,s){let i=(0,vt.default)(e),r=(0,vt.default)(t),a=(0,vt.default)(s),o=(0,vt.default)(n),l=(0,vt.default)(10).pow(18),u=o.div(l);if(i.div(a).lt(u)){let d=u.times(a).minus(i).times(r),m=i.times((0,vt.default)(1).minus(u));return d.div(m).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,n,s){return(0,T.calculate_liquidity_hub_in)(t,e,n,s)}static isSellAllowed(t){return(0,T.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,T.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,T.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,T.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,n,s,i,r,a,o,l,u,p){return(0,T.recalculate_asset_fee)(t,e,n,s,i,r,a,o,l,u,p)}static recalculateProtocolFee(t,e,n,s,i,r,a,o,l,u,p){return(0,T.recalculate_protocol_fee)(t,e,n,s,i,r,a,o,l,u,p)}static verifyAssetCap(t,e,n,s){return(0,T.verify_asset_cap)(t,e,n,s)}};var{FeeUtils:Rt}=B,Zt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.hubAssetId)}constructor(t,e,n,s,i,r){this.type="Omnipool",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=i,this.hubAssetId=r}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),i=n.get(e);if(s==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:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:s.balance,balanceOut:i.balance,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInEd:s.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,n),r=s===0n?0:_.calculateDiffToRef(i,s),a=[],o=A.isSellAllowed(t.tradeableIn),l=A.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return i>p&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,n),r=_.calculateDiffToRef(s,i),a=[],o=A.isSellAllowed(t.tradeableIn),l=A.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return i>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:i,feePct:r,errors:a}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let s=A.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?Rt.toRaw(n.assetFee).toString():"0",n?Rt.toRaw(n.protocolFee).toString():"0"),i=BigInt(s);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,n){let s=A.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?Rt.toRaw(n.assetFee).toString():"0"),i=BigInt(s);return i<0n?0n:i}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let s=A.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?Rt.toRaw(n.assetFee).toString():"0",n?Rt.toRaw(n.protocolFee).toString():"0"),i=BigInt(s);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,n){let s=A.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?Rt.toRaw(n.assetFee).toString():"0"),i=BigInt(s);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=A.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=A.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=A.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=A.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};var gt=require("polkadot-api"),ds=require("@polkadot-api/utils"),D=require("rxjs");var{FeeUtils:L}=B,ps=gt.Binary.fromText("omnipool"),ms=(0,gt.Enum)("Short"),te=class extends K{queryBus=new Yt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t),t=>String(t),6*1e3);emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(ps,t,ms),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=(0,ds.toHex)(e);return(0,gt.AccountId)(63).dec(n)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(gt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,s,i,r,a]=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:u,value:p})=>{let[d]=u,{hub_reserve:m,shares:g,tradable:b,cap:h,protocol_shares:P}=p,[y,v]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d),this.getBalance(e,d)]);return{id:d,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:v.transferable,cap:h,hubReserves:m,protocolShares:P,shares:g,tradeable:b,type:y?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:i?.decimals,existentialDeposit:i?.existential_deposit,balance:r.transferable,tradeable:s,type:i?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}async getPoolFees(t){let e=t.assetOut,n=t.assetIn,s=await this.dynamicFeesConfig.get(e);if(s?.type==="Fixed"){let{asset_fee:y,protocol_fee:v}=s.value;return{assetFee:L.fromPermill(y),protocolFee:L.fromPermill(v)}}let i=this.getOraclePair(e),r=this.getOraclePair(n),[a,o,l]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(i),this.emaOracles.get(r)]),[u,p,d]=await this.getAssetFee(t,this.block,a,o,s?.value.asset_fee_params),[m,g,b]=n===1?[0,0,0]:await this.getProtocolFee(t,this.block,a,l,s?.value.protocol_fee_params),h=u+m,P=d+b;return{assetFee:L.fromPermill(p),protocolFee:L.fromPermill(g),min:L.fromPermill(h),max:L.fromPermill(P)}}async getAssetFee(t,e,n,s,i){let{assetOut:r,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=i||await this.api.constants.DynamicFees.AssetFeeParameters();if(!n||!s)return[o,o,l];let d=L.fromPermill(o),m=L.fromPermill(l),[g]=s,{asset_fee:b,timestamp:h}=n,P=Math.max(1,e-h),y=g.volume.b_in.toString(),v=g.volume.b_out.toString(),w=g.liquidity.b.toString();r===0&&(y=g.volume.a_in.toString(),v=g.volume.a_out.toString(),w=g.liquidity.a.toString());let R=L.fromPermill(b),q=A.recalculateAssetFee(y,v,w,"9",a.toString(),L.toRaw(R).toString(),P.toString(),L.toRaw(d).toString(),L.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(q)*1e6,l]}async getProtocolFee(t,e,n,s,i){let{assetIn:r,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=i||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!n||!s)return[o,o,l];let d=L.fromPermill(o),m=L.fromPermill(l),[g]=s,{protocol_fee:b,timestamp:h}=n,P=Math.max(1,e-h),y=g.volume.b_in.toString(),v=g.volume.b_out.toString(),w=g.liquidity.b.toString();r===0&&(y=g.volume.a_in.toString(),v=g.volume.a_out.toString(),w=g.liquidity.a.toString());let R=L.fromPermill(b),q=A.recalculateProtocolFee(y,v,w,"9",a.toString(),L.toRaw(R).toString(),P.toString(),L.toRaw(d).toString(),L.toRaw(m).toString(),u.toString(),p.toString());return[o,Number(q)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,n=t.tokens.map(s=>s.id).map(s=>this.getOraclePair(s)).map(s=>this.api.query.EmaOracle.Oracles.watchValue(ps,s,ms,"best").pipe((0,D.filter)(i=>i!==void 0),(0,D.map)(i=>({pair:s,value:i}))));return(0,D.merge)(...n).pipe((0,D.finalize)(()=>{this.log(this.getPoolType(),"unsub ema oracles"),this.emaOracles.clear()})).subscribe(s=>{let{pair:i,value:r}=s;this.emaOracles.set(r,i)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,D.distinctUntilChanged)((t,e)=>!e.deltas),(0,D.finalize)(()=>{(0,D.finalize)(()=>{this.log(this.getPoolType(),"unsub dyn fees"),this.dynamicFees.clear()})})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFees.set(e.value,n)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,D.distinctUntilChanged)((t,e)=>!e.deltas),(0,D.finalize)(()=>{this.log(this.getPoolType(),"unsub dyn fees config"),this.dynamicFeesConfig.clear()})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFeesConfig.set(e.value,n)})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe((0,D.finalize)(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,D.distinctUntilChanged)((t,e)=>!e.deltas),(0,D.finalize)(()=>{this.log(this.getPoolType(),"unsub assets")})).subscribe(({deltas:t})=>{this.store.update(([e])=>{let n=t?.upserted.reduce((i,r)=>{let[a]=r.args;return i.set(a,r.value),i},new Map),s=e.tokens.map(i=>{let r=n?.get(i.id);return r?this.updateTokenState(i,r):i});return[{...e,tokens:s}]})})}subscribeUpdates(){let t=new D.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:n,shares:s,tradable:i,cap:r,protocol_shares:a}=e;return{...t,cap:r,hubReserves:n,protocolShares:a,shares:s,tradeable:i}}};var Sn={};I(Sn,{StableMath:()=>V,StableSwap:()=>ee,StableSwapClient:()=>ne});var k=require("@galacticcouncil/math-stableswap"),V=class{static getPoolAddress(t){return(0,k.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,s,i){return(0,k.calculate_amplification)(t,e,n,s,i)}static calculateInGivenOut(t,e,n,s,i,r,a){return(0,k.calculate_in_given_out)(t,e,n,s,i,r,a)}static calculateAddOneAsset(t,e,n,s,i,r,a){return(0,k.calculate_add_one_asset)(t,e,n,s,i,r,a)}static calculateSharesForAmount(t,e,n,s,i,r,a){return(0,k.calculate_shares_for_amount)(t,e,n,s,i,r,a)}static calculateOutGivenIn(t,e,n,s,i,r,a){return(0,k.calculate_out_given_in)(t,e,n,s,i,r,a)}static calculateLiquidityOutOneAsset(t,e,n,s,i,r,a){return(0,k.calculate_liquidity_out_one_asset)(t,e,n,s,i,r,a)}static calculateShares(t,e,n,s,i,r){return(0,k.calculate_shares)(t,e,n,s,i,r)}static calculateSpotPriceWithFee(t,e,n,s,i,r,a,o){return(0,k.calculate_spot_price_with_fee)(t,e,n,s,i,r,a,o)}static recalculatePegs(t,e,n,s,i){let r=(0,k.recalculate_peg)(t,e,n,s,i);return JSON.parse(r)}};var{FeeUtils:Ft}=B,ee=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit,t.amplification,t.isRampPeriod,t.id,t.fee,t.totalIssuance,t.pegs)}constructor(t,e,n,s,i,r,a,o,l,u,p){this.type="Stableswap",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=i,this.amplification=r,this.isRampPeriod=a,this.id=o,this.fee=l,this.totalIssuance=u,this.pegs=p}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),i=n.get(e);if(s==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:s.balance,balanceOut:i.balance,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:s.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,n),r=s===0n?0:_.calculateDiffToRef(i,s),a=[],o=A.isSellAllowed(t.tradeableIn),l=A.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,n),r=_.calculateDiffToRef(s,i),a=[],o=A.isSellAllowed(t.tradeableIn),l=A.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:i,feePct:r,errors:a}}calculateIn(t,e,n){let s=V.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?Ft.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(s);return i<0n?0n:i}calculateAddOneAsset(t,e,n){let s=V.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?Ft.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(s);return i<0n?0n:i}calculateSharesForAmount(t,e,n){let s=V.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?Ft.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(s);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=V.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 s=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let s=V.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?Ft.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(s);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,n){let s=V.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?Ft.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(s);return i<0n?0n:i}calculateShares(t,e,n){let s=V.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?Ft.toRaw(n.fee).toString():"0",this.getPegs()),i=BigInt(s);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=V.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 s=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(s)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:s})=>({asset_id:e,amount:n,decimals:s}));return JSON.stringify(t,mt.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],mt.jsonFormatter)}};var De=require("polkadot-api"),gs=require("@polkadot-api/utils"),hs=require("@noble/hashes/blake2b"),j=require("rxjs");var{FeeUtils:bi}=B,ne=class extends K{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=V.getPoolAddress(t),n=(0,hs.blake2b)(e,{dkLen:32}),s=(0,gs.toHex)(n);return(0,De.AccountId)(63).dec(s)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:n,final_amplification:s,initial_block:i,final_block:r}=t,a=V.calculateAmplification(n.toString(),s.toString(),i.toString(),r.toString(),e.toString()),o=Number(a)<s;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),s=e.assets.map(async i=>{let[r,a,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:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:r,type:a?.asset_type.type}});return Promise.all(s)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(De.CompatibilityLevel.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()]),s=t.map(async({keyArgs:i,value:r})=>{let[a]=i,o=this.getPoolAddress(a),[l,u,p]=await Promise.all([this.getPoolTokens(a,r),this.api.query.Stableswap.PoolPegs.getValue(a),this.api.query.Tokens.TotalIssuance.getValue(a)]),d=this.getPoolAmplification(r,e),m=u?this.getRecentPegs(u):this.getDefaultPegs(r);return l.push({id:a,tradeable:15,balance:p,decimals:18}),this.poolsData.set(a,r),{address:o,id:a,type:"Stableswap",fee:bi.fromPermill(r.fee),tokens:l,totalIssuance:p,pegs:m,...n,...d}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(s=>s.address===e).fee}}getDefaultPegs(t){return V.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,s])=>s.map(i=>i.toString()))}subscribeIssuance(){let e=this.store.pools.map(n=>n.id).map(n=>this.api.query.Tokens.TotalIssuance.watchValue(n,"best").pipe((0,j.map)(s=>({id:n,value:s}))));return(0,j.merge)(...e).pipe((0,j.finalize)(()=>{this.log(this.getPoolType(),"unsub total issuance")})).subscribe(n=>{let{id:s,value:i}=n;this.store.update(r=>{let a=[];return r.filter(o=>o.id===s).forEach(o=>{let l=o.tokens.map(u=>u.id===s?{...u,balance:i}:u);a.push({...o,tokens:l,totalIssuance:i})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,j.distinctUntilChanged)((t,e)=>!e.deltas),(0,j.finalize)(()=>{this.log(this.getPoolType(),"unsub pool pegs")})).subscribe(({deltas:t})=>{this.store.update(e=>{let n=[],s=new Map(e.map(i=>[i.id,i]));return t?.upserted.forEach(({args:i,value:r})=>{let[a]=i,o=s.get(a);if(o){let l=this.getRecentPegs(r);n.push({...o,pegs:l})}}),n})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe((0,j.finalize)(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.store.update(e=>{let n=[];return e.filter(s=>s.isRampPeriod).forEach(s=>{let i=this.poolsData.get(s.id);if(i){let r=this.getPoolAmplification(i,t);n.push({...s,...r})}}),n})})}subscribeUpdates(){let t=new j.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var vn={};I(vn,{XykMath:()=>ut,XykPool:()=>se,XykPoolClient:()=>ie});var C=require("@galacticcouncil/math-xyk"),ut=class{static getSpotPrice(t,e,n){return(0,C.get_spot_price)(t,e,n)}static calculateInGivenOut(t,e,n){return(0,C.calculate_in_given_out)(t,e,n)}static calculateOutGivenIn(t,e,n){return(0,C.calculate_out_given_in)(t,e,n)}static calculatePoolTradeFee(t,e,n){return(0,C.calculate_pool_trade_fee)(t,e,n)}static calculateLiquidityIn(t,e,n){return(0,C.calculate_liquidity_in)(t,e,n)}static calculateSpotPrice(t,e){return(0,C.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,n,s){return(0,C.calculate_spot_price_with_fee)(t,e,n,s)}static calculateShares(t,e,n){return(0,C.calculate_shares)(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,s){return(0,C.calculate_liquidity_out_asset_a)(t,e,n,s)}static calculateLiquidityOutAssetB(t,e,n,s){return(0,C.calculate_liquidity_out_asset_b)(t,e,n,s)}};var{FeeUtils:bs}=B,se=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,i){this.type="XYK",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),i=n.get(e);if(s==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:s.decimals,decimalsOut:i.decimals,balanceIn:s.balance,balanceOut:i.balance,assetInEd:s.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(s,n),r=bs.toPct(n.exchangeFee),a=s+i,o=[];(e<this.minTradingLimit||s<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:s,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(s,n),r=bs.toPct(n.exchangeFee),a=s-i,o=[];(e<this.minTradingLimit||s<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:a,feePct:r,errors:o}}calculateInGivenOut(t,e){let n=ut.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}calculateOutGivenIn(t,e){let n=ut.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(n);return s<0n?0n:s}spotPriceInGivenOut(t){let e=ut.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=ut.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=ut.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};var ys=require("polkadot-api"),fs=require("rxjs");var ie=class extends K{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(ys.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),s=e.map(async({keyArgs:i,value:r})=>{let[a]=i,[o,l]=r,[u,p,d,m]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:p?.decimals||this.decimals.get(o),existentialDeposit:p?.existential_deposit,balance:u.transferable,type:p?.asset_type.type},{id:l,decimals:m?.decimals||this.decimals.get(l),existentialDeposit:m?.existential_deposit,balance:d.transferable,type:m?.asset_type.type}],...n}});return Promise.all(s)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return fs.Subscription.EMPTY}};var wn={};I(wn,{AavePool:()=>re,AavePoolClient:()=>ae});var re=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t.address,t.tokens,t.maxInRatio,t.maxOutRatio,t.minTradingLimit)}constructor(t,e,n,s,i){this.type="Aave",this.address=t,this.tokens=e,this.maxInRatio=n,this.maxOutRatio=s,this.minTradingLimit=i}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),s=n.get(t),i=n.get(e);if(s==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:s.balance,balanceOut:i.balance,decimalsIn:s.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let s=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,n){let s=this.calculateOutGivenIn(t,e),i=[];return s>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,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}};var Ss=require("polkadot-api"),vs=require("@polkadot-api/utils"),z=require("rxjs"),ws=require("viem");var Ps=[{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:yi}=yt,fi=["Supply","Withdraw","Repay","Borrow"],ae=class extends K{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let n=t+"/"+e,s=new TextEncoder().encode(n.padEnd(32,"\0")),i=(0,vs.toHex)(s);return(0,Ss.AccountId)(63).dec(i)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:s,liqudity_in:i,liqudity_out:r})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(s),this.api.query.AssetRegistry.AssetLocations.getValue(s)]);return{address:this.getPoolId(n,s),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:i,location:o,type:a?.asset_type.type},{id:s,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:s,liqudity_out:i}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(r=>{let a=r.id===e.id?s:i;return{...r,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){return t.type==="Erc20"?mt.findNestedKey(t.location,"AccountKey20").AccountKey20.key:yi.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:n}=t;return{assetIn:e,assetOut:n,key:`${e}:${n}`}}parseEvmLog(t){let{topics:e,data:n}=t.log,s=e.map(r=>r.asHex()),i=n.asHex();try{let{eventName:r,args:a}=(0,ws.decodeEventLog)({abi:Ps,topics:s,data:i}),o=a.reserve.toLowerCase();return{eventName:r,reserve:o,key:`${r}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(n=>n.tokens).map(([n,s])=>s).map(n=>n.id);return this.api.event.Router.Executed.watch().pipe((0,z.map)(({payload:n})=>this.parseRouterLog(n)),(0,z.filter)(({assetIn:n,assetOut:s})=>e.includes(n)||e.includes(s)),(0,z.finalize)(()=>{this.log(this.getPoolType(),"unsub router executed")})).subscribe(({assetIn:n,assetOut:s,key:i})=>{this.log(this.getPoolType(),"[router:Executed]",i),this.store.update(async r=>{let a=[];for(let o of r){let[l,u]=o.tokens;if(u.id===n||u.id===s){let d=await this.getPoolDelta(o);a.push({...o,tokens:d})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,z.map)(({payload:t})=>this.parseEvmLog(t)),(0,z.filter)(t=>t!==void 0),(0,z.filter)(({eventName:t})=>fi.includes(t)),(0,z.finalize)(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({reserve:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async n=>{let s=[];for(let i of n){let[r]=i.tokens;if(this.getReserveH160Id(r).toLowerCase()===t){let o=await this.getPoolDelta(i);s.push({...i,tokens:o})}}return s})})}subscribeBalances(){return z.Subscription.EMPTY}subscribeUpdates(){let t=new z.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Et=class{static get(t){switch(t.type){case"Aave":return re.fromPool(t);case"XYK":return se.fromPool(t);case"Omnipool":return Zt.fromPool(t);case"LBP":return Qt.fromPool(t);case"Stableswap":return ee.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var at=require("rxjs");var kt=class extends N{evm;aave;omnipool;stableswap;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=at.Subscription.EMPTY;omniSub=at.Subscription.EMPTY;stableSub=at.Subscription.EMPTY;xykSub=at.Subscription.EMPTY;lbpSub=at.Subscription.EMPTY;isReady=!1;isDestroyed=new at.Subject;constructor(t,e){super(t),this.evm=e,this.lbp=new Jt(t,e),this.omnipool=new te(t,e),this.stableswap=new ne(t,e),this.xyk=new ie(t,e),this.aave=new ae(t,e),this.clients=[this.lbp,this.omnipool,this.stableswap,this.xyk,this.aave]}subscribe(t){return t.getSubscriber().pipe((0,at.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(n=>{this.pools.set(n.address,n)})})}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(s=>s.getPoolType()===e.type);if(n)return n.getPoolFees(t,e.address);throw new zt(e.type)}};var Rn={};I(Rn,{DEFAULT_BLOCK_TIME:()=>xs,DEFAULT_MIN_BUDGET:()=>_n,ORDER_MIN_BLOCK_PERIOD:()=>Is,Router:()=>Ct,TWAP_BLOCK_PERIOD:()=>ue,TWAP_MAX_DURATION:()=>On,TWAP_MAX_PRICE_IMPACT:()=>An,TWAP_TX_MULTIPLIER:()=>du,TradeOrderError:()=>In,TradeOrderType:()=>Le,TradeRouteBuilder:()=>$,TradeRouter:()=>Dt,TradeScheduler:()=>Mt,TradeType:()=>Me});var oe=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 Pi=10,le=class{isNotVisited(t,e){let n=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let s=[],i=new oe,r=[];for(r.push([e,""]),i.enqueue(r);i.size()>0;){let a=i.dequeue();if(!a||a.length>Pi)continue;let o=a[a.length-1];(n===null||o[0]===n)&&s.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),i.enqueue(p)}})}return s}findShortestPaths(t,e,n){let s=[],i=new oe,r=[];r.push([e,""]),i.enqueue(r);let a=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<a?(a=o.length,s.length=0,s.push(o)):o.length===a&&s.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&i.enqueue([...o,p])}return s}buildAndPopulateGraph(t,e){let n=new Map;for(let s of t)n.set(parseInt(s),[]);for(let[s,i,r]of e)n.get(i)?.push([r,s]);return n}};function xn(c){let t={};for(let e of c){let n=e.tokens.length;for(let s=0;s<n;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let i=0;i<n;i++){if(s==i)continue;let r=[e.address,e.tokens[s].id,e.tokens[i].id];t[e.tokens[s].id].push(r)}}}return t}var ce=class{getProposals(t,e,n){let s=n.filter(h=>h.type==="XYK"),i=n.filter(h=>h.type!=="XYK"),r=new Set(i.map(h=>h.tokens).flat().map(h=>h.id)),a=r.has(t),o=r.has(e),l=new le,u=h=>{let P=xn(h),y=Object.keys(P),v=y.flatMap(w=>P[w]);return l.buildAndPopulateGraph(y,v)};if(!a&&!o){let h=s.filter(v=>v.tokens.find(w=>w.id===t)||v.tokens.find(w=>w.id===e)),P=u(h),y=l.findPaths(P,t,e);return this.parsePaths(y)}if(a&&o){let h=u(i),P=l.findPaths(h,t,e);return this.parsePaths(P)}let p=a?e:t,d=s.filter(h=>h.tokens.some(P=>P.id===p));if(d.length===0)return[];let m=[...i,...d],g=u(m),b=l.findPaths(g,t,e);return this.parsePaths(b)}parsePaths(t){let e=[];for(let n of t){let s=[];for(let i=0;i<n.length;i++){let r=n[i],a=n[i+1];if(a==null)break;s.push(this.toEdge(r,a))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var Ct=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new ce,this.routeProposals=new Map}async withFilter(t){this.filter=t||{}}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:n=[]}=this.filter,s=new Set(e),i=new Set(n);return t.filter(r=>i.has(r.type)?!1:s.size>0?s.has(r.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(s=>s!==t).map(s=>this.getRoutes(s,t)))).filter(s=>s.length>0).map(([s])=>s[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 s=this.getAssets(n);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(s=>s.id)).flat().sort((n,s)=>n>s?1:-1);return new Set(e)}getPaths(t,e,n){let s=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(r=>this.validPath(r,s)).map(r=>this.toHops(r,s))}getProposals(t,e,n){let s=this.buildRouteKey(t,e,n);if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(s,i),i}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,s)=>n&&s)}validEdge([t,e,n],s){return s.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Et.get(e)]))}toHops(t,e){return t.map(([n,s,i])=>{let r=e.get(n);return{poolAddress:n,poolId:r?.id,pool:r?.type,assetIn:s,assetOut:i}})}};var Me=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Me||{}),Le=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Le||{}),In=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(In||{});var{FeeUtils:Ts}=B,Dt=class extends Ct{mlr;poolsSnapshot;constructor(t){super(t),this.mlr=new Map}buildCtxSync(t,e){let n=this.poolsSnapshot,s=super.validateInput(t,e,n),i=super.getPaths(t,e,n);if(!i.length)throw new Xt(t,e);return{paths:i,pools:n,poolsMap:s}}async withCtx(t,e,n){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let s=this.buildCtxSync(t,e);return n(s)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,s)=>{let i=n[n.length-1].amountOut,r=s[s.length-1].amountOut;return i>r?-1:1});return e.find(n=>n.every(s=>s.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,r)=>i+r),s=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,r)=>i+r);return[n,s]}}getPoolFeeRange(t){let e=t.min?Ts.toPct(t.min):void 0,n=t.max?Ts.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(a=>a.assetOutDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),i=n-e.assetOutDecimals,r=Math.pow(10,i);return s/BigInt(r)}async getSell(t,e,n,s){return this.withCtx(t,e,async({paths:i,poolsMap:r})=>{let a;if(s)a=await this.toSellSwaps(n,s,r);else{let o=i.map(u=>this.toSellSwaps(n,u,r)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(r,a)})}async getSells(t,e,n){return this.withCtx(t,e,async({paths:s,poolsMap:i})=>{let r=s.map(o=>this.toSellSwaps(n,o,i));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(i,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let n=e[0],s=e[e.length-1],i=this.isDirectTrade(e),r=this.getSellSpot(e),a=s.amountOut,o=i?s.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=i?s.tradeFeePct:_.calculateSellFee(o,a),d=Math.pow(10,n.assetInDecimals),m=n.amountIn*r/BigInt(d),g=_.calculateDiffToRef(o,m);return{type:"Sell",amountIn:n.amountIn,amountOut:s.amountOut,spotPrice:r,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e,toHuman(){return{type:"Sell",amountIn:S.toDecimal(n.amountIn,n.assetInDecimals),amountOut:S.toDecimal(s.amountOut,s.assetOutDecimals),spotPrice:S.toDecimal(r,s.assetOutDecimals),tradeFee:S.toDecimal(l,s.assetOutDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0Y(t,e,n){let s=[];for(let i=0;i<e.length;i++){let r=e[i],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;i>0?l=s[i-1]:l=t;let u=a.calculateOutGivenIn(o,l);s.push(u)}return s[s.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:s,pools:i,poolsMap:r}=n,l=i.filter(b=>b.tokens.some(h=>h.id===t)).map(b=>b.type==="Aave"?b.tokens:b.tokens.filter(h=>h.id===t)).map(b=>b.map(h=>h.balance).reduce((h,P)=>h+P)).sort((b,h)=>h<b?-1:1)[0],u=_.getFraction(l,.1),p=await Promise.all(s.map(b=>this.toSellSwaps(u,b,r))),m=this.findBestSellRoute(p).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,m),m}async toSellSwaps(t,e,n){let s=[];for(let i=0;i<e.length;i++){let r=e[i],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;i>0?l=s[i-1].amountOut:l=typeof t=="string"?S.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:d,feePct:m,errors:g}=a.validateAndSell(o,l,u),b=this.getPoolFeeRange(u),h=a.spotPriceOutGivenIn(o),P=Math.pow(10,o.decimalsIn),y=l*h/BigInt(P),v=_.calculateDiffToRef(d,y);s.push({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:d,spotPrice:h,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:v,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===r.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===r.assetIn},toHuman(){return{...r,amountIn:S.toDecimal(l,o.decimalsIn),amountOut:S.toDecimal(p,o.decimalsOut),calculatedOut:S.toDecimal(d,o.decimalsOut),spotPrice:S.toDecimal(h,o.decimalsOut),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:v,errors:g}}})}return s}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let s=this.buildRouteKey(t,e,n.pools),i=this.mlr.get(s);return i||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:s,poolsMap:i}=n,r=this.buildRouteKey(t,e,s),a=this.mlr.get(r);a||(a=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",a,i),l=this.getSellSpot(o),u=o[o.length-1].assetOutDecimals;return{amount:l,decimals:u}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((n,s)=>{let i=n[0].amountIn,r=s[0].amountIn;return i>r?1:-1});return e.find(n=>n.every(s=>s.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(a=>a.assetInDecimals).reduce((a,o)=>a+o),s=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),i=n-e.assetInDecimals,r=Math.pow(10,i);return s/BigInt(r)}async getBuy(t,e,n,s){return this.withCtx(t,e,async({paths:i,poolsMap:r})=>{let a;if(s)a=await this.toBuySwaps(n,s,r);else{let o=i.map(u=>this.toBuySwaps(n,u,r)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(r,a)})}async getBuys(t,e,n){return this.withCtx(t,e,async({paths:s,poolsMap:i})=>{let r=s.map(o=>this.toBuySwaps(n,o,i));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(i,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let n=e[e.length-1],s=e[0],i=this.isDirectTrade(e),r=this.getBuySpot(e),a=s.amountIn,o=i?s.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=i?s.tradeFeePct:_.calculateBuyFee(o,a),d=Math.pow(10,n.assetOutDecimals),m=n.amountOut*r/BigInt(d),g;return o===0n?g=-100:g=_.calculateDiffToRef(m,o),{type:"Buy",amountOut:n.amountOut,amountIn:s.amountIn,spotPrice:r,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e,toHuman(){return{type:"Buy",amountOut:S.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:S.toDecimal(s.amountIn,s.assetInDecimals),spotPrice:S.toDecimal(r,s.assetInDecimals),tradeFee:S.toDecimal(l,s.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e.map(b=>b.toHuman())}}}}calculateDelta0X(t,e,n){let s=[];for(let i=e.length-1;i>=0;i--){let r=e[i],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;i==e.length-1?l=t:l=s[0];let u=a.calculateInGivenOut(o,l);s.unshift(u)}return s[0]}async toBuySwaps(t,e,n){let s=[];for(let i=e.length-1;i>=0;i--){let r=e[i],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;i==e.length-1?l=typeof t=="string"?S.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let u=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:d,feePct:m,errors:g}=a.validateAndBuy(o,l,u),b=this.getPoolFeeRange(u),h=a.spotPriceInGivenOut(o),P=Math.pow(10,o.decimalsOut),y=l*h/BigInt(P),v;d===0n?v=-100:v=_.calculateDiffToRef(y,d),s.unshift({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:d,spotPrice:h,tradeFeePct:m,tradeFeeRange:b,priceImpactPct:v,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===r.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===r.assetIn},toHuman(){return{...r,amountOut:S.toDecimal(l,o.decimalsOut),amountIn:S.toDecimal(p,o.decimalsIn),calculatedIn:S.toDecimal(d,o.decimalsIn),spotPrice:S.toDecimal(h,o.decimalsIn),tradeFeePct:m,tradeFeeRange:b,priceImpactPct:v,errors:g}}})}return s}};var xs=6e3,_n=1000000000000000n,ue=6,An=-5,On=216e5,du=3,Is=6;var Bn=require("polkadot-api");var $=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:s,poolId:i})=>s==="Stableswap"?{pool:(0,Bn.Enum)("Stableswap",i),asset_in:e,asset_out:n}:{pool:(0,Bn.Enum)(s),asset_in:e,asset_out:n})}};var Mt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??_n})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,s,i){let[r,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,p=l[0],d=l[l.length-1],{assetInDecimals:m}=p,{assetOutDecimals:g}=d,b=Math.abs(u),h=this.getMinimumTradeCount(o,r),P=this.getOptimalTradeCount(b),y=i?Math.round(s/i):P,v=Math.ceil(s/h),w=Math.round(s/P),R=Math.round(s/y),q=o/BigInt(y),O=await this.router.getBestSell(t,e,q),G=o<r,Q=[];G&&Q.push("OrderTooSmall");let et=O.amountOut*BigInt(y),Y=this.toBlockPeriod(R),J=O.tradeFee*BigInt(y),ht=$.build(l),bt={assetIn:t,assetOut:e,errors:Q,frequencyMin:v,frequencyOpt:w,frequency:R,tradeCount:y,tradeFee:J,tradeImpactPct:O.priceImpactPct,tradePeriod:Y,tradeRoute:ht,type:"Dca"};return{...bt,amountIn:o,amountOut:et,tradeAmountIn:O.amountIn,tradeAmountOut:O.amountOut,toHuman(){return{...bt,amountIn:S.toDecimal(o,m),amountOut:S.toDecimal(et,g),tradeAmountIn:S.toDecimal(O.amountIn,m),tradeAmountOut:S.toDecimal(O.amountOut,g)}}}}async getMinimumOrderBudget(t){if(0===t)return this.minOrderBudget;let e=await this.router.getSpotPrice(0,t),n=10n**BigInt(12);if(e)return this.minOrderBudget*e.amount/n;throw new Error("Unable to calculate order budget")}getMinimumTradeCount(t,e){let n=e*2n/10n;if(n===0n)return 0;let s=t+n/2n;return Number(s/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[s,i]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:r,swaps:a,priceImpactPct:o}=i,l=a[0],u=a[a.length-1],{assetInDecimals:p}=l,{assetOutDecimals:d}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),b=r/BigInt(g),h=await this.router.getBestSell(l.assetIn,u.assetOut,b),P=g===1,y=r<s,v=h.priceImpactPct<-5,w=[];y||P?w.push("OrderTooSmall"):v&&w.push("OrderImpactTooBig");let R=h.amountOut*BigInt(g),q=h.tradeFee*BigInt(g),O=$.build(a),G={assetIn:t,assetOut:e,errors:w,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:O,type:"TwapSell"};return{...G,amountIn:r,amountOut:R,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:q,toHuman(){return{...G,amountIn:S.toDecimal(r,p),amountOut:S.toDecimal(R,d),tradeAmountIn:S.toDecimal(h.amountIn,p),tradeAmountOut:S.toDecimal(h.amountOut,d),tradeFee:S.toDecimal(q,d)}}}}async getTwapBuyOrder(t,e,n){let[s,i]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:r,swaps:a,priceImpactPct:o}=i,l=a[0],u=a[a.length-1],{assetInDecimals:p}=l,{assetOutDecimals:d}=u,m=Math.abs(o),g=this.getTwapTradeCount(m),b=r/BigInt(g),h=await this.router.getBestBuy(l.assetIn,u.assetOut,b),P=h.amountIn*BigInt(g),y=g===1,v=P<s,w=h.priceImpactPct<-5,R=[];v||y?R.push("OrderTooSmall"):w&&R.push("OrderImpactTooBig");let q=h.tradeFee*BigInt(g),O=$.build(a),G={assetIn:t,assetOut:e,errors:R,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:O,type:"TwapBuy"};return{...G,amountIn:P,amountOut:r,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:q,toHuman(){return{...G,amountIn:S.toDecimal(P,p),amountOut:S.toDecimal(r,d),tradeAmountIn:S.toDecimal(h.amountIn,p),tradeAmountOut:S.toDecimal(h.amountOut,d),tradeFee:S.toDecimal(q,p)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}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 En={};I(En,{BIG_10:()=>Rs,BIG_BILL:()=>Fn,StakingApi:()=>pe,StakingClient:()=>me});var W=require("@galacticcouncil/math-staking"),X=ot(require("big.js"));var qe={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},_s=c=>Object.keys(qe).includes(c);var As=require("polkadot-api"),Os=require("@polkadot-api/utils");function Bs(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=(0,Os.toHex)(e);return(0,As.AccountId)(63).dec(n)}var Ne="20000000000000000",Ue="2000",Rs=(0,X.default)(10),Fn=(0,X.default)(Rs.pow(12)),pe=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getPotBalance(){let t=await this.client.getPalletId(),e=Bs(t);return await this.balanceClient.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let s=e.created_at,i=await n.reduce(async(r,[a,o])=>{let l=await r,u=a,p=o.amount,d=o.conviction.toString().toLowerCase(),m=await this.client.getReferendumInfo(u);return m&&(m.type==="Approved"||m.type==="Rejected")&&_s(d)&&l.push({id:u,amount:p,conviction:d}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:s,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,s]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),i=s.find(r=>r)?.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,s){let i=(0,X.default)(0),r=(0,X.default)(0),a=qe.locked6x,o=(0,X.default)(n.toString()).mul(a),l=100,u=[];t.forEach(m=>{let g=qe[m.conviction],b=s.includes(m.id.toString());b&&u.push(m.id.toString());let h=(0,X.default)(m.amount.toString()).mul(l).div(o);i=i.plus(Math.floor(h.mul(g).toNumber())),r=r.plus(Math.floor(h.mul(b?a:g).toNumber()))});let p=Math.floor((0,X.default)(n.toString()).mul(a).mul(l).div(o).toNumber());s.forEach(m=>{u.includes(m)||(r=r.plus(p))});let d={democracyVote:1};return i=i.mul(d.democracyVote),i=i.plus(e.toString()||"0"),r=r.mul(d.democracyVote),r=r.plus(e.toString()||"0"),{currentActionPoints:i.toString(),maxActionPoints:r.toString()}}async getRewards(t,e,n){let s=await this.getStake(t),{potReservedBalance:i,accumulatedRewardPerStake:r,totalStake:a,stakePosition:o}=s;if(!o)return;let[l,u,p,d,m,g,b]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=(0,X.default)(l.transferable.toString()).minus(i.toString()),P=h.gt(0)&&a>0?(0,W.calculate_accumulated_rps)(r.toString(),h.toString(),a.toString()):r.toString(),y=(0,W.calculate_period_number)(u.toString(),n,b),v=(0,W.calculate_period_number)(u.toString(),o.createdAt.toString(),b),w=(0,W.calculate_rewards)(P,o.rewardPerStake.toString(),o.stake.toString()),R=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),q=(0,W.calculate_points)(v,y,d.toString(),m.toString(),R.currentActionPoints,g.toString(),o.accumulatedSlashPoints.toString()),O=(0,W.sigmoid)(q,Ne,Ue),G=(()=>{if(!e.length)return;let ht=(0,W.calculate_points)(v,y,d.toString(),m.toString(),R.maxActionPoints.toString(),g.toString(),o.accumulatedSlashPoints.toString());return(0,W.sigmoid)(ht,Ne,Ue)})(),Q=(0,X.default)(w).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,X.default)(y).minus(v).lte(p.toString()))return{rewards:"0",payablePercentage:O,extraPayablePercentage:G,constants:{a:Ne,b:Ue}};let et=(0,W.calculate_percentage_amount)(Q.toString(),O),Y=(0,X.default)(o.accumulatedLockedRewards.toString()),J=Y.gt(et)?Y:(0,X.default)(et);return{rewards:J.div(Fn).toString(),maxRewards:Q.div(Fn).toString(),allocatedRewardsPercentage:J.div(Q).mul(100).toNumber(),payablePercentage:O,extraPayablePercentage:G,constants:{a:Ne,b:Ue}}}};var me=class extends N{async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:r})=>{let[a,o,l]=r;return{address:a,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 Cn={};I(Cn,{TxBuilderFactory:()=>qt});var kn=require("polkadot-api");function Fs(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var Lt=class extends N{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new st(t),this.aaveUtils=new Pt(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:Ke})}async dryRun(t,e){let n=(0,kn.Enum)("Signed",t),s=(0,kn.Enum)("system",n),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),a=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(a){let o=Fs(a.value);throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var Ve=class extends Lt{_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:s}=e[0],i=await this.balanceClient.getBalance(this.beneficiary,s);return t>=i.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],i=n[n.length-1],r=_.getFraction(t,this.slippagePct),a=s.assetIn,o=i.assetOut,l=t+r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:$.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,s=n[0],i=n[n.length-1],r=_.getFraction(e,this.slippagePct),a=s.assetIn,o=i.assetOut,l=e-r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:$.build(n)}),s.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],s=e[e.length-1],i=_.getFraction(t,this.slippagePct),r=n.assetIn,a=s.assetOut,o=t-i,l=this.api.tx.Router.sell_all({asset_in:r,asset_out:a,min_amount_out:o,route:$.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var Ge=require("polkadot-api");var We=class extends Lt{_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:s,tradePeriod:i,tradeRoute:r}=this.order,a=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:(0,Ge.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:0n,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r,tradeRoute:a}=this.order,o=_.getFraction(i,this.slippagePct),l=i-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ge.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:s,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:r,tradeRoute:a}=this.order,o=_.getFraction(s,this.slippagePct),l=s+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,Ge.Enum)("Buy",{asset_in:e,asset_out:n,amount_out:i,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var qt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new Ve(this.client,this.evmClient).setTrade(t)}order(t){return new We(this.client,this.evmClient).setOrder(t)}};async function Si(c){let t=new Ot(c),e=new Kt(c),[n,s]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),i=new kt(c,e).withAave().withOmnipool().withStableswap().withXyk(),r=new st(c),a=new me(c),o=new $t(c),l=new Pt(e),u=new Dt(i),p=new Mt(u,{blockTime:n,minBudgetInNative:s}),d=new pe(a,r),m=new jt(o,r,{blockTime:n});return{api:{aave:l,router:u,scheduler:p,staking:d,farm:m},client:{asset:new At(c),balance:r,evm:e},ctx:{pool:i},tx:new qt(c,e),destroy:()=>{i.destroy()}}}0&&(module.exports={QueryBus,aave,api,big,client,const:null,createSdkContext,erc20,error,evm,farm,fmt,h160,json,math,pool,sor,staking,tx,xc});
1
+ "use strict";var $i=Object.create;var Te=Object.defineProperty;var Qi=Object.getOwnPropertyDescriptor;var Ji=Object.getOwnPropertyNames;var Zi=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty;var Kn=(c,t)=>()=>(c&&(t=c(c=0)),t);var I=(c,t)=>{for(var e in t)Te(c,e,{get:t[e],enumerable:!0})},we=(c,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ji(t))!ts.call(c,i)&&i!==e&&Te(c,i,{get:()=>t[i],enumerable:!(n=Qi(t,i))||n.enumerable});return c},_t=(c,t,e)=>(we(c,t,"default"),e&&we(e,t,"default")),ut=(c,t,e)=>(e=c!=null?$i(Zi(c)):{},we(t||!c||!c.__esModule?Te(e,"default",{value:c,enumerable:!0}):e,c)),es=c=>we(Te({},"__esModule",{value:!0}),c);var Wt={};var Qn=Kn(()=>{_t(Wt,require("@polkadot-api/ws-provider/node"))});var Yt={};var Jn=Kn(()=>{_t(Yt,require("@polkadot-api/ws-provider/web"))});var Ds={};I(Ds,{QueryBus:()=>jt,aave:()=>yn,api:()=>Ze,big:()=>f,client:()=>bn,const:()=>on,createSdkContext:()=>Ms,erc20:()=>St,error:()=>Pn,evm:()=>Sn,farm:()=>In,fmt:()=>_,h160:()=>xt,json:()=>Rt,math:()=>A,pool:()=>kn,sor:()=>Gn,staking:()=>Vn,tx:()=>Yn,xc:()=>dn});module.exports=es(Ds);var Ze={};I(Ze,{Papi:()=>N,getWs:()=>ns});var $n=require("@galacticcouncil/descriptors");function jn(c){switch(c){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}var N=class{client;api;constructor(t){this.client=t,this.api=this.client.getTypedApi($n.hydration)}log(t,...e){let n=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");jn(n)&&console.log(t,...e)}};var Zn=require("polkadot-api"),ti=require("polkadot-api/polkadot-sdk-compat"),ns=async c=>{let t=typeof c=="string"?c.split(","):c,i=(typeof window>"u"?(await Promise.resolve().then(()=>(Qn(),Wt))).getWsProvider:(await Promise.resolve().then(()=>(Jn(),Yt))).getWsProvider)(t);return(0,Zn.createClient)((0,ti.withPolkadotSdkCompat)(i))};var yn={};I(yn,{AAVE_GAS_LIMIT:()=>nn,AAVE_LENDING_POOL_ADDRESS:()=>Oe,AAVE_POOL_ABI:()=>tn,AAVE_POOL_DATA_PROVIDER:()=>_e,AAVE_POOL_DATA_PROVIDER_ABI:()=>Ie,AAVE_POOL_PROXY:()=>en,AAVE_ROUNDING_THRESHOLD:()=>Js,AAVE_UINT_256_MAX:()=>is,AaveClient:()=>zt,AaveUtils:()=>Tt});var tn=[{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 Ie=[{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 en="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",_e="0x112b087b60C1a166130d59266363C45F8aa99db0",Oe="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",nn=1000000n,Js=5,is=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var zt=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:Ie,address:_e,args:[Oe],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Ie,address:_e,args:[Oe,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:tn,address:en,args:[t],functionName:"getUserAccountData"})}};var dt=ut(require("big.js"));var f={};I(f,{asBigInt:()=>as,toBigInt:()=>rs,toDecimal:()=>ss});var gt=ut(require("big.js"));gt.default.NE=-18;function ss(c,t,e=6,n){let i=(0,gt.default)(c.toString()),s=(0,gt.default)(10).pow(t);return i.div(s).round(e,n).toString()}function rs(c,t){let e=(0,gt.default)(10).pow(t),i=(0,gt.default)(c).mul(e).toFixed(0,gt.default.roundDown);return BigInt(i)}function as(c){return BigInt(c.round(0,gt.default.roundDown).toFixed(0))}var St={};I(St,{ERC20:()=>sn});var sn=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 _={};I(_,{FeeUtils:()=>ln,shiftNeg:()=>cs});var ei=ut(require("big.js"));var on={};I(on,{HUB_ASSET_ID:()=>Xt,HYDRATION_OMNIPOOL_ADDRESS:()=>ls,HYDRATION_PARACHAIN_ID:()=>os,HYDRATION_SS58_PREFIX:()=>G,PERBILL_DENOMINATOR:()=>rn,PERMILL_DENOMINATOR:()=>Ot,RUNTIME_DECIMALS:()=>F,SYSTEM_ASSET_DECIMALS:()=>an,SYSTEM_ASSET_ID:()=>E,TRADEABLE_DEFAULT:()=>At});var F=18,Ot=1e6,rn=1e9,E=0,an=12,os=2034,G=63,ls="7L53bUTBbfuj14UpdCNPwmgzzHSsrsTWBHX5pys32mVWM3C1",Xt=1,At=15;var ln=class c{static toPct(t){let[e,n]=t;return c.safeDivide(e*100,n)}static toRaw(t){let[e,n]=t;return c.safeDivide(e,n)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,n=12){let i=10**n;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function cs(c,t){let e=(0,ei.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var xt={};I(xt,{H160:()=>pn,isEvmAccount:()=>ni,isEvmAddress:()=>ii,isSs58Address:()=>si});var Bt=require("polkadot-api"),cn=require("@polkadot-api/utils"),pt=require("buffer");var un="ETH\0";function ni(c){if(!c)return!1;try{let t=(0,Bt.AccountId)().enc(c),e=pt.Buffer.from(un);return pt.Buffer.from(t.subarray(0,e.length)).equals(e)}catch{return!1}}function ii(c){return!!/^0x[a-fA-F0-9]{40}$/.test(c)}function si(c){try{return(0,Bt.AccountId)(63).enc(c),!0}catch{return!1}}var pn=class c{static toAccount=t=>{let e=pt.Buffer.from(t.slice(2),"hex"),n=pt.Buffer.from(un),i=Uint8Array.from(pt.Buffer.concat([n,e,pt.Buffer.alloc(8)])),s=(0,cn.toHex)(i);return(0,Bt.AccountId)(63).dec(s)};static fromAccount=t=>{let e=(0,Bt.AccountId)().enc(t),n=pt.Buffer.from(un),i=e.slice(n.length,-8);return"0x"+pt.Buffer.from(i).toString("hex")};static fromSS58=t=>{let n=(0,Bt.AccountId)().enc(t).slice(0,20);return(0,cn.toHex)(n)};static fromAny=t=>{if(ii(t))return t;if(ni(t))return c.fromAccount(t);if(si(t))return c.fromSS58(t);throw new Error("Unknown address type")}};var Rt={};I(Rt,{findNestedKey:()=>us,findNestedObj:()=>ps,jsonFormatter:()=>ds});var us=(c,t)=>{let e=[];return JSON.stringify(c,(n,i)=>(i&&i[t]&&e.push(i),i)),e[0]},ps=(c,t,e)=>{let n;return JSON.stringify(c,(i,s)=>(s&&s[t]===e&&(n=s),s)),n},ds=(c,t)=>typeof t=="bigint"?t.toString():t;var A={};I(A,{calculateBuyFee:()=>ys,calculateDiffToAvg:()=>ms,calculateDiffToRef:()=>gs,calculateSellFee:()=>hs,getFraction:()=>bs});var at=ut(require("big.js"));function ms(c,t){let e=(0,at.default)(c.toString()),n=(0,at.default)(t.toString());return e.minus(n).abs().div(e.plus(n).div(2)).mul(100).round(2).toNumber()}function gs(c,t){if(t===0n)return 0;let e=(0,at.default)(c.toString()),n=(0,at.default)(t.toString());return e.minus(n).div(n).mul(100).round(2).toNumber()}function hs(c,t){let e=(0,at.default)(c.toString()),n=(0,at.default)(t.toString());return(0,at.default)(1).minus(n.div(e)).mul(100).round(2).toNumber()}function ys(c,t){let e=(0,at.default)(c.toString());return(0,at.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}function bs(c,t,e=2){(t<.01||t>100)&&new Error("Supported range is from 0.01% - 100%");let n=Math.pow(10,e),i=BigInt(t*n);return c*i/BigInt(100*n)}var dn={};I(dn,{convertToId:()=>fs});var ri=require("buffer");function fs(c){let e=ri.Buffer.from(c.replace("0x",""),"hex").subarray(16);return e.readUIntBE(0,e.length)}var Kt=(c,t)=>c===t?0:c==null?t==null?0:-1:t==null?c==null?0:1:typeof c.compare=="function"?c.compare(t):typeof t.compare=="function"?-t.compare(c):c<t?-1:c>t?1:0;var Ae=(c,t=e=>e!==void 0?": "+e:"")=>class extends Error{origMessage;constructor(e){super(c(e)+t(e)),this.origMessage=e!==void 0?String(e):""}};var Ps=Ae(()=>"illegal argument(s)"),ai=c=>{throw new Ps(c)};var vs=Ae(()=>"index out of bounds"),mn=c=>{throw new vs(c)},Be=(c,t,e)=>(c<t||c>=e)&&mn(c);var oi=23283064365386963e-26,Re=class{float(t=1){return this.int()*oi*t}probability(t){return this.float()<t}norm(t=1){return(this.int()*oi-.5)*2*t}normMinMax(t,e){let n=this.minmax(t,e);return this.float()<.5?n:-n}minmax(t,e){return this.float()*(e-t)+t}minmaxInt(t,e){t|=0;let n=(e|0)-t;return n?t+this.int()%n:t}minmaxUint(t,e){t>>>=0;let n=(e>>>0)-t;return n?t+this.int()%n:t}};var Fe=class extends Re{constructor(t){super(),this.rnd=t}float(t=1){return this.rnd()*t}norm(t=1){return(this.rnd()-.5)*2*t}int(){return this.rnd()*4294967296>>>0}};var li=new Fe(Math.random);var ci=c=>c!=null&&typeof c!="function"&&c.length!==void 0;var ui=Object.getPrototypeOf({}),Ee="function",pi="string",Ft=(c,t)=>{let e;if(c===t)return!0;if(c!=null){if(typeof c.equiv===Ee)return c.equiv(t)}else return c==t;if(t!=null){if(typeof t.equiv===Ee)return t.equiv(c)}else return c==t;return typeof c===pi||typeof t===pi?!1:(e=Object.getPrototypeOf(c),(e==null||e===ui)&&(e=Object.getPrototypeOf(t),e==null||e===ui)?Ts(c,t):typeof c!==Ee&&c.length!==void 0&&typeof t!==Ee&&t.length!==void 0?Ss(c,t):c instanceof Set&&t instanceof Set?xs(c,t):c instanceof Map&&t instanceof Map?ws(c,t):c instanceof Date&&t instanceof Date?c.getTime()===t.getTime():c instanceof RegExp&&t instanceof RegExp?c.toString()===t.toString():c!==c&&t!==t)},Ss=(c,t,e=Ft)=>{let n=c.length;if(n===t.length)for(;n-- >0&&e(c[n],t[n]););return n<0},xs=(c,t,e=Ft)=>c.size===t.size&&e([...c.keys()].sort(),[...t.keys()].sort()),ws=(c,t,e=Ft)=>c.size===t.size&&e([...c].sort(),[...t].sort()),Ts=(c,t,e=Ft)=>{if(Object.keys(c).length!==Object.keys(t).length)return!1;for(let n in c)if(!t.hasOwnProperty(n)||!e(c[n],t[n]))return!1;return!0};var gn=class{value;constructor(t){this.value=t}deref(){return this.value}};var di=c=>c instanceof gn;var Ce=class c{_head;_length=0;constructor(t){t&&this.into(t)}get length(){return this._length}get head(){return this._head}[Symbol.iterator](){return mi("next",this._head)}reverseIterator(){return mi("prev",this.tail)}clear(){this.release()}compare(t,e=Kt){let n=this._length;if(n<t._length)return-1;if(n>t._length)return 1;if(n===0)return 0;{let i=this._head,s=t._head,r=0;for(;n-- >0&&r===0;)r=e(i.value,s.value),i=i.next,s=s.next;return r}}concat(...t){let e=this.copy();for(let n of t)e.into(n);return e}equiv(t){if(!(t instanceof c||ci(t))||this._length!==t.length)return!1;if(!this._length||this===t)return!0;let e=t[Symbol.iterator](),n=this._head;for(let i=this._length;i-- >0;){if(!Ft(n.value,e.next().value))return!1;n=n.next}return!0}filter(t){let e=this.empty();return this.traverse(n=>(t(n.value)&&e.append(n.value),!0)),e}find(t){return this.traverse(e=>e.value!==t)}findWith(t){return this.traverse(e=>!t(e.value))}first(){return this._head?.value}insertSorted(t,e){e=e||Kt;for(let n=this._head,i=this._length;i-- >0;){if(e(t,n.value)<=0)return this.insertBefore(n,t);n=n.next}return this.append(t)}into(t){for(let e of t)this.append(e);return this}nth(t,e){let n=this.nthCell(t);return n?n.value:e}nthCellUnsafe(t){let e,n;for(t<=this._length>>>1?(e=this._head,n="next"):(e=this.tail,n="prev",t=this._length-t-1);t-- >0&&e;)e=e[n];return e}peek(){return this.tail?.value}$reduce(t,e){let n=this._head;for(let i=this._length;i-- >0&&!di(e);)e=t(e,n.value),n=n.next;return e}reduce(t,e){return this.$reduce(t,e)}release(){let t=this._head;if(!t)return!0;let e;for(let n=this._length;n-- >0;)e=t.next,delete t.value,delete t.prev,delete t.next,t=e;return this._head=void 0,this._length=0,!0}reverse(){let t=this._head,e=this.tail,n=(this._length>>>1)+(this._length&1);for(;t&&e&&n>0;){let i=t.value;t.value=e.value,e.value=i,t=t.next,e=e.prev,n--}return this}setHead(t){let e=this._head;return e?(e.value=t,e):this.prepend(t)}setNth(t,e){let n=this.nthCell(t);return!n&&mn(t),n.value=e,n}setTail(t){let e=this.tail;return e?(e.value=t,e):this.append(t)}swap(t,e){if(t!==e){let n=t.value;t.value=e.value,e.value=n}return this}toArray(t=[]){return this.traverse(e=>(t.push(e.value),!0)),t}toJSON(){return this.toArray()}toString(){let t=[];return this.traverse(e=>(t.push(String(e.value)),!0)),t.join(", ")}traverse(t,e=this._head,n){if(!this._head)return;let i=e;do{if(!t(i))break;i=i.next}while(i!==n);return i}_map(t,e){return this.traverse(n=>(t.append(e(n.value)),!0)),t}};function*mi(c,t){for(;t;)yield t.value,t=t[c]}var ke=class c extends Ce{_tail;constructor(t){super(),t&&this.into(t)}get tail(){return this._tail}append(t){if(this._tail){let e={value:t,prev:this._tail};return this._tail.next=e,this._tail=e,this._length++,e}else return this.prepend(t)}asHead(t){return t===this._head?this:(this.remove(t),this._head.prev=t,t.next=this._head,t.prev=void 0,this._head=t,this._length++,this)}asTail(t){return t===this._tail?this:(this.remove(t),this._tail.next=t,t.prev=this._tail,t.next=void 0,this._tail=t,this._length++,this)}cons(t){return this.prepend(t),this}copy(){return new c(this)}*cycle(){for(;;)yield*this}drop(){let t=this._head;if(t)return this._head=t.next,this._head?this._head.prev=void 0:this._tail=void 0,this._length--,t.value}empty(){return new c}insertAfter(t,e){let n={value:e,next:t.next,prev:t};return t.next?t.next.prev=n:this._tail=n,t.next=n,this._length++,n}insertAfterNth(t,e){return t<0&&(t+=this._length),t>=this._length-1?this.append(e):(Be(t,0,this._length),this.insertAfter(this.nthCellUnsafe(t),e))}insertBefore(t,e){let n={value:e,next:t,prev:t.prev};return t.prev?t.prev.next=n:this._head=n,t.prev=n,this._length++,n}insertBeforeNth(t,e){return t<0&&(t+=this._length),t<=0?this.prepend(e):(Be(t,0,this._length),this.insertBefore(this.nthCellUnsafe(t),e))}map(t){return this._map(new c,t)}nth(t,e){let n=this.nthCell(t);return n?n.value:e}nthCell(t){if(t<0&&(t+=this._length),!(t<0||t>=this._length))return this.nthCellUnsafe(t)}pop(){let t=this._tail;if(t)return this._tail=t.prev,this._tail?this._tail.next=void 0:this._head=void 0,this._length--,t.value}prepend(t){let e={value:t,next:this._head};return this._head?this._head.prev=e:this._tail=e,this._head=e,this._length++,e}push(t){return this.append(t),this}release(){return this._tail=void 0,super.release()}remove(t){return t.prev?t.prev.next=t.next:this._head=t.next,t.next?t.next.prev=t.prev:this._tail=t.prev,this._length--,this}rotateLeft(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:return this.push(this.drop())}}rotateRight(){switch(this._length){case 0:case 1:return this;case 2:return this.swap(this._head,this._tail);default:let t=this.peek();return this.pop(),this.prepend(t),this}}seq(t=0,e=this.length){if(t>=e||t<0)return;let n=this.nthCell(t),i=this.nthCell(e-1),s=r=>({first(){return r.value},next(){return r!==i&&r.next?s(r.next):void 0}});return n?s(n):void 0}shuffle(t,e=li){if(this._length<2)return this;for(t=t!==void 0?t:Math.ceil(1.5*Math.log2(this._length));t>0;t--){let n=this._head;for(;n;){let i=n.next;e.probability(.5)?this.asHead(n):this.asTail(n),n=i}}return this}slice(t=0,e=this.length){let n=t<0?t+this._length:t,i=e<0?e+this._length:e;(n<0||i<0)&&ai("invalid indices: ${from} / ${to}");let s=new c,r=this.nthCell(n);for(;r&&++n<=i;)s.push(r.value),r=r.next;return s}sort(t=Kt){if(!this._length)return this;let e=1;for(;;){let n=this._head;this._head=void 0,this._tail=void 0;let i=0;for(;n;){i++;let s=n,r=0;for(let o=0;o<e&&(r++,s=s.next,!!s);o++);let a=e;for(;r>0||a>0&&s;){let o;r===0?(o=s,s=s.next,a--):!s||a===0||t(n.value,s.value)<=0?(o=n,n=n.next,r--):(o=s,s=s.next,a--),this._tail?this._tail.next=o:this._head=o,o.prev=this._tail,this._tail=o}n=s}if(this._tail.next=void 0,i<=1)return this;e*=2}}splice(t,e=0,n){let i;typeof t=="number"?(t<0&&(t+=this._length),Be(t,0,this._length),i=this.nthCellUnsafe(t)):i=t;let s=new c;if(e>0)for(;i&&e-- >0;)this.remove(i),s.push(i.value),i=i.next;else i&&(i=i.next);if(n)if(i)for(let r of n)this.insertBefore(i,r);else for(let r of n)this.push(r);return s}};var Me=class c{map;items;opts;_size;constructor(t,e){let n={maxlen:1/0,maxsize:1/0,map:()=>new Map,ksize:()=>0,vsize:()=>0,...e};this.map=n.map(),this.items=new ke,this._size=0,this.opts=n,t&&this.into(t)}get length(){return this.items.length}get size(){return this._size}[Symbol.iterator](){return this.entries()}*entries(){for(let t of this.items)yield[t.k,t]}*keys(){for(let t of this.items)yield t.k}*values(){for(let t of this.items)yield t.v}copy(){let t=this.empty();t.items=this.items.copy();let e=t.items.head;for(;e;)t.map.set(e.value.k,e),e=e.next;return t}empty(){return new c(null,this.opts)}release(){this._size=0,this.map.clear();let t=this.opts.release;if(t){let e;for(;e=this.items.drop();)t(e.k,e.v);return!0}return this.items.release()}has(t){return this.map.has(t)}get(t,e){let n=this.map.get(t);return n?this.resetEntry(n):e}set(t,e){let n=this.opts.ksize(t)+this.opts.vsize(e),i=this.map.get(t),s=Math.max(0,n-(i?i.value.s:0));return this._size+=s,this.ensureSize()?this.doSetEntry(i,t,e,n):this._size-=s,e}into(t){for(let e of t)this.set(e[0],e[1]);return this}async getSet(t,e){let n=this.map.get(t);return n?this.resetEntry(n):this.set(t,await e())}delete(t){let e=this.map.get(t);return e?(this.removeEntry(e),!0):!1}resetEntry(t){return this.items.asTail(t),t.value.v}ensureSize(){let{release:t,maxsize:e,maxlen:n}=this.opts;for(;this._size>e||this.length>=n;){let i=this.items.drop();if(!i)return!1;this.map.delete(i.k),t?.(i.k,i.v),this._size-=i.s}return!0}removeEntry(t){let e=t.value;this.map.delete(e.k),this.items.remove(t),this.opts.release?.(e.k,e.v),this._size-=e.s}doSetEntry(t,e,n,i){t?(this.opts.update?.(e,t.value.v,n),t.value.v=n,t.value.s=i,this.items.asTail(t)):(this.items.push({k:e,v:n,s:i}),this.map.set(e,this.items.tail))}};var wt=class c extends Me{constructor(t,e){super(t,{ttl:3600*1e3,autoExtend:!1,...e})}empty(){return new c(null,this.opts)}has(t){return this.get(t)!==void 0}get(t,e){let n=this.map.get(t);if(n){if(n.value.t>=Date.now())return this.resetEntry(n);this.removeEntry(n)}return e}set(t,e,n=this.opts.ttl){let i=this.opts.ksize(t)+this.opts.vsize(e),s=this.map.get(t),r=Math.max(0,i-(s?s.value.s:0));return this._size+=r,this.ensureSize()?this.doSetEntry(s,t,e,i,n):this._size-=r,e}async getSet(t,e,n=this.opts.ttl){let i=this.get(t);return i!==void 0?i:this.set(t,await e(),n)}prune(){let t=Date.now(),e=this.items.head,n=0;for(;e;)e.value.t<t&&(this.removeEntry(e),n++),e=e.next;return n}ensureSize(){let{maxlen:t,maxsize:e}=this.opts,n=Date.now(),i=this.items.head;for(;i&&(this._size>e||this.length>=t);)i.value.t<n&&this.removeEntry(i),i=i.next;return super.ensureSize()}doSetEntry(t,e,n,i,s=this.opts.ttl){let r=Date.now()+s;t?(this.opts.update?.(e,t.value.v,n),t.value.v=n,t.value.s=i,t.value.t=r,this.items.asTail(t)):(this.items.push({k:e,v:n,s:i,t:r,ttl:s}),this.map.set(e,this.items.tail))}resetEntry(t){return this.opts.autoExtend&&(t.value.t=Date.now()+t.value.ttl),super.resetEntry(t)}};var jt=class{debug;constructor(t){this.debug=t||!1}log(t,e,n){this.debug&&console.log(t,e,n)}scope(t,e,n,i){let s=new Map,r=i!==void 0?new wt(null,{ttl:i}):new wt;return{get:(...u)=>{let p=n(...u);if(s.has(p)){this.log("[live]",t,p);let d=s.get(p);return Promise.resolve(d)}if(r.has(p))return this.log("[memo]",t,p),r.get(p);this.log("[fetch]",t,p);let m=e(...u).catch(d=>{throw r.delete(p),d});return r.set(p,m),m},set:(u,...p)=>{let m=n(...p);this.log("[set-live]",t,m),s.set(m,u)},clear:()=>{this.log("[clear]",t),s.clear(),r.release()}}}};var{ERC20:De}=St,{H160:hn}=xt,Is=1.01,_s=31536000n,Le=10n**27n,Tt=class{client;constructor(t){this.client=new zt(t)}async getSummary(t){let e=hn.fromAny(t),[n,i,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[a]=n,[o,l]=i,[u,p,m,d,g,y]=s,h=f.toDecimal(y,18),P=[];for(let b of o){let S=b.underlyingAsset.toLowerCase(),x=a.find(({underlyingAsset:Je})=>Je.toLowerCase()===S);if(!x)throw new Error("Missing pool reserve for "+S);let O=b.scaledATokenBalance,D=x.liquidityIndex,R=x.liquidityRate,Y=x.availableLiquidity,Z=x.priceInMarketReferenceCurrency,rt=r+6,K=this.calculateLinearInterest(R,x.lastUpdateTimestamp,rt),tt=D*K/Le,Pt=O*tt/Le,ve=Number(l!==0&&l===x.eModeCategoryId?x.eModeLiquidationThreshold:x.reserveLiquidationThreshold)/1e4,Se=x.usageAsCollateralEnabled&&b.usageAsCollateralEnabledOnUser&&b.scaledATokenBalance>0n,xe=De.toAssetId(S);P.push({aTokenBalance:Pt,availableLiquidity:Y,decimals:Number(x.decimals),isCollateral:Se,priceInRef:Z,reserveId:xe,reserveAsset:S,reserveLiquidationThreshold:ve})}return{healthFactor:Number(h),totalCollateral:u,totalDebt:p,reserves:P}}async hasBorrowPositions(t){let e=hn.fromAny(t),n=await this.client.getUserAccountData(e),[i,s]=n;return s>0n}async getHealthFactor(t){let e=hn.fromAny(t),n=await this.client.getUserAccountData(e),[i,s,r,a,o,l]=n,u=f.toDecimal(l,18);return Number(u)}async getHealthFactorAfterWithdraw(t,e,n){let{totalCollateral:i,totalDebt:s,reserves:r}=await this.getSummary(t),a=De.fromAssetId(e),o=r.find(P=>P.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,isCollateral:u,priceInRef:p,reserveLiquidationThreshold:m}=o,d=f.toBigInt(n,l),g=u?d*p/10n**BigInt(l):0n,y=i-g;if(y<=0n)return 0;let h=(0,dt.default)(y.toString()).mul(m).div(s.toString()).toFixed(6,dt.default.roundDown);return Number(h)}async getHealthFactorAfterSupply(t,e,n){let{totalCollateral:i,totalDebt:s,reserves:r}=await this.getSummary(t),a=De.fromAssetId(e),o=r.find(h=>h.reserveAsset===a);if(!o)throw new Error("Missing reserve ctx for "+a);let{decimals:l,priceInRef:u,reserveLiquidationThreshold:p}=o,d=f.toBigInt(n,l)*u/10n**BigInt(l),g=i+d;if(g<=0n)return 0;let y=(0,dt.default)(g.toString()).mul(p).div(s.toString()).toFixed(6,dt.default.roundDown);return Number(y)}async getMaxWithdraw(t,e){let{totalDebt:n,reserves:i,healthFactor:s}=await this.getSummary(t),r=De.fromAssetId(e),a=i.find(o=>o.reserveAsset===r);if(!a)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(a,n,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:n,healthFactor:i}=await this.getSummary(t),s={};for(let r of n){let a=this.calculateWithdrawMax(r,e,i);r.reserveId&&(s[r.reserveId]=a)}return s}calculateWithdrawMax(t,e,n){let{aTokenBalance:i,availableLiquidity:s,decimals:r,priceInRef:a,reserveLiquidationThreshold:o,isCollateral:l}=t,u=i;if(l&&e>0n){let m=n-Is;if(m>0){let d=(0,dt.default)(m).mul(e.toString()).div(o).toFixed(0,dt.default.roundDown),g=(0,dt.default)(d).div(a.toString()).mul(10**r).toFixed(0,dt.default.roundDown);u=i<BigInt(g)?i:BigInt(g)}else u=0n}return{amount:u<s?u:s,decimals:r}}calculateLinearInterest(t,e,n){let i=n-e;if(i<=0)return Le;let s=t*BigInt(i)/_s;return Le+s}};var bn={};I(bn,{AssetClient:()=>Et,BalanceClient:()=>ot,ChainParams:()=>Ct});var Et=class extends N{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(t){super(t)}async queryShares(){let e=await this.api.query.Stableswap.Pools.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[s]=n;return[s,i]}))}async queryBonds(){let e=await this.api.query.Bonds.Bonds.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[s]=n;return[s,i]}))}async queryAssets(){let e=await this.api.query.AssetRegistry.Assets.getEntries();return new Map(e.filter(({value:n})=>{let{asset_type:i}=n;return this.SUPPORTED_TYPES.includes(i.type)}).map(({keyArgs:n,value:i})=>{let[s]=n;return[s,i]}))}async queryAssetLocations(){let e=await this.api.query.AssetRegistry.AssetLocations.getEntries();return new Map(e.map(({keyArgs:n,value:i})=>{let[s]=n;return[s,i]}))}async mapToken(t,e,n,i){let{name:s,asset_type:r,is_sufficient:a,existential_deposit:o}=e,{symbol:l,decimals:u}=n.get(t)??{};return{id:t,name:s?.asText(),symbol:l,decimals:u,icon:l,type:r.type,isSufficient:a,location:i,existentialDeposit:o}}async mapBond(t,e,n,i){let[s,r]=i,{asset_type:a,is_sufficient:o,existential_deposit:l}=e,{symbol:u,decimals:p}=await this.mapToken(s,e,n),m=Number(r),d=new Intl.DateTimeFormat("en-GB"),g=[u,"Bond",d.format(m)].join(" ");return{id:t,name:g,symbol:u+"b",decimals:p,icon:u,type:a.type,isSufficient:o,existentialDeposit:l,underlyingAssetId:s,maturity:m}}async mapShares(t,e,n,i){let{assets:s}=i,{name:r,symbol:a,asset_type:o,is_sufficient:l,existential_deposit:u}=e,p=await Promise.all(s.map(async g=>{let{symbol:y}=await this.mapToken(g,e,n);return[g,y]})),m=Object.fromEntries(p),d=Object.values(m);return{id:t,name:d.join(", "),symbol:a?.asText()||r?.asText(),decimals:18,icon:d.join("/"),type:o.type,isSufficient:l,existentialDeposit:u,meta:m}}async mapExternal(t,e,n,i){let s=await this.mapToken(t,e,new Map,i),r=n?.find(a=>a.internalId===s.id);return r?{...s,decimals:r.decimals,name:r.name,symbol:r.symbol,icon:r.symbol,isWhiteListed:r.isWhiteListed}:s}parseMetadata(t){return new Map(Array.from(t,([e,n])=>[e,{symbol:n.symbol?.asText(),decimals:n.decimals}]))}async getOnChainAssets(t,e){let[n,i,s,r]=await Promise.all([this.queryAssets(),this.queryAssetLocations(),this.queryShares(),this.queryBonds()]),a=this.parseMetadata(n),o=[];for(let[l,u]of Array.from(n)){let p=i.get(l),{asset_type:m}=u,d;switch(m.type){case"Bond":let g=r.get(l);d=await this.mapBond(l,u,a,g);break;case"StableSwap":let y=s.get(l);d=await this.mapShares(l,u,a,y);break;case"External":d=await this.mapExternal(l,u,e,p);break;default:d=await this.mapToken(l,u,a,p)}o.push(d)}return t?o:o.filter(l=>this.isValidAsset(l))}isValidAsset(t){let e=Math.sign(t.decimals);return!!t.symbol&&(e===0||e===1)}};var T=require("rxjs");var ot=class extends N{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 i=await this.api.query.Tokens.Accounts.getValue(t,e);return this.calculateBalance(i)}async getErc20Balance(t,e){return this.getTokenBalanceData(t,e)}subscribeBalance(t){let e=this.subscribeSystemBalance(t),n=this.subscribeTokensBalance(t),i=this.subscribeErc20Balance(t);return(0,T.combineLatest)([e,n,i]).pipe((0,T.debounceTime)(250),(0,T.map)(s=>s.flat()),(0,T.startWith)([]),(0,T.bufferCount)(2,1),(0,T.map)(([s,r],a)=>a===0?r:this.getDeltas(s,r)))}subscribeSystemBalance(t){return this.api.query.System.Account.watchValue(t,"best").pipe((0,T.map)(n=>({id:0,balance:this.calculateBalance(n.data)})))}subscribeTokenBalance(t,e){return this.api.query.Tokens.Accounts.watchValue(t,e,"best").pipe((0,T.map)(i=>({id:e,balance:i})))}subscribeTokensBalance(t){return this.api.query.Tokens.Accounts.watchEntries(t,{at:"best"}).pipe((0,T.distinctUntilChanged)((n,i)=>!i.deltas),(0,T.map)(({deltas:n})=>{let i=[];return n?.deleted.forEach(s=>{let[r,a]=s.args;i.push({id:a,balance:this.calculateBalance({free:0n,reserved:0n,frozen:0n})})}),n?.upserted.forEach(s=>{let[r,a]=s.args;i.push({id:a,balance:this.calculateBalance(s.value)})}),i}))}subscribeErc20Balance(t,e){let n=new T.Subject,i=n.pipe((0,T.shareReplay)(1)),s=async()=>(await this.api.query.AssetRegistry.Assets.getEntries()).filter(({value:l})=>{let{asset_type:u}=l;return u.type==="Erc20"}).map(({keyArgs:l})=>{let[u]=l;return u}),r=async()=>{let o=e||await s(),l=async()=>{let m=(await Promise.all(o.map(async d=>{let g=await this.getTokenBalanceData(t,d);return[d,g]}))).map(([d,g])=>({id:d,balance:g}));n.next(m)};await l();let u=this.api.query.System.Number.watchValue("best").subscribe(l);return()=>u.unsubscribe()},a;return r().then(o=>a=o),i.pipe((0,T.finalize)(()=>a?.()),(0,T.pairwise)(),(0,T.map)(([o,l],u)=>u===0?l.filter(p=>p.balance.transferable>0n):this.getDeltas(o,l)),(0,T.distinctUntilChanged)((o,l)=>l.length===0))}async getTokenBalanceData(t,e){let n=await this.api.apis.CurrenciesApi.account(e,t);return this.calculateBalance(n)}calculateBalance(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,n=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:n,transferable:e}}getDeltas(t,e){let n=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,i=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!n(s.balance,i.get(s.id)))}};var Ct=class extends N{_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 Pn={};I(Pn,{AssetNotFound:()=>fn,PoolNotFound:()=>$t,RouteNotFound:()=>Qt});var fn=class extends Error{constructor(t){super(),this.message=`${t} not found`,this.name="AssetNotFound"}},$t=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}},Qt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var Sn={};I(Sn,{EvmClient:()=>Jt,createChain:()=>vn});var gi=require("viem"),Os=["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"],vn=()=>(0,gi.defineChain)({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:Os}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1});var lt=require("viem");var Jt=class{client;chain;constructor(t){this.client=t,this.chain=vn()}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return(0,lt.createPublicClient)({chain:this.chain,transport:(0,lt.http)()})}getWsProvider(){return(0,lt.createPublicClient)({transport:(0,lt.custom)({request:({method:t,params:e})=>this.client._request(t,e||[])})})}getSigner(t){return(0,lt.createWalletClient)({account:t,chain:this.chain,transport:(0,lt.custom)(window.ethereum)})}};var In={};I(In,{LiquidityMiningApi:()=>Zt,LiquidityMiningClient:()=>te});var bi=require("polkadot-api"),U=ut(require("big.js")),Tn=require("@galacticcouncil/math-liquidity-mining");var qe=class{result=new Map;getKey(t,e){return[e,t.toString()].join(",")}constructor(t,e){for(let n=0;n<t.length;++n){let[i,s]=t[n];this.result.set(this.getKey(s,i),e[n].free)}}freeBalance(t,e){return this.result.get(this.getKey(t,e))??0n}transfer(t,e,n,i){let s=this.getKey(t,e),r=this.getKey(t,n),a=this.result.get(s)??0n,o=this.result.get(r)??0n;if(a<i)throw new Error("Attempting to transfer more than is present");this.result.set(s,a+i),this.result.set(r,o+i)}};var ht=ut(require("big.js")),et=require("@galacticcouncil/math-liquidity-mining");var xn=ut(require("big.js")),wn=(0,xn.default)(10).pow(18),hi=BigInt((0,xn.default)(1).pow(18).toString()),yi=6e3;var As="1000000000000000000",Ne=class{constructor(t,e,n){this.getAccount=t;this.getAsset=e;this.multiCurrency=n}async syncGlobalFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===e)return null;if(t.total_shares_z===0n)return t;let i=await this.getAsset(t.reward_currency),s=e-t.updated_at,r=this.getAccount(t.id),a=i?.existential_deposit;if(!a)throw new Error("Missing reward currency asset list");let o=this.multiCurrency.freeBalance(t.reward_currency,r),l=(0,ht.default)(a.toString()),u=(0,ht.default)(o.toString()).minus(l.lt(o.toString())?a.toString():o.toString()),p=(0,ht.default)((0,et.calculate_global_farm_rewards)(t.total_shares_z.toString(),n.toString(),(0,ht.default)(t.yield_per_period.toString()).mul(wn).round(0,ht.default.roundDown).toFixed(),t.max_reward_per_period.toString(),s.toFixed()));if(u.lt(p)&&(p=u),p.eq(0))return t;let m=this.getAccount(0);return this.multiCurrency.transfer(t.reward_currency,r,m,BigInt(p.toFixed())),{...t,accumulated_rpz:BigInt((0,et.calculate_accumulated_rps)(t.accumulated_rpz.toString(),t.total_shares_z.toString(),p.toFixed()))}}syncYieldFarm(t,e,n){if(t.state.type!=="Active"||t.updated_at===n)return null;if(t.total_valued_shares===0n)return{...t,updated_at:n};let i=(0,et.calculate_yield_farm_delta_rpvs)(t.accumulated_rpz.toString(),e.accumulated_rpz.toString(),t.multiplier.toString(),t.total_valued_shares.toString());return{...t,accumulated_rpvs:t.accumulated_rpvs+BigInt(i),updated_at:n}}getLoyaltyMultiplier(t,e){let n=(0,ht.default)(1).mul(wn).round(0,ht.default.roundDown).toString();if(!e)return n;let{initial_reward_percentage:i,scale_coef:s}=e;return(0,et.calculate_loyalty_multiplier)(t.toFixed(),i.toString(),s.toFixed())}async claimRewards(t,e,n,i,s){if(e.state.type==="Terminated")return null;let r=Math.floor(i/t.blocks_per_period);if(n.updated_at===r)return null;let a=await this.syncGlobalFarm(t,r,s);if(!a)return null;let o=this.syncYieldFarm(e,a,r);if(!o)return null;let l=o.total_stopped-n.stopped_at_creation,u=o.updated_at-n.entered_at-l,p=this.getLoyaltyMultiplier(u,o.loyalty_curve),m=BigInt((0,et.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),p)),d=BigInt((0,et.calculate_user_reward)(n.accumulated_rpvs.toString(),n.valued_shares.toString(),n.accumulated_claimed_rewards.toString(),o.accumulated_rpvs.toString(),As));return{reward:m,maxReward:d,assetId:a.reward_currency,yieldFarmId:o.id,isActiveFarm:o.state.type==="Active"}}};var Bs=(0,U.default)(365.2425).times(24).times(60).times(60),Zt=class{client;balanceClient;options;constructor(t,e,n={}){this.client=t,this.balanceClient=e,this.options=Object.freeze({blockTime:n.blockTime??yi})}get blockTime(){return this.options.blockTime}async getOraclePrice(t,e){let n=[t,e].sort((s,r)=>s-r);if(t===e)return hi;let i=await this.client.getOraclePrice(n);if(i){let{n:s,d:r}=i[0].price,a;return t<e?a=(0,Tn.fixed_from_rational)(s.toString(),r.toString()):a=(0,Tn.fixed_from_rational)(r.toString(),s.toString()),BigInt(a)}}getFarmAddress=(t,e)=>{let n=Buffer.from("modl","utf-8"),i=Buffer.from(e?"78796b4c4d704944":"4f6d6e6957684c4d","hex"),s=Buffer.from([t]),r=Buffer.concat([n,i,s]),o="0x"+Buffer.concat([r,Buffer.alloc(32-r.length)]).toString("hex");return(0,bi.AccountId)(63).dec(o)};getGlobalRewardPerPeriod(t,e,n,i){let s=(0,U.default)(i).times(t.toString()).times(e.toString()).div(18);return s.gte(n.toString())?n.toString():s.toString()}getPoolYieldPerPeriod(t,e,n,i){let s=(0,U.default)(t.toString()).times(e),r=(0,U.default)(n.toString()).times(i);return s.div(r.toString()).toString()}farmData(t,e,n){let{yieldFarm:i,globalFarm:s,priceAdjustment:r,balance:a,id:o}=t,{multiplier:l,loyalty_curve:u}=i,{blocks_per_period:p,yield_per_period:m,total_shares_z:d,max_reward_per_period:g,pending_rewards:y,accumulated_paid_rewards:h,planned_yielding_periods:P,updated_at:b,incentivized_asset:S,reward_currency:x,price_adjustment:O,min_deposit:D}=s,R=_.shiftNeg(r??O,18),Y=_.shiftNeg(l,18),Z=_.shiftNeg(u?.initial_reward_percentage??0,18),rt=Bs.div((0,U.default)(this.blockTime).div(1e3).times(p)).toString(),K;if(d<=0)K=(0,U.default)(Y).times(m.toString()).times(rt).toString();else{let Ki=this.getGlobalRewardPerPeriod(d,m,g,R),ji=this.getPoolYieldPerPeriod(Ki,Y,d,R);K=(0,U.default)(ji).times(rt).toString()}let tt=y+h,Pt=g*BigInt(P),vt=a.transferable+tt,zn=vt-tt,ve=(0,U.default)(zn.toString()).div(g.toString()),Se=(0,U.default)(e).div(p.toString()).toString(),xe=(d>=0?ve.plus(b):ve.plus(Se)).toString(),Je=(0,U.default)(xe).times(p).toString(),zi=(0,U.default)(d.toString()).div((0,U.default)(g.toString()).div(m.toString())).div(Math.pow(10,18)).times(100).times(R).toFixed(2),Xn=(0,U.default)(tt.toString()).div(vt.toString()).gte(.999);K=Xn?"0":(0,U.default)(K).div(n?2:1).times(100).toString();let Xi=Z?(0,U.default)(K).times(Z).toString():void 0;return{apr:K,minApr:Xi,isDistributed:Xn,estimatedEndPeriod:xe,estimatedEndBlock:Je,maxRewards:Pt,incentivizedAsset:S,rewardCurrency:x,loyaltyCurve:u,currentPeriod:Se,potMaxRewards:vt,fullness:zi,yieldFarmId:i.id,globalFarmId:s.id,poolId:o,distributedRewards:tt,plannedYieldingPeriods:P,minDeposit:D}}async getAllOmnipoolFarms(){let e=(await this.client.getAllOmnipooFarms()).reduce((i,s)=>i.includes(s.keyArgs[0].toString())?i:[...i,s.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async i=>{let s=await this.getOmnipoolFarms(i);if(s)return[i,s]}));return Object.fromEntries(n.filter(i=>!!i))}async getOmnipoolFarms(t){let e=await this.client.getOmnipooFarms(Number(t)),n=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:s,value:r})=>{let[,a]=s,o=r,l=await this.client.getOmnipoolGlobalFarm(a),u=await this.client.getOmnipoolYieldFarm(Number(t),a,o);if(!l||!u)return;let p=l.reward_currency,m=l.incentivized_asset,d=this.getFarmAddress(a),g=await this.getOraclePrice(p,m),y=await this.balanceClient.getBalance(d,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:g,balance:y}}));return n?i.map(s=>s?this.farmData(s,n):void 0):[]}async getAllIsolatedFarms(){let e=(await this.client.getAllIsolatedFarms()).reduce((i,s)=>i.includes(s.keyArgs[0].toString())?i:[...i,s.keyArgs[0].toString()],[]),n=await Promise.all(e.map(async i=>{let s=await this.getIsolatedFarms(i);if(s)return[i,s]}));return Object.fromEntries(n.filter(i=>!!i))}async getIsolatedFarms(t){let e=await this.client.getIsolatedFarms(t),n=await this.client.getRelayBlockNumber(),i=await Promise.all(e.map(async({keyArgs:s,value:r})=>{let[,a]=s,o=r,l=await this.client.getIsolatedGlobalFarm(a),u=await this.client.getIsolatedYieldFarm(t,a,o);if(!l||!u)return;let p=l.reward_currency,m=l.incentivized_asset,d=this.getFarmAddress(a,!0),g=await this.getOraclePrice(p,m),y=await this.balanceClient.getBalance(d,p);return{id:t,globalFarm:l,yieldFarm:u,priceAdjustment:g,balance:y,farmAddress:d}}));return n?i.map(s=>s?this.farmData(s,n,!0):void 0):[]}async getDepositReward(t,e,n,i){let s=e.global_farm_id,r=e.yield_farm_id,a=n?await this.client.getIsolatedYieldFarm(t,s,r):await this.client.getOmnipoolYieldFarm(Number(t),s,r),o=n?await this.client.getIsolatedGlobalFarm(s):await this.client.getOmnipoolGlobalFarm(s);if(!o||!a)return;let l=o.reward_currency,u=o.incentivized_asset,p=[[this.getFarmAddress(0,n),o.reward_currency],[this.getFarmAddress(o.id,n),o.reward_currency]],m=await this.getAccountAssetBalances(p),d=await this.getOraclePrice(l,u),g=new qe(p,m),h=await new Ne(b=>this.getFarmAddress(b),b=>this.client.getAsset(b),g).claimRewards(o,a,e,i,d??o.price_adjustment);if(!h)return;let P=await this.client.getAsset(h.assetId);if(P&&!(h.reward<=P.existential_deposit))return h}async getAccountAssetBalances(t){let[e,n]=await Promise.all([Promise.all(t.filter(([s,r])=>r!==0).map(([s,r])=>this.balanceClient.getTokenBalance(s,r))),Promise.all(t.filter(([s,r])=>r===0).map(([s])=>this.balanceClient.getSystemBalance(s)))]),i=[];for(let s=0,r=0;s+r<t.length;){let a=s+r,[,o]=t[a];o===0?(i.push(n[r]),r+=1):(i.push(e[s]),s+=1)}return i}};var He=require("polkadot-api"),te=class extends N{omnipoolAssetIds=[];async getOraclePrice(t){return await this.api.query.EmaOracle.Oracles.getValue(He.Binary.fromText("omnipool"),t,(0,He.Enum)("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 kn={};I(kn,{PoolContextProvider:()=>qt,PoolError:()=>yt,PoolFactory:()=>Lt,PoolType:()=>C,aave:()=>Rn,hsm:()=>Cn,lbp:()=>_n,omni:()=>On,stable:()=>An,xyk:()=>Bn});var _n={};I(_n,{LbpMath:()=>nt,LbpPool:()=>ee,LbpPoolClient:()=>ne});var ct=require("@galacticcouncil/math-lbp"),nt=class{static getSpotPrice(t,e,n,i,s){return(0,ct.get_spot_price)(t,e,n,i,s)}static calculateInGivenOut(t,e,n,i,s){return(0,ct.calculate_in_given_out)(t,e,n,i,s)}static calculateOutGivenIn(t,e,n,i,s){return(0,ct.calculate_out_given_in)(t,e,n,i,s)}static calculateLinearWeights(t,e,n,i,s){return(0,ct.calculate_linear_weights)(t,e,n,i,s)}static calculatePoolTradeFee(t,e,n){return(0,ct.calculate_pool_trade_fee)(t,e,n)}};var C=(r=>(r.Aave="Aave",r.LBP="LBP",r.Omni="Omnipool",r.Stable="Stableswap",r.XYK="XYK",r.HSM="HSM",r))(C||{}),yt=(u=>(u.UnknownError="UnknownError",u.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",u.InsufficientTradingAmount="InsufficientTradingAmount",u.InsufficientCollateral="InsufficientCollateral",u.MaxHoldingExceeded="MaxHoldingExceeded",u.MaxInRatioExceeded="MaxInRatioExceeded",u.MaxOutRatioExceeded="MaxOutRatioExceeded",u.TradeNotAllowed="TradeNotAllowed",u.MaxBuyBackExceeded="MaxBuyBackExceeded",u.MaxBuyPriceExceeded="MaxBuyPriceExceeded",u))(yt||{});var{FeeUtils:fi}=_,ee=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),s=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,weightIn:i.weight,weightOut:s.weight}}validateAndBuy(t,e,n){let i=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&s.push("MaxOutRatioExceeded"),i===t.assetOut){let a=this.calculateTradeFee(e,n),o=fi.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),l=e+a,u=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return u>p&&s.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,amountOut:e,feePct:o,errors:s}}else{let a=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return a>o&&s.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,n){let i=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&s.push("MaxInRatioExceeded"),i===t.assetIn){let a=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return a>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}else{let a=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(a,n),l=fi.toPct(this.repayFeeApply?n.repayFee:n.exchangeFee),u=a-o,p=t.balanceOut/this.maxOutRatio;return u>p&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:u,feePct:l,errors:s}}}calculateInGivenOut(t,e){let n=nt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e){let n=nt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){let e=nt.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),this.maxOutRatio.toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=nt.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),this.maxInRatio.toString());return BigInt(e)}calculateTradeFee(t,e){let n=nt.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(n)}};var Si=require("polkadot-api"),kt=require("rxjs");var Pi=(c,t=new Map)=>e=>{let n;return t.has(e)?t.get(e):(t.set(e,n=c(e)),n)};var v=require("rxjs");var vi=require("rxjs"),Ge=class{store$=new vi.BehaviorSubject([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(t){return this.changeset.size===0?[]:t.filter(e=>this.changeset.has(e.address))}set(t){this.changeset=new Set(t.map(e=>e.address)),this.store$.next(t)}update(t){this.updateQueue=this.updateQueue.then(async()=>{let e=this.store$.value,n=new Map(e.map((a,o)=>[a.address,o])),i=await t(e),s=e.slice(),r=new Set;for(let a of i){let o=n.get(a.address);o===void 0?(n.set(a.address,s.length),s.push(a)):s[o]=a,r.add(a.address)}this.changeset=r,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};var X=class extends ot{evm;store=new Ge;shared$;mem=0;memPoolsCache=new wt(null,{ttl:6*1e3});memPools=Pi(t=>(this.log(this.getPoolType(),"sync mem pools",t),this.loadPools()),this.memPoolsCache);constructor(t,e){super(t),this.evm=e}async getMemPools(){return this.memPools(this.mem)}async getPools(){return(await this.getMemPools()).filter(e=>this.hasValidAssets(e))}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe((0,v.startWith)([]),(0,v.bufferCount)(2,1),(0,v.map)(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),(0,v.filter)(t=>t.length>0),(0,v.throttleTime)(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return(0,v.defer)(()=>{let t=new v.Subscription;return(0,v.from)(this.getMemPools()).pipe((0,v.map)(n=>n.filter(i=>this.hasValidAssets(i))),(0,v.tap)(n=>this.store.set(n))).pipe((0,v.tap)(()=>{t.add(this.subscribeBalances()),t.add(this.subscribeUpdates())}),(0,v.switchMap)(n=>(0,v.merge)((0,v.of)(n),this.store.asObservable().pipe((0,v.skip)(1)))),(0,v.finalize)(()=>{t.unsubscribe()}))}).pipe((0,v.share)({connector:()=>new v.ReplaySubject(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:n}=e,i=[this.subscribeTokensBalance(n)];if(this.hasSystemAsset(e)){let s=this.subscribeSystemBalance(n);i.push(s)}if(this.hasErc20Asset(e)){let s=e.tokens.filter(a=>a.type==="Erc20").map(a=>a.id),r=this.subscribeErc20Balance(n,s);i.push(r)}return(0,v.combineLatest)(i).pipe((0,v.map)(s=>s.flat()),(0,v.pairwise)(),(0,v.map)(([s,r])=>this.getDeltas(s,r)),(0,v.map)(s=>[n,s]))});return(0,v.combineLatest)(t).pipe((0,v.debounceTime)(250),(0,v.map)(e=>new Map(e))).subscribe(e=>this.store.update(n=>this.updateBalances(n,e)))}hasSystemAsset(t){return t.tokens.some(e=>e.id===0)}hasErc20Asset(t){return t.tokens.some(e=>e.type==="Erc20")}hasValidAssets(t){return t.tokens.every(({decimals:e,balance:n})=>n>0n&&!!e)}updateBalances=(t,e)=>{let n=[],i=new Map(t.map(s=>[s.address,s]));for(let[s,r]of e){let a=i.get(s);if(a){let o=a.tokens.map(l=>{let u=r.find(p=>p.id===l.id);return u&&l.id!==a.id?{...l,balance:u.balance.transferable}:l});n.push({...a,tokens:o})}}return n}};var ne=class extends X{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}getPoolWeights(t,e){let{start:n,end:i,initial_weight:s,final_weight:r}=t,a=nt.calculateLinearWeights(n?n.toString():"0",i?i.toString():"0",s.toString(),r.toString(),e.toString()),o=BigInt(a),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){let t=this.api.query.LBP.PoolData,e=await this.api.compatibilityToken;return t.isCompatible(Si.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let[t,e,n]=await Promise.all([this.api.query.LBP.PoolData.getEntries(),this.api.query.ParachainSystem.ValidationData.getValue(),this.getPoolLimits()]),i=e?.relay_parent_number||0,s=t.filter(({value:r})=>e&&this.isActivePool(r,i)).map(async({keyArgs:r,value:a})=>{let[o]=r,l=o.toString(),u=await this.getPoolDelta(l,a,i);return{address:l,type:"LBP",fee:a.fee,...u,...n}});return Promise.all(s)}async getPoolDelta(t,e,n){let{assets:i,repay_target:s,fee_collector:r}=e,[a,o]=this.getPoolWeights(e,n),[l,u]=i,[p,m,d,g,y]=await Promise.all([this.isRepayFeeApplied(l,s,r.toString()),this.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l),this.getBalance(t,u),this.api.query.AssetRegistry.Assets.getValue(u)]);return{repayFeeApply:p,tokens:[{id:l,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:m.transferable,weight:a,type:d?.asset_type.type},{id:u,decimals:y?.decimals,existentialDeposit:y?.existential_deposit,balance:g.transferable,weight:o,type:y?.asset_type.type}]}}isActivePool(t,e){let{start:n,end:i}=t;return n&&i?e>=n&&e<i:!1}async isRepayFeeApplied(t,e,n){if(e===0n)return!1;try{return(await this.getBalance(n,t)).transferable<e}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(t,e){let n=this.store.pools.find(s=>s.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:n.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue("best").pipe((0,kt.filter)(t=>t!==void 0),(0,kt.distinctUntilChanged)((t,e)=>t.relay_parent_number===e.relay_parent_number)).subscribe(({relay_parent_number:t})=>{this.store.update(async e=>{let n=[];for(let i of e){let s=this.poolsData.get(i.address);if(s){let{assets:r,repay_target:a,fee_collector:o}=s,[l]=r,[u,p]=this.getPoolWeights(s,t),[m,d]=i.tokens,g=[{...m,weight:u},{...d,weight:p}],y=await this.isRepayFeeApplied(l,a,o.toString());n.push({...i,tokens:g,repayFeeApply:y})}}return n})})}subscribeUpdates(){let t=new kt.Subscription;return t.add(this.subscribeValidationData()),t}};var On={};I(On,{OmniMath:()=>B,OmniPool:()=>ie,OmniPoolClient:()=>se});var w=require("@galacticcouncil/math-omnipool"),It=ut(require("big.js")),B=class{static calculateSpotPrice(t,e,n,i){return(0,w.calculate_spot_price)(t,e,n,i)}static calculateLrnaSpotPrice(t,e){return(0,w.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,n,i,s,r,a,o,l){return(0,w.calculate_in_given_out)(t,e,n,i,s,r,a,o,l)}static calculateLrnaInGivenOut(t,e,n,i,s){return(0,w.calculate_lrna_in_given_out)(t,e,n,i,s)}static calculateOutGivenIn(t,e,n,i,s,r,a,o,l){return(0,w.calculate_out_given_in)(t,e,n,i,s,r,a,o,l)}static calculateOutGivenLrnaIn(t,e,n,i,s){return(0,w.calculate_out_given_lrna_in)(t,e,n,i,s)}static calculateShares(t,e,n,i){return(0,w.calculate_shares)(t,e,n,i)}static calculateLiquidityOut(t,e,n,i,s,r,a,o){return(0,w.calculate_liquidity_out)(t,e,n,i,s,r,a,o)}static calculateLiquidityLRNAOut(t,e,n,i,s,r,a,o){return(0,w.calculate_liquidity_lrna_out)(t,e,n,i,s,r,a,o)}static calculateCapDifference(t,e,n,i){let s=(0,It.default)(e),r=(0,It.default)(t),a=(0,It.default)(i),o=(0,It.default)(n),l=(0,It.default)(10).pow(18),u=o.div(l);if(s.div(a).lt(u)){let m=u.times(a).minus(s).times(r),d=s.times((0,It.default)(1).minus(u));return m.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,n,i){return(0,w.calculate_liquidity_hub_in)(t,e,n,i)}static isSellAllowed(t){return(0,w.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,w.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,w.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,w.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,n,i,s,r,a,o,l,u,p){return(0,w.recalculate_asset_fee)(t,e,n,i,s,r,a,o,l,u,p)}static recalculateProtocolFee(t,e,n,i,s,r,a,o,l,u,p){return(0,w.recalculate_protocol_fee)(t,e,n,i,s,r,a,o,l,u,p)}static verifyAssetCap(t,e,n,i){return(0,w.verify_asset_cap)(t,e,n,i)}};var{FeeUtils:Mt}=_,ie=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),s=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:i.hubReserves,hubReservesOut:s.hubReserves,sharesIn:i.shares,sharesOut:s.shares,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,tradeableIn:i.tradeable,tradeableOut:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,n),r=i===0n?0:A.calculateDiffToRef(s,i),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&a.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&a.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return s>p&&a.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,n),r=A.calculateDiffToRef(i,s),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&a.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&a.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return s>p&&a.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:r,errors:a}}calculateInGivenOut(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,n);let i=B.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"),s=BigInt(i);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,n){let i=B.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?Mt.toRaw(n.assetFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e,n){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,n);let i=B.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"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,n){let i=B.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),n?Mt.toRaw(n.assetFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=B.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=B.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=B.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=B.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}};var bt=require("polkadot-api"),Ti=require("@polkadot-api/utils"),L=require("rxjs");var{FeeUtils:q}=_,xi=bt.Binary.fromText("omnipool"),wi=(0,bt.Enum)("Short"),se=class extends X{queryBus=new jt;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",t=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(t),t=>String(t));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",t=>this.api.query.DynamicFees.AssetFee.getValue(t),t=>String(t),6*1e3);emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",t=>this.api.query.EmaOracle.Oracles.getValue(xi,t,wi),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),n=(0,Ti.toHex)(e);return(0,bt.AccountId)(63).dec(n)}getOraclePair(t){return t===0?[0,1]:[1,t]}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.Omnipool.Assets,e=await this.api.compatibilityToken;return t.isCompatible(bt.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[n,i,s,r,a]=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:u,value:p})=>{let[m]=u,{hub_reserve:d,shares:g,tradable:y,cap:h,protocol_shares:P}=p,[b,S]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(m),this.getBalance(e,m)]);return{id:m,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:S.transferable,cap:h,hubReserves:d,protocolShares:P,shares:g,tradeable:y,type:b?.asset_type.type}}),l=await Promise.all(o);return l.push({id:t,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:r.transferable,tradeable:i,type:s?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:l,...a}]}async getPoolFees(t){let e=t.assetOut,n=t.assetIn,i=await this.dynamicFeesConfig.get(e);if(i?.type==="Fixed"){let{asset_fee:b,protocol_fee:S}=i.value;return{assetFee:q.fromPermill(b),protocolFee:q.fromPermill(S)}}let s=this.getOraclePair(e),r=this.getOraclePair(n),[a,o,l]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(s),this.emaOracles.get(r)]),[u,p,m]=await this.getAssetFee(t,this.block,a,o,i?.value.asset_fee_params),[d,g,y]=n===1?[0,0,0]:await this.getProtocolFee(t,this.block,a,l,i?.value.protocol_fee_params),h=u+d,P=m+y;return{assetFee:q.fromPermill(p),protocolFee:q.fromPermill(g),min:q.fromPermill(h),max:q.fromPermill(P)}}async getAssetFee(t,e,n,i,s){let{assetOut:r,balanceOut:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s||await this.api.constants.DynamicFees.AssetFeeParameters();if(!n||!i)return[o,o,l];let m=q.fromPermill(o),d=q.fromPermill(l),[g]=i,{asset_fee:y,timestamp:h}=n,P=Math.max(1,e-h),b=g.volume.b_in.toString(),S=g.volume.b_out.toString(),x=g.liquidity.b.toString();r===0&&(b=g.volume.a_in.toString(),S=g.volume.a_out.toString(),x=g.liquidity.a.toString());let O=q.fromPermill(y),D=B.recalculateAssetFee(b,S,x,"9",a.toString(),q.toRaw(O).toString(),P.toString(),q.toRaw(m).toString(),q.toRaw(d).toString(),u.toString(),p.toString());return[o,Number(D)*1e6,l]}async getProtocolFee(t,e,n,i,s){let{assetIn:r,balanceIn:a}=t,{min_fee:o,max_fee:l,decay:u,amplification:p}=s||await this.api.constants.DynamicFees.ProtocolFeeParameters();if(!n||!i)return[o,o,l];let m=q.fromPermill(o),d=q.fromPermill(l),[g]=i,{protocol_fee:y,timestamp:h}=n,P=Math.max(1,e-h),b=g.volume.b_in.toString(),S=g.volume.b_out.toString(),x=g.liquidity.b.toString();r===0&&(b=g.volume.a_in.toString(),S=g.volume.a_out.toString(),x=g.liquidity.a.toString());let O=q.fromPermill(y),D=B.recalculateProtocolFee(b,S,x,"9",a.toString(),q.toRaw(O).toString(),P.toString(),q.toRaw(m).toString(),q.toRaw(d).toString(),u.toString(),p.toString());return[o,Number(D)*1e6,l]}subscribeEmaOracles(){let[t]=this.store.pools,n=t.tokens.map(i=>i.id).map(i=>this.getOraclePair(i)).map(i=>this.api.query.EmaOracle.Oracles.watchValue(xi,i,wi,"best").pipe((0,L.filter)(s=>s!==void 0),(0,L.map)(s=>({pair:i,value:s}))));return(0,L.merge)(...n).pipe((0,L.finalize)(()=>{this.log(this.getPoolType(),"unsub ema oracles"),this.emaOracles.clear()})).subscribe(i=>{let{pair:s,value:r}=i;this.emaOracles.set(r,s)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe((0,L.distinctUntilChanged)((t,e)=>!e.deltas),(0,L.finalize)(()=>{(0,L.finalize)(()=>{this.log(this.getPoolType(),"unsub dyn fees"),this.dynamicFees.clear()})})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFees.set(e.value,n)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe((0,L.distinctUntilChanged)((t,e)=>!e.deltas),(0,L.finalize)(()=>{this.log(this.getPoolType(),"unsub dyn fees config"),this.dynamicFeesConfig.clear()})).subscribe(({deltas:t})=>{t?.upserted.forEach(e=>{let[n]=e.args;this.dynamicFeesConfig.set(e.value,n)})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe((0,L.finalize)(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.block=t})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe((0,L.distinctUntilChanged)((t,e)=>!e.deltas),(0,L.finalize)(()=>{this.log(this.getPoolType(),"unsub assets")})).subscribe(({deltas:t})=>{this.store.update(([e])=>{let n=t?.upserted.reduce((s,r)=>{let[a]=r.args;return s.set(a,r.value),s},new Map),i=e.tokens.map(s=>{let r=n?.get(s.id);return r?this.updateTokenState(s,r):s});return[{...e,tokens:i}]})})}subscribeUpdates(){let t=new L.Subscription;return t.add(this.subscribeAssets()),t.add(this.subscribeDynamicFees()),t.add(this.subscribeDynamicFeesConfig()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeBlock()),t}updateTokenState(t,e){let{hub_reserve:n,shares:i,tradable:s,cap:r,protocol_shares:a}=e;return{...t,cap:r,hubReserves:n,protocolShares:a,shares:i,tradeable:s}}};var An={};I(An,{StableMath:()=>V,StableSwap:()=>ft,StableSwapClient:()=>re});var k=require("@galacticcouncil/math-stableswap"),V=class{static getPoolAddress(t){return(0,k.pool_account_name)(t)}static defaultPegs(t){let e=[];for(let n=0;n<t;n++)e.push(["1","1"]);return e}static calculateAmplification(t,e,n,i,s){return(0,k.calculate_amplification)(t,e,n,i,s)}static calculateInGivenOut(t,e,n,i,s,r,a){return(0,k.calculate_in_given_out)(t,e,n,i,s,r,a)}static calculateAddOneAsset(t,e,n,i,s,r,a){return(0,k.calculate_add_one_asset)(t,e,n,i,s,r,a)}static calculateSharesForAmount(t,e,n,i,s,r,a){return(0,k.calculate_shares_for_amount)(t,e,n,i,s,r,a)}static calculateOutGivenIn(t,e,n,i,s,r,a){return(0,k.calculate_out_given_in)(t,e,n,i,s,r,a)}static calculateLiquidityOutOneAsset(t,e,n,i,s,r,a){return(0,k.calculate_liquidity_out_one_asset)(t,e,n,i,s,r,a)}static calculateShares(t,e,n,i,s,r){return(0,k.calculate_shares)(t,e,n,i,s,r)}static calculateSpotPriceWithFee(t,e,n,i,s,r,a,o){return(0,k.calculate_spot_price_with_fee)(t,e,n,i,s,r,a,o)}static recalculatePegs(t,e,n,i,s){let r=(0,k.recalculate_peg)(t,e,n,i,s);return JSON.parse(r)}};var{FeeUtils:Dt}=_,ft=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),s=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,n),r=i===0n?0:A.calculateDiffToRef(s,i),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&a.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:r,errors:a}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,n),r=A.calculateDiffToRef(i,s),a=[],o=B.isSellAllowed(t.tradeableIn),l=B.isBuyAllowed(t.tradeableOut);return(!o||!l)&&a.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&a.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:r,errors:a}}calculateIn(t,e,n){let i=V.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?Dt.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateAddOneAsset(t,e,n){let i=V.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),n?Dt.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateSharesForAmount(t,e,n){let i=V.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),n?Dt.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}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=V.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetOut==this.id)return BigInt(e);if(t.assetIn==this.id){let i=Math.pow(10,t.decimalsIn-t.decimalsOut);return BigInt(e)/BigInt(i)}let n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateOut(t,e,n){let i=V.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),n?Dt.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,n){let i=V.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),n?Dt.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateShares(t,e,n){let i=V.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),n?Dt.toRaw(n.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}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=V.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());if(t.assetIn==this.id)return BigInt(e);if(t.assetOut==this.id){let i=Math.pow(10,t.decimalsOut-t.decimalsIn);return BigInt(e)/BigInt(i)}let n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:n,decimals:i})=>({asset_id:e,amount:n,decimals:i}));return JSON.stringify(t,Rt.jsonFormatter)}getAssets(t,e){let n={asset_id:Number(t),amount:e.toString()};return JSON.stringify([n],Rt.jsonFormatter)}};var Ue=require("polkadot-api"),Ii=require("@polkadot-api/utils"),_i=require("@noble/hashes/blake2b"),Q=require("rxjs");var{FeeUtils:Rs}=_,re=class extends X{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=V.getPoolAddress(t),n=(0,_i.blake2b)(e,{dkLen:32}),i=(0,Ii.toHex)(n);return(0,Ue.AccountId)(63).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:n,final_amplification:i,initial_block:s,final_block:r}=t,a=V.calculateAmplification(n.toString(),i.toString(),s.toString(),r.toString(),e.toString()),o=Number(a)<i;return{amplification:BigInt(a),isRampPeriod:o}}async getPoolTokens(t,e){let n=this.getPoolAddress(t),i=e.assets.map(async s=>{let[r,a,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,s),this.api.query.AssetRegistry.Assets.getValue(s),this.getBalance(n,s)]);return{id:s,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:o.transferable,tradeable:r,type:a?.asset_type.type}});return Promise.all(i)}async isSupported(){let t=this.api.query.Stableswap.Pools,e=await this.api.compatibilityToken;return t.isCompatible(Ue.CompatibilityLevel.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()]),i=t.map(async({keyArgs:s,value:r})=>{let[a]=s,o=this.getPoolAddress(a),[l,u,p]=await Promise.all([this.getPoolTokens(a,r),this.api.query.Stableswap.PoolPegs.getValue(a),this.api.query.Tokens.TotalIssuance.getValue(a)]),m=this.getPoolAmplification(r,e),d=u?this.getRecentPegs(u):this.getDefaultPegs(r);return l.push({id:a,tradeable:15,balance:p,decimals:18}),this.poolsData.set(a,r),{address:o,id:a,type:"Stableswap",fee:Rs.fromPermill(r.fee),tokens:l,totalIssuance:p,pegs:d,...n,...m}});return Promise.all(i)}async getPoolFees(t,e){return{fee:this.store.pools.find(i=>i.address===e).fee}}getDefaultPegs(t){return V.defaultPegs(t.assets.length)}getRecentPegs(t){let{current:e}=t;return Array.from(e.entries()).map(([n,i])=>i.map(s=>s.toString()))}subscribeIssuance(){let e=this.store.pools.map(n=>n.id).map(n=>this.api.query.Tokens.TotalIssuance.watchValue(n,"best").pipe((0,Q.map)(i=>({id:n,value:i}))));return(0,Q.merge)(...e).pipe((0,Q.finalize)(()=>{this.log(this.getPoolType(),"unsub total issuance")})).subscribe(n=>{let{id:i,value:s}=n;this.store.update(r=>{let a=[];return r.filter(o=>o.id===i).forEach(o=>{let l=o.tokens.map(u=>u.id===i?{...u,balance:s}:u);a.push({...o,tokens:l,totalIssuance:s})}),a})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe((0,Q.distinctUntilChanged)((t,e)=>!e.deltas),(0,Q.finalize)(()=>{this.log(this.getPoolType(),"unsub pool pegs")})).subscribe(({deltas:t})=>{this.store.update(e=>{let n=[],i=new Map(e.map(s=>[s.id,s]));return t?.upserted.forEach(({args:s,value:r})=>{let[a]=s,o=i.get(a);if(o){let l=this.getRecentPegs(r);n.push({...o,pegs:l})}}),n})})}subscribeBlock(){return this.api.query.System.Number.watchValue("best").pipe((0,Q.finalize)(()=>{this.log(this.getPoolType(),"unsub block change")})).subscribe(t=>{this.store.update(e=>{let n=[];return e.filter(i=>i.isRampPeriod).forEach(i=>{let s=this.poolsData.get(i.id);if(s){let r=this.getPoolAmplification(s,t);n.push({...i,...r})}}),n})})}subscribeUpdates(){let t=new Q.Subscription;return t.add(this.subscribePoolPegs()),t.add(this.subscribeIssuance()),this.hasOnRamps()&&t.add(this.subscribeBlock()),t}hasOnRamps(){return this.store.pools.filter(t=>t.isRampPeriod).length>0}};var Bn={};I(Bn,{XykMath:()=>mt,XykPool:()=>ae,XykPoolClient:()=>oe});var M=require("@galacticcouncil/math-xyk"),mt=class{static getSpotPrice(t,e,n){return(0,M.get_spot_price)(t,e,n)}static calculateInGivenOut(t,e,n){return(0,M.calculate_in_given_out)(t,e,n)}static calculateOutGivenIn(t,e,n){return(0,M.calculate_out_given_in)(t,e,n)}static calculatePoolTradeFee(t,e,n){return(0,M.calculate_pool_trade_fee)(t,e,n)}static calculateLiquidityIn(t,e,n){return(0,M.calculate_liquidity_in)(t,e,n)}static calculateSpotPrice(t,e){return(0,M.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,n,i){return(0,M.calculate_spot_price_with_fee)(t,e,n,i)}static calculateShares(t,e,n){return(0,M.calculate_shares)(t,e,n)}static calculateLiquidityOutAssetA(t,e,n,i){return(0,M.calculate_liquidity_out_asset_a)(t,e,n,i)}static calculateLiquidityOutAssetB(t,e,n,i){return(0,M.calculate_liquidity_out_asset_b)(t,e,n,i)}};var{FeeUtils:Oi}=_,ae=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),s=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(i,n),r=Oi.toPct(n.exchangeFee),a=i+s,o=[];(e<this.minTradingLimit||i<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let u=t.balanceIn/this.maxInRatio;return a>u&&o.push("MaxInRatioExceeded"),{amountIn:a,calculatedIn:i,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(i,n),r=Oi.toPct(n.exchangeFee),a=i-s,o=[];(e<this.minTradingLimit||i<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let u=t.balanceOut/this.maxOutRatio;return a>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:a,feePct:r,errors:o}}calculateInGivenOut(t,e){let n=mt.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}calculateOutGivenIn(t,e){let n=mt.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(n);return i<0n?0n:i}spotPriceInGivenOut(t){let e=mt.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString()),n=Math.pow(10,18-t.decimalsOut);return BigInt(e)/BigInt(n)}spotPriceOutGivenIn(t){let e=mt.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString()),n=Math.pow(10,18-t.decimalsIn);return BigInt(e)/BigInt(n)}calculateTradeFee(t,e){let n=mt.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(n)}};var Ai=require("polkadot-api"),Bi=require("rxjs");var oe=class extends X{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(t){this.decimals=t?new Map(t.map(e=>[e.id,e.decimals])):new Map}async getPoolLimits(){let[t,e,n]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:t,maxOutRatio:e,minTradingLimit:n}}async isSupported(){let t=this.api.query.XYK.PoolAssets,e=await this.api.compatibilityToken;return t.isCompatible(Ai.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=this.api.query.XYK.PoolAssets,[e,n]=await Promise.all([t.getEntries(),this.getPoolLimits()]),i=e.map(async({keyArgs:s,value:r})=>{let[a]=s,[o,l]=r,[u,p,m,d]=await Promise.all([this.getBalance(a,o),this.api.query.AssetRegistry.Assets.getValue(o),this.getBalance(a,l),this.api.query.AssetRegistry.Assets.getValue(l)]);return{address:a,type:"XYK",tokens:[{id:o,decimals:p?.decimals||this.decimals.get(o),existentialDeposit:p?.existential_deposit,balance:u.transferable,type:p?.asset_type.type},{id:l,decimals:d?.decimals||this.decimals.get(l),existentialDeposit:d?.existential_deposit,balance:m.transferable,type:d?.asset_type.type}],...n}});return Promise.all(i)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return Bi.Subscription.EMPTY}};var Rn={};I(Rn,{AavePool:()=>le,AavePoolClient:()=>ce});var le=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let n=new Map(this.tokens.map(r=>[r.id,r])),i=n.get(t),s=n.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,n){let i=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,n){let i=this.calculateOutGivenIn(t,e),s=[];return i>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:s}}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}};var Fi=require("polkadot-api"),Ei=require("@polkadot-api/utils"),j=require("rxjs"),Ci=require("viem");var Ri=[{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:Fs}=St,Es=["Supply","Withdraw","Repay","Borrow"],ce=class extends X{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let n=t+"/"+e,i=new TextEncoder().encode(n.padEnd(32,"\0")),s=(0,Ei.toHex)(i);return(0,Fi.AccountId)(63).dec(s)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let e=(await this.api.apis.AaveTradeExecutor.pools()).map(async({reserve:n,atoken:i,liqudity_in:s,liqudity_out:r})=>{let[a,o,l,u]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(n),this.api.query.AssetRegistry.AssetLocations.getValue(n),this.api.query.AssetRegistry.Assets.getValue(i),this.api.query.AssetRegistry.AssetLocations.getValue(i)]);return{address:this.getPoolId(n,i),type:"Aave",tokens:[{id:n,decimals:a?.decimals,existentialDeposit:a?.existential_deposit,balance:s,location:o,type:a?.asset_type.type},{id:i,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:u,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,n]=t.tokens,{liqudity_in:i,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(e.id,n.id);return t.tokens.map(r=>{let a=r.id===e.id?i:s;return{...r,balance:a}})}async getPoolFees(){return{}}getReserveH160Id(t){if(t.type==="Erc20"&&t.location){let e=t.location.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:n}=e.value;return n.key.asHex()}throw new Error("Invalid aave reserve multilocation")}return Fs.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:n}=t;return{assetIn:e,assetOut:n,key:`${e}:${n}`}}parseEvmLog(t){let{topics:e,data:n}=t.log,i=e.map(r=>r.asHex()),s=n.asHex();try{let{eventName:r,args:a}=(0,Ci.decodeEventLog)({abi:Ri,topics:i,data:s}),o=a.reserve.toLowerCase();return{eventName:r,reserve:o,key:`${r}:${o}`}}catch{return}}subscribeRouterExecuted(){let e=this.store.pools.map(n=>n.tokens).map(([n,i])=>i).map(n=>n.id);return this.api.event.Router.Executed.watch().pipe((0,j.map)(({payload:n})=>this.parseRouterLog(n)),(0,j.filter)(({assetIn:n,assetOut:i})=>e.includes(n)||e.includes(i)),(0,j.finalize)(()=>{this.log(this.getPoolType(),"unsub router executed")})).subscribe(({assetIn:n,assetOut:i,key:s})=>{this.log(this.getPoolType(),"[router:Executed]",s),this.store.update(async r=>{let a=[];for(let o of r){let[l,u]=o.tokens;if(u.id===n||u.id===i){let m=await this.getPoolDelta(o);a.push({...o,tokens:m})}}return a})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,j.map)(({payload:t})=>this.parseEvmLog(t)),(0,j.filter)(t=>t!==void 0),(0,j.filter)(({eventName:t})=>Es.includes(t)),(0,j.finalize)(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({reserve:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async n=>{let i=[];for(let s of n){let[r]=s.tokens;if(this.getReserveH160Id(r).toLowerCase()===t){let o=await this.getPoolDelta(s);i.push({...s,tokens:o})}}return i})})}subscribeBalances(){return j.Subscription.EMPTY}subscribeUpdates(){let t=new j.Subscription;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var Lt=class{static get(t){switch(t.type){case"Aave":return le.fromPool(t);case"XYK":return ae.fromPool(t);case"Omnipool":return ie.fromPool(t);case"LBP":return ee.fromPool(t);case"Stableswap":return ft.fromPool(t);case"HSM":return ft.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var st=require("rxjs");var Cn={};I(Cn,{HsmMath:()=>it,HsmPool:()=>Fn,HsmPoolClient:()=>me});var W=require("@galacticcouncil/math-hsm"),it=class{static calculateCollateralInGivenHollarOut(t,e,n){return(0,W.calculate_collateral_in_given_hollar_out)(t,e,n)}static calculateCollateralOutGivenHollarIn(t,e,n){return(0,W.calculate_collateral_out_given_hollar_in)(t,e,n)}static calculateHollarOutGivenCollateralIn(t,e,n){return(0,W.calculate_hollar_out_given_collateral_in)(t,e,n)}static calculateHollarInGivenCollateralOut(t,e,n){return(0,W.calculate_hollar_in_given_collateral_out)(t,e,n)}static calculateImbalance(t,e,n){return(0,W.calculate_imbalance)(t,e,n)}static calculateBuybackLimit(t,e){return(0,W.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,n){return(0,W.calculate_buyback_price_with_fee)(t,e,n)}static calculateMaxPrice(t,e){return(0,W.calculate_max_price)(t,e)}};var{FeeUtils:ue}=_,Fn=class c extends ft{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,n,i){let s=this.calculateBuybackLimit(t);e>s&&i.push("MaxBuyBackExceeded");let r=this.calculateBuyPrice(t,e,n),a=this.calculateMaxPrice(t);return r>a&&i.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&i.push("InsufficientCollateral"),i}validateTradeHollarOut(t,e,n){return this.collateralBalance+t>this.maxInHolding&&n.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&n.push("FacilitatorCapacityExceeded"),n}validateTradeConstraints(t,e,n){let i=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,n,i):this.validateTradeHollarOut(e,n,i)}validateAndBuy(t,e){let n=this.calculateInGivenOut(t,e),i=this.validateTradeConstraints(t,n,e);return{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e){let n=this.calculateOutGivenIn(t,e),i=this.validateTradeConstraints(t,e,n);return{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:i}}calculateHollarInGivenCollateralOut(t,e){let n=super.calculateInGivenOut(t,e,{fee:this.fee}),i=it.calculateHollarInGivenCollateralOut(e.toString(),n.toString(),ue.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),n=it.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),ue.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let n=super.calculateOutGivenIn(t,e,{fee:this.fee}),i=it.calculateCollateralOutGivenHollarIn(e.toString(),n.toString(),ue.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),n=it.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),ue.toRaw(this.purchaseFee).toString());return BigInt(n)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),n=it.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(n)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),n=it.calculateBuybackLimit(e.toString(),ue.toRaw(this.buyBackRate).toString());return BigInt(n)}calculateBuyPrice(t,e,n){let i=n*10n**BigInt(t.decimalsIn);return e*10n**BigInt(t.decimalsOut)/i}calculateMaxPrice(t){let e=this.getCollateralPeg(),n=it.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[i,s]=JSON.parse(n),r=10n**BigInt(18-t.decimalsOut);return BigInt(i)*r/BigInt(s)}spotPriceInGivenOut(t){let e=f.toBigInt(1,t.decimalsOut);return this.calculateInGivenOut(t,e)}spotPriceOutGivenIn(t){let e=f.toBigInt(1,t.decimalsIn);return this.calculateOutGivenIn(t,e)}getCollateralPeg(){let t=this.tokens.findIndex(i=>i.id!==this.hollarId),e=this.pegs[t],n=this.tokens[t].decimals;return this.isDefaultPeg(e)?[f.toBigInt(1,18).toString(),f.toBigInt(1,n).toString()]:e}isDefaultPeg(t){let[e,n]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&n==="1"}};var Ve=require("polkadot-api"),Mi=require("@polkadot-api/utils"),H=require("rxjs"),Di=require("viem");var pe=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var de=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[n,i]=await this.client.readContract({abi:pe,address:t,functionName:"getFacilitatorBucket",args:[e]});return n-i}};var{FeeUtils:En}=_,{H160:ki}=xt,Cs=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],me=class extends X{ghoClient;stableClient;constructor(t,e,n){super(t,e),this.stableClient=n,this.ghoClient=new de(e)}getPoolType(){return"HSM"}getPoolId(t){return this.getPoolAddress("hsm:"+t)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(t){if(t){let e=t.interior;if(e.type==="X1"&&e.value.type==="AccountKey20"){let{value:n}=e.value;return n.key.asHex()}}throw Error("Invalid hollar multilocation")}getPoolAddress(t){let e=t.padEnd(32,"\0"),n=new TextEncoder().encode(e),i=(0,Mi.toHex)(n);return(0,Ve.AccountId)(63).dec(i)}async isSupported(){let t=this.api.query.HSM.Collaterals,e=await this.api.compatibilityToken;return t.isCompatible(Ve.CompatibilityLevel.BackwardsCompatible,e)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,n,i]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(t),this.api.query.HSM.Collaterals.getEntries(),this.stableClient.getPools()]);if(n.length===0)return[];let s=this.getFacilitatorAddress(),r=ki.fromAny(s),a=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(a,r),l=n.map(async({keyArgs:p,value:m})=>{let[d]=p,{pool_id:g,max_buy_price_coefficient:y,max_in_holding:h,purchase_fee:P,buy_back_fee:b,buyback_rate:S}=m,x=i.find(O=>O.id===g);if(x){let O=this.getPoolId(g),D=await this.getBalance(s,d);return{...x,address:O,type:"HSM",tokens:x.tokens.filter(R=>R.id!==g),hsmAddress:s,hsmMintCapacity:o,hollarId:t,hollarH160:a,collateralId:d,collateralBalance:D.transferable,maxBuyPriceCoefficient:y,maxInHolding:h,purchaseFee:En.fromPermill(P),buyBackFee:En.fromPermill(b),buyBackRate:En.fromPerbill(S)}}});return(await Promise.all(l)).filter(p=>p!==null)}async getPoolFees(){return{}}parseEvmLog(t){let{topics:e,data:n}=t.log,i=e.map(r=>r.asHex()),s=n.asHex();try{let{eventName:r,args:a}=(0,Di.decodeEventLog)({abi:pe,topics:i,data:s}),o=a.facilitatorAddress.toLowerCase();return{eventName:r,facilitator:o,key:`${r}:${o}`}}catch{return}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe((0,H.map)(({payload:t})=>this.parseEvmLog(t)),(0,H.filter)(t=>t!==void 0),(0,H.filter)(({eventName:t})=>Cs.includes(t)),(0,H.finalize)(()=>{this.log(this.getPoolType(),"unsub evm log")})).subscribe(({facilitator:t,key:e})=>{this.log(this.getPoolType(),"[evm:Log]",e),this.store.update(async n=>{let i=[],[{hsmAddress:s,hollarH160:r}]=n,a=ki.fromAny(s);if(a.toLowerCase()===t){let l=await this.ghoClient.getFacilitatorCapacity(r,a);for(let u of n)i.push({...u,hsmMintCapacity:l})}return i})})}subscribeBalances(){let t=[],e=[];this.store.pools.forEach(s=>{let{tokens:r,collateralId:a}=s;r.find(l=>l.id===a).type==="Erc20"?e.push(a):t.push(a)});let[{hsmAddress:n}]=this.store.pools,i=[];if(t.length>0){let s=this.subscribeTokensBalance(n);i.push(s)}if(e.length>0){let s=this.subscribeErc20Balance(n,e);i.push(s)}return i.length>0?(0,H.combineLatest)(i).pipe((0,H.map)(s=>s.flat()),(0,H.pairwise)(),(0,H.map)(([s,r])=>this.getDeltas(s,r)),(0,H.finalize)(()=>{this.log(this.getPoolType(),"unsub collateral balance")})).subscribe(s=>{this.store.update(r=>{let a=[],o=new Map(r.map(l=>[l.collateralId,l]));return s.forEach(({id:l,balance:u})=>{let p=o.get(l);p&&(this.log(this.getPoolType(),"[collateral:Balance]",l,u.transferable),a.push({...p,collateralBalance:u.transferable}))}),a})}):H.Subscription.EMPTY}subscribeUpdates(){let t=new H.Subscription;return t.add(this.subscribeEvmLog()),t}};var qt=class extends N{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=st.Subscription.EMPTY;omniSub=st.Subscription.EMPTY;stableSub=st.Subscription.EMPTY;hsmSub=st.Subscription.EMPTY;xykSub=st.Subscription.EMPTY;lbpSub=st.Subscription.EMPTY;isReady=!1;isDestroyed=new st.Subject;constructor(t,e){super(t),this.evm=e,this.aave=new ce(t,e),this.omnipool=new se(t,e),this.stableswap=new re(t,e),this.hsm=new me(t,e,this.stableswap),this.xyk=new oe(t,e),this.lbp=new ne(t,e),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}subscribe(t){return t.getSubscriber().pipe((0,st.takeUntil)(this.isDestroyed)).subscribe(e=>{e.forEach(n=>{this.pools.set(n.address,n)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(t){return this.xyk.withOverride(t),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let e=this.pools.values();return Array.from(e)}let t=await Promise.all(this.clients.filter(e=>this.active.has(e.getPoolType())).map(e=>e.getPools()));return this.isReady=!0,t.flat()}async getPoolFees(t,e){let n=this.clients.find(i=>i.getPoolType()===e.type);if(n)return n.getPoolFees(t,e.address);throw new $t(e.type)}};var Gn={};I(Gn,{DEFAULT_BLOCK_TIME:()=>qi,DEFAULT_MIN_BUDGET:()=>Ln,ORDER_MIN_BLOCK_PERIOD:()=>Ni,Router:()=>Nt,TWAP_BLOCK_PERIOD:()=>be,TWAP_MAX_DURATION:()=>Nn,TWAP_MAX_PRICE_IMPACT:()=>qn,TWAP_TX_MULTIPLIER:()=>lp,TradeOrderError:()=>Dn,TradeOrderType:()=>Ye,TradeRouteBuilder:()=>J,TradeRouter:()=>Ht,TradeScheduler:()=>Gt,TradeType:()=>We});var ge=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 ks=10,he=class{isNotVisited(t,e){let n=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(n=!1)}),n}findPaths(t,e,n){let i=[],s=new ge,r=[];for(r.push([e,""]),s.enqueue(r);s.size()>0;){let a=s.dequeue();if(!a||a.length>ks)continue;let o=a[a.length-1];(n===null||o[0]===n)&&i.push(a),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,a)){let p=[...a];p.push(u),s.enqueue(p)}})}return i}findShortestPaths(t,e,n){let i=[],s=new ge,r=[];r.push([e,""]),s.enqueue(r);let a=1/0;for(;s.size()>0;){let o=s.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===n){o.length<a?(a=o.length,i.length=0,i.push(o)):o.length===a&&i.push(o);continue}let u=t.get(l[0]);for(let p of u??[])this.isNotVisited(p,o)&&s.enqueue([...o,p])}return i}buildAndPopulateGraph(t,e){let n=new Map;for(let i of t)n.set(parseInt(i),[]);for(let[i,s,r]of e)n.get(s)?.push([r,i]);return n}};function Mn(c){let t={};for(let e of c){let n=e.tokens.length;for(let i=0;i<n;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let s=0;s<n;s++){if(i==s)continue;let r=[e.address,e.tokens[i].id,e.tokens[s].id];t[e.tokens[i].id].push(r)}}}return t}var ye=class{getProposals(t,e,n){let i=n.filter(h=>h.type==="XYK"),s=n.filter(h=>h.type!=="XYK"),r=new Set(s.map(h=>h.tokens).flat().map(h=>h.id)),a=r.has(t),o=r.has(e),l=new he,u=h=>{let P=Mn(h),b=Object.keys(P),S=b.flatMap(x=>P[x]);return l.buildAndPopulateGraph(b,S)};if(!a&&!o){let h=i.filter(S=>S.tokens.find(x=>x.id===t)||S.tokens.find(x=>x.id===e)),P=u(h),b=l.findPaths(P,t,e);return this.parsePaths(b)}if(a&&o){let h=u(s),P=l.findPaths(h,t,e);return this.parsePaths(P)}let p=a?e:t,m=i.filter(h=>h.tokens.some(P=>P.id===p));if(m.length===0)return[];let d=[...s,...m],g=u(d),y=l.findPaths(g,t,e);return this.parsePaths(y)}parsePaths(t){let e=[];for(let n of t){let i=[];for(let s=0;s<n.length;s++){let r=n[s],a=n[s+1];if(a==null)break;i.push(this.toEdge(r,a))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var Nt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new ye,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,n){return`${t}->${e}::${n.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:n=[]}=this.filter,i=new Set(e),s=new Set(n);return t.filter(r=>s.has(r.type)?!1:i.size>0?i.has(r.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let n=await this.getPools();return this.validateInput(t,e,n),this.getPaths(t,e,n)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(i=>i!==t).map(i=>this.getRoutes(i,t)))).filter(i=>i.length>0).map(([i])=>i[0].assetIn).sort()}validateInput(t,e,n){if(n.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(n);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(n)}getAssets(t){let e=t.map(n=>n.tokens.map(i=>i.id)).flat().sort((n,i)=>n>i?1:-1);return new Set(e)}getPaths(t,e,n){let i=this.toPoolsMap(n);return this.getProposals(t,e,n).filter(r=>this.validPath(r,i)).map(r=>this.toHops(r,i))}getProposals(t,e,n){let i=this.buildRouteKey(t,e,n);if(this.routeProposals.has(i))return this.routeProposals.get(i);let s=this.routeSuggester.getProposals(t,e,n);return this.routeProposals.set(i,s),s}validPath(t,e){return t.length>0&&t.map(n=>this.validEdge(n,e)).reduce((n,i)=>n&&i)}validEdge([t,e,n],i){return i.get(t)?.validatePair(e,n)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Lt.get(e)]))}toHops(t,e){return t.map(([n,i,s])=>{let r=e.get(n);return{poolAddress:n,poolId:r?.id,pool:r?.type,assetIn:i,assetOut:s}})}};var We=(e=>(e.Buy="Buy",e.Sell="Sell",e))(We||{}),Ye=(n=>(n.Dca="Dca",n.TwapSell="TwapSell",n.TwapBuy="TwapBuy",n))(Ye||{}),Dn=(n=>(n.OrderTooSmall="OrderTooSmall",n.OrderTooBig="OrderTooBig",n.OrderImpactTooBig="OrderImpactTooBig",n))(Dn||{});var{FeeUtils:Li}=_,Ht=class extends Nt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,n){let i=super.validateInput(t,e,n),s=super.getPaths(t,e,n);if(!s.length)throw new Qt(t,e);return{paths:s,pools:n,poolsMap:i}}async withCtx(t,e,n){let i=await super.getPools(),s=this.buildCtxSync(t,e,i);return n(s)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((n,i)=>{let s=n[n.length-1].amountOut,r=i[i.length-1].amountOut;return s>r?-1:1});return e.find(n=>n.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(n=>n.tradeFeeRange).length>0){let n=t.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,r)=>s+r),i=t.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,r)=>s+r);return[n,i]}}getPoolFeeRange(t){let e=t.min?Li.toPct(t.min):void 0,n=t.max?Li.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(a=>a.assetOutDecimals).reduce((a,o)=>a+o),i=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),s=n-e.assetOutDecimals,r=Math.pow(10,s);return i/BigInt(r)}async getSell(t,e,n,i){return this.withCtx(t,e,async({paths:s,poolsMap:r})=>{let a;if(i)a=await this.toSellSwaps(n,i,r);else{let o=s.map(u=>this.toSellSwaps(n,u,r)),l=await Promise.all(o);a=this.findBestSellRoute(l)}return this.buildSell(r,a)})}async getSells(t,e,n){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let r=i.map(o=>this.toSellSwaps(n,o,s));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(s,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let n=e[0],i=e[e.length-1],s=this.isDirectTrade(e),r=this.getSellSpot(e),a=i.amountOut,o=s?i.calculatedOut:this.calculateDelta0Y(n.amountIn,e,t),l=o-a,u=this.getRouteFeeRange(e),p=s?i.tradeFeePct:A.calculateSellFee(o,a),m=Math.pow(10,n.assetInDecimals),d=n.amountIn*r/BigInt(m),g=A.calculateDiffToRef(o,d);return{type:"Sell",amountIn:n.amountIn,amountOut:i.amountOut,spotPrice:r,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e,toHuman(){return{type:"Sell",amountIn:f.toDecimal(n.amountIn,n.assetInDecimals),amountOut:f.toDecimal(i.amountOut,i.assetOutDecimals),spotPrice:f.toDecimal(r,i.assetOutDecimals),tradeFee:f.toDecimal(l,i.assetOutDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0Y(t,e,n){let i=[];for(let s=0;s<e.length;s++){let r=e[s],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s>0?l=i[s-1]:l=t;let u=a.calculateOutGivenIn(o,l);i.push(u)}return i[i.length-1]}async calculateMostLiquidRoute(t,e,n){let{paths:i,pools:s,poolsMap:r}=n,l=s.filter(y=>y.tokens.some(h=>h.id===t)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(h=>h.id===t)).map(y=>y.map(h=>h.balance).reduce((h,P)=>h+P)).sort((y,h)=>h<y?-1:1)[0],u=A.getFraction(l,.1),p=await Promise.all(i.map(y=>this.toSellSwaps(u,y,r))),d=this.findBestSellRoute(p).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),g=this.buildRouteKey(t,e,s);return this.mlr.set(g,d),d}async toSellSwaps(t,e,n){let i=[];for(let s=0;s<e.length;s++){let r=e[s],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s>0?l=i[s-1].amountOut:l=typeof t=="string"?f.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,a),{amountOut:p,calculatedOut:m,feePct:d,errors:g}=a.validateAndSell(o,l,u),y=this.getPoolFeeRange(u),h=a.spotPriceOutGivenIn(o),P=Math.pow(10,o.decimalsIn),b=l*h/BigInt(P),S=A.calculateDiffToRef(m,b);i.push({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:m,spotPrice:h,tradeFeePct:d,tradeFeeRange:y,priceImpactPct:S,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===r.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===r.assetIn},toHuman(){return{...r,amountIn:f.toDecimal(l,o.decimalsIn),amountOut:f.toDecimal(p,o.decimalsOut),calculatedOut:f.toDecimal(m,o.decimalsOut),spotPrice:f.toDecimal(h,o.decimalsOut),tradeFeePct:d,tradeFeeRange:y,priceImpactPct:S,errors:g}}})}return i}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async n=>{let i=this.buildRouteKey(t,e,n.pools),s=this.mlr.get(i);return s||this.calculateMostLiquidRoute(t,e,n)})}async getSpotPrice(t,e){return this.withCtx(t,e,async n=>{let{pools:i,poolsMap:s}=n,r=this.buildRouteKey(t,e,i),a=this.mlr.get(r);a||(a=await this.calculateMostLiquidRoute(t,e,n));let o=await this.toSellSwaps("1",a,s),l=this.getSellSpot(o),u=o[o.length-1].assetOutDecimals;return{amount:l,decimals:u}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((n,i)=>{let s=n[0].amountIn,r=i[0].amountIn;return s>r?1:-1});return e.find(n=>n.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,n){return this.getBuy(t,e,n)}getBuySpot(t){let e=t[0];if(t.length===1)return e.spotPrice;let n=t.map(a=>a.assetInDecimals).reduce((a,o)=>a+o),i=t.map(a=>a.spotPrice).reduce((a,o)=>a*o),s=n-e.assetInDecimals,r=Math.pow(10,s);return i/BigInt(r)}async getBuy(t,e,n,i){return this.withCtx(t,e,async({paths:s,poolsMap:r})=>{let a;if(i)a=await this.toBuySwaps(n,i,r);else{let o=s.map(u=>this.toBuySwaps(n,u,r)),l=await Promise.all(o);a=this.findBestBuyRoute(l)}return this.buildBuy(r,a)})}async getBuys(t,e,n){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let r=i.map(o=>this.toBuySwaps(n,o,s));return(await Promise.all(r)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(s,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let n=e[e.length-1],i=e[0],s=this.isDirectTrade(e),r=this.getBuySpot(e),a=i.amountIn,o=s?i.calculatedIn:this.calculateDelta0X(n.amountOut,e,t),l=a-o,u=this.getRouteFeeRange(e),p=s?i.tradeFeePct:A.calculateBuyFee(o,a),m=Math.pow(10,n.assetOutDecimals),d=n.amountOut*r/BigInt(m),g;return o===0n?g=-100:g=A.calculateDiffToRef(d,o),{type:"Buy",amountOut:n.amountOut,amountIn:i.amountIn,spotPrice:r,tradeFee:l,tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e,toHuman(){return{type:"Buy",amountOut:f.toDecimal(n.amountOut,n.assetOutDecimals),amountIn:f.toDecimal(i.amountIn,i.assetInDecimals),spotPrice:f.toDecimal(r,i.assetInDecimals),tradeFee:f.toDecimal(l,i.assetInDecimals),tradeFeePct:p,tradeFeeRange:u,priceImpactPct:g,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0X(t,e,n){let i=[];for(let s=e.length-1;s>=0;s--){let r=e[s],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s==e.length-1?l=t:l=i[0];let u=a.calculateInGivenOut(o,l);i.unshift(u)}return i[0]}async toBuySwaps(t,e,n){let i=[];for(let s=e.length-1;s>=0;s--){let r=e[s],a=n.get(r.poolAddress);if(a==null)throw new Error("Pool does not exit");let o=a.parsePair(r.assetIn,r.assetOut),l;s==e.length-1?l=typeof t=="string"?f.toBigInt(t,o.decimalsOut):t:l=i[0].amountIn;let u=await this.ctx.getPoolFees(o,a),{amountIn:p,calculatedIn:m,feePct:d,errors:g}=a.validateAndBuy(o,l,u),y=this.getPoolFeeRange(u),h=a.spotPriceInGivenOut(o),P=Math.pow(10,o.decimalsOut),b=l*h/BigInt(P),S;m===0n?S=-100:S=A.calculateDiffToRef(b,m),i.unshift({...r,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:m,spotPrice:h,tradeFeePct:d,tradeFeeRange:y,priceImpactPct:S,errors:g,isSupply(){return a.type==="Aave"&&a.tokens[0].id===r.assetIn},isWithdraw(){return a.type==="Aave"&&a.tokens[1].id===r.assetIn},toHuman(){return{...r,amountOut:f.toDecimal(l,o.decimalsOut),amountIn:f.toDecimal(p,o.decimalsIn),calculatedIn:f.toDecimal(m,o.decimalsIn),spotPrice:f.toDecimal(h,o.decimalsIn),tradeFeePct:d,tradeFeeRange:y,priceImpactPct:S,errors:g}}})}return i}};var qi=6e3,Ln=1000000000000000n,be=6,qn=-5,Nn=216e5,lp=3,Ni=6;var Hn=require("polkadot-api");var J=class{static build(t){return t.map(({assetIn:e,assetOut:n,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,Hn.Enum)("Stableswap",s),asset_in:e,asset_out:n}:{pool:(0,Hn.Enum)(i),asset_in:e,asset_out:n})}};var Gt=class{schedulerOptions;router;constructor(t,e={}){this.router=t,this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Ln})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,n,i,s){let[r,a]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:o,swaps:l,priceImpactPct:u}=a,p=l[0],m=l[l.length-1],{assetInDecimals:d}=p,{assetOutDecimals:g}=m,y=Math.abs(u),h=this.getMinimumTradeCount(o,r),P=this.getOptimalTradeCount(y),b=s?Math.round(i/s):P,S=Math.ceil(i/h),x=Math.round(i/P),O=Math.round(i/b),D=o/BigInt(b),R=await this.router.getBestSell(t,e,D),Y=o<r,Z=[];Y&&Z.push("OrderTooSmall");let rt=R.amountOut*BigInt(b),K=this.toBlockPeriod(O),tt=R.tradeFee*BigInt(b),Pt=J.build(l),vt={assetIn:t,assetOut:e,errors:Z,frequencyMin:S,frequencyOpt:x,frequency:O,tradeCount:b,tradeFee:tt,tradeImpactPct:R.priceImpactPct,tradePeriod:K,tradeRoute:Pt,type:"Dca"};return{...vt,amountIn:o,amountOut:rt,tradeAmountIn:R.amountIn,tradeAmountOut:R.amountOut,toHuman(){return{...vt,amountIn:f.toDecimal(o,d),amountOut:f.toDecimal(rt,g),tradeAmountIn:f.toDecimal(R.amountIn,d),tradeAmountOut:f.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 i=t+n/2n;return Number(i/n)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getTwapSellOrder(t,e,n){let[i,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestSell(t,e,n)]),{amountIn:r,swaps:a,priceImpactPct:o}=s,l=a[0],u=a[a.length-1],{assetInDecimals:p}=l,{assetOutDecimals:m}=u,d=Math.abs(o),g=this.getTwapTradeCount(d),y=r/BigInt(g),h=await this.router.getBestSell(l.assetIn,u.assetOut,y),P=g===1,b=r<i,S=h.priceImpactPct<-5,x=[];b||P?x.push("OrderTooSmall"):S&&x.push("OrderImpactTooBig");let O=h.amountOut*BigInt(g),D=h.tradeFee*BigInt(g),R=J.build(a),Y={assetIn:t,assetOut:e,errors:x,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapSell"};return{...Y,amountIn:r,amountOut:O,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:D,toHuman(){return{...Y,amountIn:f.toDecimal(r,p),amountOut:f.toDecimal(O,m),tradeAmountIn:f.toDecimal(h.amountIn,p),tradeAmountOut:f.toDecimal(h.amountOut,m),tradeFee:f.toDecimal(D,m)}}}}async getTwapBuyOrder(t,e,n){let[i,s]=await Promise.all([this.getMinimumOrderBudget(t),this.router.getBestBuy(t,e,n)]),{amountOut:r,swaps:a,priceImpactPct:o}=s,l=a[0],u=a[a.length-1],{assetInDecimals:p}=l,{assetOutDecimals:m}=u,d=Math.abs(o),g=this.getTwapTradeCount(d),y=r/BigInt(g),h=await this.router.getBestBuy(l.assetIn,u.assetOut,y),P=h.amountIn*BigInt(g),b=g===1,S=P<i,x=h.priceImpactPct<-5,O=[];S||b?O.push("OrderTooSmall"):x&&O.push("OrderImpactTooBig");let D=h.tradeFee*BigInt(g),R=J.build(a),Y={assetIn:t,assetOut:e,errors:O,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:6,tradeRoute:R,type:"TwapBuy"};return{...Y,amountIn:P,amountOut:r,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:D,toHuman(){return{...Y,amountIn:f.toDecimal(P,p),amountOut:f.toDecimal(r,m),tradeAmountIn:f.toDecimal(h.amountIn,p),tradeAmountOut:f.toDecimal(h.amountOut,m),tradeFee:f.toDecimal(D,p)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let i=216e5/(this.blockTime*6);return Math.round(i)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,n=Math.round(e);return Math.max(n,6)}};var Vn={};I(Vn,{BIG_10:()=>Wi,BIG_BILL:()=>Un,StakingApi:()=>fe,StakingClient:()=>Pe});var z=require("@galacticcouncil/math-staking"),$=ut(require("big.js"));var ze={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},Hi=c=>Object.keys(ze).includes(c);var Gi=require("polkadot-api"),Ui=require("@polkadot-api/utils");function Vi(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=(0,Ui.toHex)(e);return(0,Gi.AccountId)(63).dec(n)}var Xe="20000000000000000",Ke="2000",Wi=(0,$.default)(10),Un=(0,$.default)(Wi.pow(12)),fe=class{client;balanceClient;constructor(t,e){this.client=t,this.balanceClient=e}async getPotBalance(){let t=await this.client.getPalletId(),e=Vi(t);return await this.balanceClient.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let i=e.created_at,s=await n.reduce(async(r,[a,o])=>{let l=await r,u=a,p=o.amount,m=o.conviction.toString().toLowerCase(),d=await this.client.getReferendumInfo(u);return d&&(d.type==="Approved"||d.type==="Rejected")&&Hi(m)&&l.push({id:u,amount:p,conviction:m}),l},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:i,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:s}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,i]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),s=i.find(r=>r)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:s,stakePosition:s?await this.getStakingPosition(s):void 0}}getCurrentActionPoints(t,e,n,i){let s=(0,$.default)(0),r=(0,$.default)(0),a=ze.locked6x,o=(0,$.default)(n.toString()).mul(a),l=100,u=[];t.forEach(d=>{let g=ze[d.conviction],y=i.includes(d.id.toString());y&&u.push(d.id.toString());let h=(0,$.default)(d.amount.toString()).mul(l).div(o);s=s.plus(Math.floor(h.mul(g).toNumber())),r=r.plus(Math.floor(h.mul(y?a:g).toNumber()))});let p=Math.floor((0,$.default)(n.toString()).mul(a).mul(l).div(o).toNumber());i.forEach(d=>{u.includes(d)||(r=r.plus(p))});let m={democracyVote:1};return s=s.mul(m.democracyVote),s=s.plus(e.toString()||"0"),r=r.mul(m.democracyVote),r=r.plus(e.toString()||"0"),{currentActionPoints:s.toString(),maxActionPoints:r.toString()}}async getRewards(t,e,n){let i=await this.getStake(t),{potReservedBalance:s,accumulatedRewardPerStake:r,totalStake:a,stakePosition:o}=i;if(!o)return;let[l,u,p,m,d,g,y]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=(0,$.default)(l.transferable.toString()).minus(s.toString()),P=h.gt(0)&&a>0?(0,z.calculate_accumulated_rps)(r.toString(),h.toString(),a.toString()):r.toString(),b=(0,z.calculate_period_number)(u.toString(),n,y),S=(0,z.calculate_period_number)(u.toString(),o.createdAt.toString(),y),x=(0,z.calculate_rewards)(P,o.rewardPerStake.toString(),o.stake.toString()),O=this.getCurrentActionPoints(o.votes,o.actionPoints,o.stake,e),D=(0,z.calculate_points)(S,b,m.toString(),d.toString(),O.currentActionPoints,g.toString(),o.accumulatedSlashPoints.toString()),R=(0,z.sigmoid)(D,Xe,Ke),Y=(()=>{if(!e.length)return;let Pt=(0,z.calculate_points)(S,b,m.toString(),d.toString(),O.maxActionPoints.toString(),g.toString(),o.accumulatedSlashPoints.toString());return(0,z.sigmoid)(Pt,Xe,Ke)})(),Z=(0,$.default)(x).plus(o.accumulatedUnpaidRewards.toString()).plus(o.accumulatedLockedRewards.toString());if((0,$.default)(b).minus(S).lte(p.toString()))return{rewards:"0",payablePercentage:R,extraPayablePercentage:Y,constants:{a:Xe,b:Ke}};let rt=(0,z.calculate_percentage_amount)(Z.toString(),R),K=(0,$.default)(o.accumulatedLockedRewards.toString()),tt=K.gt(rt)?K:(0,$.default)(rt);return{rewards:tt.div(Un).toString(),maxRewards:Z.div(Un).toString(),allocatedRewardsPercentage:tt.div(Z).mul(100).toNumber(),payablePercentage:R,extraPayablePercentage:Y,constants:{a:Xe,b:Ke}}}};var Pe=class extends N{async getPalletId(){let t=this.api.constants.Staking.PalletId;return(await t()).asText()}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:r})=>{let[a,o,l]=r;return{address:a,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 Yn={};I(Yn,{TxBuilderFactory:()=>Vt});var Wn=require("polkadot-api");function Yi(c){let t=[],e=c;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var Ut=class extends N{evm;evmClient;balanceClient;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balanceClient=new ot(t),this.aaveUtils=new Tt(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:nn})}async dryRun(t,e){let n=(0,Wn.Enum)("Signed",t),i=(0,Wn.Enum)("system",n),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall),a=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(a){let o=Yi(a.value);throw new Error("Dry run execution error!",{cause:o})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var je=class extends Ut{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:n}=this.trade;if(n==="Buy")return this.buildBuyTx();let{assetIn:i}=e[0],s=await this.balanceClient.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,i=n[0],s=n[n.length-1],r=A.getFraction(t,this.slippagePct),a=i.assetIn,o=s.assetOut,l=t+r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.buy({asset_in:a,asset_out:o,amount:e,max_sell_amount:l}):u=this.api.tx.Router.buy({asset_in:a,asset_out:o,amount_out:e,max_amount_in:l,route:J.build(n)}),this.wrapTx("RouterBuy",u)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:n}=this.trade,i=n[0],s=n[n.length-1],r=A.getFraction(e,this.slippagePct),a=i.assetIn,o=s.assetOut,l=e-r,u;return this.isDirectOmnipoolTrade(n)?u=this.api.tx.Omnipool.sell({asset_in:a,asset_out:o,amount:t,min_buy_amount:l}):u=this.api.tx.Router.sell({asset_in:a,asset_out:o,amount_in:t,min_amount_out:l,route:J.build(n)}),i.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSell",u)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,n=e[0],i=e[e.length-1],s=A.getFraction(t,this.slippagePct),r=n.assetIn,a=i.assetOut,o=t-s,l=this.api.tx.Router.sell_all({asset_in:r,asset_out:a,min_amount_out:o,route:J.build(e)});return n.isWithdraw()&&await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSellAll",l)}};var $e=require("polkadot-api");var Qe=class extends Ut{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradePeriod:s,tradeRoute:r}=this.order,a=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:(0,$e.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return this.wrapTx("DcaSchedule",a)}buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:a}=this.order,o=A.getFraction(s,this.slippagePct),l=s-o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,$e.Enum)("Sell",{asset_in:e,asset_out:n,amount_in:i,min_amount_out:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapSell",u)}buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:n,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:a}=this.order,o=A.getFraction(i,this.slippagePct),l=i+o,u=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,$e.Enum)("Buy",{asset_in:e,asset_out:n,amount_out:s,max_amount_in:l,route:a})},start_execution_block:void 0});return this.wrapTx("DcaSchedule.twapBuy",u)}};var Vt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new je(this.client,this.evmClient).setTrade(t)}order(t){return new Qe(this.client,this.evmClient).setOrder(t)}};async function Ms(c){let t=new Ct(c),e=new Jt(c),[n,i]=await Promise.all([t.getBlockTime(),t.getMinOrderBudget()]),s=new qt(c,e).withAave().withOmnipool().withStableswap().withXyk(),r=new ot(c),a=new Pe(c),o=new te(c),l=new Tt(e),u=new Ht(s),p=new Gt(u,{blockTime:n,minBudgetInNative:i}),m=new fe(a,r),d=new Zt(o,r,{blockTime:n});return{api:{aave:l,router:u,scheduler:p,staking:m,farm:d},client:{asset:new Et(c),balance:r,evm:e},ctx:{pool:s},tx:new Vt(c,e),destroy:()=>{s.destroy()}}}0&&(module.exports={QueryBus,aave,api,big,client,const:null,createSdkContext,erc20,error,evm,farm,fmt,h160,json,math,pool,sor,staking,tx,xc});