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