@galacticcouncil/sdk 10.7.1 → 10.8.0-pr293-a9f6dbd
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.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var we=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var ze=[{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 ut="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Je="0x112b087b60C1a166130d59266363C45F8aa99db0",Ze="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",J=1000000n;var Os=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var re=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getBlockTimestamp(){let e=await this.rpcAdapter.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.rpcAdapter.readContract({abi:ze,address:Je,functionName:"getReservesData",args:[Ze]})}async getUserReservesData(e){return await this.rpcAdapter.readContract({abi:ze,address:Je,functionName:"getUserReservesData",args:[Ze,e]})}async getUserAccountData(e){return await this.rpcAdapter.readContract({abi:we,address:ut,functionName:"getUserAccountData",args:[e]})}};import{decodeAddress as Oe,encodeAddress as pt}from"@polkadot/util-crypto";import{hexToU8a as Ut,isHex as qt,u8aToHex as Wt}from"@polkadot/util";import{Buffer as V}from"buffer";var Ns=2090,K=1e6,mt=1e9,Te="1",Es=2034,L=63,se=18,R="0",et=12,ie=15;var tt="ETH\0";function Xt(d){if(!d)return!1;try{let e=Oe(d,!0),t=V.from(tt);return V.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Vt(d){return!!/^0x[a-fA-F0-9]{40}$/.test(d)}function Yt(d){try{let e=qt(d)?Ut(d):Oe(d);return pt(e),!0}catch{return!1}}var X=class d{static toAccount=e=>{let t=V.from(e.slice(2),"hex"),r=V.from(tt);return pt(new Uint8Array(V.concat([r,t,V.alloc(8)])),63)};static fromAccount=e=>{let t=Oe(e),r=V.from(tt),s=t.slice(r.length,-8);return"0x"+V.from(s).toString("hex")};static fromSS58=e=>{let r=Oe(e).slice(0,20);return Wt(r)};static fromAny=e=>{if(Vt(e))return e;if(Xt(e))return d.fromAccount(e);if(Yt(e))return d.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Ie}from"buffer";var H=class{static fromAssetId(e){let t=Number(e),r=Ie.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Ie.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Ie.from("0000000000000000000000000000000100000000","hex"),r=Ie.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as x}from"bignumber.js";var Kt=12;x.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Kt});var v=m(0),N=m(1),qs=m("Infinity");function A(d,e){let t=new x(e.toString()),r=new x(10).pow(t);return d.times(r).decimalPlaces(4)}function m(d){return new x(d.toString())}function Ws(d,e){let t=m(d);return A(t,e)}function I(d,e){return d.shiftedBy(-1*e).toString()}var Ae=m("1e27"),$t=m("1.01"),Qt=m("31536000"),dt=4,Fe=-1,$=class{client;constructor(e){this.client=new re(e)}async getSummary(e){let t=X.fromAny(e),[r,s,i,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[n]=r,[a,l]=s,[c,u,p,h,g,b]=i,y=m(b).dividedBy(1e18).decimalPlaces(6,x.ROUND_DOWN),S=m(c),f=m(u),B=[];for(let O of a){let T=O.underlyingAsset.toLowerCase(),w=n.find(({underlyingAsset:Gt})=>Gt.toLowerCase()===T);if(!w)throw new Error("Missing pool reserve for "+T);let C=m(O.scaledATokenBalance),M=m(w.liquidityIndex),Be=m(w.liquidityRate),xe=m(w.availableLiquidity),$e=m(w.priceInMarketReferenceCurrency),Qe=o+6,je=this.calculateLinearInterest(Be,w.lastUpdateTimestamp,Qe),ve=M.multipliedBy(je).dividedBy(Ae).decimalPlaces(0,x.ROUND_DOWN),Dt=C.multipliedBy(ve).dividedBy(Ae).decimalPlaces(0,x.ROUND_DOWN),Mt=m(l!==0&&l===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold).div(1e4),Lt=w.usageAsCollateralEnabled&&O.usageAsCollateralEnabledOnUser&&m(O.scaledATokenBalance).gt(0),Ht=H.toAssetId(T);B.push({aTokenBalance:Dt,availableLiquidity:xe,decimals:Number(w.decimals),isCollateral:Lt,priceInRef:$e,reserveId:Ht,reserveAsset:T,reserveLiquidationThreshold:Mt})}return{healthFactor:y.toNumber(),currentLiquidationThreshold:m(h).dividedBy(10**dt).toNumber(),totalCollateral:S,totalDebt:f,reserves:B}}async hasBorrowPositions(e){let t=X.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=X.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,o,n,a,l]=r;return this.calculateHealthFactorFromBalances(m(i),m(s),m(n))}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:o,currentLiquidationThreshold:n}=await this.getSummary(e);if(i.lte(0))return Fe;let a=H.fromAssetId(t),l=o.find(B=>B.reserveAsset===a);if(!l)throw new Error("Missing reserve ctx for "+a);let{decimals:c,isCollateral:u,priceInRef:p,reserveLiquidationThreshold:h}=l,g=A(m(r),c).decimalPlaces(0,x.ROUND_DOWN),b=u?g.multipliedBy(p).dividedBy(m(10).pow(c)).decimalPlaces(0,x.ROUND_DOWN):v,y=s.minus(b);if(y.lte(0))return 0;let S=s.multipliedBy(m(n)).minus(b.multipliedBy(h)).dividedBy(y);return y.multipliedBy(S).dividedBy(i).decimalPlaces(6,x.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:o,currentLiquidationThreshold:n}=await this.getSummary(e);if(i.lte(0))return Fe;let a=H.fromAssetId(t),l=o.find(f=>f.reserveAsset===a);if(!l)throw new Error("Missing reserve ctx for "+a);let{decimals:c,priceInRef:u,reserveLiquidationThreshold:p}=l,g=A(m(r),c).decimalPlaces(0,x.ROUND_DOWN).multipliedBy(u).dividedBy(m(10).pow(c)).decimalPlaces(0,x.ROUND_DOWN),b=s.plus(g);if(b.lte(0))return 0;let y=s.multipliedBy(m(n)).plus(g.multipliedBy(p)).dividedBy(b);return b.multipliedBy(y).dividedBy(i).decimalPlaces(6,x.ROUND_DOWN).toNumber()}async getHealthFactorAfterSwap(e,t,r,s,i){let{totalDebt:o,reserves:n,healthFactor:a}=await this.getSummary(e);if(o.lte(0))return Fe;let l=H.fromAssetId(r),c=H.fromAssetId(i),u=n.find(w=>w.reserveAsset===l),p=n.find(w=>w.reserveAsset===c);if(!u)throw new Error(`Missing reserve ctx for ${l}`);if(!p)throw new Error(`Missing reserve ctx for ${c}`);let h=A(m(t),u.decimals).decimalPlaces(0,x.ROUND_DOWN),g=A(m(s),p.decimals).decimalPlaces(0,x.ROUND_DOWN),b=h.multipliedBy(u.priceInRef).dividedBy(m(10).pow(u.decimals)).decimalPlaces(0,x.ROUND_DOWN),y=g.multipliedBy(p.priceInRef).dividedBy(m(10).pow(p.decimals)).decimalPlaces(0,x.ROUND_DOWN),S=u.isCollateral?b.multipliedBy(u.reserveLiquidationThreshold):v,O=y.multipliedBy(p.reserveLiquidationThreshold).minus(S).dividedBy(o);return m(a).plus(O).decimalPlaces(6,x.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),o=H.fromAssetId(t),n=s.find(a=>a.reserveAsset===o);if(!n)throw new Error("Missing reserve data for "+o);return this.calculateWithdrawMax(n,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let o of r){let n=this.calculateWithdrawMax(o,t,s);o.reserveId&&(i[o.reserveId]=n)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:o,priceInRef:n,reserveLiquidationThreshold:a,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let p=m(r).minus($t);if(p.gt(0)){let g=p.multipliedBy(t).dividedBy(a).decimalPlaces(0,x.ROUND_DOWN).dividedBy(n).multipliedBy(m(10).pow(o)).decimalPlaces(0,x.ROUND_DOWN);c=x.minimum(s,g)}else c=v}return{amount:x.minimum(c,i),decimals:o}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ae:e.multipliedBy(s).dividedBy(Qt).plus(Ae).decimalPlaces(0,x.ROUND_DOWN)}calculateHealthFactorFromBalances(e,t,r){return e.lte(0)?Fe:t.multipliedBy(r).dividedBy(e).dividedBy(m(10).pow(dt)).decimalPlaces(6,x.ROUND_DOWN).toNumber()}};function gt(d){switch(d){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var _=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");gt(r)&&console.log(e,...t)}};var Q=class extends _{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e=="0"){let u=this.api.consts.balances.existentialDeposit;return{id:"0",name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:i,assetType:o,isSufficient:n,existentialDeposit:a}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:o.toHuman(),isSufficient:n?n.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,o]=s,{assetType:n,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(i.toString(),t,r),p=o.toNumber(),h=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",h.format(p)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:p}}getShares(e,t,r,s){let{assets:i}=s,{name:o,symbol:n,assetType:a,isSufficient:l,existentialDeposit:c}=t,p=i.map(b=>b.toString()).map(b=>{let{symbol:y}=this.getToken(b,t,r);return[b,y]}),h=Object.fromEntries(p),g=Object.values(h);return{id:e,name:g.join(", "),symbol:n?.isSome?n.toHuman():o.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:h}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),o=r?.find(n=>n.internalId===i.id);return o?{...i,decimals:o.decimals,name:o.name,symbol:o.symbol,icon:o.symbol,isWhiteListed:o.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:o}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:o.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,o,n]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,n),c=a.map(([{args:[u]},p])=>{let h=p.unwrap(),g=s.get(u.toString()),{assetType:b}=h;switch(b.toString()){case"Bond":let y=o.get(u.toString());return this.getBond(u.toString(),h,l,y);case"StableSwap":let S=i.get(u.toString());return this.getShares(u.toString(),h,l,S);case"External":return this.getExternal(u.toString(),h,t,g);default:return this.getToken(u.toString(),h,l,g)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var G=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeSystemBalances(e,t){return this.api.query.system.account.multi(e,r=>{let s=[];r.forEach((i,o)=>{let n=this.calculateFreeBalance(i.data),a=e[o];s.push([a,n])}),t(s)})}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(o=>[e,o]):s.map(({args:[o,n]})=>[o.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,o=>{let n=[];o.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=i[l][1];n.push([u,c])}),t(n)})}async subscribeTokenBalances(e,t){return this.api.query.tokens.accounts.multi(e,r=>{let s=[];r.forEach((i,o)=>{let n=this.calculateFreeBalance(i),a=e[o];s.push([a,n])}),t(s)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),o=async()=>{let n=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async subscribeErc20Balances(e,t){let r=async()=>{let s=await Promise.all(e.map(async i=>{let[o,n]=i;return[i,await this.getErc20Balance(o,n)]}));t(s)};return this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return x(t).lt(r)?x(0):x(t).minus(r)}};var ae=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(o=>[e,o]):s.map(({args:[o,n]})=>[o.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,o=>{let n=[];o.forEach((a,l)=>{let c=i[l][1],u=this.calculateBalance(a);n.push([c,u])}),t(n)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),o=async()=>{let n=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=x(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",o=t.plus(s).toString();return{free:t.toString(),total:o,transferable:i,reserved:s,frozen:r}}};var ne=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as ht}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as jt}from"@polkadot/types";import{u8aConcat as yt}from"@polkadot/util";import{isAddress as bt}from"@polkadot/util-crypto";var rt=class extends _{balanceClient;constructor(e){super(e),this.balanceClient=new G(e)}secondsInYear=new x(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,o]=s.args,n=i.unwrap().toString(),a=o.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(h,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,o]=s.args,n=i.unwrap().toString(),a=o.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),h=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(h,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new x(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[o]=i.unwrap(),n=o.price.n.toString(),a=o.price.d.toString(),l;return Number(t)<Number(r)?l=ht(n,a):l=ht(a,n),l}getGlobalRewardPerPeriod(e,t,r,s){let o=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return o.gte(r)?r:o}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return yt(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new jt(e,this.padEndU8a(yt(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!bt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&bt(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:n,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new x(a.totalSharesZ.toString()),p=a.plannedYieldingPeriods.toString(),h=new x(a.yieldPerPeriod.toString()),g=new x(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),y=new x(n.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new x(r).times(b)),f;if(u.isZero())f=h.times(y).times(S);else{let C=this.getGlobalRewardPerPeriod(u,h,g,l);f=this.getPoolYieldPerPeriod(C,y,u,l).times(S)}let B=new x(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),O=g.times(p),T=c?B.plus(c):O;return B.div(T).gte(.999)?v:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,a)=>n.plus(a),v).toString():void 0}};var Re=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Pt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ne=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ft=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},St=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Bt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},xt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{encodeFunctionData as zt,decodeFunctionResult as Jt}from"viem";var Zt=1e7,Ee=class{api;constructor(e){this.api=e}async getBlock(){let e=await this.api.query.ethereum.currentBlock(),{header:t}=e.unwrap(),r=t.timestamp.toBigInt()/1000n,s=t.number.toBigInt();return{timestamp:r,number:s}}readContract=(async e=>{let{abi:t,address:r,functionName:s,args:i}=e,o=zt({abi:t,functionName:s,args:i}),n=this.api.call.ethereumRuntimeRPCApi.call,a=n.meta.params,l=["",r,o,0,Zt,null,null,null,!1,[]];a.find(g=>g.name==="authorization_list")&&l.push([]);let c=await n(...l);if(c.isErr)throw console.error(s,c.asErr.toHuman()),new Error("Contract read failure");let{value:u,exitReason:p,usedGas:h}=c.asOk;if(p.isSucceed)return Jt({abi:t,functionName:s,data:u.toHex()});throw console.log(s,p.toString(),h.toHuman()),new Error("Contract read error")})};import{defineChain as er}from"viem";var tr=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],vt=d=>{let t=[d.endpoint,...tr],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return er({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1})};import{createPublicClient as Tt,createWalletClient as rr,custom as sr,http as ir}from"viem";function wt(d){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return d.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Ce=class{api;chain;constructor(e){this.api=e,this.chain=vt(this.provider)}get provider(){let{provider:e}=this.api._options;return e}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return Tt({chain:this.chain,transport:ir()})}getWsProvider(){return Tt({chain:this.chain,transport:wt(this.provider)})}getSigner(e){return rr({account:e,chain:this.chain,transport:sr(window.ethereum)})}getRPCAdapter(){return new Ee(this.api)}};var st=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var oe=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.rpcAdapter.readContract({abi:st,address:e,functionName:"latestRoundData"}),this.rpcAdapter.readContract({abi:st,address:e,functionName:"decimals"}),this.rpcAdapter.getBlock()]),[o,n,a,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),u=Number(c);return{price:n,decimals:s,updatedAt:u<0?0:u}}};import{memoize1 as gs}from"@thi.ng/memoize";var E=(o=>(o.Aave="Aave",o.LBP="Lbp",o.Omni="Omnipool",o.Stable="Stableswap",o.XYK="Xyk",o.HSM="Hsm",o))(E||{}),j=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(j||{});var ke=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new d(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,assetInED:v,assetOutED:v}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return A(N,e.decimalsOut)}spotPriceOutGivenIn(e){return A(N,e.decimalsIn)}calculateTradeFee(e,t){return v}};import{encodeAddress as or}from"@polkadot/util-crypto";import{stringToU8a as lr}from"@polkadot/util";import{decodeEventLog as cr}from"viem";import{memoize1 as ar}from"@thi.ng/memoize";import{TLRUCache as nr}from"@thi.ng/cache";var D=class extends G{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new nr(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=ar(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new oe(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(e){}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=[],t=[],r=[],s=[];for(let n of this.augmentedPools){let{address:a,tokens:l}=n;l.filter(c=>c.id==="0").forEach(()=>{e.push(a)}),l.filter(c=>["Token","StableSwap"].includes(c.type)&&c.id!=="0"&&c.id!==n.id).forEach(c=>{t.push([a,c.id])}),l.filter(c=>c.type==="Erc20").forEach(c=>{r.push([a,c.id])})}let i=n=>{n.forEach(([a,l])=>{let c=this.pools.find(u=>u.address===a);if(c){let u=c.tokens.findIndex(p=>p.id==="0");c.tokens[u].balance=l.toString()}})},o=n=>{n.forEach(([a,l])=>{let[c,u]=a,p=this.pools.find(h=>h.address===c);if(p){let h=p.tokens.findIndex(g=>g.id===u);p.tokens[h].balance=l.toString()}})};if(e.length>0){let n=await this.subscribeSystemBalances(e,i);s.push(n)}if(t.length>0){let n=await this.subscribeTokenBalances(t,o);s.push(n)}if(r.length>0){let n=await this.subscribeErc20Balances(r,o);s.push(n)}return()=>{for(let n of s)try{n()}catch(a){console.warn("Balance unsub failed",a)}}}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}};function _e(d,e){let t=[];return JSON.stringify(d,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Ra(d,e,t){let r;return JSON.stringify(d,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Na=(d,e)=>typeof e=="bigint"?e.toString():e;var ur=["Supply","Withdraw","Repay","Borrow"],De=class extends D{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return or(lr(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?_e(e.location,"accountKey20").accountKey20.key:H.fromAssetId(e.id)}isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,o]=r.data.toJSON();this.pools.filter(n=>n.tokens.some(a=>a.id===i.toString()||a.id===o.toString())).forEach(n=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${o}`),this.updatePoolState(n)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:o,args:n}=cr({abi:we,topics:i.topics,data:i.data});if(ur.includes(o)){let a=n.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===a}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${o} ${a}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(o=>{let n=o.id===t.id?s.toString():i.toString();return{...o,balance:n}})}};import{calculate_in_given_out as mr,calculate_out_given_in as pr,calculate_linear_weights as dr,calculate_pool_trade_fee as gr,get_spot_price as hr}from"@galacticcouncil/math-lbp";var W=class{static getSpotPrice(e,t,r,s,i){return hr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return mr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return pr(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return dr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return gr(e,t,r)}};var P=class d{static toPct(e){let[t,r]=e;return d.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return d.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var Me=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new d(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:n,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let o=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let n=this.calculateTradeFee(t,r),a=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(n),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let n=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let o=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let n=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:n,feePct:0,errors:i}}else{let n=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(n,r),l=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=n.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?v:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?v:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(N,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(N,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var Le=class extends D{MAX_FINAL_WEIGHT=A(m(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:i,assets:o,initialWeight:n,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=W.calculateLinearWeights(s.toString(),i.toString(),n.toString(),a.toString(),r),[p,h]=o,g=p.toString(),b=m(u),y=h.toString(),S=this.MAX_FINAL_WEIGHT.minus(m(b)),[f,B,O]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,y)]);return{repayFeeApply:f,tokens:[{id:g,weight:b,balance:B.toString()},{id:y,weight:S,balance:O.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t>=r&&t<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,o])=>this.isActivePool(o.unwrap(),r.toNumber())).map(async([{args:[i]},o])=>{let n=o.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,n,r.toString());this.poolsData.set(i.toString(),n);let[c,u]=n.fee;return{address:a,type:"Lbp",fee:P.fromRate(c.toNumber(),u.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return P.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let o=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,o)}else{let o=this.pools.findIndex(n=>n.address==r.address);this.pools.splice(o,1)}})})}};import{calculate_in_given_out as yr,calculate_lrna_in_given_out as br,calculate_out_given_in as Pr,calculate_out_given_lrna_in as fr,calculate_spot_price as Sr,calculate_lrna_spot_price as Br,calculate_shares as xr,calculate_liquidity_out as vr,calculate_liquidity_lrna_out as wr,calculate_liquidity_hub_in as Tr,is_sell_allowed as Or,is_buy_allowed as Ir,is_add_liquidity_allowed as Ar,is_remove_liquidity_allowed as Fr,recalculate_asset_fee as Rr,recalculate_protocol_fee as Nr,verify_asset_cap as Er}from"@galacticcouncil/math-omnipool";var F=class{static calculateSpotPrice(e,t,r,s){return Sr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return Br(e,t)}static calculateInGivenOut(e,t,r,s,i,o,n,a,l){return yr(e,t,r,s,i,o,n,a,l,"0")}static calculateLrnaInGivenOut(e,t,r,s,i){return br(e,t,r,s,i,"0")}static calculateOutGivenIn(e,t,r,s,i,o,n,a,l){return Pr(e,t,r,s,i,o,n,a,l,"0")}static calculateOutGivenLrnaIn(e,t,r,s,i){return fr(e,t,r,s,i,"0")}static calculateShares(e,t,r,s){return xr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,o,n,a){return vr(e,t,r,s,i,o,n,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,o,n,a){return wr(e,t,r,s,i,o,n,a)}static calculateCapDifference(e,t,r,s){let i=x(t),o=x(e),n=x(s),l=x(r).shiftedBy(-18);if(i.div(n).lt(l)){let u=l.times(n).minus(i).times(o),p=i.times(x(1).minus(l));return u.div(p).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return Tr(e,t,r,s)}static isSellAllowed(e){return Or(e)}static isBuyAllowed(e){return Ir(e)}static isAddLiquidityAllowed(e){return Ar(e)}static isRemoveLiquidityAllowed(e){return Fr(e)}static recalculateAssetFee(e,t,r,s,i,o,n,a,l,c,u){return Rr(e,t,r,s,i,o,n,a,l,c,u)}static recalculateProtocolFee(e,t,r,s,i,o,n,a,l,c,u){return Nr(e,t,r,s,i,o,n,a,l,c,u)}static verifyAssetCap(e,t,r,s){return Er(e,t,r,s)}};var He=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new d(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),o=i.minus(s),n=s===v?v:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let p=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(p)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let p=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(p)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=F.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():v.toString(),r?P.toRaw(r.protocolFee).toString():v.toString()),i=m(s);return i.isNegative()?v:i}calculateLrnaInGivenOut(e,t,r){let s=F.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():v.toString()),i=m(s);return i.isNegative()?v:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=F.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():v.toString(),r?P.toRaw(r.protocolFee).toString():v.toString()),i=m(s);return i.isNegative()?v:i}calculateOutGivenLrnaIn(e,t,r){let s=F.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():v.toString()),i=m(s);return i.isNegative()?v:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=F.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=F.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=F.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=F.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Cr}from"@polkadot/util-crypto";import{stringToU8a as kr}from"@polkadot/util";import{memoize1 as it}from"@thi.ng/memoize";import{TLRUCache as _r}from"@thi.ng/cache";var Ot="omnipool",It="Short",Ge=class extends D{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new _r(null,{ttl:6*1e3});memOracleQuery=it(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(Ot,t,It)},this.memQueryCache);memFeesQuery=it(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=it(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return Cr(kr("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),o=r.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:p,cap:h,protocolShares:g}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:p.bits.toNumber(),balance:b.toString(),cap:m(h.toString()),protocolShares:m(g.toString())}}),n=await Promise.all(o);return n.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:n,...this.getPoolLimits()}]}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,o;if(this.isAssetConfigSupported()&&(o=await this.getDynamicFeesConfiguration(s).then(f=>f.unwrapOr(null))),o?.isFixed){let f=o.asFixed.assetFee.toNumber(),B=o.asFixed.protocolFee.toNumber();return{assetFee:P.fromPermill(f),protocolFee:P.fromPermill(B)}}let[n,a,l]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[c,u,p]=this.getAssetFee(t,e,n,a,o?.isDynamic?o.asDynamic.assetFeeParams:void 0),[h,g,b]=i==="1"?[0,0,0]:this.getProtocolFee(t,e,n,l,o?.isDynamic?o.asDynamic.protocolFeeParams:void 0),y=c+h,S=p+b;return{assetFee:P.fromPermill(u),protocolFee:P.fromPermill(g),min:P.fromPermill(y),max:P.fromPermill(S)}}getAssetFee(e,t,r,s,i){let{assetOut:o,balanceOut:n}=e,{minFee:a,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.assetFeeParameters,p=P.fromPermill(a.toNumber()),h=P.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[g]=s.unwrap(),{assetFee:b,timestamp:y}=r.unwrap(),S=Math.max(1,t-y.toNumber()),f=g.volume.bIn.toString(),B=g.volume.bOut.toString(),O=g.liquidity.b.toString();o==="0"&&(f=g.volume.aIn.toString(),B=g.volume.aOut.toString(),O=g.liquidity.a.toString());let T=P.fromPermill(b.toNumber()),w=F.recalculateAssetFee(f,B,O,"9",n.toString(),P.toRaw(T).toString(),S.toString(),P.toRaw(p).toString(),P.toRaw(h).toString(),c.toString(),u.toString());return[a.toNumber(),Number(w)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:o,balanceIn:n}=e,{minFee:a,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.protocolFeeParameters,p=P.fromPermill(a.toNumber()),h=P.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[g]=s.unwrap(),{protocolFee:b,timestamp:y}=r.unwrap(),S=Math.max(1,t-y.toNumber()),f=g.volume.bIn.toString(),B=g.volume.bOut.toString(),O=g.liquidity.b.toString();o==="0"&&(f=g.volume.aIn.toString(),B=g.volume.aOut.toString(),O=g.liquidity.a.toString());let T=P.fromPermill(b.toNumber()),w=F.recalculateProtocolFee(f,B,O,"9",n.toString(),P.toRaw(T).toString(),S.toString(),P.toRaw(p).toString(),P.toRaw(h).toString(),c.toString(),u.toString());return[a.toNumber(),Number(w)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let p=l.unwrap();return this.updateTokenState(u,p)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});if(r.push(i),this.isAssetConfigSupported()){let a=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,u)=>{let p=t[u];this.dynamicFeesConfiguration.set(p,c)})});r.push(a)}let o=t.map(a=>{let l=this.getOracleKey(a);return[Ot,l,It]}),n=await this.api.query.emaOracle.oracles.multi(o,a=>{a.forEach(async(l,c)=>{let u=o[c],[p,h,g]=u;this.oracles.set(h.join(":"),l)})});return r.push(n),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:o,protocolShares:n}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(o.toString()),protocolShares:m(n.toString()),tradeable:i.bits.toNumber()}}};import{calculate_in_given_out as Dr,calculate_out_given_in as Mr,calculate_pool_trade_fee as Lr,get_spot_price as Hr,calculate_liquidity_in as Gr,calculate_shares as Ur,calculate_spot_price as qr,calculate_spot_price_with_fee as Wr,calculate_liquidity_out_asset_a as Xr,calculate_liquidity_out_asset_b as Vr}from"@galacticcouncil/math-xyk";var Y=class{static getSpotPrice(e,t,r){return Hr(e,t,r)}static calculateInGivenOut(e,t,r){return Dr(e,t,r)}static calculateOutGivenIn(e,t,r){return Mr(e,t,r)}static calculatePoolTradeFee(e,t,r){return Lr(e,t,r)}static calculateLiquidityIn(e,t,r){return Gr(e,t,r)}static calculateSpotPrice(e,t){return qr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return Wr(e,t,r,s)}static calculateShares(e,t,r){return Ur(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Xr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Vr(e,t,r,s)}};var Ue=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new d(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),o=P.toPct(r.exchangeFee),n=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:o,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),o=P.toPct(r.exchangeFee),n=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:o,errors:a}}calculateInGivenOut(e,t){let r=Y.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?v:s}calculateOutGivenIn(e,t){let r=Y.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?v:s}spotPriceInGivenOut(e){let t=Y.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(N,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=Y.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(N,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=Y.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var qe=class extends D{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[o,n]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(i,o.toString()),this.getBalance(i,n.toString())]);return{address:i,type:"Xyk",tokens:[{id:o.toString(),balance:a.toString()},{id:n.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return P.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};import{calculate_in_given_out as Yr,calculate_out_given_in as Kr,calculate_amplification as $r,calculate_add_one_asset as Qr,calculate_liquidity_out_one_asset as jr,calculate_shares as zr,calculate_shares_for_amount as Jr,calculate_spot_price_with_fee as Zr,pool_account_name as es,recalculate_peg as ts}from"@galacticcouncil/math-stableswap";var k=class{static getPoolAddress(e){return es(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return $r(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,o,n){return Yr(e,t,r,s,i,o,n)}static calculateAddOneAsset(e,t,r,s,i,o,n){return Qr(e,t,r,s,i,o,n)}static calculateSharesForAmount(e,t,r,s,i,o,n){return Jr(e,t,r,s,i,o,n)}static calculateOutGivenIn(e,t,r,s,i,o,n){return Kr(e,t,r,s,i,o,n)}static calculateLiquidityOutOneAsset(e,t,r,s,i,o,n){return jr(e,t,r,s,i,o,n)}static calculateShares(e,t,r,s,i,o){return zr(e,t,r,s,i,o)}static calculateSpotPriceWithFee(e,t,r,s,i,o,n,a){return Zr(e,t,r,s,i,o,n,a)}static recalculatePegs(e,t,r,s,i,o){let n=ts(e,t,r,s,i,o);return JSON.parse(n)}};var Z=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new d(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:n,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),o=i.minus(s),n=s===v?v:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:a}}calculateIn(e,t,r){let s=k.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=m(s);return i.isNegative()?v:i}calculateAddOneAsset(e,t,r){let s=k.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=m(s);return i.isNegative()?v:i}calculateSharesForAmount(e,t,r){let s=k.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=m(s);return i.isNegative()?v:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=A(N,e.decimalsIn-e.decimalsOut);return m(t).div(s).decimalPlaces(0,1)}let r=A(N,18-e.decimalsIn);return m(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=k.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=m(s);return i.isNegative()?v:i}calculateWithdrawOneAsset(e,t,r){let s=k.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=m(s);return i.isNegative()?v:i}calculateShares(e,t,r){let s=k.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():v.toString(),this.getPegs()),i=m(s);return i.isNegative()?v:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=A(N,e.decimalsOut-e.decimalsIn);return m(t).div(s).decimalPlaces(0,1)}let r=A(N,18-e.decimalsOut);return m(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as rs,encodeAddress as ss}from"@polkadot/util-crypto";var We=class extends D{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=k.getPoolAddress(t);return ss(rs(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:o,finalBlock:n}=t,a=k.calculateAmplification(s.toString(),i.toString(),o.toString(),n.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async o=>{let[n,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:n.bits.toNumber(),balance:a.toString()}});return Promise.all(i)}isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[o]},n])=>{try{let a=n.unwrap(),l=o.toString(),c=this.getPoolAddress(l),[u,p,h]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(c,l,a),this.getPoolPegs(l,a,r.toString())]);return p.push({id:l,tradeable:15,balance:u.totalIssuance}),this.poolsData.set(c,a),{address:c,id:l,type:"Stableswap",fee:P.fromPermill(a.fee.toNumber()),tokens:p,...u,...h,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${o.toString()}
|
|
2
|
-
`,String(a)),null}});return(await Promise.all(s)).filter(o=>o!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let i=s.unwrap(),o=await this.getLatestPegs(t,i,r),n=o.map(({pair:y,updatedAt:S})=>[y,S]),a=this.getRecentPegs(i),l=P.fromPermill(t.fee.toNumber()),c=P.fromPerbill(i.maxPegUpdate.toNumber()),u=o.find(y=>y.source),p=i.updatedAt?i.updatedAt.toString():u?.updatedAt;if(!p)throw Error(e+" current peg unknown");let[h,g]=k.recalculatePegs(JSON.stringify(a),p,JSON.stringify(n),r,P.toRaw(c).toString(),P.toRaw(l).toString()),b=Number(h)*1e6;return{pegsFee:P.fromPermill(b),pegs:g}}getDefaultPegs(e){let t=e.fee,r=k.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t.toNumber()),pegs:r}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([n,a])=>a.toString()),o=s.map(async(n,a)=>{if(n.isOracle){let[l,c,u]=n.asOracle,p=[u.toString(),i[a]].map(B=>Number(B)).sort((B,O)=>B-O),h=await this.api.query.emaOracle.oracles(l,p,c),[{price:g,updatedAt:b}]=h.unwrap(),y=g.n.toString(),S=g.d.toString();return{pair:u.toString()===p[0].toString()?[y,S]:[S,y],updatedAt:b.toString(),source:"ema"}}else if(n.isMmOracle){let l=n.asMmOracle,{price:c,decimals:u,updatedAt:p}=await this.mmOracle.getData(l.toString()),h=10**u;return{pair:[c.toString(),h.toString()],updatedAt:p.toString(),source:"mm"}}else{if(n.isValue)return{pair:n.asValue.map(c=>c.toString()),updatedAt:r};throw Error(n.type+" is not supported")}});return Promise.all(o)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[i,o]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),n=r.tokens.map(a=>a.id===r.id?{...a,balance:i.totalIssuance}:a);Object.assign(r,{tokens:n},i,o)}})})}};import{calculate_collateral_in_given_hollar_out as is,calculate_collateral_out_given_hollar_in as as,calculate_hollar_in_given_collateral_out as ns,calculate_hollar_out_given_collateral_in as os,calculate_imbalance as ls,calculate_max_price as cs,calculate_buyback_limit as us,calculate_buyback_price_with_fee as ms}from"@galacticcouncil/math-hsm";var U=class{static calculateCollateralInGivenHollarOut(e,t,r){return is(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return as(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return os(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return ns(e,t,r)}static calculateImbalance(e,t,r){return ls(e,t,r)}static calculateBuybackLimit(e,t){return us(e,t)}static calculateBuybackPriceWithFee(e,t,r){return ms(e,t,r)}static calculateMaxPrice(e,t){return cs(e,t)}};var Xe=class d extends Z{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new d(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let o=this.calculateBuyPrice(e,t,r),n=this.calculateMaxPrice(e);return o.gt(n)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=U.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),P.toRaw(this.buyBackFee).toString());return m(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=U.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),P.toRaw(this.purchaseFee).toString());return m(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=U.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),P.toRaw(this.buyBackFee).toString());return m(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=U.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),P.toRaw(this.purchaseFee).toString());return m(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=U.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return m(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=U.calculateBuybackLimit(t.toString(),P.toRaw(this.buyBackRate).toString());return m(r)}calculateBuyPrice(e,t,r){let s=U.calculateBuybackPriceWithFee(r.toFixed(),t.toFixed(),P.toRaw(this.buyBackFee).toString()),[i,o]=JSON.parse(s),n=m(10).pow(e.decimalsIn-e.decimalsOut);return m(i).times(n).dividedBy(m(o))}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=U.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return m(s).div(m(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=A(N,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=A(N,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[A(N,18).toString(),A(N,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};import{stringToU8a as At}from"@polkadot/util";import{encodeAddress as Ft}from"@polkadot/util-crypto";import{decodeEventLog as ps}from"viem";var le=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var ce=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getFacilitatorCapacity(e,t){let[r,s]=await this.rpcAdapter.readContract({abi:le,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var ds=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Ve=class extends D{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new ce(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return Ft(At(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return Ft(At("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return _e(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),o=X.fromAny(i),n=this.getHollarAddress(t.unwrap()),a=await this.ghoTokenClient.getFacilitatorCapacity(n,o),l=r.map(async([{args:[u]},p])=>{let h=p.unwrap(),g=u.toString(),{poolId:b,maxBuyPriceCoefficient:y,maxInHolding:S,purchaseFee:f,buyBackFee:B,buybackRate:O}=h,T=s.find(w=>w.id===b.toString());if(T){let w=this.getPoolId(b.toString()),C=await this.getBalance(i,g);return{...T,address:w,type:"Hsm",tokens:T.tokens.filter(M=>M.id!==b.toString()),hsmAddress:i,hsmMintCapacity:m(a),hollarId:e,hollarH160:n,collateralId:g,collateralBalance:C,maxBuyPriceCoefficient:m(y.toString()),maxInHolding:m(S.unwrap().toString()),purchaseFee:P.fromPermill(f.toNumber()),buyBackFee:P.fromPermill(B.toNumber()),buyBackRate:P.fromPerbill(O.toNumber())}}});return(await Promise.all(l)).filter(u=>u!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:o,args:n}=ps({abi:le,topics:i.topics,data:i.data}),[a]=this.pools,{hsmAddress:l,hollarH160:c}=a,u=X.fromAny(l),p=u.toLowerCase()===n.facilitatorAddress.toLowerCase();if(ds.includes(o)&&p){let h=await this.ghoTokenClient.getFacilitatorCapacity(c,u);this.log(`Sync HSM facilitator via [evm:Log] :: ${o} ${h}`),this.pools.forEach(g=>{Object.assign(g,{hsmMintCapacity:h})})}}catch{}}})}async subscribeBalances(){let e=[],t=[],r=[];for(let i of this.pools){let{tokens:o,hsmAddress:n,collateralId:a}=i;o.find(c=>c.id===a).type==="Erc20"?t.push([n,a]):e.push([n,a])}let s=i=>{i.forEach(([o,n])=>{let[a,l]=o,c=this.pools.find(u=>u.tokens.some(p=>p.id===l));c&&Object.assign(c,{collateralBalance:n})})};if(e.length>0){let i=await this.subscribeTokenBalances(e,s);r.push(i)}if(t.length>0){let i=await this.subscribeErc20Balances(t,s);r.push(i)}return()=>{for(let i of r)try{i()}catch(o){console.warn("Balance unsub failed",o)}}}async subscribeUpdates(){return()=>{}}};var ue=class extends _{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=gs(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new Q(this.api),this.aaveClient=new De(this.api,t),this.xykClient=new qe(this.api,t),this.omniClient=new Ge(this.api,t),this.lbpClient=new Le(this.api,t),this.stableClient=new We(this.api,t),this.hsmClient=new Ve(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Re(t.type)}}};var me=class extends ue{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var pe=class{static get(e){switch(e.type){case"Aave":return ke.fromPool(e);case"Xyk":return Ue.fromPool(e);case"Omnipool":return He.fromPool(e);case"Lbp":return Me.fromPool(e);case"Stableswap":return Z.fromPool(e);case"Hsm":return Xe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as hs}from"@noble/hashes/sha2";import{bytesToHex as ys}from"@noble/hashes/utils";function Kc(d){let e=d.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=hs(t);return ys(r)}var de=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var bs=10,ge=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new de,o=[];for(o.push([t,""]),i.enqueue(o);i.size()>0;){let n=i.dequeue();if(!n||n.length>bs)continue;let a=n[n.length-1];(r===null||a[0]===r)&&s.push(n),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,n)){let u=[...n];u.push(c),i.enqueue(u)}})}return s}findShortestPaths(e,t,r){let s=[],i=new de,o=[];o.push([t,""]),i.enqueue(o);let n=1/0;for(;i.size()>0;){let a=i.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<n?(n=a.length,s.length=0,s.push(a)):a.length===n&&s.push(a);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,a)&&i.enqueue([...a,u])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,o]of t){let n=parseInt(i),a=parseInt(o);r.get(n)?.push([a,s])}return r}};function at(d){let e={};for(let t of d){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let o=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(o)}}}return e}var he=class{getProposals(e,t,r){let s=r.filter(f=>f.type==="Xyk"),i=r.filter(f=>f.type!=="Xyk"),o=parseInt(e),n=parseInt(t),a=new Set(i.map(f=>f.tokens).flat().map(f=>f.id)),l=a.has(e),c=a.has(t),u=new ge,p=f=>{let B=at(f),O=Object.keys(B),T=O.flatMap(w=>B[w]);return u.buildAndPopulateGraph(O,T)};if(!l&&!c){let f=s.filter(T=>T.tokens.find(w=>w.id===e)||T.tokens.find(w=>w.id===t)),B=p(f),O=u.findPaths(B,o,n);return this.parsePaths(O)}if(l&&c){let f=p(i),B=u.findPaths(f,o,n);return this.parsePaths(B)}let h=l?t:e,g=s.filter(f=>f.tokens.some(B=>B.id===h));if(g.length===0)return[];let b=[...i,...g],y=p(b),S=u.findPaths(y,o,n);return this.parsePaths(S)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let o=r[i],n=r[i+1];if(n==null)break;s.push(this.toEdge(o,n))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ye=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new he,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}buildRouteKey(e,t,r){return`${e}->${t}::${r.length}`}async getPools(){return this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRouteableAssets(e){let t=await this.getAllAssets();return(await Promise.all(t.map(s=>s.id).filter(s=>s!==e).map(s=>this.getRoutes(s,e)))).filter(s=>s.length>0).map(([s])=>s[0].assetIn).sort()}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(n=>this.validPath(n,s)).map(n=>this.toHops(n,s))}getProposals(e,t,r){let s=this.buildRouteKey(e,t,r);if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,pe.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let o=t.get(r);return{poolAddress:r,poolId:o?.id,pool:o?.type,assetIn:s,assetOut:i}})}};var Ps=m("100");function Mu(d,e){return d.minus(e).abs().div(d.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function be(d,e){return d.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Rt(d,e){return N.minus(e.div(d)).multipliedBy(100).decimalPlaces(4)}function Nt(d,e){return e.div(d).minus(N).multipliedBy(100).decimalPlaces(4)}function z(d,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),d.div(Ps).multipliedBy(e).decimalPlaces(0,1)}var nt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(nt||{}),ot=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(ot||{}),Et=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Et||{});var ee=class extends ye{mlr;poolsSnapshot;constructor(e,t={}){super(e,t),this.mlr=new Map}buildCtxSync(e,t){let r=this.poolsSnapshot,s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(!i.length)throw new Ne(e,t);return{paths:i,pools:r,poolsMap:s}}async withCtx(e,t,r){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let s=this.buildCtxSync(e,t);return r(s)}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,o=s[s.length-1].amountOut;return i.isGreaterThan(o)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,o)=>i+o),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,o)=>i+o);return[r,s]}}getPoolFeeRange(e){let t=e.min?P.toPct(e.min):void 0,r=e.max?P.toPct(e.max):void 0;if(t&&r)return[t,r]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){return this.withCtx(e,t,async({paths:i,poolsMap:o})=>{let n;if(s)n=await this.toSellSwaps(r,s,o);else{let a=i.map(c=>this.toSellSwaps(r,c,o)),l=await Promise.all(a);n=this.findBestSellRoute(l)}return this.buildSell(o,n)})}async getSellTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let o=s.map(a=>this.toSellSwaps(r,a,i));return(await Promise.all(o)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildSell(i,a)).sort((a,l)=>a.amountOut.isGreaterThan(l.amountOut)?-1:1)})}buildSell(e,t){let r=t[0],s=t[t.length-1],i=this.isDirectTrade(t),o=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetOutDecimals)).reduce((b,y)=>b.multipliedBy(y)),n=A(o,s.assetOutDecimals),a=i?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,c=i?s.tradeFeePct:Rt(a,l).toNumber(),u=a.minus(l),p=this.getRouteFeeRange(t),h=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(n),g=be(a,h);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:n,tradeFee:u,tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:I(r.amountIn,r.assetInDecimals),amountOut:I(s.amountOut,s.assetOutDecimals),spotPrice:I(n,s.assetOutDecimals),tradeFee:I(u,s.assetOutDecimals),tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g.toNumber(),swaps:t.map(b=>b.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let o=t[i],n=r.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i>0?l=s[i-1]:l=e;let c=n.calculateOutGivenIn(a,l);s.push(c)}return s[s.length-1]}async calculateMostLiquidRoute(e,t,r){let{paths:s,pools:i,poolsMap:o}=r,c=i.filter(y=>y.tokens.some(S=>S.id===e)).map(y=>y.type==="Aave"?y.tokens:y.tokens.filter(S=>S.id===e)).map(y=>y.map(S=>m(S.balance).shiftedBy(-1*S.decimals)).reduce((S,f)=>S.plus(f))).sort((y,S)=>S.isLessThan(y)?-1:1)[0].div(100).multipliedBy(.1),u=s.map(async y=>await this.toSellSwaps(c,y,o)),p=await Promise.all(u),g=this.findBestSellRoute(p).map(y=>({poolAddress:y.poolAddress,poolId:y?.poolId,pool:y.pool,assetIn:y.assetIn,assetOut:y.assetOut})),b=this.buildRouteKey(e,t,i);return this.mlr.set(b,g),g}async toSellSwaps(e,t,r){let s=[],i=[];for(let a=0;a<t.length;a++){let l=t[a],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let u=c.parsePair(l.assetIn,l.assetOut);s[a]=c,i[a]=u}let o=await Promise.all(i.map((a,l)=>this.poolService.getPoolFees(a,s[l]))),n=[];for(let a=0;a<t.length;a++){let l=t[a],c=s[a],u=o[a],p=i[a],h;a>0?h=n[a-1].amountOut:h=A(m(e),p.decimalsIn).decimalPlaces(0,1);let{amountOut:g,calculatedOut:b,feePct:y,errors:S}=c.validateAndSell(p,h,u),f=this.getPoolFeeRange(u),B=c.spotPriceOutGivenIn(p),O=h.shiftedBy(-1*p.decimalsIn).multipliedBy(B),T=be(b,O),w=c.type==="Aave";n.push({...l,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:h,amountOut:g,calculatedOut:b,spotPrice:B,tradeFeePct:y,tradeFeeRange:f,priceImpactPct:T.toNumber(),errors:S,isSupply:()=>w&&c.tokens[0].id===l.assetIn,isWithdraw:()=>w&&c.tokens[1].id===l.assetIn,toHuman(){return{...l,amountIn:I(h,p.decimalsIn),amountOut:I(g,p.decimalsOut),calculatedOut:I(b,p.decimalsOut),spotPrice:I(B,p.decimalsOut),tradeFeePct:y,priceImpactPct:T.toNumber(),errors:S}}})}return n}async getMostLiquidRoute(e,t){return this.withCtx(e,t,async r=>{let s=this.buildRouteKey(e,t,r.pools),i=this.mlr.get(s);return i||this.calculateMostLiquidRoute(e,t,r)})}async getBestSpotPrice(e,t){return this.withCtx(e,t,async r=>{let{pools:s,poolsMap:i}=r,o=this.buildRouteKey(e,t,s),n=this.mlr.get(o);n||(n=await this.calculateMostLiquidRoute(e,t,r));let a=await this.toSellSwaps("1",n,i),l=a.map(p=>p.spotPrice.shiftedBy(-1*p.assetOutDecimals)).reduce((p,h)=>p.multipliedBy(h)),c=a[a.length-1].assetOutDecimals;return{amount:A(l,c),decimals:c}}).catch(()=>{})}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,o=s[0].amountIn;return i.isGreaterThan(o)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){return this.withCtx(e,t,async({paths:i,poolsMap:o})=>{let n;if(s)n=await this.toBuySwaps(r,s,o);else{let a=i.map(c=>this.toBuySwaps(r,c,o)),l=await Promise.all(a);n=this.findBestBuyRoute(l)}return this.buildBuy(o,n)})}async getBuyTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let o=s.map(a=>this.toBuySwaps(r,a,i));return(await Promise.all(o)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildBuy(i,a)).sort((a,l)=>a.amountIn.isGreaterThan(l.amountIn)?1:-1)})}buildBuy(e,t){let r=t[t.length-1],s=t[0],i=this.isDirectTrade(t),o=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetInDecimals)).reduce((b,y)=>b.multipliedBy(y)),n=A(o,s.assetInDecimals),a=i?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,c=i?s.tradeFeePct:Nt(a,l).toNumber(),u=l.minus(a),p=this.getRouteFeeRange(t),h=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(n),g;return a.isZero()?g=-100:g=be(h,a).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:n,tradeFee:u,tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g,swaps:t,toHuman(){return{type:"Buy",amountOut:I(r.amountOut,r.assetOutDecimals),amountIn:I(s.amountIn,s.assetInDecimals),spotPrice:I(n,s.assetInDecimals),tradeFee:I(u,s.assetInDecimals),tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g,swaps:t.map(b=>b.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let o=t[i],n=r.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i==t.length-1?l=e:l=s[0];let c=n.calculateInGivenOut(a,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[],i=[];for(let a=0;a<t.length;a++){let l=t[a],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let u=c.parsePair(l.assetIn,l.assetOut);s[a]=c,i[a]=u}let o=await Promise.all(i.map((a,l)=>this.poolService.getPoolFees(a,s[l]))),n=[];for(let a=t.length-1;a>=0;a--){let l=t[a],c=s[a],u=o[a],p=i[a],h;a==t.length-1?h=A(m(e),p.decimalsOut).decimalPlaces(0,1):h=n[0].amountIn;let{amountIn:g,calculatedIn:b,feePct:y,errors:S}=c.validateAndBuy(p,h,u),f=this.getPoolFeeRange(u),B=c.spotPriceInGivenOut(p),O=h.shiftedBy(-1*p.decimalsOut).multipliedBy(B),T;b.isZero()?T=-100:T=be(O,b).toNumber(),n.unshift({...l,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:g,amountOut:h,calculatedIn:b,spotPrice:B,tradeFeePct:y,tradeFeeRange:f,priceImpactPct:T,errors:S,isSupply(){return c.type==="Aave"&&c.tokens[0].id===l.assetIn},isWithdraw(){return c.type==="Aave"&&c.tokens[1].id===l.assetIn},toHuman(){return{...l,amountIn:I(g,p.decimalsIn),amountOut:I(h,p.decimalsOut),calculatedIn:I(b,p.decimalsIn),spotPrice:I(B,p.decimalsIn),tradeFeePct:y,tradeFeeRange:f,priceImpactPct:T,errors:S}}})}return n}};var Ct=6e3,kt=m(1e15),Pe=6,lt=-5,ct=360*60*1e3,nm=3,_t=6;var q=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var fe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Ct,minBudgetInNative:t.minBudgetInNative??kt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[o,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:c}=n,u=l[0],p=l[l.length-1],{assetInDecimals:h}=u,{assetOutDecimals:g}=p,b=Math.abs(c),y=this.getMinimumTradeCount(a,o),S=this.getOptimalTradeCount(b),f=i?Math.round(s/i):S,B=Math.ceil(s/y),O=Math.round(s/S),T=Math.round(s/f),w=a.dividedBy(f).decimalPlaces(0,1),C=await this.router.getBestSell(e,t,I(w,h)),M=a.isLessThan(o),Be=[];M&&Be.push("OrderTooSmall");let xe=C.amountOut.multipliedBy(f),$e=this.toBlockPeriod(T),Qe=C.tradeFee.multipliedBy(f),je=q.build(l),ve={assetIn:e,assetOut:t,errors:Be,frequencyMin:B,frequencyOpt:O,frequency:T,tradeCount:f,tradeFee:Qe,tradeImpactPct:C.priceImpactPct,tradePeriod:$e,tradeRoute:je,type:"Dca"};return{...ve,amountIn:a,amountOut:xe,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...ve,amountIn:I(a,h),amountOut:I(xe,g),tradeAmountIn:I(C.amountIn,h),tradeAmountOut:I(C.amountOut,g)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);let r=await this.router.getBestSpotPrice(e,"0");if(r)return this.minOrderBudget.times(m(10).pow(12)).div(r.amount).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:n,priceImpactPct:a}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,h=Math.abs(a),g=this.getTwapTradeCount(h),b=o.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestSell(l.assetIn,c.assetOut,I(b,u)),S=g===1,f=o.isLessThan(s),B=y.priceImpactPct<lt,O=[];f||S?O.push("OrderTooSmall"):B&&O.push("OrderImpactTooBig");let T=y.amountOut.multipliedBy(g),w=y.tradeFee.multipliedBy(g),C=q.build(n),M={assetIn:e,assetOut:t,errors:O,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:Pe,tradeRoute:C,type:"TwapSell"};return{...M,amountIn:o,amountOut:T,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:w,toHuman(){return{...M,amountIn:I(o,u),amountOut:I(T,p),tradeAmountIn:I(y.amountIn,u),tradeAmountOut:I(y.amountOut,p),tradeFee:I(w,p)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:o,swaps:n,priceImpactPct:a}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,h=Math.abs(a),g=this.getTwapTradeCount(h),b=o.dividedBy(g).decimalPlaces(0,1),y=await this.router.getBestBuy(l.assetIn,c.assetOut,I(b,p)),S=y.amountIn.multipliedBy(g),f=g===1,B=S.isLessThan(s),O=y.priceImpactPct<lt,T=[];B||f?T.push("OrderTooSmall"):O&&T.push("OrderImpactTooBig");let w=y.tradeFee.multipliedBy(g),C=q.build(n),M={assetIn:e,assetOut:t,errors:T,tradeCount:g,tradeImpactPct:y.priceImpactPct,tradePeriod:Pe,tradeRoute:C,type:"TwapBuy"};return{...M,amountIn:S,amountOut:o,tradeAmountIn:y.amountIn,tradeAmountOut:y.amountOut,tradeFee:w,toHuman(){return{...M,amountIn:I(S,u),amountOut:I(o,p),tradeAmountIn:I(y.amountIn,u),tradeAmountOut:I(y.amountOut,p),tradeFee:I(w,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>ct){let s=ct/(this.blockTime*Pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,_t)}};var te=class extends _{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new G(e),this.aaveUtils=new $(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r=this.api.call.dryRunApi.dryRunCall,s=r.meta.params,i=[{System:{Signed:e}},t.inner.toHex()];s.length===3&&i.push(4);let o;try{o=await r(...i)}catch(n){throw console.error(n),new Error("Dry run execution failed!")}if(o.isOk)return o.asOk;throw console.log(o.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),J)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Ye=class extends te{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:o}=s,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,o)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],o=z(e,this.slippagePct),n=s.assetIn,a=i.assetOut,l=e.plus(o),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,n,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(n,a,t.toFixed(),l.toFixed(),q.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let p=this.dispatchWithExtraGas(c);return this.wrapTx("RouterBuy",p,J)}return this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],o=z(t,this.slippagePct),n=s.assetIn,a=i.assetOut,l=t.minus(o),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(n,a,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(n,a,e.toFixed(),l.toFixed(),q.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let p=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSell",p,J)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=z(e,this.slippagePct),o=r.assetIn,n=s.assetOut,a=e.minus(i),l=this.api.tx.router.sellAll(o,n,a.toFixed(),q.build(t));if(await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,J)}return this.wrapTx("RouterSellAll",l)}};var Ke=class extends te{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:o}=this.order,n=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:o}}},null);return this.wrapTx("DcaSchedule",n)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:o,tradeRoute:n}=this.order,a=z(i,this.slippagePct),l=i.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:n}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:o,tradeRoute:n}=this.order,a=z(s,this.slippagePct),l=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:n}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var Se=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new Ye(this.api,this.evm).setTrade(e)}order(e){return new Ke(this.api,this.evm).setOrder(e)}};var fs={router:{}};function sp(d,e=fs){let t=new ne(d),r=new Ce(d),s=new me(d,r),i=new $(r),o=new ee(s,e.router),n=new ee(s,{exclude:["Hsm"]}),a=new fe(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:o,scheduler:a},client:{asset:new Q(d),balance:new G(d),balanceV2:new ae(d)},ctx:{pool:s},evm:r,tx:new Se(d,r),destroy:()=>{s.destroy()}}}export{re as AaveClient,ke as AavePool,De as AavePoolClient,$ as AaveUtils,Q as AssetClient,ft as AssetNotFound,Ns as BASILISK_PARACHAIN_ID,G as BalanceClient,ae as BalanceClientV2,x as BigNumber,me as CachingPoolService,ne as ChainParams,Kt as DECIMAL_PLACES,Ct as DEFAULT_BLOCK_TIME,kt as DEFAULT_MIN_BUDGET,H as ERC20,Ce as EvmClient,Ee as EvmRpcAdapter,rt as FarmClient,X as H160,Te as HUB_ASSET_ID,Es as HYDRADX_PARACHAIN_ID,L as HYDRADX_SS58_PREFIX,qs as INFINITY,W as LbpMath,Me as LbpPool,Le as LbpPoolClient,oe as MmOracleClient,N as ONE,_t as ORDER_MIN_BLOCK_PERIOD,F as OmniMath,He as OmniPool,Ge as OmniPoolClient,mt as PERBILL_DENOMINATOR,K as PERMILL_DENOMINATOR,_ as PolkadotApiClient,Pt as PoolConfigNotFound,j as PoolError,pe as PoolFactory,Re as PoolNotFound,ue as PoolService,E as PoolType,xt as ProviderConfigNotFound,se as RUNTIME_DECIMALS,Ne as RouteNotFound,ye as Router,et as SYSTEM_ASSET_DECIMALS,R as SYSTEM_ASSET_ID,k as StableMath,Z as StableSwap,We as StableSwapClient,St as StorageConfigNotFound,Bt as SubscriptionNotSupported,ie as TRADEABLE_DEFAULT,Pe as TWAP_BLOCK_PERIOD,ct as TWAP_MAX_DURATION,lt as TWAP_MAX_PRICE_IMPACT,nm as TWAP_TX_MULTIPLIER,Et as TradeOrderError,ot as TradeOrderType,q as TradeRouteBuilder,ee as TradeRouter,fe as TradeScheduler,nt as TradeType,Se as TxBuilderFactory,Y as XykMath,Ue as XykPool,qe as XykPoolClient,v as ZERO,Na as bnFormatter,m as bnum,Nt as calculateBuyFee,Mu as calculateDiffToAvg,be as calculateDiffToRef,Rt as calculateSellFee,vt as createChain,sp as createSdkContext,_e as findNestedKey,Ra as findNestedObj,z as getFraction,Kc as hashPools,Xt as isEvmAccount,Vt as isEvmAddress,Yt as isSs58Address,A as scale,Ws as toBn,I as toDecimals};
|
|
1
|
+
var we=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var Je=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var ut="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Ze="0x112b087b60C1a166130d59266363C45F8aa99db0",et="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",J=1000000n;var Os=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var re=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getBlockTimestamp(){let e=await this.rpcAdapter.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.rpcAdapter.readContract({abi:Je,address:Ze,functionName:"getReservesData",args:[et]})}async getUserReservesData(e){return await this.rpcAdapter.readContract({abi:Je,address:Ze,functionName:"getUserReservesData",args:[et,e]})}async getUserAccountData(e){return await this.rpcAdapter.readContract({abi:we,address:ut,functionName:"getUserAccountData",args:[e]})}};import{decodeAddress as Oe,encodeAddress as pt}from"@polkadot/util-crypto";import{hexToU8a as Ut,isHex as qt,u8aToHex as Wt}from"@polkadot/util";import{Buffer as X}from"buffer";var Ns=2090,K=1e6,mt=1e9,Te="1",Es=2034,L=63,se=18,R="0",tt=12,ie=15;var rt="ETH\0";function Vt(d){if(!d)return!1;try{let e=Oe(d,!0),t=X.from(rt);return X.from(e.subarray(0,t.length)).equals(t)}catch{return!1}}function Xt(d){return!!/^0x[a-fA-F0-9]{40}$/.test(d)}function Yt(d){try{let e=qt(d)?Ut(d):Oe(d);return pt(e),!0}catch{return!1}}var V=class d{static toAccount=e=>{let t=X.from(e.slice(2),"hex"),r=X.from(rt);return pt(new Uint8Array(X.concat([r,t,X.alloc(8)])),63)};static fromAccount=e=>{let t=Oe(e),r=X.from(rt),s=t.slice(r.length,-8);return"0x"+X.from(s).toString("hex")};static fromSS58=e=>{let r=Oe(e).slice(0,20);return Wt(r)};static fromAny=e=>{if(Xt(e))return e;if(Vt(e))return d.fromAccount(e);if(Yt(e))return d.fromSS58(e);throw new Error("Unknown address type")}};import{Buffer as Ie}from"buffer";var H=class{static fromAssetId(e){let t=Number(e),r=Ie.alloc(20,0);return r[15]=1,r.writeUInt32BE(t,16),"0x"+r.toString("hex")}static toAssetId(e){let t=Ie.from(e.replace("0x",""),"hex");return t.length!==20||!this.isAssetAddress(e)?null:t.readUInt32BE(16)}static isAssetAddress(e){let t=Ie.from("0000000000000000000000000000000100000000","hex"),r=Ie.from(e.replace("0x",""),"hex");return r.length!==20?!1:r.subarray(0,16).equals(t.subarray(0,16))}};import{BigNumber as v}from"bignumber.js";var Kt=12;v.config({EXPONENTIAL_AT:[-100,100],ROUNDING_MODE:4,DECIMAL_PLACES:Kt});var x=m(0),N=m(1),qs=m("Infinity");function A(d,e){let t=new v(e.toString()),r=new v(10).pow(t);return d.times(r).decimalPlaces(4)}function m(d){return new v(d.toString())}function Ws(d,e){let t=m(d);return A(t,e)}function I(d,e){return d.shiftedBy(-1*e).toString()}var Ae=m("1e27"),$t=m("1.01"),Qt=m("31536000"),dt=4,Fe=-1,$=class{client;constructor(e){this.client=new re(e)}async getSummary(e){let t=V.fromAny(e),[r,s,i,o]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[n]=r,[a,l]=s,[c,u,p,y,g,b]=i,h=m(b).dividedBy(1e18).decimalPlaces(6,v.ROUND_DOWN),S=m(c),f=m(u),B=[];for(let T of a){let O=T.underlyingAsset.toLowerCase(),w=n.find(({underlyingAsset:Gt})=>Gt.toLowerCase()===O);if(!w)throw new Error("Missing pool reserve for "+O);let C=m(T.scaledATokenBalance),M=m(w.liquidityIndex),Be=m(w.liquidityRate),xe=m(w.availableLiquidity),Qe=m(w.priceInMarketReferenceCurrency),je=o+6,ze=this.calculateLinearInterest(Be,w.lastUpdateTimestamp,je),ve=M.multipliedBy(ze).dividedBy(Ae).decimalPlaces(0,v.ROUND_DOWN),Dt=C.multipliedBy(ve).dividedBy(Ae).decimalPlaces(0,v.ROUND_DOWN),Mt=m(l!==0&&l===w.eModeCategoryId?w.eModeLiquidationThreshold:w.reserveLiquidationThreshold).div(1e4),Lt=w.usageAsCollateralEnabled&&T.usageAsCollateralEnabledOnUser&&m(T.scaledATokenBalance).gt(0),Ht=H.toAssetId(O);B.push({aTokenBalance:Dt,availableLiquidity:xe,decimals:Number(w.decimals),isCollateral:Lt,priceInRef:Qe,reserveId:Ht,reserveAsset:O,reserveLiquidationThreshold:Mt})}return{healthFactor:h.toNumber(),currentLiquidationThreshold:m(y).dividedBy(10**dt).toNumber(),totalCollateral:S,totalDebt:f,reserves:B}}async hasBorrowPositions(e){let t=V.fromAny(e),r=await this.client.getUserAccountData(t),[s,i]=r;return i>0n}async getHealthFactor(e){let t=V.fromAny(e),r=await this.client.getUserAccountData(t),[s,i,o,n,a,l]=r;return this.calculateHealthFactorFromBalances(m(i),m(s),m(n))}async getHealthFactorAfterWithdraw(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:o,currentLiquidationThreshold:n}=await this.getSummary(e);if(i.lte(0))return Fe;let a=H.fromAssetId(t),l=o.find(B=>B.reserveAsset===a);if(!l)throw new Error("Missing reserve ctx for "+a);let{decimals:c,isCollateral:u,priceInRef:p,reserveLiquidationThreshold:y}=l,g=A(m(r),c).decimalPlaces(0,v.ROUND_DOWN),b=u?g.multipliedBy(p).dividedBy(m(10).pow(c)).decimalPlaces(0,v.ROUND_DOWN):x,h=s.minus(b);if(h.lte(0))return 0;let S=s.multipliedBy(m(n)).minus(b.multipliedBy(y)).dividedBy(h);return h.multipliedBy(S).dividedBy(i).decimalPlaces(6,v.ROUND_DOWN).toNumber()}async getHealthFactorAfterSupply(e,t,r){let{totalCollateral:s,totalDebt:i,reserves:o,currentLiquidationThreshold:n}=await this.getSummary(e);if(i.lte(0))return Fe;let a=H.fromAssetId(t),l=o.find(f=>f.reserveAsset===a);if(!l)throw new Error("Missing reserve ctx for "+a);let{decimals:c,priceInRef:u,reserveLiquidationThreshold:p}=l,g=A(m(r),c).decimalPlaces(0,v.ROUND_DOWN).multipliedBy(u).dividedBy(m(10).pow(c)).decimalPlaces(0,v.ROUND_DOWN),b=s.plus(g);if(b.lte(0))return 0;let h=s.multipliedBy(m(n)).plus(g.multipliedBy(p)).dividedBy(b);return b.multipliedBy(h).dividedBy(i).decimalPlaces(6,v.ROUND_DOWN).toNumber()}async getHealthFactorAfterSwap(e,t,r,s,i){let{totalDebt:o,reserves:n,healthFactor:a}=await this.getSummary(e);if(o.lte(0))return Fe;let l=H.fromAssetId(r),c=H.fromAssetId(i),u=n.find(w=>w.reserveAsset===l),p=n.find(w=>w.reserveAsset===c);if(!u)throw new Error(`Missing reserve ctx for ${l}`);if(!p)throw new Error(`Missing reserve ctx for ${c}`);let y=A(m(t),u.decimals).decimalPlaces(0,v.ROUND_DOWN),g=A(m(s),p.decimals).decimalPlaces(0,v.ROUND_DOWN),b=y.multipliedBy(u.priceInRef).dividedBy(m(10).pow(u.decimals)).decimalPlaces(0,v.ROUND_DOWN),h=g.multipliedBy(p.priceInRef).dividedBy(m(10).pow(p.decimals)).decimalPlaces(0,v.ROUND_DOWN),S=u.isCollateral?b.multipliedBy(u.reserveLiquidationThreshold):x,T=h.multipliedBy(p.reserveLiquidationThreshold).minus(S).dividedBy(o);return m(a).plus(T).decimalPlaces(6,v.ROUND_DOWN).toNumber()}async getMaxWithdraw(e,t){let{totalDebt:r,reserves:s,healthFactor:i}=await this.getSummary(e),o=H.fromAssetId(t),n=s.find(a=>a.reserveAsset===o);if(!n)throw new Error("Missing reserve data for "+o);return this.calculateWithdrawMax(n,r,i)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:r,healthFactor:s}=await this.getSummary(e),i={};for(let o of r){let n=this.calculateWithdrawMax(o,t,s);o.reserveId&&(i[o.reserveId]=n)}return i}calculateWithdrawMax(e,t,r){let{aTokenBalance:s,availableLiquidity:i,decimals:o,priceInRef:n,reserveLiquidationThreshold:a,isCollateral:l}=e,c=s;if(l&&t.gt(0)){let p=m(r).minus($t);if(p.gt(0)){let g=p.multipliedBy(t).dividedBy(a).decimalPlaces(0,v.ROUND_DOWN).dividedBy(n).multipliedBy(m(10).pow(o)).decimalPlaces(0,v.ROUND_DOWN);c=v.minimum(s,g)}else c=x}return{amount:v.minimum(c,i),decimals:o}}calculateLinearInterest(e,t,r){let s=r-t;return s<=0?Ae:e.multipliedBy(s).dividedBy(Qt).plus(Ae).decimalPlaces(0,v.ROUND_DOWN)}calculateHealthFactorFromBalances(e,t,r){return e.lte(0)?Fe:t.multipliedBy(r).dividedBy(e).dividedBy(m(10).pow(dt)).decimalPlaces(6,v.ROUND_DOWN).toNumber()}};function gt(d){switch(d){case!0:case"true":case 1:case"1":case"on":case"yes":return!0;default:return!1}}import"@galacticcouncil/api-augment/hydradx";import"@galacticcouncil/api-augment/basilisk";var _=class{api;constructor(e){this.api=e}get chainDecimals(){return this.api.registry.chainDecimals[0]}get chainToken(){return this.api.registry.chainTokens[0]}log(e,...t){let r=typeof window>"u"?process.env.GC_DEBUG:window.localStorage.getItem("gc.debug");gt(r)&&console.log(e,...t)}};var Q=class extends _{SUPPORTED_TYPES=["StableSwap","Bond","Token","External","Erc20"];constructor(e){super(e)}async safeSharesQuery(){try{let e=await this.api.query.stableswap.pools.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async safeBondsQuery(){try{let e=await this.api.query.bonds.bonds.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}async metadataQuery(){try{let e=await this.api.query.assetRegistry.assetMetadataMap.entries();return new Map(e.map(([{args:[t]},r])=>{let{decimals:s,symbol:i}=r.unwrap();return[t.toString(),{decimals:s.toNumber(),symbol:i.toHuman()}]}))}catch{return new Map([])}}async locationsQuery(){try{let e=await this.api.query.assetRegistry.assetLocations.entries();return new Map(e.map(([{args:[t]},r])=>[t.toString(),r.unwrap()]))}catch{return new Map([])}}getSystemTokenName(e){switch(e){case"HDX":return"Hydration";case"BSX":return"Basilisk";default:return e}}getToken(e,t,r,s){if(e=="0"){let u=this.api.consts.balances.existentialDeposit;return{id:"0",name:this.getSystemTokenName(this.chainToken),symbol:this.chainToken,decimals:this.chainDecimals,icon:this.chainToken,type:"Token",isSufficient:!0,existentialDeposit:u.toString()}}let{name:i,assetType:o,isSufficient:n,existentialDeposit:a}=t,{symbol:l,decimals:c}=r.get(e)??{};return{id:e,name:i.toHuman(),symbol:l,decimals:c,icon:l,type:o.toHuman(),isSufficient:n?n.toHuman():!0,location:s?.toJSON(),existentialDeposit:a.toString()}}getBond(e,t,r,s){let[i,o]=s,{assetType:n,isSufficient:a,existentialDeposit:l}=t,{symbol:c,decimals:u}=this.getToken(i.toString(),t,r),p=o.toNumber(),y=new Intl.DateTimeFormat("en-GB"),g=[c,"Bond",y.format(p)].join(" ");return{id:e,name:g,symbol:c+"b",decimals:u,icon:c,type:n.toString(),isSufficient:a.toHuman(),existentialDeposit:l.toString(),underlyingAssetId:i.toString(),maturity:p}}getShares(e,t,r,s){let{assets:i}=s,{name:o,symbol:n,assetType:a,isSufficient:l,existentialDeposit:c}=t,p=i.map(b=>b.toString()).map(b=>{let{symbol:h}=this.getToken(b,t,r);return[b,h]}),y=Object.fromEntries(p),g=Object.values(y);return{id:e,name:g.join(", "),symbol:n?.isSome?n.toHuman():o.toHuman(),decimals:18,icon:g.join("/"),type:a.toString(),isSufficient:l.toHuman(),existentialDeposit:c.toString(),meta:y}}getExternal(e,t,r,s){let i=this.getToken(e,t,new Map,s),o=r?.find(n=>n.internalId===i.id);return o?{...i,decimals:o.decimals,name:o.name,symbol:o.symbol,icon:o.symbol,isWhiteListed:o.isWhiteListed}:i}normalizeMetadata(e,t){return t.size?t:new Map(e.map(([{args:[r]},s])=>{let{decimals:i,symbol:o}=s.unwrap();return[r.toString(),{decimals:Number(i.toString()),symbol:o.toHuman()}]}))}getSupportedAssets(e){return e.filter(([t,r])=>{if(r.isNone)return!1;let s=r.unwrap();return this.isSupportedAsset(s)})}async getOnChainAssets(e,t){let[r,s,i,o,n]=await Promise.all([this.api.query.assetRegistry.assets.entries(),this.locationsQuery(),this.safeSharesQuery(),this.safeBondsQuery(),this.metadataQuery()]),a=this.getSupportedAssets(r),l=this.normalizeMetadata(a,n),c=a.map(([{args:[u]},p])=>{let y=p.unwrap(),g=s.get(u.toString()),{assetType:b}=y;switch(b.toString()){case"Bond":let h=o.get(u.toString());return this.getBond(u.toString(),y,l,h);case"StableSwap":let S=i.get(u.toString());return this.getShares(u.toString(),y,l,S);case"External":return this.getExternal(u.toString(),y,t,g);default:return this.getToken(u.toString(),y,l,g)}});return e?c:c.filter(u=>this.isValidAsset(u))}isValidAsset(e){let t=Math.sign(e.decimals);return!!e.symbol&&(t===0||t===1)}isSupportedAsset(e){let t=e.assetType.toString();return this.SUPPORTED_TYPES.includes(t)}};var G=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateFreeBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateFreeBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateFreeBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateFreeBalance(r)))}async subscribeSystemBalances(e,t){return this.api.query.system.account.multi(e,r=>{let s=[];r.forEach((i,o)=>{let n=this.calculateFreeBalance(i.data),a=e[o];s.push([a,n])}),t(s)})}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(o=>[e,o]):s.map(({args:[o,n]})=>[o.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,o=>{let n=[];o.forEach((a,l)=>{let c=this.calculateFreeBalance(a),u=i[l][1];n.push([u,c])}),t(n)})}async subscribeTokenBalances(e,t){return this.api.query.tokens.accounts.multi(e,r=>{let s=[];r.forEach((i,o)=>{let n=this.calculateFreeBalance(i),a=e[o];s.push([a,n])}),t(s)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),o=async()=>{let n=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async subscribeErc20Balances(e,t){let r=async()=>{let s=await Promise.all(e.map(async i=>{let[o,n]=i;return[i,await this.getErc20Balance(o,n)]}));t(s)};return this.api.rpc.chain.subscribeNewHeads(async()=>{r()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateFreeBalance(e){let t=e.free.toString(),r=e.frozen.toString();return v(t).lt(r)?v(0):v(t).minus(r)}};var ae=class extends _{constructor(e){super(e)}async getBalance(e,t){let r=await this.api.query.assetRegistry.assets(t),{assetType:s}=r.unwrap();return s.toString()==="Erc20"?this.getErc20Balance(e,t):t==="0"?this.getSystemBalance(e):this.getTokenBalance(e,t)}async getSystemBalance(e){let{data:t}=await this.api.query.system.account(e);return this.calculateBalance(t)}async getTokenBalance(e,t){let r=await this.api.query.tokens.accounts(e,t);return this.calculateBalance(r)}async getErc20Balance(e,t){let r=await this.getTokenBalanceData(e,t);return this.calculateBalance(r)}async subscribeSystemBalance(e,t){return this.api.query.system.account(e,({data:r})=>t("0",this.calculateBalance(r)))}async subscribeTokenBalance(e,t,r){let s=await this.api.query.tokens.accounts.keys(e),i=r?r.map(o=>[e,o]):s.map(({args:[o,n]})=>[o.toString(),n.toString()]);return this.api.query.tokens.accounts.multi(i,o=>{let n=[];o.forEach((a,l)=>{let c=i[l][1],u=this.calculateBalance(a);n.push([c,u])}),t(n)})}async subscribeErc20Balance(e,t,r){let i=r||await(async()=>(await this.api.query.assetRegistry.assets.entries()).filter(([a,l])=>{let{assetType:c}=l.unwrap();return c.toString()==="Erc20"}).map(([{args:[a]}])=>a.toString()))(),o=async()=>{let n=await Promise.all(i.map(async a=>[a,await this.getErc20Balance(e,a)]));t(n)};return this.api.rpc.chain.subscribeNewHeads(async()=>{o()})}async getTokenBalanceData(e,t){return this.api.call.currenciesApi.account(t,e)}calculateBalance(e){let t=v(e.free.toString()),r=e.frozen.toString(),s=e.reserved.toString(),i=t.gte(r)?t.minus(r).toString():"0",o=t.plus(s).toString();return{free:t.toString(),total:o,transferable:i,reserved:s,frozen:r}}};var ne=class{api;_minOrderBudget;_blockTime;constructor(e){this.api=e}get blockTime(){return this._blockTime===void 0&&(this._blockTime=this.api.consts.aura.slotDuration.toNumber()),this._blockTime}get minOrderBudget(){return this._minOrderBudget===void 0&&(this._minOrderBudget=this.api.consts.dca.minBudgetInNativeCurrency.toString()),m(this._minOrderBudget)}};import{fixed_from_rational as ht}from"@galacticcouncil/math-liquidity-mining";import{GenericAccountId32 as jt}from"@polkadot/types";import{u8aConcat as yt}from"@polkadot/util";import{isAddress as bt}from"@polkadot/util-crypto";var st=class extends _{balanceClient;constructor(e){super(e),this.balanceClient=new G(e)}secondsInYear=new v(365.2425).times(24).times(60).times(60);async getOmnipoolFarms(e){let t=await this.api.query.omnipoolWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,o]=s.args,n=i.unwrap().toString(),a=o.toString(),l=(await this.api.query.omnipoolWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.omnipoolWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),y=this.getAccountResolver(this.api.registry)(Number(a),!1).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(y,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getIsolatedPoolFarms(e){let t=await this.api.query.xykWarehouseLM.activeYieldFarm.entries(e);return await Promise.all(t.map(async([s,i])=>{let[,o]=s.args,n=i.unwrap().toString(),a=o.toString(),l=(await this.api.query.xykWarehouseLM.globalFarm(a)).unwrap(),c=(await this.api.query.xykWarehouseLM.yieldFarm(e,a,n)).unwrap(),u=await this.getOraclePrice(l)??l.priceAdjustment.toString(),y=this.getAccountResolver(this.api.registry)(Number(a),!0).toString(),g=l.rewardCurrency.toString(),b=await this.balanceClient.getTokenBalanceData(y,g);return{assetId:e,globalFarm:l,yieldFarm:c,priceAdjustment:u,potBalance:b.free.toString()}}))}async getOraclePrice(e){let t=e.rewardCurrency.toString(),r=e.incentivizedAsset.toString(),s=[t,r].sort();if(t===r)return new v(1).shiftedBy(18).toString();let i=await this.api.query.emaOracle.oracles("omnipool",s,"TenMinutes");if(i.isNone)return;let[o]=i.unwrap(),n=o.price.n.toString(),a=o.price.d.toString(),l;return Number(t)<Number(r)?l=ht(n,a):l=ht(a,n),l}getGlobalRewardPerPeriod(e,t,r,s){let o=e.times(t).shiftedBy(-18).times(s).shiftedBy(-18);return o.gte(r)?r:o}getPoolYieldPerPeriod(e,t,r,s){return e.times(t).div(r.times(s).shiftedBy(-18))}padEndU8a(e,t){return yt(e,Array(Math.max(0,t-e.length)).fill(0))}getAccountResolver=e=>(t,r)=>{let s="modl",i=r?"0x78796b4c4d704944":"0x4f6d6e6957684c4d";return new jt(e,this.padEndU8a(yt(s,i,typeof t!="number"?t.toU8a():[t]),32))};async getFarmApr(e,t){if(t==="isolatedpool"&&!bt(e))throw new Error("You must pass an address of isolated pool as id");if(t==="omnipool"&&bt(e))throw new Error("You must pass an asset id of omnipool");let r=6,s=t==="omnipool"?await this.getOmnipoolFarms(e):await this.getIsolatedPoolFarms(e);return s.length?s.map(({yieldFarm:n,globalFarm:a,priceAdjustment:l,potBalance:c})=>{let u=new v(a.totalSharesZ.toString()),p=a.plannedYieldingPeriods.toString(),y=new v(a.yieldPerPeriod.toString()),g=new v(a.maxRewardPerPeriod.toString()),b=a.blocksPerPeriod.toString(),h=new v(n.multiplier.toString()).shiftedBy(-18),S=this.secondsInYear.div(new v(r).times(b)),f;if(u.isZero())f=y.times(h).times(S);else{let C=this.getGlobalRewardPerPeriod(u,y,g,l);f=this.getPoolYieldPerPeriod(C,h,u,l).times(S)}let B=new v(a.pendingRewards.toString()).plus(a.accumulatedPaidRewards.toString()),T=g.times(p),O=c?B.plus(c):T;return B.div(O).gte(.999)?x:f.div(t==="isolatedpool"?2:1).times(100)}).reduce((n,a)=>n.plus(a),x).toString():void 0}};var Re=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}},Pt=class extends Error{constructor(e,t){super(),this.message=`${e} pool missing ${t}`,this.name="PoolConfigNotFound"}},Ne=class extends Error{constructor(e,t){super(),this.message=`Route from ${e} to ${t} not found in pool configuration`,this.name="RouteNotFound"}},ft=class extends Error{constructor(e){super(),this.message=`Asset ${e} not available in current network`,this.name="AssetNotFound"}},St=class extends Error{constructor(e){super(),this.message=`Storage missing ${e}`,this.name="StorageConfigNotFound"}},Bt=class extends Error{constructor(e){super(),this.message=`Subscription type "${e}" not supported`,this.name="SubscriptionNotSupported"}},xt=class extends Error{constructor(e){super(),this.message=`${e}`,this.name="ProviderConfigNotFound"}};import{encodeFunctionData as zt,decodeFunctionResult as Jt}from"viem";var Zt=1e7,Ee=class{api;constructor(e){this.api=e}async getBlock(){let e=await this.api.query.ethereum.currentBlock(),{header:t}=e.unwrap(),r=t.timestamp.toBigInt()/1000n,s=t.number.toBigInt();return{timestamp:r,number:s}}readContract=(async e=>{let{abi:t,address:r,functionName:s,args:i}=e,o=zt({abi:t,functionName:s,args:i}),n=this.api.call.ethereumRuntimeRPCApi.call,l=await n(...["",r,o,0,Zt,null,null,null,!1,[],[]]);if(l.isErr)throw console.error(s,l.asErr.toHuman()),new Error("Contract read failure");let{value:c,exitReason:u,usedGas:p}=l.asOk;if(u.isSucceed)return Jt({abi:t,functionName:s,data:c.toHex()});throw console.log(s,u.toString(),p.toHuman()),new Error("Contract read error")})};import{defineChain as er}from"viem";var tr=["wss://hydration-rpc.n.dwellir.com","wss://hydration.dotters.network","wss://rpc.helikon.io/hydradx","wss://hydration.ibp.network","wss://rpc.cay.hydration.cloud","wss://rpc.parm.hydration.cloud","wss://rpc.roach.hydration.cloud","wss://rpc.zipp.hydration.cloud","wss://rpc.sin.hydration.cloud","wss://rpc.coke.hydration.cloud"],vt=d=>{let t=[d.endpoint,...tr],r=Array.from(new Set(t.map(s=>s.replace("wss://","https://").replace("ws://","http://"))));return er({id:222222,name:"Hydration",network:"hydration",nativeCurrency:{decimals:18,name:"WETH",symbol:"WETH"},rpcUrls:{default:{http:r}},blockExplorers:{default:{name:"Hydration Explorer",url:"https://hydration.subscan.io"}},testnet:!1})};import{createPublicClient as Tt,createWalletClient as rr,custom as sr,http as ir}from"viem";function wt(d){let e=async({method:t,params:r})=>{let s=Array.isArray(r)?r:[];return d.send(t,s)};return()=>({request:e,config:{name:"PolkadotWsTransport",type:"webSocket",key:"polkadotWs",request:e}})}var Ce=class{api;chain;constructor(e){this.api=e,this.chain=vt(this.provider)}get provider(){let{provider:e}=this.api._options;return e}get chainId(){return this.chain.id}get chainCurrency(){return this.chain.nativeCurrency.symbol}get chainDecimals(){return this.chain.nativeCurrency.decimals}getProvider(){return Tt({chain:this.chain,transport:ir()})}getWsProvider(){return Tt({chain:this.chain,transport:wt(this.provider)})}getSigner(e){return rr({account:e,chain:this.chain,transport:sr(window.ethereum)})}getRPCAdapter(){return new Ee(this.api)}};var it=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}];var oe=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getData(e,t=6){let[r,s,i]=await Promise.all([this.rpcAdapter.readContract({abi:it,address:e,functionName:"latestRoundData"}),this.rpcAdapter.readContract({abi:it,address:e,functionName:"decimals"}),this.rpcAdapter.getBlock()]),[o,n,a,l]=r,c=i.number-(i.timestamp-l)/BigInt(t),u=Number(c);return{price:n,decimals:s,updatedAt:u<0?0:u}}};import{memoize1 as gs}from"@thi.ng/memoize";var E=(o=>(o.Aave="Aave",o.LBP="Lbp",o.Omni="Omnipool",o.Stable="Stableswap",o.XYK="Xyk",o.HSM="Hsm",o))(E||{}),j=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(j||{});var ke=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new d(e)}constructor(e){this.type="Aave",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,assetInED:x,assetOutED:x}}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=[];return t.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=[];return r.isGreaterThan(e.balanceOut)&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return A(N,e.decimalsOut)}spotPriceOutGivenIn(e){return A(N,e.decimalsIn)}calculateTradeFee(e,t){return x}};import{encodeAddress as or}from"@polkadot/util-crypto";import{stringToU8a as lr}from"@polkadot/util";import{decodeEventLog as cr}from"viem";import{memoize1 as ar}from"@thi.ng/memoize";import{TLRUCache as nr}from"@thi.ng/cache";var D=class extends G{evm;mmOracle;pools=[];subs=[];assets=new Map([]);mem=0;onNewBlockHandler;onEventsHandler;memPoolsCache=new nr(null,{maxlen:1,ttl:3600*1e3,release:e=>{this.mem>e&&this.log(this.getPoolType(),`mem ${e} released at`,new Date)}});memPools=ar(e=>(this.log(this.getPoolType(),`mem ${e} sync`),this.getPools()),this.memPoolsCache);constructor(e,t){super(e),this.evm=t,this.mmOracle=new oe(t),this.onNewBlockHandler=this.onNewBlock.bind(this),this.onEventsHandler=this.onEvents.bind(this)}onNewBlock(e){}onEvents(e){}get augmentedPools(){return this.pools.filter(e=>this.isValidPool(e)).map(e=>this.withMetadata(e))}async withAssets(e){this.assets=new Map(e.map(t=>[t.id,t])),this.mem=this.mem+1}async getPoolsMem(){return this.memPools(this.mem)}async getPools(){this.unsubscribe(),this.pools=await this.loadPools();let e=this.subscribeBalances(),t=this.subscribeUpdates();this.subs.push(e),this.subs.push(t);let r=this.getPoolType();return this.log(r,`mem ${this.mem} pools(${this.augmentedPools.length})`),this.log(r,`mem ${this.mem} subs(${this.subs.length})`),this.augmentedPools}async subscribeBalances(){let e=[],t=[],r=[],s=[];for(let n of this.augmentedPools){let{address:a,tokens:l}=n;l.filter(c=>c.id==="0").forEach(()=>{e.push(a)}),l.filter(c=>["Token","StableSwap"].includes(c.type)&&c.id!=="0"&&c.id!==n.id).forEach(c=>{t.push([a,c.id])}),l.filter(c=>c.type==="Erc20").forEach(c=>{r.push([a,c.id])})}let i=n=>{n.forEach(([a,l])=>{let c=this.pools.find(u=>u.address===a);if(c){let u=c.tokens.findIndex(p=>p.id==="0");c.tokens[u].balance=l.toString()}})},o=n=>{n.forEach(([a,l])=>{let[c,u]=a,p=this.pools.find(y=>y.address===c);if(p){let y=p.tokens.findIndex(g=>g.id===u);p.tokens[y].balance=l.toString()}})};if(e.length>0){let n=await this.subscribeSystemBalances(e,i);s.push(n)}if(t.length>0){let n=await this.subscribeTokenBalances(t,o);s.push(n)}if(r.length>0){let n=await this.subscribeErc20Balances(r,o);s.push(n)}return()=>{for(let n of s)try{n()}catch(a){console.warn("Balance unsub failed",a)}}}unsubscribe(){this.subs.forEach(e=>{e.then(t=>t()).catch(t=>console.warn("Unsub failed",t))})}isValidPool(e){return e.type==="Xyk"?e.tokens.every(t=>this.assets.get(t.id)):!0}withMetadata(e){return e.tokens=e.tokens.map(t=>{let r=this.assets.get(t.id);return{...t,...r}}),e}};function _e(d,e){let t=[];return JSON.stringify(d,(r,s)=>(s&&s[e]&&t.push(s),s)),t[0]}function Ra(d,e,t){let r;return JSON.stringify(d,(s,i)=>(i&&i[e]===t&&(r=i),i)),r}var Na=(d,e)=>typeof e=="bigint"?e.toString():e;var ur=["Supply","Withdraw","Repay","Borrow"],De=class extends D{getPoolType(){return"Aave"}getPoolId(e,t){let r="aave:"+e+"/"+t;return or(lr(r.padEnd(32,"\0")),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:0}}getReserveH160Id(e){return e.type==="Erc20"?_e(e.location,"accountKey20").accountKey20.key:H.fromAssetId(e.id)}isSupported(){return this.api.call.aaveTradeExecutor.pools!==void 0}async loadPools(){return(await this.api.call.aaveTradeExecutor.pools()).map(({reserve:t,atoken:r,liqudityIn:s,liqudityOut:i})=>({address:this.getPoolId(t.toString(),r.toString()),type:"Aave",tokens:[{id:t.toString(),balance:s.toString()},{id:r.toString(),balance:i.toString()}],...this.getPoolLimits()}))}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(t=>{let{event:r}=t,s=`${r.section}:${r.method}`;if(s==="router:Executed"){let[i,o]=r.data.toJSON();this.pools.filter(n=>n.tokens.some(a=>a.id===i.toString()||a.id===o.toString())).forEach(n=>{this.log(`Sync AAVE via [router:Executed] :: ${i}:${o}`),this.updatePoolState(n)})}if(s==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:o,args:n}=cr({abi:we,topics:i.topics,data:i.data});if(ur.includes(o)){let a=n.reserve.toLowerCase();this.pools.filter(l=>{let[c]=l.tokens;return this.getReserveH160Id(c).toLowerCase()===a}).forEach(l=>{this.log(`Sync AAVE via [evm:Log] :: ${o} ${a}`),this.updatePoolState(l)})}}catch{}}})}async subscribeBalances(){return()=>{}}async subscribeUpdates(){return()=>{}}async updatePoolState(e){let[t,r]=e.tokens,{liqudityIn:s,liqudityOut:i}=await this.api.call.aaveTradeExecutor.pool(t.id,r.id);e.tokens=e.tokens.map(o=>{let n=o.id===t.id?s.toString():i.toString();return{...o,balance:n}})}};import{calculate_in_given_out as mr,calculate_out_given_in as pr,calculate_linear_weights as dr,calculate_pool_trade_fee as gr,get_spot_price as hr}from"@galacticcouncil/math-lbp";var W=class{static getSpotPrice(e,t,r,s,i){return hr(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i){return mr(e,t,r,s,i)}static calculateOutGivenIn(e,t,r,s,i){return pr(e,t,r,s,i)}static calculateLinearWeights(e,t,r,s,i){return dr(e,t,r,s,i)}static calculatePoolTradeFee(e,t,r){return gr(e,t,r)}};var P=class d{static toPct(e){let[t,r]=e;return d.safeDivide(t*100,r)}static toRaw(e){let[t,r]=e;return d.safeDivide(t,r)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,r=12){let s=10**r;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};var Me=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new d(e)}constructor(e){this.type="Lbp",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.fee=e.fee,this.repayFeeApply=e.repayFeeApply}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(a=>[a.id,a])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:n,decimalsIn:s.decimals,decimalsOut:i.decimals,weightIn:s.weight,weightOut:i.weight}}validateAndBuy(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let o=e.balanceOut.div(this.maxOutRatio);if(t.isGreaterThan(o)&&i.push("MaxOutRatioExceeded"),s===e.assetOut){let n=this.calculateTradeFee(t,r),a=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),l=t.plus(n),c=this.calculateInGivenOut(e,l),u=e.balanceIn.div(this.maxInRatio);return c.isGreaterThan(u)&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:t,feePct:a,errors:i}}else{let n=this.calculateInGivenOut(e,t),a=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(a)&&i.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,amountOut:t,feePct:0,errors:i}}}validateAndSell(e,t,r){let s=this.tokens[0].id,i=[];t.isLessThan(this.minTradingLimit)&&i.push("InsufficientTradingAmount");let o=e.balanceIn.div(this.maxInRatio);if(t.isGreaterThan(o)&&i.push("MaxInRatioExceeded"),s===e.assetIn){let n=this.calculateOutGivenIn(e,t),a=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(a)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:n,feePct:0,errors:i}}else{let n=this.calculateOutGivenIn(e,t),a=this.calculateTradeFee(n,r),l=P.toPct(this.repayFeeApply?r.repayFee:r.exchangeFee),c=n.minus(a),u=e.balanceOut.div(this.maxOutRatio);return c.isGreaterThan(u)&&i.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:n,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(e,t){let r=W.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?x:s}calculateOutGivenIn(e,t){let r=W.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?x:s}spotPriceInGivenOut(e){let t=W.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),A(N,e.decimalsOut).toString());return m(t)}spotPriceOutGivenIn(e){let t=W.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),A(N,e.decimalsIn).toString());return m(t)}calculateTradeFee(e,t){let r=W.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return m(r)}};var Le=class extends D{MAX_FINAL_WEIGHT=A(m(100),6);poolsData=new Map([]);getPoolType(){return"Lbp"}getPoolLimits(){let e=this.api.consts.lbp.maxInRatio.toNumber(),t=this.api.consts.lbp.maxOutRatio.toNumber(),r=this.api.consts.lbp.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getPoolDelta(e,t,r){let{start:s,end:i,assets:o,initialWeight:n,finalWeight:a,repayTarget:l,feeCollector:c}=t,u=W.calculateLinearWeights(s.toString(),i.toString(),n.toString(),a.toString(),r),[p,y]=o,g=p.toString(),b=m(u),h=y.toString(),S=this.MAX_FINAL_WEIGHT.minus(m(b)),[f,B,T]=await Promise.all([this.isRepayFeeApplied(g,l.toString(),c.toString()),this.getBalance(e,g),this.getBalance(e,h)]);return{repayFeeApply:f,tokens:[{id:g,weight:b,balance:B.toString()},{id:h,weight:S,balance:T.toString()}]}}isActivePool(e,t){if(e.start.isEmpty||e.end.isEmpty)return!1;let r=e.start.unwrap().toNumber(),s=e.end.unwrap().toNumber();return t>=r&&t<s}async isRepayFeeApplied(e,t,r){let s=m(t);if(s.isZero())return!1;try{return(await this.getBalance(e,r)).isLessThan(s)}catch{return!0}}isSupported(){return this.api.query.lbp!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.lbp.poolData.entries(),this.api.query.parachainSystem.validationData()]),{relayParentNumber:r}=t.unwrap(),s=e.filter(([i,o])=>this.isActivePool(o.unwrap(),r.toNumber())).map(async([{args:[i]},o])=>{let n=o.unwrap(),a=i.toString(),l=await this.getPoolDelta(a,n,r.toString());this.poolsData.set(i.toString(),n);let[c,u]=n.fee;return{address:a,type:"Lbp",fee:P.fromRate(c.toNumber(),u.toNumber()),...l,...this.getPoolLimits()}});return Promise.all(s)}async getPoolFees(e,t,r){let s=this.pools.find(i=>i.address===r);return{repayFee:this.getRepayFee(),exchangeFee:s.fee}}getRepayFee(){let[e,t]=this.api.consts.lbp.repayFee;return P.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return this.api.query.parachainSystem.validationData(async e=>{let{relayParentNumber:t}=e.unwrap();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s)if(this.isActivePool(s,t.toNumber())){let o=await this.getPoolDelta(r.address,s,t.toString());Object.assign(r,o)}else{let o=this.pools.findIndex(n=>n.address==r.address);this.pools.splice(o,1)}})})}};import{calculate_in_given_out as yr,calculate_lrna_in_given_out as br,calculate_out_given_in as Pr,calculate_out_given_lrna_in as fr,calculate_spot_price as Sr,calculate_lrna_spot_price as Br,calculate_shares as xr,calculate_liquidity_out as vr,calculate_liquidity_lrna_out as wr,calculate_liquidity_hub_in as Tr,is_sell_allowed as Or,is_buy_allowed as Ir,is_add_liquidity_allowed as Ar,is_remove_liquidity_allowed as Fr,recalculate_asset_fee as Rr,recalculate_protocol_fee as Nr,verify_asset_cap as Er}from"@galacticcouncil/math-omnipool";var F=class{static calculateSpotPrice(e,t,r,s){return Sr(e,t,r,s)}static calculateLrnaSpotPrice(e,t){return Br(e,t)}static calculateInGivenOut(e,t,r,s,i,o,n,a,l,c){return yr(e,t,r,s,i,o,n,a,l,c)}static calculateLrnaInGivenOut(e,t,r,s,i,o){return br(e,t,r,s,i,o)}static calculateOutGivenIn(e,t,r,s,i,o,n,a,l,c){return Pr(e,t,r,s,i,o,n,a,l,c)}static calculateOutGivenLrnaIn(e,t,r,s,i,o){return fr(e,t,r,s,i,o)}static calculateShares(e,t,r,s){return xr(e,t,r,s)}static calculateLiquidityOut(e,t,r,s,i,o,n,a){return vr(e,t,r,s,i,o,n,a)}static calculateLiquidityLRNAOut(e,t,r,s,i,o,n,a){return wr(e,t,r,s,i,o,n,a)}static calculateCapDifference(e,t,r,s){let i=v(t),o=v(e),n=v(s),l=v(r).shiftedBy(-18);if(i.div(n).lt(l)){let u=l.times(n).minus(i).times(o),p=i.times(v(1).minus(l));return u.div(p).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,r,s){return Tr(e,t,r,s)}static isSellAllowed(e){return Or(e)}static isBuyAllowed(e){return Ir(e)}static isAddLiquidityAllowed(e){return Ar(e)}static isRemoveLiquidityAllowed(e){return Fr(e)}static recalculateAssetFee(e,t,r,s,i,o,n,a,l,c,u){return Rr(e,t,r,s,i,o,n,a,l,c,u)}static recalculateProtocolFee(e,t,r,s,i,o,n,a,l,c,u){return Nr(e,t,r,s,i,o,n,a,l,c,u)}static verifyAssetCap(e,t,r,s){return Er(e,t,r,s)}};var He=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new d(e)}constructor(e){this.type="Omnipool",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.hubAssetId=e.hubAssetId}validatePair(e,t){return this.hubAssetId!=t}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,hubReservesIn:s.hubReserves,hubReservesOut:i.hubReserves,sharesIn:s.shares,sharesOut:i.shares,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,tradeableIn:s.tradeable,tradeableOut:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),o=i.minus(s),n=s===x?x:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let u=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(u)&&a.push("MaxOutRatioExceeded");let p=e.balanceIn.div(this.maxInRatio);return i.isGreaterThan(p)&&a.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let u=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(u)&&a.push("MaxInRatioExceeded");let p=e.balanceOut.div(this.maxOutRatio);return i.isGreaterThan(p)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:a}}calculateInGivenOut(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,r);let s=F.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():x.toString(),r?P.toRaw(r.protocolFee).toString():x.toString(),r?P.toRaw(r.maxSlipFee).toString():x.toString()),i=m(s);return i.isNegative()?x:i}calculateLrnaInGivenOut(e,t,r){let s=F.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():x.toString(),r?P.toRaw(r.maxSlipFee).toString():x.toString()),i=m(s);return i.isNegative()?x:i}calculateOutGivenIn(e,t,r){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,r);let s=F.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():x.toString(),r?P.toRaw(r.protocolFee).toString():x.toString(),r?P.toRaw(r.maxSlipFee).toString():x.toString()),i=m(s);return i.isNegative()?x:i}calculateOutGivenLrnaIn(e,t,r){let s=F.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toFixed(0),r?P.toRaw(r.assetFee).toString():x.toString(),r?P.toRaw(r.maxSlipFee).toString():x.toString()),i=m(s);return i.isNegative()?x:i}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=F.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceLrnaInGivenOut(e){let t=F.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsOut)).decimalPlaces(0,1)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=F.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}spotPriceOutGivenLrnaIn(e){let t=F.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return m(t).shiftedBy(-1*(18-e.decimalsIn)).decimalPlaces(0,1)}};import{encodeAddress as Cr}from"@polkadot/util-crypto";import{stringToU8a as kr}from"@polkadot/util";import{memoize1 as Ge}from"@thi.ng/memoize";import{TLRUCache as _r}from"@thi.ng/cache";var Ot="omnipool",It="Short",Ue=class extends D{dynamicFees=new Map;dynamicFeesConfiguration=new Map;oracles=new Map;memQueryCache=new _r(null,{ttl:6*1e3});memOracleQuery=Ge(e=>{let t=e.split(":");return this.api.query.emaOracle.oracles(Ot,t,It)},this.memQueryCache);memFeesQuery=Ge(e=>this.api.query.dynamicFees.assetFee(e),this.memQueryCache);memFeesConfigurationQuery=Ge(e=>this.api.query.dynamicFees.assetFeeConfiguration(e),this.memQueryCache);memSlipFeeQuery=Ge(e=>this.api.query.omnipool.slipFee(),this.memQueryCache);getPoolType(){return"Omnipool"}getPoolId(){return Cr(kr("modlomnipool".padEnd(32,"\0")),63)}getOracleKey(e){return e==="0"?["0","1"]:["1",e]}getPoolLimits(){let e=this.api.consts.omnipool.maxInRatio.toNumber(),t=this.api.consts.omnipool.maxOutRatio.toNumber(),r=this.api.consts.omnipool.minimumTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}async getDynamicFees(e){return this.dynamicFees.has(e)?this.dynamicFees.get(e):this.memFeesQuery(e)}async getDynamicFeesConfiguration(e){return this.dynamicFeesConfiguration.has(e)?this.dynamicFeesConfiguration.get(e):this.memFeesConfigurationQuery(e)}async getOraclePrice(e){let r=this.getOracleKey(e).join(":");return this.oracles.has(r)?this.oracles.get(r):this.memOracleQuery(r)}isSupported(){return this.api.query.omnipool!==void 0}isAssetConfigSupported(){return this.api.query.dynamicFees.assetFeeConfiguration!==void 0}async loadPools(){let e=this.api.consts.omnipool.hubAssetId.toString(),t=this.getPoolId(),[r,s,i]=await Promise.all([this.api.query.omnipool.assets.entries(),this.api.query.omnipool.hubAssetTradability(),this.getBalance(t,e)]),o=r.map(async([{args:[a]},l])=>{let{hubReserve:c,shares:u,tradable:p,cap:y,protocolShares:g}=l.unwrap(),b=await this.getBalance(t,a.toString());return{id:a.toString(),hubReserves:m(c.toString()),shares:m(u.toString()),tradeable:p.bits.toNumber(),balance:b.toString(),cap:m(y.toString()),protocolShares:m(g.toString())}}),n=await Promise.all(o);return n.push({id:e,tradeable:s.bits.toNumber(),balance:i.toString()}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:n,...this.getPoolLimits()}]}isSlipFeeSupported(){return this.api.query.omnipool.slipFee!==void 0}async getMaxSlipFee(){if(!this.isSlipFeeSupported())return 0;let e=await this.memSlipFeeQuery("slipFee");return e.isNone?0:e.unwrap().maxSlipFee.toNumber()}async getPoolFees(e,t,r){let s=t.assetOut,i=t.assetIn,o=await this.getMaxSlipFee(),n;if(this.isAssetConfigSupported()&&(n=await this.getDynamicFeesConfiguration(s).then(B=>B.unwrapOr(null))),n?.isFixed){let B=n.asFixed.assetFee.toNumber(),T=n.asFixed.protocolFee.toNumber();return{assetFee:P.fromPermill(B),protocolFee:P.fromPermill(T),maxSlipFee:P.fromPermill(o)}}let[a,l,c]=await Promise.all([this.getDynamicFees(s),this.getOraclePrice(s),this.getOraclePrice(i)]),[u,p,y]=this.getAssetFee(t,e,a,l,n?.isDynamic?n.asDynamic.assetFeeParams:void 0),[g,b,h]=i==="1"?[0,0,0]:this.getProtocolFee(t,e,a,c,n?.isDynamic?n.asDynamic.protocolFeeParams:void 0),S=u+g,f=y+h;return{assetFee:P.fromPermill(p),protocolFee:P.fromPermill(b),maxSlipFee:P.fromPermill(o),min:P.fromPermill(S),max:P.fromPermill(f)}}getAssetFee(e,t,r,s,i){let{assetOut:o,balanceOut:n}=e,{minFee:a,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.assetFeeParameters,p=P.fromPermill(a.toNumber()),y=P.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[g]=s.unwrap(),{assetFee:b,timestamp:h}=r.unwrap(),S=Math.max(1,t-h.toNumber()),f=g.volume.bIn.toString(),B=g.volume.bOut.toString(),T=g.liquidity.b.toString();o==="0"&&(f=g.volume.aIn.toString(),B=g.volume.aOut.toString(),T=g.liquidity.a.toString());let O=P.fromPermill(b.toNumber()),w=F.recalculateAssetFee(f,B,T,"9",n.toString(),P.toRaw(O).toString(),S.toString(),P.toRaw(p).toString(),P.toRaw(y).toString(),c.toString(),u.toString());return[a.toNumber(),Number(w)*1e6,l.toNumber()]}getProtocolFee(e,t,r,s,i){let{assetIn:o,balanceIn:n}=e,{minFee:a,maxFee:l,decay:c,amplification:u}=i||this.api.consts.dynamicFees.protocolFeeParameters,p=P.fromPermill(a.toNumber()),y=P.fromPermill(l.toNumber());if(r.isNone||s.isNone)return[a.toNumber(),a.toNumber(),l.toNumber()];let[g]=s.unwrap(),{protocolFee:b,timestamp:h}=r.unwrap(),S=Math.max(1,t-h.toNumber()),f=g.volume.bIn.toString(),B=g.volume.bOut.toString(),T=g.liquidity.b.toString();o==="0"&&(f=g.volume.aIn.toString(),B=g.volume.aOut.toString(),T=g.liquidity.a.toString());let O=P.fromPermill(b.toNumber()),w=F.recalculateProtocolFee(f,B,T,"9",n.toString(),P.toRaw(O).toString(),S.toString(),P.toRaw(p).toString(),P.toRaw(y).toString(),c.toString(),u.toString());return[a.toNumber(),Number(w)*1e6,l.toNumber()]}async subscribeUpdates(){let[e]=this.pools,t=e.tokens.map(a=>a.id),r=[],s=await this.api.query.omnipool.assets.multi(t,a=>{e.tokens=a.map((l,c)=>{let u=e.tokens[c];if(l.isNone)return u;let p=l.unwrap();return this.updateTokenState(u,p)})});r.push(s);let i=await this.api.query.dynamicFees.assetFee.multi(t,a=>{a.forEach((l,c)=>{let u=t[c];this.dynamicFees.set(u,l)})});if(r.push(i),this.isAssetConfigSupported()){let a=await this.api.query.dynamicFees.assetFeeConfiguration.multi(t,l=>{l.forEach((c,u)=>{let p=t[u];this.dynamicFeesConfiguration.set(p,c)})});r.push(a)}let o=t.map(a=>{let l=this.getOracleKey(a);return[Ot,l,It]}),n=await this.api.query.emaOracle.oracles.multi(o,a=>{a.forEach(async(l,c)=>{let u=o[c],[p,y,g]=u;this.oracles.set(y.join(":"),l)})});return r.push(n),()=>{for(let a of r)try{a()}catch(l){console.warn("Omnipool unsubscribe failed",l)}}}updateTokenState(e,t){let{hubReserve:r,shares:s,tradable:i,cap:o,protocolShares:n}=t;return{...e,hubReserves:m(r.toString()),shares:m(s.toString()),cap:m(o.toString()),protocolShares:m(n.toString()),tradeable:i.bits.toNumber()}}};import{calculate_in_given_out as Dr,calculate_out_given_in as Mr,calculate_pool_trade_fee as Lr,get_spot_price as Hr,calculate_liquidity_in as Gr,calculate_shares as Ur,calculate_spot_price as qr,calculate_spot_price_with_fee as Wr,calculate_liquidity_out_asset_a as Vr,calculate_liquidity_out_asset_b as Xr}from"@galacticcouncil/math-xyk";var Y=class{static getSpotPrice(e,t,r){return Hr(e,t,r)}static calculateInGivenOut(e,t,r){return Dr(e,t,r)}static calculateOutGivenIn(e,t,r){return Mr(e,t,r)}static calculatePoolTradeFee(e,t,r){return Lr(e,t,r)}static calculateLiquidityIn(e,t,r){return Gr(e,t,r)}static calculateSpotPrice(e,t){return qr(e,t)}static calculateSpotPriceWithFee(e,t,r,s){return Wr(e,t,r,s)}static calculateShares(e,t,r){return Ur(e,t,r)}static calculateLiquidityOutAssetA(e,t,r,s){return Vr(e,t,r,s)}static calculateLiquidityOutAssetB(e,t,r,s){return Xr(e,t,r,s)}};var qe=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new d(e)}constructor(e){this.type="Xyk",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,decimalsIn:s.decimals,decimalsOut:i.decimals,balanceIn:o,balanceOut:n,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateTradeFee(s,r),o=P.toPct(r.exchangeFee),n=s.plus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount");let l=e.balanceOut.div(this.maxOutRatio);t.isGreaterThan(l)&&a.push("MaxOutRatioExceeded");let c=e.balanceIn.div(this.maxInRatio);return n.isGreaterThan(c)&&a.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:t,feePct:o,errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateTradeFee(s,r),o=P.toPct(r.exchangeFee),n=s.minus(i),a=[];(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount");let l=e.balanceIn.div(this.maxInRatio);t.isGreaterThan(l)&&a.push("MaxInRatioExceeded");let c=e.balanceOut.div(this.maxOutRatio);return n.isGreaterThan(c)&&a.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:s,amountOut:n,feePct:o,errors:a}}calculateInGivenOut(e,t){let r=Y.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?x:s}calculateOutGivenIn(e,t){let r=Y.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toFixed(0)),s=m(r);return s.isNegative()?x:s}spotPriceInGivenOut(e){let t=Y.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString()),r=A(N,18-e.decimalsOut);return m(t).div(r)}spotPriceOutGivenIn(e){let t=Y.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString()),r=A(N,18-e.decimalsIn);return m(t).div(r)}calculateTradeFee(e,t){let r=Y.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return m(r)}};var We=class extends D{getPoolType(){return"Xyk"}getPoolLimits(){let e=this.api.consts.xyk.maxInRatio.toNumber(),t=this.api.consts.xyk.maxOutRatio.toNumber(),r=this.api.consts.xyk.minTradingLimit.toNumber();return{maxInRatio:e,maxOutRatio:t,minTradingLimit:r}}isSupported(){return this.api.query.xyk!==void 0}async loadPools(){let t=(await this.api.query.xyk.poolAssets.entries()).map(async([{args:[r]},s])=>{let i=r.toString(),[o,n]=s.unwrap(),[a,l]=await Promise.all([this.getBalance(i,o.toString()),this.getBalance(i,n.toString())]);return{address:i,type:"Xyk",tokens:[{id:o.toString(),balance:a.toString()},{id:n.toString(),balance:l.toString()}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolFees(e,t,r){return{exchangeFee:this.getExchangeFee()}}getExchangeFee(){let[e,t]=this.api.consts.xyk.getExchangeFee;return P.fromRate(e.toNumber(),t.toNumber())}async subscribeUpdates(){return()=>{}}};import{calculate_in_given_out as Yr,calculate_out_given_in as Kr,calculate_amplification as $r,calculate_add_one_asset as Qr,calculate_liquidity_out_one_asset as jr,calculate_shares as zr,calculate_shares_for_amount as Jr,calculate_spot_price_with_fee as Zr,pool_account_name as es,recalculate_peg as ts}from"@galacticcouncil/math-stableswap";var k=class{static getPoolAddress(e){return es(e)}static defaultPegs(e){let t=[];for(let r=0;r<e;r++)t.push(["1","1"]);return t}static calculateAmplification(e,t,r,s,i){return $r(e,t,r,s,i)}static calculateInGivenOut(e,t,r,s,i,o,n){return Yr(e,t,r,s,i,o,n)}static calculateAddOneAsset(e,t,r,s,i,o,n){return Qr(e,t,r,s,i,o,n)}static calculateSharesForAmount(e,t,r,s,i,o,n){return Jr(e,t,r,s,i,o,n)}static calculateOutGivenIn(e,t,r,s,i,o,n){return Kr(e,t,r,s,i,o,n)}static calculateLiquidityOutOneAsset(e,t,r,s,i,o,n){return jr(e,t,r,s,i,o,n)}static calculateShares(e,t,r,s,i,o){return zr(e,t,r,s,i,o)}static calculateSpotPriceWithFee(e,t,r,s,i,o,n,a){return Zr(e,t,r,s,i,o,n,a)}static recalculatePegs(e,t,r,s,i,o){let n=ts(e,t,r,s,i,o);return JSON.parse(n)}};var Z=class d{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;id;fee;totalIssuance;pegs;pegsFee;static fromPool(e){return new d(e)}constructor(e){this.type="Stableswap",this.address=e.address,this.tokens=e.tokens,this.maxInRatio=e.maxInRatio,this.maxOutRatio=e.maxOutRatio,this.minTradingLimit=e.minTradingLimit,this.amplification=e.amplification,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs,this.pegsFee=e.pegsFee}validatePair(e,t){return!0}parsePair(e,t){let r=new Map(this.tokens.map(c=>[c.id,c])),s=r.get(e),i=r.get(t);if(s==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");let o=m(s.balance),n=m(i.balance),a=m(s.existentialDeposit),l=m(i.existentialDeposit);return{assetIn:e,assetOut:t,balanceIn:o,balanceOut:n,decimalsIn:s.decimals,decimalsOut:i.decimals,tradeableIn:this.id===e?15:s.tradeable,tradeableOut:this.id===t?15:i.tradeable,assetInED:a,assetOutED:l}}validateAndBuy(e,t,r){let s=this.calculateInGivenOut(e,t),i=this.calculateInGivenOut(e,t,r),o=i.minus(s),n=s===x?x:o.div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetInED))&&a.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:s,amountOut:t,feePct:n.toNumber(),errors:a}}validateAndSell(e,t,r){let s=this.calculateOutGivenIn(e,t),i=this.calculateOutGivenIn(e,t,r),n=s.minus(i).div(s).multipliedBy(100).decimalPlaces(4),a=[],l=F.isSellAllowed(e.tradeableIn),c=F.isBuyAllowed(e.tradeableOut);return(!l||!c)&&a.push("TradeNotAllowed"),(t.isLessThan(this.minTradingLimit)||s.isLessThan(e.assetOutED))&&a.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:s,amountOut:i,feePct:n.toNumber(),errors:a}}calculateIn(e,t,r){let s=k.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=m(s);return i.isNegative()?x:i}calculateAddOneAsset(e,t,r){let s=k.calculateAddOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetIn),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=m(s);return i.isNegative()?x:i}calculateSharesForAmount(e,t,r){let s=k.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toFixed(0),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=m(s);return i.isNegative()?x:i}calculateInGivenOut(e,t,r){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,r):e.assetIn==this.id?this.calculateSharesForAmount(e,t,r):this.calculateIn(e,t,r)}spotPriceInGivenOut(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetOut,e.assetIn,this.totalIssuance,"0",this.getPegs());if(e.assetOut==this.id)return m(t);if(e.assetIn==this.id){let s=A(N,e.decimalsIn-e.decimalsOut);return m(t).div(s).decimalPlaces(0,1)}let r=A(N,18-e.decimalsIn);return m(t).div(r).decimalPlaces(0,1)}calculateOut(e,t,r){let s=k.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toFixed(0),this.amplification,r?P.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=m(s);return i.isNegative()?x:i}calculateWithdrawOneAsset(e,t,r){let s=k.calculateLiquidityOutOneAsset(this.getReserves(),t.toFixed(0),Number(e.assetOut),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=m(s);return i.isNegative()?x:i}calculateShares(e,t,r){let s=k.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification,this.totalIssuance,r?P.toRaw(r.fee).toString():x.toString(),this.getPegs()),i=m(s);return i.isNegative()?x:i}calculateOutGivenIn(e,t,r){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,r):e.assetOut==this.id?this.calculateShares(e,t,r):this.calculateOut(e,t,r)}spotPriceOutGivenIn(e){let t=k.calculateSpotPriceWithFee(this.id,this.getReserves(),this.amplification,e.assetIn,e.assetOut,this.totalIssuance,"0",this.getPegs());if(e.assetIn==this.id)return m(t);if(e.assetOut==this.id){let s=A(N,e.decimalsOut-e.decimalsIn);return m(t).div(s).decimalPlaces(0,1)}let r=A(N,18-e.decimalsOut);return m(t).div(r).decimalPlaces(0,1)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:r,decimals:s})=>({asset_id:Number(t),amount:r,decimals:s}));return JSON.stringify(e)}getAssets(e,t){let r={asset_id:Number(e),amount:t.toFixed(0)};return JSON.stringify([r])}};import{blake2AsHex as rs,encodeAddress as ss}from"@polkadot/util-crypto";var Ve=class extends D{poolsData=new Map([]);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=Number(e),r=k.getPoolAddress(t);return ss(rs(r),63)}getPoolLimits(){return{maxInRatio:0,maxOutRatio:0,minTradingLimit:this.api.consts.stableswap.minTradingLimit.toNumber()}}async getPoolDelta(e,t,r){let{initialAmplification:s,finalAmplification:i,initialBlock:o,finalBlock:n}=t,a=k.calculateAmplification(s.toString(),i.toString(),o.toString(),n.toString(),r),l=await this.api.query.tokens.totalIssuance(e);return{amplification:a,totalIssuance:l.toString()}}async getPoolTokens(e,t,r){let{assets:s}=r,i=s.map(async o=>{let[n,a]=await Promise.all([this.api.query.stableswap.assetTradability(t,o.toString()),this.getBalance(e,o.toString())]);return{id:o.toString(),tradeable:n.bits.toNumber(),balance:a.toString()}});return Promise.all(i)}isSupported(){return this.api.query.stableswap!==void 0}async loadPools(){let[e,t]=await Promise.all([this.api.query.stableswap.pools.entries(),this.api.query.system.number()]),r=t.toNumber(),s=e.map(async([{args:[o]},n])=>{try{let a=n.unwrap(),l=o.toString(),c=this.getPoolAddress(l),[u,p,y]=await Promise.all([this.getPoolDelta(l,a,r.toString()),this.getPoolTokens(c,l,a),this.getPoolPegs(l,a,r.toString())]);return p.push({id:l,tradeable:15,balance:u.totalIssuance}),this.poolsData.set(c,a),{address:c,id:l,type:"Stableswap",fee:P.fromPermill(a.fee.toNumber()),tokens:p,...u,...y,...this.getPoolLimits()}}catch(a){return console.warn(`Skipping pool ${o.toString()}
|
|
2
|
+
`,String(a)),null}});return(await Promise.all(s)).filter(o=>o!==null)}async getPoolFees(e,t,r){return{fee:this.pools.find(i=>i.address===r).pegsFee}}async getPoolPegs(e,t,r){let s=await this.api.query.stableswap.poolPegs(e);if(s.isNone)return this.getDefaultPegs(t);let i=s.unwrap(),o=await this.getLatestPegs(t,i,r),n=o.map(({pair:h,updatedAt:S})=>[h,S]),a=this.getRecentPegs(i),l=P.fromPermill(t.fee.toNumber()),c=P.fromPerbill(i.maxPegUpdate.toNumber()),u=o.find(h=>h.source),p=i.updatedAt?i.updatedAt.toString():u?.updatedAt;if(!p)throw Error(e+" current peg unknown");let[y,g]=k.recalculatePegs(JSON.stringify(a),p,JSON.stringify(n),r,P.toRaw(c).toString(),P.toRaw(l).toString()),b=Number(y)*1e6;return{pegsFee:P.fromPermill(b),pegs:g}}getDefaultPegs(e){let t=e.fee,r=k.defaultPegs(e.assets.length);return{pegsFee:P.fromPermill(t.toNumber()),pegs:r}}getRecentPegs(e){let{current:t}=e;return Array.from(t.entries()).map(([r,s])=>s.map(i=>i.toString()))}async getLatestPegs(e,t,r){let{source:s}=t,i=Array.from(e.assets.entries()).map(([n,a])=>a.toString()),o=s.map(async(n,a)=>{if(n.isOracle){let[l,c,u]=n.asOracle,p=[u.toString(),i[a]].map(B=>Number(B)).sort((B,T)=>B-T),y=await this.api.query.emaOracle.oracles(l,p,c),[{price:g,updatedAt:b}]=y.unwrap(),h=g.n.toString(),S=g.d.toString();return{pair:u.toString()===p[0].toString()?[h,S]:[S,h],updatedAt:b.toString(),source:"ema"}}else if(n.isMmOracle){let l=n.asMmOracle,{price:c,decimals:u,updatedAt:p}=await this.mmOracle.getData(l.toString()),y=10**u;return{pair:[c.toString(),y.toString()],updatedAt:p.toString(),source:"mm"}}else{if(n.isValue)return{pair:n.asValue.map(c=>c.toString()),updatedAt:r};throw Error(n.type+" is not supported")}});return Promise.all(o)}async subscribeUpdates(){return this.api.query.system.number(async e=>{let t=e.toString();this.pools.forEach(async r=>{let s=this.poolsData.get(r.address);if(s){let[i,o]=await Promise.all([this.getPoolDelta(r.id,s,t),this.getPoolPegs(r.id,s,t)]),n=r.tokens.map(a=>a.id===r.id?{...a,balance:i.totalIssuance}:a);Object.assign(r,{tokens:n},i,o)}})})}};import{calculate_collateral_in_given_hollar_out as is,calculate_collateral_out_given_hollar_in as as,calculate_hollar_in_given_collateral_out as ns,calculate_hollar_out_given_collateral_in as os,calculate_imbalance as ls,calculate_max_price as cs,calculate_buyback_limit as us,calculate_buyback_price_with_fee as ms}from"@galacticcouncil/math-hsm";var U=class{static calculateCollateralInGivenHollarOut(e,t,r){return is(e,t,r)}static calculateCollateralOutGivenHollarIn(e,t,r){return as(e,t,r)}static calculateHollarOutGivenCollateralIn(e,t,r){return os(e,t,r)}static calculateHollarInGivenCollateralOut(e,t,r){return ns(e,t,r)}static calculateImbalance(e,t,r){return ls(e,t,r)}static calculateBuybackLimit(e,t){return us(e,t)}static calculateBuybackPriceWithFee(e,t,r){return ms(e,t,r)}static calculateMaxPrice(e,t){return cs(e,t)}};var Xe=class d extends Z{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new d(e)}constructor(e){super(e),this.type="Hsm",this.hsmAddress=e.hsmAddress,this.hsmMintCapacity=e.hsmMintCapacity,this.hollarId=e.hollarId,this.hollarH160=e.hollarH160,this.collateralId=e.collateralId,this.collateralBalance=e.collateralBalance,this.maxBuyPriceCoefficient=e.maxBuyPriceCoefficient,this.maxInHolding=e.maxInHolding,this.purchaseFee=e.purchaseFee,this.buyBackFee=e.buyBackFee,this.buyBackRate=e.buyBackRate}validatePair(e,t){return!0}parsePair(e,t){return super.parsePair(e,t)}validateTradeHollarIn(e,t,r,s){let i=this.calculateBuybackLimit(e);t.gt(i)&&s.push("MaxBuyBackExceeded");let o=this.calculateBuyPrice(e,t,r),n=this.calculateMaxPrice(e);return o.gt(n)&&s.push("MaxBuyPriceExceeded"),r.gt(this.collateralBalance)&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(e,t,r){return this.collateralBalance.plus(e).gt(this.maxInHolding)&&r.push("MaxHoldingExceeded"),t.gt(this.hsmMintCapacity)&&r.push("FacilitatorCapacityExceeded"),r}validateTradeConstraints(e,t,r){let s=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,r,s):this.validateTradeHollarOut(t,r,s)}validateAndBuy(e,t){let r=this.calculateInGivenOut(e,t),s=this.validateTradeConstraints(e,r,t);return{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t){let r=this.calculateOutGivenIn(e,t),s=this.validateTradeConstraints(e,t,r);return{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(e,t){let r=super.calculateInGivenOut(e,t,{fee:this.fee}),s=U.calculateHollarInGivenCollateralOut(t.toFixed(0),r.toFixed(0),P.toRaw(this.buyBackFee).toString());return m(s)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),r=U.calculateCollateralInGivenHollarOut(e.toFixed(0),JSON.stringify(t),P.toRaw(this.purchaseFee).toString());return m(r)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let r=super.calculateOutGivenIn(e,t,{fee:this.fee}),s=U.calculateCollateralOutGivenHollarIn(t.toFixed(0),r.toFixed(0),P.toRaw(this.buyBackFee).toString());return m(s)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),r=U.calculateHollarOutGivenCollateralIn(e.toFixed(0),JSON.stringify(t),P.toRaw(this.purchaseFee).toString());return m(r)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),r=U.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return m(r)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),r=U.calculateBuybackLimit(t.toString(),P.toRaw(this.buyBackRate).toString());return m(r)}calculateBuyPrice(e,t,r){let s=U.calculateBuybackPriceWithFee(r.toFixed(),t.toFixed(),P.toRaw(this.buyBackFee).toString()),[i,o]=JSON.parse(s),n=m(10).pow(e.decimalsIn-e.decimalsOut);return m(i).times(n).dividedBy(m(o))}calculateMaxPrice(e){let t=this.getCollateralPeg(),r=U.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toFixed(0)),[s,i]=JSON.parse(r);return m(s).div(m(i)).shiftedBy(-1*e.decimalsOut)}spotPriceInGivenOut(e){let t=A(N,e.decimalsOut);return this.calculateInGivenOut(e,t)}spotPriceOutGivenIn(e){let t=A(N,e.decimalsIn);return this.calculateOutGivenIn(e,t)}getCollateralPeg(){let e=this.tokens.findIndex(s=>s.id!==this.hollarId),t=this.pegs[e],r=this.tokens[e].decimals;return this.isDefaultPeg(t)?[A(N,18).toString(),A(N,r).toString()]:t}isDefaultPeg(e){let[t,r]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&r==="1"}};import{stringToU8a as At}from"@polkadot/util";import{encodeAddress as Ft}from"@polkadot/util-crypto";import{decodeEventLog as ps}from"viem";var le=[{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitator",outputs:[{type:"tuple",components:[{name:"addr",type:"address"},{name:"label",type:"bytes32"},{name:"bucketCapacity",type:"uint128"},{name:"bucketLevel",type:"uint128"}]}],stateMutability:"view",type:"function"},{inputs:[{internalType:"address",name:"facilitator",type:"address"}],name:"getFacilitatorBucket",outputs:[{internalType:"uint256",name:"",type:"uint256"},{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"getFacilitatorsList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!0,internalType:"bytes32",name:"label",type:"bytes32"},{indexed:!1,internalType:"uint256",name:"bucketCapacity",type:"uint256"}],name:"FacilitatorAdded",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldCapacity",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newCapacity",type:"uint256"}],name:"FacilitatorBucketCapacityUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"},{indexed:!1,internalType:"uint256",name:"oldLevel",type:"uint256"},{indexed:!1,internalType:"uint256",name:"newLevel",type:"uint256"}],name:"FacilitatorBucketLevelUpdated",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"facilitatorAddress",type:"address"}],name:"FacilitatorRemoved",type:"event"}];var ce=class{rpcAdapter;constructor(e){this.rpcAdapter=e.getRPCAdapter()}async getFacilitatorCapacity(e,t){let[r,s]=await this.rpcAdapter.readContract({abi:le,address:e,functionName:"getFacilitatorBucket",args:[t]});return r-s}};var ds=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Ye=class extends D{stableClient;ghoTokenClient;constructor(e,t,r){super(e,t),this.stableClient=r,this.ghoTokenClient=new ce(t)}getPoolType(){return"Hsm"}getPoolId(e){let t="hsm:"+e;return Ft(At(t.padEnd(32,"\0")),63)}getFacilitatorAddress(){return Ft(At("modlpy/hsmod".padEnd(32,"\0")),63)}getHollarAddress(e){return _e(e,"accountKey20").accountKey20.key}isSupported(){return this.api.query.hsm!==void 0}async loadPools(){let e=this.api.consts.hsm.hollarId.toString(),[t,r,s]=await Promise.all([this.api.query.assetRegistry.assetLocations(e),this.api.query.hsm.collaterals.entries(),this.stableClient.getPoolsMem()]);if(r.length===0)return[];let i=this.getFacilitatorAddress(),o=V.fromAny(i),n=this.getHollarAddress(t.unwrap()),a=await this.ghoTokenClient.getFacilitatorCapacity(n,o),l=r.map(async([{args:[u]},p])=>{let y=p.unwrap(),g=u.toString(),{poolId:b,maxBuyPriceCoefficient:h,maxInHolding:S,purchaseFee:f,buyBackFee:B,buybackRate:T}=y,O=s.find(w=>w.id===b.toString());if(O){let w=this.getPoolId(b.toString()),C=await this.getBalance(i,g);return{...O,address:w,type:"Hsm",tokens:O.tokens.filter(M=>M.id!==b.toString()),hsmAddress:i,hsmMintCapacity:m(a),hollarId:e,hollarH160:n,collateralId:g,collateralBalance:C,maxBuyPriceCoefficient:m(h.toString()),maxInHolding:m(S.unwrap().toString()),purchaseFee:P.fromPermill(f.toNumber()),buyBackFee:P.fromPermill(B.toNumber()),buyBackRate:P.fromPerbill(T.toNumber())}}});return(await Promise.all(l)).filter(u=>u!==null)}async getPoolFees(e,t,r){return{}}onEvents(e){e.forEach(async t=>{let{event:r}=t;if(`${r.section}:${r.method}`==="evm:Log"){let[i]=r.data.toJSON();try{let{eventName:o,args:n}=ps({abi:le,topics:i.topics,data:i.data}),[a]=this.pools,{hsmAddress:l,hollarH160:c}=a,u=V.fromAny(l),p=u.toLowerCase()===n.facilitatorAddress.toLowerCase();if(ds.includes(o)&&p){let y=await this.ghoTokenClient.getFacilitatorCapacity(c,u);this.log(`Sync HSM facilitator via [evm:Log] :: ${o} ${y}`),this.pools.forEach(g=>{Object.assign(g,{hsmMintCapacity:y})})}}catch{}}})}async subscribeBalances(){let e=[],t=[],r=[];for(let i of this.pools){let{tokens:o,hsmAddress:n,collateralId:a}=i;o.find(c=>c.id===a).type==="Erc20"?t.push([n,a]):e.push([n,a])}let s=i=>{i.forEach(([o,n])=>{let[a,l]=o,c=this.pools.find(u=>u.tokens.some(p=>p.id===l));c&&Object.assign(c,{collateralBalance:n})})};if(e.length>0){let i=await this.subscribeTokenBalances(e,s);r.push(i)}if(t.length>0){let i=await this.subscribeErc20Balances(t,s);r.push(i)}return()=>{for(let i of r)try{i()}catch(o){console.warn("Balance unsub failed",o)}}}async subscribeUpdates(){return()=>{}}};var ue=class extends _{api;evm;assetClient;aaveClient;xykClient;omniClient;lbpClient;stableClient;hsmClient;clients=[];onChainAssets=[];block=0;blockHandlers=[];eventHandlers=[];disconnectSubscribeNewHeads=null;disconnectSubscribeEvents=null;memRegistry=gs(e=>(this.log(`Registry mem ${e} sync`),this.syncRegistry()));constructor(e,t){super(e),this.api=e,this.evm=t,this.assetClient=new Q(this.api),this.aaveClient=new De(this.api,t),this.xykClient=new We(this.api,t),this.omniClient=new Ue(this.api,t),this.lbpClient=new Le(this.api,t),this.stableClient=new Ve(this.api,t),this.hsmClient=new Ye(this.api,t,this.stableClient),this.clients=[this.aaveClient,this.xykClient,this.omniClient,this.lbpClient,this.stableClient,this.hsmClient],this.blockHandlers=this.clients.map(r=>r.onNewBlockHandler),this.eventHandlers=this.clients.map(r=>r.onEventsHandler),this.api.rpc.chain.subscribeNewHeads(async r=>{let s=r.number.toNumber();this.onNewBlock(s)}).then(r=>{this.disconnectSubscribeNewHeads=r}),this.api.query.system.events(r=>{this.onEvents(r)}).then(r=>{this.disconnectSubscribeEvents=r})}onNewBlock(e){this.block=e;for(let t of this.blockHandlers)try{t(e)}catch(r){this.log("onNewBlock handler error",r)}}onEvents(e){for(let t of this.eventHandlers)try{t(e)}catch(r){this.log("onEvents handler error",r)}}get assets(){return this.onChainAssets}get isRegistrySynced(){return this.onChainAssets.length>0}async syncRegistry(e){let t=await this.assetClient.getOnChainAssets(!1,e);this.clients.forEach(r=>r.withAssets(t)),this.onChainAssets=t}async getPools(e={}){this.isRegistrySynced||await this.memRegistry(1);let{includeOnly:t=[],exclude:r=[]}=e;return t.length>0?this.getFilteredPools(s=>t.includes(s.getPoolType())):r.length>0?this.getFilteredPools(s=>!r.includes(s.getPoolType())):this.getFilteredPools(s=>s.isSupported())}async getFilteredPools(e){let t=this.clients.filter(e);return(await Promise.all(t.map(s=>s.getPoolsMem()))).flat()}destroy(){this.aaveClient.unsubscribe(),this.xykClient.unsubscribe(),this.omniClient.unsubscribe(),this.lbpClient.unsubscribe(),this.stableClient.unsubscribe(),this.hsmClient.unsubscribe(),this.disconnectSubscribeNewHeads?.(),this.disconnectSubscribeEvents?.()}async getPoolFees(e,t){switch(t.type){case"Aave":return this.aaveClient.getPoolFees(this.block,e,t.address);case"Xyk":return this.xykClient.getPoolFees(this.block,e,t.address);case"Omnipool":return this.omniClient.getPoolFees(this.block,e,t.address);case"Lbp":return this.lbpClient.getPoolFees(this.block,e,t.address);case"Stableswap":return this.stableClient.getPoolFees(this.block,e,t.address);case"Hsm":return this.hsmClient.getPoolFees(this.block,e,t.address);default:throw new Re(t.type)}}};var me=class extends ue{feeCache=new Map;constructor(e,t){super(e,t)}onNewBlock(e){super.onNewBlock(e),this.feeCache.clear()}async getPoolFees(e,t){let r=[t.address,e.assetIn,e.assetOut].join("-");if(this.feeCache.has(r))return this.feeCache.get(r);let s=super.getPoolFees(e,t);return this.feeCache.set(r,s),s}async destroy(){this.feeCache.clear(),super.destroy()}};var pe=class{static get(e){switch(e.type){case"Aave":return ke.fromPool(e);case"Xyk":return qe.fromPool(e);case"Omnipool":return He.fromPool(e);case"Lbp":return Me.fromPool(e);case"Stableswap":return Z.fromPool(e);case"Hsm":return Xe.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{sha256 as hs}from"@noble/hashes/sha2";import{bytesToHex as ys}from"@noble/hashes/utils";function Kc(d){let e=d.map(s=>s.address).sort().join(":"),t=new TextEncoder().encode(e),r=hs(t);return ys(r)}var de=class{constructor(e=1/0){this.capacity=e}storage=[];enqueue(e){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(e)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var bs=10,ge=class{isNotVisited(e,t){let r=!0;return t.forEach(s=>{(s[0]===e[0]||s[1]===e[1])&&(r=!1)}),r}findPaths(e,t,r){let s=[],i=new de,o=[];for(o.push([t,""]),i.enqueue(o);i.size()>0;){let n=i.dequeue();if(!n||n.length>bs)continue;let a=n[n.length-1];(r===null||a[0]===r)&&s.push(n),e.get(a[0])?.forEach(c=>{if(this.isNotVisited(c,n)){let u=[...n];u.push(c),i.enqueue(u)}})}return s}findShortestPaths(e,t,r){let s=[],i=new de,o=[];o.push([t,""]),i.enqueue(o);let n=1/0;for(;i.size()>0;){let a=i.dequeue();if(!a)continue;let l=a[a.length-1];if(l[0]===r){a.length<n?(n=a.length,s.length=0,s.push(a)):a.length===n&&s.push(a);continue}let c=e.get(l[0]);for(let u of c??[])this.isNotVisited(u,a)&&i.enqueue([...a,u])}return s}buildAndPopulateGraph(e,t){let r=new Map;for(let s of e)r.set(parseInt(s),[]);for(let[s,i,o]of t){let n=parseInt(i),a=parseInt(o);r.get(n)?.push([a,s])}return r}};function at(d){let e={};for(let t of d){let r=t.tokens.length;for(let s=0;s<r;s++){e[t.tokens[s].id]||(e[t.tokens[s].id]=[]);for(let i=0;i<r;i++){if(s==i)continue;let o=[t.address,t.tokens[s].id,t.tokens[i].id];e[t.tokens[s].id].push(o)}}}return e}var he=class{getProposals(e,t,r){let s=r.filter(f=>f.type==="Xyk"),i=r.filter(f=>f.type!=="Xyk"),o=parseInt(e),n=parseInt(t),a=new Set(i.map(f=>f.tokens).flat().map(f=>f.id)),l=a.has(e),c=a.has(t),u=new ge,p=f=>{let B=at(f),T=Object.keys(B),O=T.flatMap(w=>B[w]);return u.buildAndPopulateGraph(T,O)};if(!l&&!c){let f=s.filter(O=>O.tokens.find(w=>w.id===e)||O.tokens.find(w=>w.id===t)),B=p(f),T=u.findPaths(B,o,n);return this.parsePaths(T)}if(l&&c){let f=p(i),B=u.findPaths(f,o,n);return this.parsePaths(B)}let y=l?t:e,g=s.filter(f=>f.tokens.some(B=>B.id===y));if(g.length===0)return[];let b=[...i,...g],h=p(b),S=u.findPaths(h,o,n);return this.parsePaths(S)}parsePaths(e){let t=[];for(let r of e){let s=[];for(let i=0;i<r.length;i++){let o=r[i],n=r[i+1];if(n==null)break;s.push(this.toEdge(o,n))}t.push(s)}return t}toEdge(e,t){return[t[1],e[0].toString(),t[0].toString()]}};var ye=class{routeSuggester;routeProposals;routerOptions;poolService;constructor(e,t={}){this.poolService=e,this.routeSuggester=new he,this.routeProposals=new Map,this.routerOptions=Object.freeze(t)}buildRouteKey(e,t,r){return`${e}->${t}::${r.length}`}async getPools(){return this.poolService.getPools(this.routerOptions)}async getAllAssets(){let e=await this.getPools(),t=this.getAssets(e);return[...new Map(t).values()]}async getRouteableAssets(e){let t=await this.getAllAssets();return(await Promise.all(t.map(s=>s.id).filter(s=>s!==e).map(s=>this.getRoutes(s,e)))).filter(s=>s.length>0).map(([s])=>s[0].assetIn).sort()}async getRoutes(e,t){let r=await this.getPools();return this.validateInput(e,t,r),this.getPaths(e,t,r)}validateInput(e,t,r){if(r.length===0)throw new Error("No pools configured");if(e===t)throw new Error("Trading pair can't be identical");let s=this.getAssets(r);if(s.get(e)===null)throw new Error(e+" is not supported asset");if(s.get(t)===null)throw new Error(t+" is not supported asset");return this.toPoolsMap(r)}getAssets(e){let t=e.map(r=>r.tokens.map(s=>({id:s.id,name:s.name,symbol:s.symbol,decimals:s.decimals,icon:s.icon,type:s.type,isSufficient:s.isSufficient,existentialDeposit:s.existentialDeposit,meta:s.meta,location:s.location,isWhiteListed:s.isWhiteListed}))).flat();return new Map(t.map(r=>[r.id,r]))}getPaths(e,t,r){let s=this.toPoolsMap(r);return this.getProposals(e,t,r).filter(n=>this.validPath(n,s)).map(n=>this.toHops(n,s))}getProposals(e,t,r){let s=this.buildRouteKey(e,t,r);if(this.routeProposals.has(s))return this.routeProposals.get(s);let i=this.routeSuggester.getProposals(e,t,r);return this.routeProposals.set(s,i),i}validPath(e,t){return e.length>0&&e.map(r=>this.validEdge(r,t)).reduce((r,s)=>r&&s)}validEdge([e,t,r],s){return s.get(e)?.validatePair(t,r)||!1}toPoolsMap(e){return new Map(e.map(t=>[t.address,pe.get(t)]))}toHops(e,t){return e.map(([r,s,i])=>{let o=t.get(r);return{poolAddress:r,poolId:o?.id,pool:o?.type,assetIn:s,assetOut:i}})}};var Ps=m("100");function Mu(d,e){return d.minus(e).abs().div(d.plus(e).div(2)).multipliedBy(100).decimalPlaces(2)}function be(d,e){return d.minus(e).div(e).multipliedBy(100).decimalPlaces(2)}function Rt(d,e){return N.minus(e.div(d)).multipliedBy(100).decimalPlaces(4)}function Nt(d,e){return e.div(d).minus(N).multipliedBy(100).decimalPlaces(4)}function z(d,e){return(e<.01||e>100)&&new Error("Supported range is from 0.01% - 100%"),d.div(Ps).multipliedBy(e).decimalPlaces(0,1)}var nt=(t=>(t.Buy="Buy",t.Sell="Sell",t))(nt||{}),ot=(r=>(r.Dca="Dca",r.TwapSell="TwapSell",r.TwapBuy="TwapBuy",r))(ot||{}),Et=(r=>(r.OrderTooSmall="OrderTooSmall",r.OrderTooBig="OrderTooBig",r.OrderImpactTooBig="OrderImpactTooBig",r))(Et||{});var ee=class extends ye{mlr;poolsSnapshot;constructor(e,t={}){super(e,t),this.mlr=new Map}buildCtxSync(e,t){let r=this.poolsSnapshot,s=super.validateInput(e,t,r),i=super.getPaths(e,t,r);if(!i.length)throw new Ne(e,t);return{paths:i,pools:r,poolsMap:s}}async withCtx(e,t,r){this.poolsSnapshot||(this.poolsSnapshot=await super.getPools());let s=this.buildCtxSync(e,t);return r(s)}isDirectTrade(e){return e.length==1}findBestSellRoute(e){let t=e.sort((r,s)=>{let i=r[r.length-1].amountOut,o=s[s.length-1].amountOut;return i.isGreaterThan(o)?-1:1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}getRouteFeeRange(e){if(e.filter(r=>r.tradeFeeRange).length>0){let r=e.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,o)=>i+o),s=e.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,o)=>i+o);return[r,s]}}getPoolFeeRange(e,t){let r=e.min?P.toPct(e.min):void 0,s=e.max?P.toPct(e.max):void 0;if(r&&s)return[r,Math.max(s,t)]}async getBestSell(e,t,r){return this.getSell(e,t,r)}async getSell(e,t,r,s){return this.withCtx(e,t,async({paths:i,poolsMap:o})=>{let n;if(s)n=await this.toSellSwaps(r,s,o);else{let a=i.map(c=>this.toSellSwaps(r,c,o)),l=await Promise.all(a);n=this.findBestSellRoute(l)}return this.buildSell(o,n)})}async getSellTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let o=s.map(a=>this.toSellSwaps(r,a,i));return(await Promise.all(o)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildSell(i,a)).sort((a,l)=>a.amountOut.isGreaterThan(l.amountOut)?-1:1)})}buildSell(e,t){let r=t[0],s=t[t.length-1],i=this.isDirectTrade(t),o=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetOutDecimals)).reduce((b,h)=>b.multipliedBy(h)),n=A(o,s.assetOutDecimals),a=i?s.calculatedOut:this.calculateDelta0Y(r.amountIn,t,e),l=s.amountOut,c=i?s.tradeFeePct:Rt(a,l).toNumber(),u=a.minus(l),p=this.getRouteFeeRange(t),y=r.amountIn.shiftedBy(-1*r.assetInDecimals).multipliedBy(n),g=be(a,y);return{type:"Sell",amountIn:r.amountIn,amountOut:s.amountOut,spotPrice:n,tradeFee:u,tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g.toNumber(),swaps:t,toHuman(){return{type:"Sell",amountIn:I(r.amountIn,r.assetInDecimals),amountOut:I(s.amountOut,s.assetOutDecimals),spotPrice:I(n,s.assetOutDecimals),tradeFee:I(u,s.assetOutDecimals),tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g.toNumber(),swaps:t.map(b=>b.toHuman())}}}}calculateDelta0Y(e,t,r){let s=[];for(let i=0;i<t.length;i++){let o=t[i],n=r.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i>0?l=s[i-1]:l=e;let c=n.calculateOutGivenIn(a,l);s.push(c)}return s[s.length-1]}async calculateMostLiquidRoute(e,t,r){let{paths:s,pools:i,poolsMap:o}=r,c=i.filter(h=>h.tokens.some(S=>S.id===e)).map(h=>h.type==="Aave"?h.tokens:h.tokens.filter(S=>S.id===e)).map(h=>h.map(S=>m(S.balance).shiftedBy(-1*S.decimals)).reduce((S,f)=>S.plus(f))).sort((h,S)=>S.isLessThan(h)?-1:1)[0].div(100).multipliedBy(.1),u=s.map(async h=>await this.toSellSwaps(c,h,o)),p=await Promise.all(u),g=this.findBestSellRoute(p).map(h=>({poolAddress:h.poolAddress,poolId:h?.poolId,pool:h.pool,assetIn:h.assetIn,assetOut:h.assetOut})),b=this.buildRouteKey(e,t,i);return this.mlr.set(b,g),g}async toSellSwaps(e,t,r){let s=[],i=[];for(let a=0;a<t.length;a++){let l=t[a],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let u=c.parsePair(l.assetIn,l.assetOut);s[a]=c,i[a]=u}let o=await Promise.all(i.map((a,l)=>this.poolService.getPoolFees(a,s[l]))),n=[];for(let a=0;a<t.length;a++){let l=t[a],c=s[a],u=o[a],p=i[a],y;a>0?y=n[a-1].amountOut:y=A(m(e),p.decimalsIn).decimalPlaces(0,1);let{amountOut:g,calculatedOut:b,feePct:h,errors:S}=c.validateAndSell(p,y,u),f=this.getPoolFeeRange(u,h),B=c.spotPriceOutGivenIn(p),T=y.shiftedBy(-1*p.decimalsIn).multipliedBy(B),O=be(b,T),w=c.type==="Aave";n.push({...l,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:y,amountOut:g,calculatedOut:b,spotPrice:B,tradeFeePct:h,tradeFeeRange:f,priceImpactPct:O.toNumber(),errors:S,isSupply:()=>w&&c.tokens[0].id===l.assetIn,isWithdraw:()=>w&&c.tokens[1].id===l.assetIn,toHuman(){return{...l,amountIn:I(y,p.decimalsIn),amountOut:I(g,p.decimalsOut),calculatedOut:I(b,p.decimalsOut),spotPrice:I(B,p.decimalsOut),tradeFeePct:h,priceImpactPct:O.toNumber(),errors:S}}})}return n}async getMostLiquidRoute(e,t){return this.withCtx(e,t,async r=>{let s=this.buildRouteKey(e,t,r.pools),i=this.mlr.get(s);return i||this.calculateMostLiquidRoute(e,t,r)})}async getBestSpotPrice(e,t){return this.withCtx(e,t,async r=>{let{pools:s,poolsMap:i}=r,o=this.buildRouteKey(e,t,s),n=this.mlr.get(o);n||(n=await this.calculateMostLiquidRoute(e,t,r));let a=await this.toSellSwaps("1",n,i),l=a.map(p=>p.spotPrice.shiftedBy(-1*p.assetOutDecimals)).reduce((p,y)=>p.multipliedBy(y)),c=a[a.length-1].assetOutDecimals;return{amount:A(l,c),decimals:c}}).catch(()=>{})}findBestBuyRoute(e){let t=e.sort((r,s)=>{let i=r[0].amountIn,o=s[0].amountIn;return i.isGreaterThan(o)?1:-1});return t.find(r=>r.every(s=>s.errors.length==0))||t[0]}async getBestBuy(e,t,r){return this.getBuy(e,t,r)}async getBuy(e,t,r,s){return this.withCtx(e,t,async({paths:i,poolsMap:o})=>{let n;if(s)n=await this.toBuySwaps(r,s,o);else{let a=i.map(c=>this.toBuySwaps(r,c,o)),l=await Promise.all(a);n=this.findBestBuyRoute(l)}return this.buildBuy(o,n)})}async getBuyTrades(e,t,r){return this.withCtx(e,t,async({paths:s,poolsMap:i})=>{let o=s.map(a=>this.toBuySwaps(r,a,i));return(await Promise.all(o)).filter(a=>a.every(l=>l.errors.length==0)).map(a=>this.buildBuy(i,a)).sort((a,l)=>a.amountIn.isGreaterThan(l.amountIn)?1:-1)})}buildBuy(e,t){let r=t[t.length-1],s=t[0],i=this.isDirectTrade(t),o=t.map(b=>b.spotPrice.shiftedBy(-1*b.assetInDecimals)).reduce((b,h)=>b.multipliedBy(h)),n=A(o,s.assetInDecimals),a=i?s.calculatedIn:this.calculateDelta0X(r.amountOut,t,e),l=s.amountIn,c=i?s.tradeFeePct:Nt(a,l).toNumber(),u=l.minus(a),p=this.getRouteFeeRange(t),y=r.amountOut.shiftedBy(-1*r.assetOutDecimals).multipliedBy(n),g;return a.isZero()?g=-100:g=be(y,a).toNumber(),{type:"Buy",amountOut:r.amountOut,amountIn:s.amountIn,spotPrice:n,tradeFee:u,tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g,swaps:t,toHuman(){return{type:"Buy",amountOut:I(r.amountOut,r.assetOutDecimals),amountIn:I(s.amountIn,s.assetInDecimals),spotPrice:I(n,s.assetInDecimals),tradeFee:I(u,s.assetInDecimals),tradeFeePct:c,tradeFeeRange:p,priceImpactPct:g,swaps:t.map(b=>b.toHuman())}}}}calculateDelta0X(e,t,r){let s=[];for(let i=t.length-1;i>=0;i--){let o=t[i],n=r.get(o.poolAddress);if(n==null)throw new Error("Pool does not exit");let a=n.parsePair(o.assetIn,o.assetOut),l;i==t.length-1?l=e:l=s[0];let c=n.calculateInGivenOut(a,l);s.unshift(c)}return s[0]}async toBuySwaps(e,t,r){let s=[],i=[];for(let a=0;a<t.length;a++){let l=t[a],c=r.get(l.poolAddress);if(!c)throw new Error("Pool does not exit");let u=c.parsePair(l.assetIn,l.assetOut);s[a]=c,i[a]=u}let o=await Promise.all(i.map((a,l)=>this.poolService.getPoolFees(a,s[l]))),n=[];for(let a=t.length-1;a>=0;a--){let l=t[a],c=s[a],u=o[a],p=i[a],y;a==t.length-1?y=A(m(e),p.decimalsOut).decimalPlaces(0,1):y=n[0].amountIn;let{amountIn:g,calculatedIn:b,feePct:h,errors:S}=c.validateAndBuy(p,y,u),f=this.getPoolFeeRange(u,h),B=c.spotPriceInGivenOut(p),T=y.shiftedBy(-1*p.decimalsOut).multipliedBy(B),O;b.isZero()?O=-100:O=be(T,b).toNumber(),n.unshift({...l,assetInDecimals:p.decimalsIn,assetOutDecimals:p.decimalsOut,amountIn:g,amountOut:y,calculatedIn:b,spotPrice:B,tradeFeePct:h,tradeFeeRange:f,priceImpactPct:O,errors:S,isSupply(){return c.type==="Aave"&&c.tokens[0].id===l.assetIn},isWithdraw(){return c.type==="Aave"&&c.tokens[1].id===l.assetIn},toHuman(){return{...l,amountIn:I(g,p.decimalsIn),amountOut:I(y,p.decimalsOut),calculatedIn:I(b,p.decimalsIn),spotPrice:I(B,p.decimalsIn),tradeFeePct:h,tradeFeeRange:f,priceImpactPct:O,errors:S}}})}return n}};var Ct=6e3,kt=m(1e15),Pe=6,lt=-5,ct=360*60*1e3,nm=3,_t=6;var q=class{static build(e){return e.map(({assetIn:t,assetOut:r,pool:s,poolId:i})=>s==="Stableswap"?{pool:{Stableswap:i},assetIn:t,assetOut:r}:{pool:s,assetIn:t,assetOut:r})}};var fe=class{schedulerOptions;router;constructor(e,t={}){this.router=e,this.schedulerOptions=Object.freeze({blockTime:t.blockTime??Ct,minBudgetInNative:t.minBudgetInNative??kt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(e,t,r,s,i){let[o,n]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:a,swaps:l,priceImpactPct:c}=n,u=l[0],p=l[l.length-1],{assetInDecimals:y}=u,{assetOutDecimals:g}=p,b=Math.abs(c),h=this.getMinimumTradeCount(a,o),S=this.getOptimalTradeCount(b),f=i?Math.round(s/i):S,B=Math.ceil(s/h),T=Math.round(s/S),O=Math.round(s/f),w=a.dividedBy(f).decimalPlaces(0,1),C=await this.router.getBestSell(e,t,I(w,y)),M=a.isLessThan(o),Be=[];M&&Be.push("OrderTooSmall");let xe=C.amountOut.multipliedBy(f),Qe=this.toBlockPeriod(O),je=C.tradeFee.multipliedBy(f),ze=q.build(l),ve={assetIn:e,assetOut:t,errors:Be,frequencyMin:B,frequencyOpt:T,frequency:O,tradeCount:f,tradeFee:je,tradeImpactPct:C.priceImpactPct,tradePeriod:Qe,tradeRoute:ze,type:"Dca"};return{...ve,amountIn:a,amountOut:xe,tradeAmountIn:C.amountIn,tradeAmountOut:C.amountOut,toHuman(){return{...ve,amountIn:I(a,y),amountOut:I(xe,g),tradeAmountIn:I(C.amountIn,y),tradeAmountOut:I(C.amountOut,g)}}}}async getMinimumOrderBudget(e){if("0"===e)return this.minOrderBudget;let t=await this.router.getBestSpotPrice("0",e);if(t)return this.minOrderBudget.times(t.amount).div(m(10).pow(12)).decimalPlaces(0,1);let r=await this.router.getBestSpotPrice(e,"0");if(r)return this.minOrderBudget.times(m(10).pow(12)).div(r.amount).decimalPlaces(0,1);throw new Error("Unable to calculate order budget")}getMinimumTradeCount(e,t){let r=t.multipliedBy(.2),s=e.dividedBy(r).toNumber();return Math.round(s)}getOptimalTradeCount(e){let t=Math.round(e*10)||1;return Math.max(t,3)}async getTwapSellOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestSell(e,t,r)]),{amountIn:o,swaps:n,priceImpactPct:a}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,y=Math.abs(a),g=this.getTwapTradeCount(y),b=o.dividedBy(g).decimalPlaces(0,1),h=await this.router.getBestSell(l.assetIn,c.assetOut,I(b,u)),S=g===1,f=o.isLessThan(s),B=h.priceImpactPct<lt,T=[];f||S?T.push("OrderTooSmall"):B&&T.push("OrderImpactTooBig");let O=h.amountOut.multipliedBy(g),w=h.tradeFee.multipliedBy(g),C=q.build(n),M={assetIn:e,assetOut:t,errors:T,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:Pe,tradeRoute:C,type:"TwapSell"};return{...M,amountIn:o,amountOut:O,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:w,toHuman(){return{...M,amountIn:I(o,u),amountOut:I(O,p),tradeAmountIn:I(h.amountIn,u),tradeAmountOut:I(h.amountOut,p),tradeFee:I(w,p)}}}}async getTwapBuyOrder(e,t,r){let[s,i]=await Promise.all([this.getMinimumOrderBudget(e),this.router.getBestBuy(e,t,r)]),{amountOut:o,swaps:n,priceImpactPct:a}=i,l=n[0],c=n[n.length-1],{assetInDecimals:u}=l,{assetOutDecimals:p}=c,y=Math.abs(a),g=this.getTwapTradeCount(y),b=o.dividedBy(g).decimalPlaces(0,1),h=await this.router.getBestBuy(l.assetIn,c.assetOut,I(b,p)),S=h.amountIn.multipliedBy(g),f=g===1,B=S.isLessThan(s),T=h.priceImpactPct<lt,O=[];B||f?O.push("OrderTooSmall"):T&&O.push("OrderImpactTooBig");let w=h.tradeFee.multipliedBy(g),C=q.build(n),M={assetIn:e,assetOut:t,errors:O,tradeCount:g,tradeImpactPct:h.priceImpactPct,tradePeriod:Pe,tradeRoute:C,type:"TwapBuy"};return{...M,amountIn:S,amountOut:o,tradeAmountIn:h.amountIn,tradeAmountOut:h.amountOut,tradeFee:w,toHuman(){return{...M,amountIn:I(S,u),amountOut:I(o,p),tradeAmountIn:I(h.amountIn,u),tradeAmountOut:I(h.amountOut,p),tradeFee:I(w,u)}}}}getTwapTradeCount(e){let t=this.getOptimalTradeCount(e);if(this.getTwapExecutionTime(t)>ct){let s=ct/(this.blockTime*Pe);return Math.round(s)}return t}getTwapExecutionTime(e){return e*Pe*this.blockTime}toBlockPeriod(e){let t=e/this.blockTime,r=Math.round(t);return Math.max(r,_t)}};var te=class extends _{evm;evmClient;balanceClient;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balanceClient=new G(e),this.aaveUtils=new $(t)}wrapTx(e,t,r){return{hex:t.toHex(),name:e,extraGas:r,get:()=>t,dryRun:s=>this.dryRun(s,t)}}async dryRun(e,t){let r=this.api.call.dryRunApi.dryRunCall,s=[{System:{Signed:e}},t.inner.toHex(),4],i;try{i=await r(...s)}catch(o){throw console.error(o),new Error("Dry run execution failed!")}if(i.isOk)return i.asOk;throw console.log(i.asErr.toHuman()),new Error("Dry run execution error!")}dispatchWithExtraGas(e){return this.api.tx.dispatcher.dispatchWithExtraGas(e.inner.toHex(),J)}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var Ke=class extends te{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:r}=this.trade;if(r==="Buy")return this.buildBuyTx();let s=t[0],{assetIn:i,assetOut:o}=s,a=(await this.balanceClient.getBalance(this.beneficiary,i)).minus(5),l=!0;return s.isWithdraw()&&(l=(await this.aaveUtils.getMaxWithdraw(this.beneficiary,o)).amount.isGreaterThanOrEqualTo(a)),l&&e.isGreaterThanOrEqualTo(a)?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],o=z(e,this.slippagePct),n=s.assetIn,a=i.assetOut,l=e.plus(o),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.buy(a,n,t.toFixed(),l.toFixed()):c=this.api.tx.router.buy(n,a,t.toFixed(),l.toFixed(),q.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let p=this.dispatchWithExtraGas(c);return this.wrapTx("RouterBuy",p,J)}return this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:r}=this.trade,s=r[0],i=r[r.length-1],o=z(t,this.slippagePct),n=s.assetIn,a=i.assetOut,l=t.minus(o),c;if(this.isDirectOmnipoolTrade(r)?c=this.api.tx.omnipool.sell(n,a,e.toFixed(),l.toFixed()):c=this.api.tx.router.sell(n,a,e.toFixed(),l.toFixed(),q.build(r)),await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let p=this.dispatchWithExtraGas(c);return this.wrapTx("RouterSell",p,J)}return this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,r=t[0],s=t[t.length-1],i=z(e,this.slippagePct),o=r.assetIn,n=s.assetOut,a=e.minus(i),l=this.api.tx.router.sellAll(o,n,a.toFixed(),q.build(t));if(await this.aaveUtils.hasBorrowPositions(this.beneficiary)){let u=this.dispatchWithExtraGas(l);return this.wrapTx("RouterSellAll",u,J)}return this.wrapTx("RouterSellAll",l)}};var $e=class extends te{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradePeriod:i,tradeRoute:o}=this.order,n=this.api.tx.dca.schedule({owner:this.beneficiary,period:i,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:"0",route:o}}},null);return this.wrapTx("DcaSchedule",n)}buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:o,tradeRoute:n}=this.order,a=z(i,this.slippagePct),l=i.minus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Sell:{assetIn:t,assetOut:r,amountIn:s.toFixed(),minAmountOut:l.toFixed(),route:n}}},null);return this.wrapTx("DcaSchedule.twapSell",c)}buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:r,tradeAmountIn:s,tradeAmountOut:i,tradePeriod:o,tradeRoute:n}=this.order,a=z(s,this.slippagePct),l=s.plus(a),c=this.api.tx.dca.schedule({owner:this.beneficiary,period:o,maxRetries:this.maxRetries,totalAmount:e.toFixed(),slippage:this.slippagePct*1e4,order:{Buy:{assetIn:t,assetOut:r,amountOut:i.toFixed(),maxAmountIn:l.toFixed(),route:n}}},null);return this.wrapTx("DcaSchedule.twapBuy",c)}};var Se=class{api;evm;constructor(e,t){this.api=e,this.evm=t}trade(e){return new Ke(this.api,this.evm).setTrade(e)}order(e){return new $e(this.api,this.evm).setOrder(e)}};var fs={router:{}};function sp(d,e=fs){let t=new ne(d),r=new Ce(d),s=new me(d,r),i=new $(r),o=new ee(s,e.router),n=new ee(s,{exclude:["Hsm"]}),a=new fe(n,{blockTime:t.blockTime,minBudgetInNative:t.minOrderBudget});return{api:{aave:i,router:o,scheduler:a},client:{asset:new Q(d),balance:new G(d),balanceV2:new ae(d)},ctx:{pool:s},evm:r,tx:new Se(d,r),destroy:()=>{s.destroy()}}}export{re as AaveClient,ke as AavePool,De as AavePoolClient,$ as AaveUtils,Q as AssetClient,ft as AssetNotFound,Ns as BASILISK_PARACHAIN_ID,G as BalanceClient,ae as BalanceClientV2,v as BigNumber,me as CachingPoolService,ne as ChainParams,Kt as DECIMAL_PLACES,Ct as DEFAULT_BLOCK_TIME,kt as DEFAULT_MIN_BUDGET,H as ERC20,Ce as EvmClient,Ee as EvmRpcAdapter,st as FarmClient,V as H160,Te as HUB_ASSET_ID,Es as HYDRADX_PARACHAIN_ID,L as HYDRADX_SS58_PREFIX,qs as INFINITY,W as LbpMath,Me as LbpPool,Le as LbpPoolClient,oe as MmOracleClient,N as ONE,_t as ORDER_MIN_BLOCK_PERIOD,F as OmniMath,He as OmniPool,Ue as OmniPoolClient,mt as PERBILL_DENOMINATOR,K as PERMILL_DENOMINATOR,_ as PolkadotApiClient,Pt as PoolConfigNotFound,j as PoolError,pe as PoolFactory,Re as PoolNotFound,ue as PoolService,E as PoolType,xt as ProviderConfigNotFound,se as RUNTIME_DECIMALS,Ne as RouteNotFound,ye as Router,tt as SYSTEM_ASSET_DECIMALS,R as SYSTEM_ASSET_ID,k as StableMath,Z as StableSwap,Ve as StableSwapClient,St as StorageConfigNotFound,Bt as SubscriptionNotSupported,ie as TRADEABLE_DEFAULT,Pe as TWAP_BLOCK_PERIOD,ct as TWAP_MAX_DURATION,lt as TWAP_MAX_PRICE_IMPACT,nm as TWAP_TX_MULTIPLIER,Et as TradeOrderError,ot as TradeOrderType,q as TradeRouteBuilder,ee as TradeRouter,fe as TradeScheduler,nt as TradeType,Se as TxBuilderFactory,Y as XykMath,qe as XykPool,We as XykPoolClient,x as ZERO,Na as bnFormatter,m as bnum,Nt as calculateBuyFee,Mu as calculateDiffToAvg,be as calculateDiffToRef,Rt as calculateSellFee,vt as createChain,sp as createSdkContext,_e as findNestedKey,Ra as findNestedObj,z as getFraction,Kc as hashPools,Vt as isEvmAccount,Xt as isEvmAddress,Yt as isSs58Address,A as scale,Ws as toBn,I as toDecimals};
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
export declare class OmniMath {
|
|
2
2
|
static calculateSpotPrice(assetInBalance: string, assetInHubReserve: string, assetOutBalance: string, assetOutHubReserve: string): string;
|
|
3
3
|
static calculateLrnaSpotPrice(assetBalance: string, assetHubReserve: string): string;
|
|
4
|
-
static calculateInGivenOut(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, protocolFee: string): string;
|
|
5
|
-
static calculateLrnaInGivenOut(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
|
|
6
|
-
static calculateOutGivenIn(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountIn: string, assetFee: string, protocolFee: string): string;
|
|
7
|
-
static calculateOutGivenLrnaIn(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string): string;
|
|
4
|
+
static calculateInGivenOut(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, protocolFee: string, maxSlipFee: string): string;
|
|
5
|
+
static calculateLrnaInGivenOut(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, maxSlipFee: string): string;
|
|
6
|
+
static calculateOutGivenIn(assetInBalance: string, assetInHubReserve: string, assetInShares: string, assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountIn: string, assetFee: string, protocolFee: string, maxSlipFee: string): string;
|
|
7
|
+
static calculateOutGivenLrnaIn(assetOutBalance: string, assetOutHubReserve: string, assetOutShares: string, amountOut: string, assetFee: string, maxSlipFee: string): string;
|
|
8
8
|
static calculateShares(assetReserve: string, assetHubReserve: string, assetShares: string, amountIn: string): string;
|
|
9
9
|
static calculateLiquidityOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
|
|
10
10
|
static calculateLiquidityLRNAOut(assetReserve: string, assetHubReserve: string, assetShares: string, positionAmount: string, positionShares: string, positionPrice: string, sharesToRemove: string, withdrawalFee: string): string;
|
|
@@ -10,6 +10,7 @@ export declare class OmniPoolClient extends PoolClient {
|
|
|
10
10
|
private memOracleQuery;
|
|
11
11
|
private memFeesQuery;
|
|
12
12
|
private memFeesConfigurationQuery;
|
|
13
|
+
private memSlipFeeQuery;
|
|
13
14
|
getPoolType(): PoolType;
|
|
14
15
|
private getPoolId;
|
|
15
16
|
private getOracleKey;
|
|
@@ -20,6 +21,8 @@ export declare class OmniPoolClient extends PoolClient {
|
|
|
20
21
|
isSupported(): boolean;
|
|
21
22
|
isAssetConfigSupported(): boolean;
|
|
22
23
|
loadPools(): Promise<PoolBase[]>;
|
|
24
|
+
isSlipFeeSupported(): boolean;
|
|
25
|
+
private getMaxSlipFee;
|
|
23
26
|
getPoolFees(block: number, poolPair: PoolPair, _poolAddress: string): Promise<OmniPoolFees>;
|
|
24
27
|
private getAssetFee;
|
|
25
28
|
private getProtocolFee;
|