@galacticcouncil/sdk-next 1.5.0 → 1.5.1
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/client/index.cjs +1 -1
- package/build/client/index.mjs +1 -1
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.mjs +1 -1
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +1 -1
package/build/pool/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var $t=Object.defineProperty;var F=(u,e)=>{for(var t in e)$t(u,t,{get:e[t],enumerable:!0})};import Wt from"buffer";typeof window<"u"&&(window.Buffer=Wt.Buffer);var yt={};F(yt,{LbpMath:()=>O,LbpPool:()=>se,LbpPoolClient:()=>ue});import{calculate_in_given_out as Yt,calculate_out_given_in as Xt,calculate_linear_weights as Kt,calculate_pool_trade_fee as zt,get_spot_price as jt}from"@galacticcouncil/math-lbp";var O=class{static getSpotPrice(e,t,a,i,s){return jt(e,t,a,i,s)}static calculateInGivenOut(e,t,a,i,s){return Yt(e,t,a,i,s)}static calculateOutGivenIn(e,t,a,i,s){return Xt(e,t,a,i,s)}static calculateLinearWeights(e,t,a,i,s){return Kt(e,t,a,i,s)}static calculatePoolTradeFee(e,t,a){return zt(e,t,a)}};import{big as st,RUNTIME_DECIMALS as nt}from"@galacticcouncil/common";var f=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n.HSM="HSM",n))(f||{}),H=(l=>(l.UnknownError="UnknownError",l.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",l.InsufficientTradingAmount="InsufficientTradingAmount",l.InsufficientCollateral="InsufficientCollateral",l.MaxHoldingExceeded="MaxHoldingExceeded",l.MaxInRatioExceeded="MaxInRatioExceeded",l.MaxOutRatioExceeded="MaxOutRatioExceeded",l.TradeNotAllowed="TradeNotAllowed",l.MaxBuyBackExceeded="MaxBuyBackExceeded",l.MaxBuyPriceExceeded="MaxBuyPriceExceeded",l))(H||{});var xe={};F(xe,{withTimeout:()=>Qt});function Qt(u,e,t="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(t)),e);u.then(n=>{clearTimeout(s),a(n)},n=>{clearTimeout(s),i(n)})})}import{RUNTIME_DECIMALS as en}from"@galacticcouncil/common";var y={};F(y,{FeeUtils:()=>He,shiftNeg:()=>ta});import ea from"big.js";var He=class u{static toPct(e){let[t,a]=e;return u.safeDivide(t*100,a)}static toRaw(e){let[t,a]=e;return u.safeDivide(t,a)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,a=12){let i=10**a;return Math.round(e*i/t)/i}static safeRound(e){return parseFloat(e.toPrecision(15))}};function ta(u,e){let t=ea(typeof u=="bigint"?u.toString():u);return e===0?t.toString():t.div(Math.pow(10,e)).toString()}var ie={};F(ie,{findNestedKey:()=>aa,findNestedObj:()=>ia,jsonFormatter:()=>sa});var aa=(u,e)=>{let t=[];return JSON.stringify(u,(a,i)=>(i&&i[e]&&t.push(i),i)),t[0]},ia=(u,e,t)=>{let a;return JSON.stringify(u,(i,s)=>(s&&s[e]===t&&(a=s),s)),a},sa=(u,e)=>typeof e=="bigint"?e.toString():e;var L={};F(L,{calculateBuyFee:()=>la,calculateDiffToAvg:()=>na,calculateDiffToRef:()=>ra,calculateSellFee:()=>oa});import k from"big.js";function na(u,e){let t=k(u.toString()),a=k(e.toString());return t.minus(a).abs().div(t.plus(a).div(2)).mul(100).round(2).toNumber()}function ra(u,e){if(e===0n)return 0;let t=k(u.toString()),a=k(e.toString());return t.minus(a).div(a).mul(100).round(2).toNumber()}function oa(u,e){if(u===0n)return 0;let t=k(u.toString()),a=k(e.toString());return k(1).minus(a.div(t)).mul(100).round(2).toNumber()}function la(u,e){if(u===0n)return 0;let t=k(u.toString());return k(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as it}from"@thi.ng/cache";var $=class{debug;constructor(e){this.debug=e||!1}log(e,t,a){this.debug&&console.log(e,t,a)}scope(e,t,a,i){let s=new Map,n=i!==void 0?new it(null,{ttl:i}):new it;return{get:(...l)=>{let p=a(...l);if(s.has(p)){this.log("[live]",e,p);let d=s.get(p);return Promise.resolve(d)}if(n.has(p))return this.log("[memo]",e,p),n.get(p);this.log("[fetch]",e,p);let m=t(...l).catch(d=>{throw n.delete(p),d});return n.set(p,m),m},set:(l,...p)=>{let m=a(...p);this.log("[set-live]",e,m),s.set(m,l)},clear:()=>{this.log("[clear]",e),s.clear(),n.release()}}}};var{FeeUtils:rt}=y,se=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,weightIn:i.weight,weightOut:s.weight}}validateAndBuy(e,t,a){let i=this.tokens[0].id,s=[];t<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=e.balanceOut/this.maxOutRatio;if(t>n&&s.push("MaxOutRatioExceeded"),i===e.assetOut){let r=this.calculateTradeFee(t,a),o=rt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),c=t+r,l=this.calculateInGivenOut(e,c),p=e.balanceIn/this.maxInRatio;return l>p&&s.push("MaxInRatioExceeded"),{amountIn:l,calculatedIn:l,amountOut:t,feePct:o,errors:s}}else{let r=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return r>o&&s.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}}validateAndSell(e,t,a){let i=this.tokens[0].id,s=[];t<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=e.balanceIn/this.maxInRatio;if(t>n&&s.push("MaxInRatioExceeded"),i===e.assetIn){let r=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return r>o&&s.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}else{let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,a),c=rt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),l=r-o,p=e.balanceOut/this.maxOutRatio;return l>p&&s.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:l,feePct:c,errors:s}}}calculateInGivenOut(e,t){let a=O.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(e,t){let a=O.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(e){let t=O.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),st.toBigInt(1,nt).toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=O.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),st.toBigInt(1,nt).toString());return BigInt(t)}calculateTradeFee(e,t){let a=O.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(a)}};import{CompatibilityLevel as Za}from"polkadot-api";import{Subscription as ei,distinctUntilChanged as ti,filter as ai,map as ii}from"rxjs";import{memoize1 as Ha}from"@thi.ng/memoize";import{TLRUCache as Na}from"@thi.ng/cache";import{ReplaySubject as gt,Subscription as bt,combineLatest as qa,defer as Ga,from as Va,interval as Ua,merge as qe,of as $a,EMPTY as le}from"rxjs";import{bufferCount as Wa,bufferTime as Ya,catchError as ce,filter as Be,finalize as Ge,map as X,pairwise as Ve,repeat as Ue,skip as Xa,share as Ka,startWith as za,switchMap as ht,tap as N,throttleTime as ja}from"rxjs/operators";import{hydration as Aa,hydrationNext as Ia,hydrationIce as wa}from"@galacticcouncil/descriptors";import{log as Pa}from"@galacticcouncil/common";import{map as va,shareReplay as Sa,tap as Ta}from"rxjs";import{defer as ca,from as ua,of as ot,timer as pa}from"rxjs";import{catchError as ma,distinctUntilChanged as da,expand as ga,map as Ne,shareReplay as ba,skip as ha,switchMap as ya,timeout as fa}from"rxjs/operators";function lt(u,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let a=()=>ca(()=>ua(u._request("system_health",[]))).pipe(fa({first:t}),Ne(()=>"online"),ma(()=>ot("offline")));return ot({state:"offline",delayMs:0}).pipe(ga(s=>pa(s.delayMs).pipe(ya(a),Ne(n=>({state:n,delayMs:e})))),ha(1),Ne(s=>s.state),da(),ba({bufferSize:1,refCount:!0}))}var{logger:xa}=Pa,Ae=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(va(({value:t})=>t))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",lt(e))}static getInstance(e){return this.instance||(this.instance=new u(e)),this.instance}watched(e,t){return t.pipe(Ta({error:a=>xa.error(e,a)}),Sa({bufferSize:1,refCount:!0}))}};var _=class{client;api;apiNext;apiIce;watcher;at;constructor(e,t){this.client=e,this.api=this.client.getTypedApi(Aa),this.apiNext=this.client.getTypedApi(Ia),this.apiIce=this.client.getTypedApi(wa),this.watcher=Ae.getInstance(this.client),this.at=t??"best"}};import{getWsProvider as Xn}from"polkadot-api/ws";import{withLogsRecorder as zn}from"polkadot-api/logs-provider";import{Binary as ur}from"polkadot-api";import{log as Oa}from"@galacticcouncil/common";import{combineLatest as Ba,concat as Fa,defer as ne,from as ct}from"rxjs";import{bufferCount as ut,distinctUntilChanged as pt,debounceTime as _a,map as W,retry as Ea,startWith as mt,switchMap as dt,tap as re,take as Ra,skip as ka,connect as Ca}from"rxjs/operators";var{logger:Y}=Oa,oe=class extends _{erc20Ids=null;constructor(e,t){super(e,t)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:a}=await t.getValue(e,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(e,t){let i=await this.api.query.Tokens.Accounts.getValue(e,t,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return ne(()=>{let t=this.watchSystemBalance(e),a=this.watchTokensBalance(e),i=this.watchErc20Balance(e);return Ba([t,a,i]).pipe(Ca(s=>Fa(s.pipe(Ra(1)),s.pipe(ka(1),_a(250)))))}).pipe(W(t=>t.flat()),mt([]),ut(2,1),W(([t,a],i)=>i===0?a:this.getDeltas(t,a))).pipe(re({subscribe:()=>Y.debug("balance: subscribe",e),error:t=>Y.error("balance",t)}),Ea({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return ne(()=>t.watchValue(e,{at:"best"})).pipe(W(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),re({error:a=>Y.error("balance(system)",a)}))}watchTokenBalance(e,t){let a=this.api.query.Tokens.Accounts;return ne(()=>a.watchValue(e,t,{at:"best"})).pipe(W(({value:i})=>({id:t,balance:this.getBreakdown(i)})),re({error:i=>Y.error("balance(token)",i)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return ne(()=>t.watchEntries(e,{at:"best"})).pipe(pt((a,i)=>!i.deltas),W(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown(s.value)})}),i}),re({error:a=>Y.error("balance(tokens)",a)}))}watchErc20Balance(e,t){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(e,r)]))).map(([r,o])=>({id:r,balance:o}));return ne(()=>ct(t?Promise.resolve(t):a()).pipe(dt(s=>this.watcher.bestBlock$.pipe(dt(()=>ct(i(s))))),mt([]),ut(2,1),W(([s,n],r)=>r===0?n.filter(o=>o.balance.total>0n):this.getDeltas(s,n)),pt((s,n)=>n.length===0),re({error:s=>Y.error("balance(erc20)",s)})))}async getBalanceData(e,t){let a=await this.api.apis.CurrenciesApi.account(t,e,{at:this.at});return this.getBreakdown(a)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,a=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:a,transferable:t}}getDeltas(e,t){let a=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,i=e.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return t.filter(s=>!a(s.balance,i.get(s.id)))}};import{BehaviorSubject as Ma}from"rxjs";var Ie=class{store$=new Ma([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(e){return this.changeset.size===0?[]:e.filter(t=>this.changeset.has(t.address))}set(e){this.changeset=new Set(e.map(t=>t.address)),this.store$.next(e)}update(e){this.updateQueue=this.updateQueue.then(async()=>{let t=this.store$.value,a=new Map(t.map((r,o)=>[r.address,o])),i=await e(t),s=t.slice(),n=new Set;for(let r of i){let o=a.get(r.address);o===void 0?(a.set(r.address,s.length),s.push(r)):s[o]=r,n.add(r.address)}this.changeset=n,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};import{log as La}from"@galacticcouncil/common";var Da={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:we}=La,Oe=class{type;constructor(e){this.type=e}prefix(){return this.pad(`pool(${Da[this.type]})`,10)}trace(e,...t){we.trace(`${this.prefix()} ${e} :`,...t)}debug(e,...t){we.debug(`${this.prefix()} ${e} :`,...t)}info(e,...t){we.info(`${this.prefix()} ${e} :`,...t)}error(e,...t){we.error(`${this.prefix()} ${e} :`,...t)}pad(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}};var{withTimeout:Qa}=xe,Ja=3e3,S=class extends _{evm;balance;store=new Ie;log;shared$;resync$=new gt(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new Na(null,{ttl:6*1e3});memPools=Ha(e=>(this.log.info("pool_sync",{mem:e}),this.loadPools()),this.memPoolsCache);constructor(e,t,a){super(e,a),this.evm=t,this.balance=new oe(e,a),this.log=new Oe(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let t=(await this.getMemPools()).filter(a=>this.hasValidAssets(a));return this.store.set(t),t}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe(za([]),Wa(2,1),X(([e,t])=>e.length===0?t:this.store.applyChangeset(t)),Be(e=>e.length>0),ja(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return Ga(()=>{let e=new bt;return e.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe(ht(()=>{let t=new bt;return Va(Qa(this.getMemPools(),6e4,"getMemPools stalled")).pipe(N(()=>this.log.info("pool_synced",{mem:this.mem})),X(i=>i.filter(s=>this.hasValidAssets(s))),N(i=>this.store.set(i)),ce(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),le))).pipe(N(()=>{t.add(this.subscribeBalances()),t.add(this.subscribeUpdates())}),ht(i=>qe($a(i),this.store.asObservable().pipe(Xa(1)))),Ge(()=>{t.unsubscribe()}))}),Ge(()=>e.unsubscribe()))}).pipe(Ka({connector:()=>new gt(1),resetOnRefCountZero:!0}))}subscribeBalances(){let e=this.store.pools.map(t=>{let{address:a}=t,i=[this.balance.watchTokensBalance(a)];if(this.hasSystemAsset(t)){let s=this.balance.watchSystemBalance(a);i.push(s)}if(this.hasErc20Asset(t)){let s=t.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),n=this.balance.watchErc20Balance(a,s);i.push(n)}return qa(i).pipe(X(s=>s.flat()),Ve(),X(([s,n])=>this.balance.getDeltas(s,n)),Be(s=>s.length>0),X(s=>[a,s]))});return qe(...e).pipe(Ya(250),Be(t=>t.length>0),X(t=>new Map(t)),this.watchGuard("balances")).subscribe(t=>{this.store.update(a=>this.updateBalances(a,t))})}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({decimals:t,balance:a})=>e.type==="XYK"?a>0n&&!!t:!!t)}updateBalances=(e,t)=>{let a=[],i=new Map(e.map(s=>[s.address,s]));for(let[s,n]of t){let r=i.get(s);if(r){let o=r.tokens.map(c=>{let l=n.find(p=>p.id===c.id);return l&&c.id!==r.id?{...c,balance:l.balance.transferable}:c});a.push({...r,tokens:o})}}return a};resync(e=!1){let t=Date.now();!e&&t-this.resyncAt<Ja||(this.resyncAt=t,this.mem++,this.resync$.next())}requestResync(e=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(e)},0))}startWatchdog(){let i=this.watcher.connection$.pipe(Ve(),Be(([r,o])=>r==="offline"&&o==="online"),N(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),ce(r=>(this.log.error("watchdog_recovery_error",r),le)),Ue({delay:1e3})),s=this.watcher.finalizedBlock$.pipe(Ve(),N(([r,o])=>{let c=Number(r.number),l=Number(o.number),p=l-c;p>=3&&(this.log.debug("watchdog_gap",{from:c,to:l,gap:p}),this.requestResync())}),ce(r=>(this.log.error("watchdog_gap_error",r),le)),Ue({delay:1e3})),n=Ua(36e5).pipe(N(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),ce(r=>(this.log.error("watchdog_periodic_error",r),le)),Ue({delay:1e3}));return qe(i,s,n).subscribe()}watchGuard(e){return t=>t.pipe(N({error:a=>{this.log.error(e,a),this.requestResync(!0)}}),Ge(()=>{this.log.debug(e,"unsub")}),ce(()=>le))}};var ue=class extends S{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[e,t,a]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:a}}getPoolWeights(e,t){let{start:a,end:i,initial_weight:s,final_weight:n}=e,r=O.calculateLinearWeights(a?a.toString():"0",i?i.toString():"0",s.toString(),n.toString(),t.toString()),o=BigInt(r),c=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,c]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Za.BackwardsCompatible)}async loadPools(){let[e,t,a]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),this.getPoolLimits()]),i=t?.relay_parent_number||0,s=e.filter(({value:n})=>t&&this.isActivePool(n,i)).map(async({keyArgs:n,value:r})=>{let[o]=n,c=o.toString(),l=await this.getPoolDelta(c,r,i);return{address:c,type:"LBP",fee:r.fee,...l,...a}});return Promise.all(s)}async getPoolDelta(e,t,a){let{assets:i,repay_target:s,fee_collector:n}=t,[r,o]=this.getPoolWeights(t,a),[c,l]=i,[p,m,d,g,b]=await Promise.all([this.isRepayFeeApplied(c,s,n.toString()),this.balance.getBalance(e,c),this.api.query.AssetRegistry.Assets.getValue(c,{at:this.at}),this.balance.getBalance(e,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:c,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:m.transferable,weight:r,type:d?.asset_type.type},{id:l,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(e,t){let{start:a,end:i}=e;return a&&i?t>=a&&t<i:!1}async isRepayFeeApplied(e,t,a){if(t===0n)return!1;try{return(await this.balance.getBalance(a,e)).transferable<t}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(e,t){let a=this.store.pools.find(s=>s.address===t);return{repayFee:await this.getRepayFee(),exchangeFee:a.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe(ii(({value:e})=>e),ai(e=>e!==void 0),ti((e,t)=>e.relay_parent_number===t.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:e})=>{this.store.update(async t=>{let a=[];for(let i of t){let s=this.poolsData.get(i.address);if(s){let{assets:n,repay_target:r,fee_collector:o}=s,[c]=n,[l,p]=this.getPoolWeights(s,e),[m,d]=i.tokens,g=[{...m,weight:l},{...d,weight:p}],b=await this.isRepayFeeApplied(c,r,o.toString());a.push({...i,tokens:g,repayFeeApply:b})}}return a})})}subscribeUpdates(){let e=new ei;return e.add(this.subscribeValidationData()),e}};var St={};F(St,{OmniMath:()=>h,OmniPool:()=>pe,OmniPoolClient:()=>me,OmniPoolFee:()=>q,getEmaKey:()=>_e,getEmaPair:()=>z});import{calculate_in_given_out as si,calculate_lrna_in_given_out as ni,calculate_out_given_in as ri,calculate_out_given_lrna_in as oi,calculate_spot_price as li,calculate_lrna_spot_price as ci,calculate_shares as ui,calculate_liquidity_out as pi,calculate_liquidity_lrna_out as mi,verify_asset_cap as di,calculate_liquidity_hub_in as gi,is_sell_allowed as bi,is_buy_allowed as hi,is_add_liquidity_allowed as yi,is_remove_liquidity_allowed as fi,recalculate_asset_fee as Pi,recalculate_protocol_fee as vi}from"@galacticcouncil/math-omnipool";import K from"big.js";var h=class{static calculateSpotPrice(e,t,a,i){return li(e,t,a,i)}static calculateLrnaSpotPrice(e,t){return ci(e,t)}static calculateInGivenOut(e,t,a,i,s,n,r,o,c,l){return si(e,t,a,i,s,n,r,o,c,l)}static calculateLrnaInGivenOut(e,t,a,i,s,n){return ni(e,t,a,i,s,n)}static calculateOutGivenIn(e,t,a,i,s,n,r,o,c,l){return ri(e,t,a,i,s,n,r,o,c,l)}static calculateOutGivenLrnaIn(e,t,a,i,s,n){return oi(e,t,a,i,s,n)}static calculateShares(e,t,a,i){return ui(e,t,a,i)}static calculateLiquidityOut(e,t,a,i,s,n,r,o){return pi(e,t,a,i,s,n,r,o)}static calculateLiquidityLRNAOut(e,t,a,i,s,n,r,o){return mi(e,t,a,i,s,n,r,o)}static calculateCapDifference(e,t,a,i){let s=K(t),n=K(e),r=K(i),o=K(a),c=K(10).pow(18),l=o.div(c);if(s.div(r).lt(l)){let m=l.times(r).minus(s).times(n),d=s.times(K(1).minus(l));return m.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,a,i){return gi(e,t,a,i)}static isSellAllowed(e){return bi(e)}static isBuyAllowed(e){return hi(e)}static isAddLiquidityAllowed(e){return yi(e)}static isRemoveLiquidityAllowed(e){return fi(e)}static recalculateAssetFee(e,t,a,i,s,n,r,o,c,l,p){return Pi(e,t,a,i,s,n,r,o,c,l,p)}static recalculateProtocolFee(e,t,a,i,s,n,r,o,c,l,p){return vi(e,t,a,i,s,n,r,o,c,l,p)}static verifyAssetCap(e,t,a,i){return di(e,t,a,i)}};import{big as Si}from"@galacticcouncil/common";var{FeeUtils:R}=y,pe=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,hubReservesIn:i.hubReserves,hubReservesOut:s.hubReserves,sharesIn:i.shares,sharesOut:s.shares,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,tradeableIn:i.tradeable,tradeableOut:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=this.calculateInGivenOut(e,t,a),n=i===0n?0:L.calculateBuyFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetInEd)&&r.push("InsufficientTradingAmount");let l=e.balanceOut/this.maxOutRatio;t>l&&r.push("MaxOutRatioExceeded");let p=e.balanceIn/this.maxInRatio;return s>p&&r.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:t,feePct:n,errors:r}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=this.calculateOutGivenIn(e,t,a),n=L.calculateSellFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetOutEd)&&r.push("InsufficientTradingAmount");let l=e.balanceIn/this.maxInRatio;t>l&&r.push("MaxInRatioExceeded");let p=e.balanceOut/this.maxOutRatio;return s>p&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:s,feePct:n,errors:r}}calculateInGivenOut(e,t,a){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,a);let i=h.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.protocolFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateLrnaInGivenOut(e,t,a){let i=h.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(e,t,a){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,a);let i=h.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.protocolFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenLrnaIn(e,t,a){let i=h.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=h.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return this.normalizeSpot(BigInt(t),e.decimalsOut,e.decimalsIn)}spotPriceLrnaInGivenOut(e){let t=h.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsOut,e.decimalsIn)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=h.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsIn,e.decimalsOut)}spotPriceOutGivenLrnaIn(e){let t=h.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsIn,e.decimalsOut)}normalizeSpot(e,t,a){let i=t-a;if(i===0)return e;let s=Si.pow10(Math.abs(i));return i>0?e*s:e/s}};import{AccountId as Ti,Binary as ft,CompatibilityLevel as xi,Enum as Ai}from"polkadot-api";import{toHex as Ii}from"@polkadot-api/utils";import{Subscription as wi,distinctUntilChanged as $e,filter as Oi,finalize as We,map as j,merge as Bi,tap as Ee}from"rxjs";import{HYDRATION_SS58_PREFIX as Fi}from"@galacticcouncil/common";var{FeeUtils:v}=y,q=class u{static compute(e,t,a,i,s,n,r,o){let c=e.assetIn,[l,p,m]=u.getAssetFee(e,t,a,i,n),d=0,g=0,b=0;c!==1&&([d,g,b]=u.getProtocolFee(e,t,a,s,r));let B=l+d,x=m+b;return{assetFee:v.fromPermill(p),protocolFee:v.fromPermill(g),maxSlipFee:v.fromPermill(o),min:v.fromPermill(B),max:v.fromPermill(x)}}static getAssetFee(e,t,a,i,s){let{assetOut:n,balanceOut:r}=e,{min_fee:o,max_fee:c,decay:l,amplification:p}=s;if(!a||!i)return[o,o,c];let m=v.fromPermill(o),d=v.fromPermill(c),[g]=i,{asset_fee:b,timestamp:B}=a,x=Math.max(1,t-B),A=g.volume.b_in.toString(),I=g.volume.b_out.toString(),w=g.liquidity.b.toString();n===0&&(A=g.volume.a_in.toString(),I=g.volume.a_out.toString(),w=g.liquidity.a.toString());let D=v.fromPermill(b),ae=h.recalculateAssetFee(A,I,w,"9",r.toString(),v.toRaw(D).toString(),x.toString(),v.toRaw(m).toString(),v.toRaw(d).toString(),l.toString(),p.toString());return[o,Number(ae)*1e6,c]}static getProtocolFee(e,t,a,i,s){let{assetIn:n,balanceIn:r}=e,{min_fee:o,max_fee:c,decay:l,amplification:p}=s;if(!a||!i)return[o,o,c];let m=v.fromPermill(o),d=v.fromPermill(c),[g]=i,{protocol_fee:b,timestamp:B}=a,x=Math.max(1,t-B),A=g.volume.b_in.toString(),I=g.volume.b_out.toString(),w=g.liquidity.b.toString();n===0&&(A=g.volume.a_in.toString(),I=g.volume.a_out.toString(),w=g.liquidity.a.toString());let D=v.fromPermill(b),ae=h.recalculateProtocolFee(A,I,w,"9",r.toString(),v.toRaw(D).toString(),x.toString(),v.toRaw(m).toString(),v.toRaw(d).toString(),l.toString(),p.toString());return[o,Number(ae)*1e6,c]}};var z=u=>u===0?[0,1]:[1,u],_e=u=>z(u).join(":");var{FeeUtils:Ye}=y,Pt=ft.toHex(ft.fromText("omnipool")),vt=Ai("Short"),me=class extends S{queryBus=new $;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",e=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(e,{at:this.at}),e=>String(e));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",e=>this.api.query.DynamicFees.AssetFee.getValue(e,{at:this.at}),e=>String(e),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",e=>this.api.query.EmaOracle.Oracles.getValue(Pt,e,vt,{at:this.at}),e=>e.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let e="modlomnipool".padEnd(32,"\0"),t=new TextEncoder().encode(e),a=Ii(t);return Ti(Fi).dec(a)}async getPoolLimits(){let[e,t,a]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:a}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(xi.BackwardsCompatible)}async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=this.getPoolAddress(),[a,i,s,n,r,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(e,{at:this.at}),this.balance.getBalance(t,e),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=o;let c=a.map(async({keyArgs:p,value:m})=>{let[d]=p,{hub_reserve:g,shares:b,tradable:B,cap:x,protocol_shares:A}=m,[I,w]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d,{at:this.at}),this.balance.getBalance(t,d)]);return{id:d,decimals:I?.decimals,existentialDeposit:I?.existential_deposit,balance:w.transferable,cap:x,hubReserves:g,protocolShares:A,shares:b,tradeable:B,type:I?.asset_type.type}}),l=await Promise.all(c);return l.push({id:e,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:n.transferable,tradeable:i,type:s?.asset_type.type}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:l,...r}]}async getPoolFees(e){let t=e.assetOut,a=e.assetIn,s=await this.maxSlipFee.get()??0,n=await this.dynamicFeesConfig.get(t);if(n?.type==="Fixed"){let{asset_fee:m,protocol_fee:d}=n.value;return{assetFee:Ye.fromPermill(m),protocolFee:Ye.fromPermill(d),maxSlipFee:Ye.fromPermill(s)}}let[r,o,c,l,p]=await Promise.all([this.dynamicFees.get(t),this.emaOracles.get(z(t)),this.emaOracles.get(z(a)),n?n.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),n?n.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return q.compute(e,this.block,r,o,c,l,p,s)}subscribeEmaOracles(){let[e]=this.store.pools,a=e.tokens.map(i=>i.id).map(i=>z(i)).map(i=>this.api.query.EmaOracle.Oracles.watchValue(Pt,i,vt,{at:"best"}).pipe(j(({value:s})=>s),Oi(s=>s!==void 0),j((s,n)=>({value:s,index:n})),Ee(({index:s})=>{s>0&&this.log.trace("emaOracle.Oracles",i.join(":"))}),j(({value:s})=>({pair:i,value:s}))));return Bi(...a).pipe(We(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(i=>{let{pair:s,value:n}=i;this.emaOracles.set(n,s)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe($e((e,t)=>!t.deltas),j((e,t)=>({value:e,index:t})),Ee(({value:e,index:t})=>{t>0&&this.log.trace("dynamicFees.AssetFee",e.deltas?.upserted)}),We(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:e}})=>{e?.upserted.forEach(t=>{let[a]=t.args;this.dynamicFees.set(t.value,a)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe($e((e,t)=>!t.deltas),j((e,t)=>({value:e,index:t})),Ee(({value:e,index:t})=>{t>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",e.deltas?.upserted)}),We(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:e}})=>{e?.upserted.forEach(t=>{let[a]=t.args;this.dynamicFeesConfig.set(t.value,a)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(e=>{this.block=e})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe($e((e,t)=>!t.deltas),j((e,t)=>({value:e,index:t})),Ee(({value:e,index:t})=>{t>0&&this.log.trace("omnipool.Assets",e.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:e}})=>{this.store.update(([t])=>{let a=e?.upserted.reduce((s,n)=>{let[r]=n.args;return s.set(r,n.value),s},new Map),i=t.tokens.map(s=>{let n=a?.get(s.id);return n?this.updateTokenState(s,n):s});return[{...t,tokens:i}]})})}subscribeUpdates(){let e=new wi;return e.add(this.subscribeAssets()),e.add(this.subscribeDynamicFees()),e.add(this.subscribeDynamicFeesConfig()),e.add(this.subscribeEmaOracles()),e.add(this.subscribeBlock()),e}updateTokenState(e,t){let{hub_reserve:a,shares:i,tradable:s,cap:n,protocol_shares:r}=t;return{...e,cap:n,hubReserves:a,protocolShares:r,shares:i,tradeable:s}}};var Et={};F(Et,{StableMath:()=>P,StableSwap:()=>G,StableSwapClient:()=>he});import{calculate_in_given_out as _i,calculate_out_given_in as Ei,calculate_amplification as Ri,calculate_add_one_asset as ki,calculate_liquidity_out_one_asset as Ci,calculate_shares as Mi,calculate_shares_for_amount as Li,calculate_spot_price_with_fee as Di,pool_account_name as Hi,recalculate_peg as Ni}from"@galacticcouncil/math-stableswap";var P=class{static getPoolAddress(e){return Hi(e)}static defaultPegs(e){let t=[];for(let a=0;a<e;a++)t.push(["1","1"]);return t}static calculateAmplification(e,t,a,i,s){return Ri(e,t,a,i,s)}static calculateInGivenOut(e,t,a,i,s,n,r){return _i(e,t,a,i,s,n,r)}static calculateAddOneAsset(e,t,a,i,s,n,r){return ki(e,t,a,i,s,n,r)}static calculateSharesForAmount(e,t,a,i,s,n,r){return Li(e,t,a,i,s,n,r)}static calculateOutGivenIn(e,t,a,i,s,n,r){return Ei(e,t,a,i,s,n,r)}static calculateLiquidityOutOneAsset(e,t,a,i,s,n,r){return Ci(e,t,a,i,s,n,r)}static calculateShares(e,t,a,i,s,n){return Mi(e,t,a,i,s,n)}static calculateSpotPriceWithFee(e,t,a,i,s,n,r,o){return Di(e,t,a,i,s,n,r,o)}static recalculatePegs(e,t,a,i,s,n){let r=Ni(e,t,a,i,s,n);return JSON.parse(r)}};import{RUNTIME_DECIMALS as qi,big as Tt}from"@galacticcouncil/common";var{FeeUtils:Q}=y,G=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(e){return new u(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.isRampPeriod=e.isRampPeriod,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs}validatePair(e,t){return!0}parsePair(e,t){let a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,tradeableIn:this.id===e?15:i.tradeable,tradeableOut:this.id===t?15:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=this.calculateInGivenOut(e,t,a),n=i===0n?0:L.calculateBuyFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);return(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:i,amountOut:t,feePct:n,errors:r}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=this.calculateOutGivenIn(e,t,a),n=L.calculateSellFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);return(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:i,amountOut:s,feePct:n,errors:r}}calculateIn(e,t,a){let i=P.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),a?Q.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateAddOneAsset(e,t,a){let i=P.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),a?Q.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateSharesForAmount(e,t,a){let i=P.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),a?Q.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateInGivenOut(e,t,a){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,a):e.assetIn==this.id?this.calculateSharesForAmount(e,t,a):this.calculateIn(e,t,a)}spotPriceInGivenOut(e){let t=P.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetOut.toString(),e.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(t),e.assetOut===this.id,e.assetIn===this.id,e.decimalsOut,e.decimalsIn)}calculateOut(e,t,a){let i=P.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),a?Q.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateWithdrawOneAsset(e,t,a){let i=P.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),a?Q.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateShares(e,t,a){let i=P.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),a?Q.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(e,t,a){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,a):e.assetOut==this.id?this.calculateShares(e,t,a):this.calculateOut(e,t,a)}spotPriceOutGivenIn(e){let t=P.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetIn.toString(),e.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(t),e.assetIn===this.id,e.assetOut===this.id,e.decimalsIn,e.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:a,decimals:i})=>({asset_id:t,amount:a,decimals:i}));return JSON.stringify(e,ie.jsonFormatter)}getAssets(e,t){let a={asset_id:Number(e),amount:t.toString()};return JSON.stringify([a],ie.jsonFormatter)}normalizeSpot(e,t,a,i,s){return t?e*Tt.pow10(qi-s):a?e/Tt.pow10(s-i):e}};import{AccountId as Vi,CompatibilityLevel as Ui}from"polkadot-api";import{toHex as $i}from"@polkadot-api/utils";import{blake2b as Wi}from"@noble/hashes/blake2b";import{Subscription as Yi,distinctUntilChanged as _t,filter as Xi,map as Z,merge as Ki,tap as Ke}from"rxjs";import{HYDRATION_SS58_PREFIX as zi,RUNTIME_DECIMALS as ji}from"@galacticcouncil/common";import{Binary as Gi}from"polkadot-api";import{decodeEventLog as It}from"viem";var Xe=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}],xt=[{anonymous:!1,inputs:[{indexed:!1,name:"key",type:"string"},{indexed:!1,name:"value",type:"uint128"},{indexed:!1,name:"timestamp",type:"uint128"}],name:"OracleUpdate",type:"event"}],At=[{anonymous:!1,inputs:[{indexed:!0,name:"roundId",type:"uint80"},{indexed:!1,name:"answer",type:"int256"},{indexed:!1,name:"timestamp",type:"uint256"}],name:"PriceUpdated",type:"event"}];var de=class{static parse(e){let{address:t,topics:a,data:i}=e.log,s=t.toLowerCase(),n=Gi.toHex(i);try{let{eventName:r,args:o}=It({abi:At,topics:a,data:n});return{eventName:`ManagedOracle.${r}`,emitter:s,value:o.answer,timestamp:o.timestamp}}catch{}try{let{eventName:r,args:o}=It({abi:xt,topics:a,data:n});return{eventName:`DIA.${r}`,emitter:s,key:o.key,value:o.value,timestamp:o.timestamp}}catch{}}};var ge=class{adapter;constructor(e){this.adapter=e.getRPCAdapter()}async getData(e,t=6){let[a,i,s]=await Promise.all([this.adapter.readContract({abi:Xe,address:e,functionName:"latestRoundData"}),this.adapter.readContract({abi:Xe,address:e,functionName:"decimals"}),this.adapter.getBlock()]),[n,r,o,c]=a,l=s.number-(s.timestamp-c)/BigInt(t),p=Number(l);return{price:r,decimals:i,updatedAt:p<0?0:p}}};var wt={"EUR/USD":"0xaa47a5662269270d3df33ae08f806e383611575c","sUSDs/USD":"0x4b32bffc6acd751446e79e8687ef3815fd7924fd","sUSDe/USD":"0x22cdea305cee63d082e79f8c5db939eecd0265d0"},Ot={"0xcfab6a4031c70da0f0cf6f31a252c16119db3611":"0xaafd758688cefd0a7b7770a825f1aad551e16185"},Bt={"bifrosto:5:15:LastBlock":"0xaafd758688cefd0a7b7770a825f1aad551e16185"};function Ft(u,e,t){let a=Buffer.from(u.replace(/^0x/,""),"hex").toString("ascii").replace(/\0+$/,""),[i,s]=[e[0],e[1]].sort((n,r)=>n-r);return`${a}:${i}:${s}:${t}`}var{FeeUtils:J}=y,be=class u{static compute(e,t,a,i){let s=u.getRecent(t),n=J.fromPermill(e.fee),r=J.fromPerbill(t.max_peg_update),o=a.map(({pair:g,updatedAt:b})=>[g,b]),c=a.find(g=>g.source),l=t.updated_at?t.updated_at.toString():c?.updatedAt;if(!l)throw new Error("Current peg unknown!");let[p,m]=P.recalculatePegs(JSON.stringify(s),l,JSON.stringify(o),i.toString(),J.toRaw(r).toString(),J.toRaw(n).toString()),d=Number(p)*1e6;return{pegsFee:J.fromPermill(d),pegs:m}}static getDefault(e){return{pegsFee:J.fromPermill(e.fee),pegs:P.defaultPegs(e.assets.length)}}static getRecent(e){let{current:t}=e;return Array.from(t.entries()).map(([a,i])=>i.map(s=>s.toString()))}};var{FeeUtils:Qi}=y,Ji=["ManagedOracle.PriceUpdated","DIA.OracleUpdate"],he=class extends S{poolsData=new Map([]);mmOracle=new ge(this.evm);mmAddresses=new Set;mmRouting={byEmitter:new Map,byDiaKey:new Map,byEma:new Map};queryBus=new $;emaOracles=this.queryBus.scope("EmaOracle.Oracles",(e,t,a)=>this.api.query.EmaOracle.Oracles.getValue(e,t,a,{at:this.at}),(e,t,a)=>`${e.toString()}:${t.join(":")}:${a.type}`,6*1e3);mmOracles=this.queryBus.scope("MmOracle",e=>this.mmOracle.getData(e),e=>e.toLowerCase(),600*1e3);pegs=this.queryBus.scope("Stableswap.PoolPegs",e=>this.api.query.Stableswap.PoolPegs.getValue(e,{at:this.at}),e=>String(e),6*1e3);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=P.getPoolAddress(e),a=Wi(t,{dkLen:32}),i=$i(a);return Vi(zi).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(e,t){let{initial_amplification:a,final_amplification:i,initial_block:s,final_block:n}=e,r=P.calculateAmplification(a.toString(),i.toString(),s.toString(),n.toString(),t.toString()),o=Number(r)<i;return{amplification:BigInt(r),isRampPeriod:o}}async getPoolTokens(e,t){let a=this.getPoolAddress(e),i=t.assets.map(async s=>{let[n,r,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(e,s,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.balance.getBalance(a,s)]);return{id:s,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:o.transferable,tradeable:n,type:r?.asset_type.type}});return Promise.all(i)}buildRouting(){this.mmRouting.byEmitter.clear(),this.mmRouting.byDiaKey.clear(),this.mmRouting.byEma.clear();for(let e of this.mmAddresses)this.mmRouting.byEmitter.set(e,e);for(let[e,t]of Object.entries(Ot)){let a=e.toLowerCase(),i=t.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byEmitter.set(a,i)}for(let[e,t]of Object.entries(wt)){let a=t.toLowerCase();this.mmAddresses.has(a)&&this.mmRouting.byDiaKey.set(e,a)}for(let[e,t]of Object.entries(Bt)){let a=t.toLowerCase();this.mmAddresses.has(a)&&this.mmRouting.byEma.set(e,a)}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(Ui.BackwardsCompatible)}async loadPools(){let[e,t,a,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.Stableswap.PoolPegs.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]);for(let{keyArgs:n,value:r}of t){let[o]=n;this.pegs.set(r,o);for(let c of r.source)c.type==="MMOracle"&&this.mmAddresses.add(c.value.toString().toLowerCase())}this.buildRouting();let s=e.map(async({keyArgs:n,value:r})=>{let[o]=n,c=this.getPoolAddress(o),[l,p,m,d]=await Promise.all([this.getPoolTokens(o,r),this.getPoolAmplification(r,a),this.getPoolPegs(o,r,a),this.api.query.Tokens.TotalIssuance.getValue(o,{at:this.at})]);return l.push({id:o,tradeable:15,balance:d,decimals:ji}),this.poolsData.set(o,r),{address:c,id:o,type:"Stableswap",fee:Qi.fromPermill(r.fee),tokens:l,totalIssuance:d,...m,...i,...p}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.store.pools.find(i=>i.address===t).fee}}async getPoolPegs(e,t,a){let i=await this.pegs.get(e);if(!i)return be.getDefault(t);let s=await this.getLatestPegs(t,i,a);return be.compute(t,i,s,a)}async getLatestPegs(e,t,a){let{source:i}=t,s=e.assets,n=i.map(async(r,o)=>{if(r.type==="Oracle"){let[c,l,p]=r.value,m=[p,s[o]].sort((x,A)=>x-A),d=await this.emaOracles.get(c,m,l);if(!d)throw new Error("EmaOracle missing for "+c+" / "+m);let[{price:g,updated_at:b}]=d;return{pair:p===m[0]?[g.n.toString(),g.d.toString()]:[g.d.toString(),g.n.toString()],updatedAt:b.toString(),source:r.type}}if(r.type==="MMOracle"){let c=r.value.toString(),{price:l,decimals:p,updatedAt:m}=await this.mmOracles.get(c),d=(10n**BigInt(p)).toString();return{pair:[l.toString(),d],updatedAt:m.toString(),source:r.type}}if(r.type==="Value")return{pair:r.value.map(l=>l.toString()),updatedAt:a.toString()};throw new Error(r+" source not supported")});return Promise.all(n)}subscribeIssuance(){let t=this.store.pools.map(a=>a.id).map(a=>this.api.query.Tokens.TotalIssuance.watchValue(a,{at:"best"}).pipe(Z(({value:i})=>i),Z((i,s)=>({value:i,index:s})),Ke(({index:i,value:s})=>{i>0&&this.log.trace("tokens.TotalIssuance",a,s)}),Z(({value:i})=>({id:a,value:i}))));return Ki(...t).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(a=>{let{id:i,value:s}=a;this.store.update(n=>{let r=[];return n.filter(o=>o.id===i).forEach(o=>{let c=o.tokens.map(l=>l.id===i?{...l,balance:s}:l);r.push({...o,tokens:c,totalIssuance:s})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe(_t((e,t)=>!t.deltas),Z((e,t)=>({value:e,index:t})),Ke(({value:e,index:t})=>{t>0&&this.log.trace("stableswap.PoolPegs",e.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:e=>this.log.error("stableswap.PoolPegs",e),next:({value:{deltas:e}})=>{for(let{args:t,value:a}of e?.upserted??[]){let[i]=t;this.pegs.set(a,i)}}})}subscribeEmaOracles(){return this.api.query.EmaOracle.Oracles.watchEntries({at:"best"}).pipe(_t((e,t)=>!t.deltas),Z((e,t)=>({value:e,index:t})),Ke(({value:e,index:t})=>{t>0&&this.log.trace("emaOracle.Oracles",e.deltas?.upserted)}),this.watchGuard("emaOracle.Oracles")).subscribe(async({value:{deltas:e}})=>{let t=new Set;for(let{args:a,value:i}of e?.upserted??[]){let[s,n,r]=a;this.emaOracles.set(i,s,n,r);let o=Ft(s,n,r.type),c=this.mmRouting.byEma.get(o);c&&t.add(c)}for(let a of t){let i=await this.mmOracle.getData(a);this.log.trace("mmOracle.Hybrid",{h160:a,fresh:i}),this.mmOracles.set(i,a)}})}subscribeMMOracles(){return this.api.event.EVM.Log.watch().pipe(Z(({events:e})=>e.map(t=>de.parse(t.payload)).filter(t=>!!t).filter(({eventName:t})=>Ji.includes(t))),Xi(e=>e.length>0),this.watchGuard("evm.Log")).subscribe(async e=>{let t=new Set;for(let a of e){if(console.log(a),a.eventName==="ManagedOracle.PriceUpdated"){let i=this.mmRouting.byEmitter.get(a.emitter);i&&t.add(i)}if(a.eventName==="DIA.OracleUpdate"&&a.key){let i=this.mmRouting.byDiaKey.get(a.key);i&&t.add(i)}}for(let a of t){let i=await this.mmOracle.getData(a);this.log.trace("mmOracle",{h160:a,fresh:i}),this.mmOracles.set(i,a)}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(e=>{this.store.update(async t=>{let a=[];for(let i of t){let s=this.poolsData.get(i.id);if(s){let n=await this.getPoolPegs(i.id,s,e),r=this.getPoolAmplification(s,e);a.push({...i,...n,...r})}}return a})})}subscribeUpdates(){let e=new Yi;return e.add(this.subscribePoolPegs()),e.add(this.subscribeEmaOracles()),e.add(this.subscribeMMOracles()),e.add(this.subscribeIssuance()),e.add(this.subscribeBlock()),e}};var kt={};F(kt,{XykMath:()=>C,XykPool:()=>ye,XykPoolClient:()=>fe});import{calculate_in_given_out as Zi,calculate_out_given_in as es,calculate_pool_trade_fee as ts,get_spot_price as as,calculate_liquidity_in as is,calculate_shares as ss,calculate_spot_price as ns,calculate_spot_price_with_fee as rs,calculate_liquidity_out_asset_a as os,calculate_liquidity_out_asset_b as ls}from"@galacticcouncil/math-xyk";var C=class{static getSpotPrice(e,t,a){return as(e,t,a)}static calculateInGivenOut(e,t,a){return Zi(e,t,a)}static calculateOutGivenIn(e,t,a){return es(e,t,a)}static calculatePoolTradeFee(e,t,a){return ts(e,t,a)}static calculateLiquidityIn(e,t,a){return is(e,t,a)}static calculateSpotPrice(e,t){return ns(e,t)}static calculateSpotPriceWithFee(e,t,a,i){return rs(e,t,a,i)}static calculateShares(e,t,a){return ss(e,t,a)}static calculateLiquidityOutAssetA(e,t,a,i){return os(e,t,a,i)}static calculateLiquidityOutAssetB(e,t,a,i){return ls(e,t,a,i)}};import{big as cs}from"@galacticcouncil/common";var{FeeUtils:Rt}=y,ye=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=this.calculateTradeFee(i,a),n=Rt.toPct(a.exchangeFee),r=i+s,o=[];(t<this.minTradingLimit||i<e.assetInEd)&&o.push("InsufficientTradingAmount");let c=e.balanceOut/this.maxOutRatio;t>c&&o.push("MaxOutRatioExceeded");let l=e.balanceIn/this.maxInRatio;return r>l&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:i,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=this.calculateTradeFee(i,a),n=Rt.toPct(a.exchangeFee),r=i-s,o=[];(t<this.minTradingLimit||i<e.assetOutEd)&&o.push("InsufficientTradingAmount");let c=e.balanceIn/this.maxInRatio;t>c&&o.push("MaxInRatioExceeded");let l=e.balanceOut/this.maxOutRatio;return r>l&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(e,t){let a=C.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(e,t){let a=C.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(e){let t=C.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString());return this.normalizeSpot(BigInt(t),e.decimalsOut,e.decimalsIn)}spotPriceOutGivenIn(e){let t=C.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsIn,e.decimalsOut)}calculateTradeFee(e,t){let a=C.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(a)}normalizeSpot(e,t,a){let i=t-a;if(i===0)return e;let s=cs.pow10(Math.abs(i));return i>0?e*s:e/s}};import{CompatibilityLevel as us}from"polkadot-api";import{Subscription as ps}from"rxjs";var fe=class extends S{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(e){this.decimals=e?new Map(e.map(t=>[t.id,t.decimals])):new Map}async getPoolLimits(){let[e,t,a]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:a}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(us.BackwardsCompatible)}async loadPools(){let[e,t]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),a=e.map(async({keyArgs:i,value:s})=>{let[n]=i,[r,o]=s,[c,l,p,m]=await Promise.all([this.balance.getBalance(n,r),this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.balance.getBalance(n,o),this.api.query.AssetRegistry.Assets.getValue(o,{at:this.at})]);return{address:n,type:"XYK",tokens:[{id:r,decimals:l?.decimals||this.decimals.get(r),existentialDeposit:l?.existential_deposit,balance:c.transferable,type:l?.asset_type.type},{id:o,decimals:m?.decimals||this.decimals.get(o),existentialDeposit:m?.existential_deposit,balance:p.transferable,type:m?.asset_type.type}],...t}});return Promise.all(a)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return ps.EMPTY}};var Nt={};F(Nt,{AavePool:()=>Pe,AavePoolClient:()=>ve});import{big as Ct,RUNTIME_DECIMALS as Mt}from"@galacticcouncil/common";var Pe=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=[];return t>e.balanceOut&&s.push("TradeNotAllowed"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=[];return i>e.balanceOut&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return Ct.toBigInt(1,Mt)}spotPriceOutGivenIn(e){return Ct.toBigInt(1,Mt)}calculateTradeFee(e,t){return 0n}};import{AccountId as hs}from"polkadot-api";import{toHex as ys}from"@polkadot-api/utils";import{Subscription as Lt,filter as je,map as Dt,mergeMap as Ht}from"rxjs";import{erc20 as fs,HYDRATION_SS58_PREFIX as Ps}from"@galacticcouncil/common";var ze=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var Lu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{Binary as ms}from"polkadot-api";import{decodeEventLog as ds}from"viem";var ke=class{static parse(e){let{topics:t,data:a}=e.log,i=ms.toHex(a);try{let{eventName:s,args:n}=ds({abi:ze,topics:t,data:i}),r=n.reserve.toLowerCase();return{eventName:s,reserve:r,key:`${s}:${r}`}}catch{return}}};import ep from"big.js";import{big as ap,erc20 as gs,h160 as bs}from"@galacticcouncil/common";var{ERC20:sp}=gs,{H160:np}=bs;var rp=10n**27n;var{ERC20:vs}=fs,Ss=["Supply","Withdraw","Repay","Borrow"],ve=class extends S{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(e,t){let a=e+"/"+t,i=new TextEncoder().encode(a.padEnd(32,"\0")),s=ys(i);return hs(Ps).dec(s)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:a,atoken:i,liqudity_in:s,liqudity_out:n})=>{let[r,o,c,l]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(a,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(a,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at})]);return{address:this.getPoolId(a,i),type:"Aave",tokens:[{id:a,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:s,location:o,type:r?.asset_type.type},{id:i,decimals:c?.decimals,existentialDeposit:c?.existential_deposit,balance:n,location:l,type:c?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolDelta(e){let[t,a]=e.tokens,{liqudity_in:i,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(t.id,a.id,{at:this.at});return e.tokens.map(n=>{let r=n.id===t.id?i:s;return{...n,balance:r}})}async getPoolFees(){return{}}getReserveH160Id(e){if(e.type==="Erc20"&&e.location){let t=e.location.interior;if(t.type==="X1"&&t.value.type==="AccountKey20"){let{value:a}=t.value;return a.key}throw new Error("Invalid aave reserve multilocation")}return vs.fromAssetId(e.id)}parseRouterLog(e){let{asset_in:t,asset_out:a}=e;return{assetIn:t,assetOut:a,key:`${t}:${a}`}}subscribeRouterExecuted(){let t=this.store.pools.map(a=>a.tokens).map(([a,i])=>i).map(a=>a.id);return this.api.event.Router.Executed.watch().pipe(Ht(({events:a})=>a),Dt(({payload:a})=>this.parseRouterLog(a)),je(({assetIn:a,assetOut:i})=>t.includes(a)||t.includes(i)),this.watchGuard("router.Execute")).subscribe(({assetIn:a,assetOut:i,key:s})=>{this.log.trace("router.Executed",s),this.store.update(async n=>{let r=[];for(let o of n){let[c,l]=o.tokens;if(l.id===a||l.id===i){let m=await this.getPoolDelta(o);r.push({...o,tokens:m})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Ht(({events:e})=>e),Dt(({payload:e})=>ke.parse(e)),je(e=>e!==void 0),je(({eventName:e})=>Ss.includes(e)),this.watchGuard("evm.Log")).subscribe(({reserve:e,eventName:t})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async a=>{let i=[];for(let s of a){let[n]=s.tokens;if(this.getReserveH160Id(n).toLowerCase()===e){let o=await this.getPoolDelta(s);i.push({...s,tokens:o})}}return i})})}subscribeBalances(){return Lt.EMPTY}subscribeUpdates(){let e=new Lt;return e.add(this.subscribeRouterExecuted()),e.add(this.subscribeEvmLog()),e}};var Vt={};F(Vt,{HsmMath:()=>T,HsmPool:()=>Se,HsmPoolClient:()=>Te});import{calculate_collateral_in_given_hollar_out as Ts,calculate_collateral_out_given_hollar_in as xs,calculate_hollar_in_given_collateral_out as As,calculate_hollar_out_given_collateral_in as Is,calculate_imbalance as ws,calculate_max_price as Os,calculate_buyback_limit as Bs,calculate_buyback_price_with_fee as Fs}from"@galacticcouncil/math-hsm";var T=class{static calculateCollateralInGivenHollarOut(e,t,a){return Ts(e,t,a)}static calculateCollateralOutGivenHollarIn(e,t,a){return xs(e,t,a)}static calculateHollarOutGivenCollateralIn(e,t,a){return Is(e,t,a)}static calculateHollarInGivenCollateralOut(e,t,a){return As(e,t,a)}static calculateImbalance(e,t,a){return ws(e,t,a)}static calculateBuybackLimit(e,t){return Bs(e,t)}static calculateBuybackPriceWithFee(e,t,a){return Fs(e,t,a)}static calculateMaxPrice(e,t){return Os(e,t)}};import{big as M,RUNTIME_DECIMALS as Ce}from"@galacticcouncil/common";var{FeeUtils:ee}=y,Se=class u extends G{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new u(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,a){let i=this.parsePair(e.assetOut,e.assetIn),s=super.calculateInGivenOut(i,t,{fee:this.fee}),n=this.calculateBuybackLimit(e);t>n&&a.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(e);return this.calculateBuyPrice(e,t,s)>r&&a.push("MaxBuyPriceExceeded"),s>this.collateralBalance&&a.push("InsufficientCollateral"),a}validateTradeHollarOut(e,t,a){return this.collateralBalance+e>this.maxInHolding&&a.push("MaxHoldingExceeded"),t>this.hsmMintCapacity&&a.push("FacilitatorCapacityExceeded"),a}validateTradeConstraints(e,t,a){let i=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,i):this.validateTradeHollarOut(t,a,i)}validateAndBuy(e,t){let a=this.calculateInGivenOut(e,t),i=this.validateTradeConstraints(e,a,t);return{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t){let a=this.calculateOutGivenIn(e,t),i=this.validateTradeConstraints(e,t,a);return{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:i}}calculateHollarInGivenCollateralOut(e,t){let a=super.calculateInGivenOut(e,t,{fee:this.fee}),i=T.calculateHollarInGivenCollateralOut(t.toString(),a.toString(),ee.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),a=T.calculateCollateralInGivenHollarOut(e.toString(),JSON.stringify(t),ee.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let a=super.calculateOutGivenIn(e,t,{fee:this.fee}),i=T.calculateCollateralOutGivenHollarIn(t.toString(),a.toString(),ee.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),a=T.calculateHollarOutGivenCollateralIn(e.toString(),JSON.stringify(t),ee.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),a=T.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return BigInt(a)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),a=T.calculateBuybackLimit(t.toString(),ee.toRaw(this.buyBackRate).toString());return BigInt(a)}calculateBuyPrice(e,t,a){let i=T.calculateBuybackPriceWithFee(a.toString(),t.toString(),ee.toRaw(this.buyBackFee).toString()),[s,n]=JSON.parse(i),r=M.pow10(e.decimalsIn+Ce-e.decimalsOut);return BigInt(s)*r/BigInt(n)}calculateMaxPrice(e){let t=this.getCollateralPeg(),a=T.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toString()),[i,s]=JSON.parse(a),n=M.pow10(Ce-e.decimalsOut);return BigInt(i)*n/BigInt(s)}spotPriceInGivenOut(e){let t=M.toBigInt(1,e.decimalsOut),i=this.calculateInGivenOut(e,t)*M.pow10(Ce-e.decimalsOut);return this.normalizeSpotPrice(i,e.decimalsOut,e.decimalsIn)}spotPriceOutGivenIn(e){let t=M.toBigInt(1,e.decimalsIn),i=this.calculateOutGivenIn(e,t)*M.pow10(Ce-e.decimalsIn);return this.normalizeSpotPrice(i,e.decimalsIn,e.decimalsOut)}getCollateralPeg(){let e=this.tokens.findIndex(i=>i.id!==this.hollarId),t=this.pegs[e],a=this.tokens[e].decimals;return this.isDefaultPeg(t)?[M.toBigInt(1,18).toString(),M.toBigInt(1,a).toString()]:t}isDefaultPeg(e){let[t,a]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&a==="1"}normalizeSpotPrice(e,t,a){let i=t-a;if(i===0)return e;let s=M.pow10(Math.abs(i));return i>0?e*s:e/s}};import{AccountId as Rs,CompatibilityLevel as ks}from"polkadot-api";import{toHex as Cs}from"@polkadot-api/utils";import{Subscription as Qe,combineLatest as Ms,filter as qt,map as Je,mergeMap as Ls,pairwise as Ds}from"rxjs";import{h160 as Hs,HYDRATION_SS58_PREFIX as Ns}from"@galacticcouncil/common";import{Binary as _s}from"polkadot-api";import{decodeEventLog as Es}from"viem";var Me=[{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 Le=class{static parse(e){let{topics:t,data:a}=e.log,i=_s.toHex(a);try{let{eventName:s,args:n}=Es({abi:Me,topics:t,data:i}),r=n.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:r,key:`${s}:${r}`}}catch{return}}};var De=class{client;constructor(e){this.client=e.getWsProvider()}async getFacilitatorCapacity(e,t){let[a,i]=await this.client.readContract({abi:Me,address:e,functionName:"getFacilitatorBucket",args:[t]});return a-i}};var{FeeUtils:Ze}=y,{H160:Gt}=Hs,qs=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Te=class extends S{ghoClient;stableClient;constructor(e,t,a,i){super(e,t,i),this.stableClient=a,this.ghoClient=new De(t)}getPoolType(){return"HSM"}getPoolId(e){return this.getPoolAddress("hsm:"+e)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(e){if(e){let t=e.interior;if(t.type==="X1"&&t.value.type==="AccountKey20"){let{value:a}=t.value;return a.key}}throw Error("Invalid hollar multilocation")}getPoolAddress(e){let t=e.padEnd(32,"\0"),a=new TextEncoder().encode(t),i=Cs(a);return Rs(Ns).dec(i)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(ks.BackwardsCompatible)}async loadPools(){let e=await this.api.constants.HSM.HollarId(),[t,a,i]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(e,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(a.length===0)return[];let s=this.getFacilitatorAddress(),n=Gt.fromAny(s),r=this.getHollarAddress(t),o=await this.ghoClient.getFacilitatorCapacity(r,n),c=a.map(async({keyArgs:p,value:m})=>{let[d]=p,{pool_id:g,max_buy_price_coefficient:b,max_in_holding:B,purchase_fee:x,buy_back_fee:A,buyback_rate:I}=m,w=i.find(D=>D.id===g);if(w){let D=this.getPoolId(g),ae=await this.balance.getBalance(s,d);return{...w,address:D,type:"HSM",tokens:w.tokens.filter(Ut=>Ut.id!==g),hsmAddress:s,hsmMintCapacity:o,hollarId:e,hollarH160:r,collateralId:d,collateralBalance:ae.transferable,maxBuyPriceCoefficient:b,maxInHolding:B,purchaseFee:Ze.fromPermill(x),buyBackFee:Ze.fromPermill(A),buyBackRate:Ze.fromPerbill(I)}}});return(await Promise.all(c)).filter(p=>p!==null)}async getPoolFees(){return{}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Ls(({events:e})=>e),Je(({payload:e})=>Le.parse(e)),qt(e=>e!==void 0),qt(({eventName:e})=>qs.includes(e)),this.watchGuard("evm.Log")).subscribe(({eventName:e,facilitator:t})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async a=>{let i=[],[{hsmAddress:s,hollarH160:n}]=a,r=Gt.fromAny(s);if(r.toLowerCase()===t){let c=await this.ghoClient.getFacilitatorCapacity(n,r);for(let l of a)i.push({...l,hsmMintCapacity:c})}return i})})}subscribeCollateralBalance(){let e=[],t=[];this.store.pools.forEach(s=>{let{tokens:n,collateralId:r}=s;n.find(c=>c.id===r).type==="Erc20"?t.push(r):e.push(r)});let[{hsmAddress:a}]=this.store.pools,i=[];if(e.length>0){let s=this.balance.watchTokensBalance(a);i.push(s)}if(t.length>0){let s=this.balance.watchErc20Balance(a,t);i.push(s)}return i.length>0?Ms(i).pipe(Je(s=>s.flat()),Ds(),Je(([s,n])=>this.balance.getDeltas(s,n)),this.watchGuard("balances")).subscribe(s=>{this.store.update(n=>{let r=[],o=new Map(n.map(c=>[c.collateralId,c]));return s.forEach(({id:c,balance:l})=>{let p=o.get(c);p&&(this.log.trace("balances",{id:c,balance:l}),r.push({...p,collateralBalance:l.transferable}))}),r})}):Qe.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(e=>{let t=new Map(e.map(a=>[a.id,a]));this.store.update(a=>{let i=[];for(let s of a){let n=t.get(s.id);n&&i.push({...s,fee:n.fee,tokens:n.tokens.filter(r=>r.id!==s.id),totalIssuance:n.totalIssuance,pegs:n.pegs,amplification:n.amplification,isRampPeriod:n.isRampPeriod})}return i})})}subscribeBalances(){return Qe.EMPTY}subscribeUpdates(){let e=new Qe;return e.add(this.subscribeCollateralBalance()),e.add(this.subscribeStableswapUpdates()),e.add(this.subscribeEvmLog()),e}};var et=class{static get(e){switch(e.type){case"Aave":return Pe.fromPool(e);case"XYK":return ye.fromPool(e);case"Omnipool":return pe.fromPool(e);case"LBP":return se.fromPool(e);case"Stableswap":return G.fromPool(e);case"HSM":return Se.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{log as Gs}from"@galacticcouncil/common";import{Subject as Vs,Subscription as V,takeUntil as Us}from"rxjs";var te=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}};var{logger:$s}=Gs,tt=class extends _{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=V.EMPTY;omniSub=V.EMPTY;stableSub=V.EMPTY;hsmSub=V.EMPTY;xykSub=V.EMPTY;lbpSub=V.EMPTY;isReady=!1;isDestroyed=new Vs;constructor(e,t,a){super(e,a),this.evm=t,this.aave=new ve(e,t,a),this.omnipool=new me(e,t,a),this.stableswap=new he(e,t,a),this.hsm=new Te(e,t,this.stableswap,a),this.xyk=new fe(e,t,a),this.lbp=new ue(e,t,a),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(e){return this.isHistorical?V.EMPTY:e.getSubscriber().pipe(Us(this.isDestroyed)).subscribe(t=>{t.forEach(a=>{this.pools.set(a.address,a)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||($s.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(e){return this.xyk.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let t=this.pools.values();return Array.from(t)}let e=await Promise.all(this.clients.filter(t=>this.active.has(t.getPoolType())).map(t=>t.getPools()));return this.isReady=!0,e.flat()}async getPoolFees(e,t){let a=this.clients.find(i=>i.getPoolType()===t.type);if(a)return a.getPoolFees(e,t.address);throw new te(t.type)}};var at=class{constructor(e){this.snapshot=e;let{aave:t,xyk:a,lbp:i,stable:s,omni:n}=e.pools;this.flat=[...t,...a,...i,...s,...n]}flat;async getPools(){return this.flat}async getPoolFees(e,t){let{block:a,states:i}=this.snapshot;switch(t.type){case"Aave":return{};case"XYK":{let{exchangeFee:s}=i.xyk;return{exchangeFee:s}}case"LBP":{let{repayFee:s}=i.lbp;return{exchangeFee:t.fee,repayFee:s}}case"Stableswap":return{fee:t.fee};case"Omnipool":{let s=e.assetOut,n=e.assetIn,{dynamicFees:r,emaOracles:o,assetFeeParams:c,protocolFeeParams:l,maxSlipFee:p}=i.omni,m=r.find(({asset:b})=>b===s)?.fee,d=o.find(({pair:b})=>b.join(":")===_e(s))?.oracle,g=o.find(({pair:b})=>b.join(":")===_e(n))?.oracle;return q.compute(e,a,m,d,g,c,l,p)}default:throw new te(t.type)}}};export{tt as PoolContextProvider,H as PoolError,et as PoolFactory,f as PoolType,at as SnapshotPoolCtxProvider,Nt as aave,Vt as hsm,yt as lbp,St as omni,Et as stable,kt as xyk};
|
|
1
|
+
var $t=Object.defineProperty;var F=(u,e)=>{for(var t in e)$t(u,t,{get:e[t],enumerable:!0})};import Wt from"buffer";typeof window<"u"&&(window.Buffer=Wt.Buffer);var yt={};F(yt,{LbpMath:()=>O,LbpPool:()=>ie,LbpPoolClient:()=>ce});import{calculate_in_given_out as Yt,calculate_out_given_in as Xt,calculate_linear_weights as Kt,calculate_pool_trade_fee as zt,get_spot_price as jt}from"@galacticcouncil/math-lbp";var O=class{static getSpotPrice(e,t,a,i,s){return jt(e,t,a,i,s)}static calculateInGivenOut(e,t,a,i,s){return Yt(e,t,a,i,s)}static calculateOutGivenIn(e,t,a,i,s){return Xt(e,t,a,i,s)}static calculateLinearWeights(e,t,a,i,s){return Kt(e,t,a,i,s)}static calculatePoolTradeFee(e,t,a){return zt(e,t,a)}};import{big as st,RUNTIME_DECIMALS as nt}from"@galacticcouncil/common";var f=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n.HSM="HSM",n))(f||{}),H=(l=>(l.UnknownError="UnknownError",l.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",l.InsufficientTradingAmount="InsufficientTradingAmount",l.InsufficientCollateral="InsufficientCollateral",l.MaxHoldingExceeded="MaxHoldingExceeded",l.MaxInRatioExceeded="MaxInRatioExceeded",l.MaxOutRatioExceeded="MaxOutRatioExceeded",l.TradeNotAllowed="TradeNotAllowed",l.MaxBuyBackExceeded="MaxBuyBackExceeded",l.MaxBuyPriceExceeded="MaxBuyPriceExceeded",l))(H||{});var Te={};F(Te,{withTimeout:()=>Qt});function Qt(u,e,t="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(t)),e);u.then(n=>{clearTimeout(s),a(n)},n=>{clearTimeout(s),i(n)})})}import{RUNTIME_DECIMALS as Js}from"@galacticcouncil/common";var y={};F(y,{FeeUtils:()=>Ne,shiftNeg:()=>ta});import ea from"big.js";var Ne=class u{static toPct(e){let[t,a]=e;return u.safeDivide(t*100,a)}static toRaw(e){let[t,a]=e;return u.safeDivide(t,a)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,a=12){let i=10**a;return Math.round(e*i/t)/i}static safeRound(e){return parseFloat(e.toPrecision(15))}};function ta(u,e){let t=ea(typeof u=="bigint"?u.toString():u);return e===0?t.toString():t.div(Math.pow(10,e)).toString()}var ae={};F(ae,{findNestedKey:()=>aa,findNestedObj:()=>ia,jsonFormatter:()=>sa});var aa=(u,e)=>{let t=[];return JSON.stringify(u,(a,i)=>(i&&i[e]&&t.push(i),i)),t[0]},ia=(u,e,t)=>{let a;return JSON.stringify(u,(i,s)=>(s&&s[e]===t&&(a=s),s)),a},sa=(u,e)=>typeof e=="bigint"?e.toString():e;var L={};F(L,{calculateBuyFee:()=>la,calculateDiffToAvg:()=>na,calculateDiffToRef:()=>ra,calculateSellFee:()=>oa});import k from"big.js";function na(u,e){let t=k(u.toString()),a=k(e.toString());return t.minus(a).abs().div(t.plus(a).div(2)).mul(100).round(2).toNumber()}function ra(u,e){if(e===0n)return 0;let t=k(u.toString()),a=k(e.toString());return t.minus(a).div(a).mul(100).round(2).toNumber()}function oa(u,e){if(u===0n)return 0;let t=k(u.toString()),a=k(e.toString());return k(1).minus(a.div(t)).mul(100).round(2).toNumber()}function la(u,e){if(u===0n)return 0;let t=k(u.toString());return k(e.toString()).div(t).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as it}from"@thi.ng/cache";var $=class{debug;constructor(e){this.debug=e||!1}log(e,t,a){this.debug&&console.log(e,t,a)}scope(e,t,a,i){let s=new Map,n=i!==void 0?new it(null,{ttl:i}):new it;return{get:(...l)=>{let p=a(...l);if(s.has(p)){this.log("[live]",e,p);let d=s.get(p);return Promise.resolve(d)}if(n.has(p))return this.log("[memo]",e,p),n.get(p);this.log("[fetch]",e,p);let m=t(...l).catch(d=>{throw n.delete(p),d});return n.set(p,m),m},set:(l,...p)=>{let m=a(...p);this.log("[set-live]",e,m),s.set(m,l)},clear:()=>{this.log("[clear]",e),s.clear(),n.release()}}}};var{FeeUtils:rt}=y,ie=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,weightIn:i.weight,weightOut:s.weight}}validateAndBuy(e,t,a){let i=this.tokens[0].id,s=[];t<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=e.balanceOut/this.maxOutRatio;if(t>n&&s.push("MaxOutRatioExceeded"),i===e.assetOut){let r=this.calculateTradeFee(t,a),o=rt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),c=t+r,l=this.calculateInGivenOut(e,c),p=e.balanceIn/this.maxInRatio;return l>p&&s.push("MaxInRatioExceeded"),{amountIn:l,calculatedIn:l,amountOut:t,feePct:o,errors:s}}else{let r=this.calculateInGivenOut(e,t),o=e.balanceIn/this.maxInRatio;return r>o&&s.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:t,feePct:0,errors:s}}}validateAndSell(e,t,a){let i=this.tokens[0].id,s=[];t<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=e.balanceIn/this.maxInRatio;if(t>n&&s.push("MaxInRatioExceeded"),i===e.assetIn){let r=this.calculateOutGivenIn(e,t),o=e.balanceOut/this.maxOutRatio;return r>o&&s.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:r,feePct:0,errors:s}}else{let r=this.calculateOutGivenIn(e,t),o=this.calculateTradeFee(r,a),c=rt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),l=r-o,p=e.balanceOut/this.maxOutRatio;return l>p&&s.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:r,amountOut:l,feePct:c,errors:s}}}calculateInGivenOut(e,t){let a=O.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(e,t){let a=O.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(e){let t=O.getSpotPrice(e.balanceOut.toString(),e.balanceIn.toString(),e.weightOut.toString(),e.weightIn.toString(),st.toBigInt(1,nt).toString());return BigInt(t)}spotPriceOutGivenIn(e){let t=O.getSpotPrice(e.balanceIn.toString(),e.balanceOut.toString(),e.weightIn.toString(),e.weightOut.toString(),st.toBigInt(1,nt).toString());return BigInt(t)}calculateTradeFee(e,t){let a=O.calculatePoolTradeFee(e.toString(),this.repayFeeApply?t.repayFee[0]:t.exchangeFee[0],this.repayFeeApply?t.repayFee[1]:t.exchangeFee[1]);return BigInt(a)}};import{CompatibilityLevel as Za}from"polkadot-api";import{Subscription as ei,distinctUntilChanged as ti,filter as ai,map as ii}from"rxjs";import{memoize1 as Ha}from"@thi.ng/memoize";import{TLRUCache as Na}from"@thi.ng/cache";import{ReplaySubject as gt,Subscription as bt,combineLatest as qa,defer as Ga,from as Va,interval as Ua,merge as Ge,of as $a,EMPTY as oe}from"rxjs";import{bufferCount as Wa,bufferTime as Ya,catchError as le,filter as Oe,finalize as Ve,map as X,pairwise as Ue,repeat as $e,skip as Xa,share as Ka,startWith as za,switchMap as ht,tap as N,throttleTime as ja}from"rxjs/operators";import{hydration as Aa,hydrationNext as wa,hydrationIce as Ia}from"@galacticcouncil/descriptors";import{log as Pa}from"@galacticcouncil/common";import{map as va,shareReplay as Sa,tap as Ta}from"rxjs";import{defer as ca,from as ua,of as ot,timer as pa}from"rxjs";import{catchError as ma,distinctUntilChanged as da,expand as ga,map as qe,shareReplay as ba,skip as ha,switchMap as ya,timeout as fa}from"rxjs/operators";function lt(u,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let a=()=>ca(()=>ua(u._request("system_health",[]))).pipe(fa({first:t}),qe(()=>"online"),ma(()=>ot("offline")));return ot({state:"offline",delayMs:0}).pipe(ga(s=>pa(s.delayMs).pipe(ya(a),qe(n=>({state:n,delayMs:e})))),ha(1),qe(s=>s.state),da(),ba({bufferSize:1,refCount:!0}))}var{logger:xa}=Pa,xe=class u{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(va(({value:t})=>t))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",lt(e))}static getInstance(e){return this.instance||(this.instance=new u(e)),this.instance}watched(e,t){return t.pipe(Ta({error:a=>xa.error(e,a)}),Sa({bufferSize:1,refCount:!0}))}};var _=class{client;api;apiNext;apiIce;watcher;at;constructor(e,t){this.client=e,this.api=this.client.getTypedApi(Aa),this.apiNext=this.client.getTypedApi(wa),this.apiIce=this.client.getTypedApi(Ia),this.watcher=xe.getInstance(this.client),this.at=t??"best"}};import{getWsProvider as Wn}from"polkadot-api/ws";import{withLogsRecorder as Xn}from"polkadot-api/logs-provider";import{Binary as lr}from"polkadot-api";import{log as Oa}from"@galacticcouncil/common";import{combineLatest as Ba,concat as Fa,defer as se,from as ct}from"rxjs";import{bufferCount as ut,distinctUntilChanged as pt,debounceTime as _a,map as W,retry as Ea,startWith as mt,switchMap as dt,tap as ne,take as Ra,skip as ka,connect as Ca}from"rxjs/operators";var{logger:Y}=Oa,re=class extends _{erc20Ids=null;constructor(e,t){super(e,t)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:a}=await t.getValue(e,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(e,t){let i=await this.api.query.Tokens.Accounts.getValue(e,t,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return se(()=>{let t=this.watchSystemBalance(e),a=this.watchTokensBalance(e),i=this.watchErc20Balance(e);return Ba([t,a,i]).pipe(Ca(s=>Fa(s.pipe(Ra(1)),s.pipe(ka(1),_a(250)))))}).pipe(W(t=>t.flat()),mt([]),ut(2,1),W(([t,a],i)=>i===0?a:this.getDeltas(t,a))).pipe(ne({subscribe:()=>Y.debug("balance: subscribe",e),error:t=>Y.error("balance",t)}),Ea({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return se(()=>t.watchValue(e,{at:"best"})).pipe(W(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),ne({error:a=>Y.error("balance(system)",a)}))}watchTokenBalance(e,t){let a=this.api.query.Tokens.Accounts;return se(()=>a.watchValue(e,t,{at:"best"})).pipe(W(({value:i})=>({id:t,balance:this.getBreakdown(i)})),ne({error:i=>Y.error("balance(token)",i)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return se(()=>t.watchEntries(e,{at:"best"})).pipe(pt((a,i)=>!i.deltas),W(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown(s.value)})}),i}),ne({error:a=>Y.error("balance(tokens)",a)}))}watchErc20Balance(e,t){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(e,r)]))).map(([r,o])=>({id:r,balance:o}));return se(()=>ct(t?Promise.resolve(t):a()).pipe(dt(s=>this.watcher.bestBlock$.pipe(dt(()=>ct(i(s))))),mt([]),ut(2,1),W(([s,n],r)=>r===0?n.filter(o=>o.balance.total>0n):this.getDeltas(s,n)),pt((s,n)=>n.length===0),ne({error:s=>Y.error("balance(erc20)",s)})))}async getBalanceData(e,t){let a=await this.api.apis.CurrenciesApi.account(t,e,{at:this.at});return this.getBreakdown(a)}getBreakdown(e){let t=e.frozen-e.reserved,a=t>0n?t:0n,i=e.free>=a?e.free-a:0n,s=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:s,transferable:i}}getDeltas(e,t){let a=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,i=e.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return t.filter(s=>!a(s.balance,i.get(s.id)))}};import{BehaviorSubject as Ma}from"rxjs";var Ae=class{store$=new Ma([]);updateQueue=Promise.resolve();changeset=new Set;get pools(){return this.store$.value}asObservable(){return this.store$.asObservable()}applyChangeset(e){return this.changeset.size===0?[]:e.filter(t=>this.changeset.has(t.address))}set(e){this.changeset=new Set(e.map(t=>t.address)),this.store$.next(e)}update(e){this.updateQueue=this.updateQueue.then(async()=>{let t=this.store$.value,a=new Map(t.map((r,o)=>[r.address,o])),i=await e(t),s=t.slice(),n=new Set;for(let r of i){let o=a.get(r.address);o===void 0?(a.set(r.address,s.length),s.push(r)):s[o]=r,n.add(r.address)}this.changeset=n,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};import{log as La}from"@galacticcouncil/common";var Da={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:we}=La,Ie=class{type;constructor(e){this.type=e}prefix(){return this.pad(`pool(${Da[this.type]})`,10)}trace(e,...t){we.trace(`${this.prefix()} ${e} :`,...t)}debug(e,...t){we.debug(`${this.prefix()} ${e} :`,...t)}info(e,...t){we.info(`${this.prefix()} ${e} :`,...t)}error(e,...t){we.error(`${this.prefix()} ${e} :`,...t)}pad(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}};var{withTimeout:Qa}=Te,Ja=3e3,S=class extends _{evm;balance;store=new Ae;log;shared$;resync$=new gt(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new Na(null,{ttl:6*1e3});memPools=Ha(e=>(this.log.info("pool_sync",{mem:e}),this.loadPools()),this.memPoolsCache);constructor(e,t,a){super(e,a),this.evm=t,this.balance=new re(e,a),this.log=new Ie(this.getPoolType())}async getMemPools(){return this.memPools(this.mem)}async getPools(){let t=(await this.getMemPools()).filter(a=>this.hasValidAssets(a));return this.store.set(t),t}getSubscriber(){return this.shared$||(this.shared$=this.subscribeStore()),this.shared$.pipe(za([]),Wa(2,1),X(([e,t])=>e.length===0?t:this.store.applyChangeset(t)),Oe(e=>e.length>0),ja(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return Ga(()=>{let e=new bt;return e.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe(ht(()=>{let t=new bt;return Va(Qa(this.getMemPools(),6e4,"getMemPools stalled")).pipe(N(()=>this.log.info("pool_synced",{mem:this.mem})),X(i=>i.filter(s=>this.hasValidAssets(s))),N(i=>this.store.set(i)),le(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),oe))).pipe(N(()=>{t.add(this.subscribeBalances()),t.add(this.subscribeUpdates())}),ht(i=>Ge($a(i),this.store.asObservable().pipe(Xa(1)))),Ve(()=>{t.unsubscribe()}))}),Ve(()=>e.unsubscribe()))}).pipe(Ka({connector:()=>new gt(1),resetOnRefCountZero:!0}))}subscribeBalances(){let e=this.store.pools.map(t=>{let{address:a}=t,i=[this.balance.watchTokensBalance(a)];if(this.hasSystemAsset(t)){let s=this.balance.watchSystemBalance(a);i.push(s)}if(this.hasErc20Asset(t)){let s=t.tokens.filter(r=>r.type==="Erc20").map(r=>r.id),n=this.balance.watchErc20Balance(a,s);i.push(n)}return qa(i).pipe(X(s=>s.flat()),Ue(),X(([s,n])=>this.balance.getDeltas(s,n)),Oe(s=>s.length>0),X(s=>[a,s]))});return Ge(...e).pipe(Ya(250),Oe(t=>t.length>0),X(t=>new Map(t)),this.watchGuard("balances")).subscribe(t=>{this.store.update(a=>this.updateBalances(a,t))})}hasSystemAsset(e){return e.tokens.some(t=>t.id===0)}hasErc20Asset(e){return e.tokens.some(t=>t.type==="Erc20")}hasValidAssets(e){return e.tokens.every(({decimals:t,balance:a})=>e.type==="XYK"?a>0n&&!!t:!!t)}updateBalances=(e,t)=>{let a=[],i=new Map(e.map(s=>[s.address,s]));for(let[s,n]of t){let r=i.get(s);if(r){let o=r.tokens.map(c=>{let l=n.find(p=>p.id===c.id);return l&&c.id!==r.id?{...c,balance:l.balance.transferable}:c});a.push({...r,tokens:o})}}return a};resync(e=!1){let t=Date.now();!e&&t-this.resyncAt<Ja||(this.resyncAt=t,this.mem++,this.resync$.next())}requestResync(e=!1){this.resyncPending||(this.resyncPending=!0,setTimeout(()=>{this.resyncPending=!1,this.resync(e)},0))}startWatchdog(){let i=this.watcher.connection$.pipe(Ue(),Oe(([r,o])=>r==="offline"&&o==="online"),N(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),le(r=>(this.log.error("watchdog_recovery_error",r),oe)),$e({delay:1e3})),s=this.watcher.finalizedBlock$.pipe(Ue(),N(([r,o])=>{let c=Number(r.number),l=Number(o.number),p=l-c;p>=3&&(this.log.debug("watchdog_gap",{from:c,to:l,gap:p}),this.requestResync())}),le(r=>(this.log.error("watchdog_gap_error",r),oe)),$e({delay:1e3})),n=Ua(36e5).pipe(N(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),le(r=>(this.log.error("watchdog_periodic_error",r),oe)),$e({delay:1e3}));return Ge(i,s,n).subscribe()}watchGuard(e){return t=>t.pipe(N({error:a=>{this.log.error(e,a),this.requestResync(!0)}}),Ve(()=>{this.log.debug(e,"unsub")}),le(()=>oe))}};var ce=class extends S{MAX_FINAL_WEIGHT=100000000n;poolsData=new Map([]);getPoolType(){return"LBP"}async getPoolLimits(){let[e,t,a]=await Promise.all([this.api.constants.LBP.MaxInRatio(),this.api.constants.LBP.MaxOutRatio(),this.api.constants.LBP.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:a}}getPoolWeights(e,t){let{start:a,end:i,initial_weight:s,final_weight:n}=e,r=O.calculateLinearWeights(a?a.toString():"0",i?i.toString():"0",s.toString(),n.toString(),t.toString()),o=BigInt(r),c=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,c]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Za.BackwardsCompatible)}async loadPools(){let[e,t,a]=await Promise.all([this.api.query.LBP.PoolData.getEntries({at:this.at}),this.api.query.ParachainSystem.ValidationData.getValue({at:this.at}),this.getPoolLimits()]),i=t?.relay_parent_number||0,s=e.filter(({value:n})=>t&&this.isActivePool(n,i)).map(async({keyArgs:n,value:r})=>{let[o]=n,c=o.toString(),l=await this.getPoolDelta(c,r,i);return{address:c,type:"LBP",fee:r.fee,...l,...a}});return Promise.all(s)}async getPoolDelta(e,t,a){let{assets:i,repay_target:s,fee_collector:n}=t,[r,o]=this.getPoolWeights(t,a),[c,l]=i,[p,m,d,g,b]=await Promise.all([this.isRepayFeeApplied(c,s,n.toString()),this.balance.getBalance(e,c),this.api.query.AssetRegistry.Assets.getValue(c,{at:this.at}),this.balance.getBalance(e,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at})]);return{repayFeeApply:p,tokens:[{id:c,decimals:d?.decimals,existentialDeposit:d?.existential_deposit,balance:m.transferable,weight:r,type:d?.asset_type.type},{id:l,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:g.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(e,t){let{start:a,end:i}=e;return a&&i?t>=a&&t<i:!1}async isRepayFeeApplied(e,t,a){if(t===0n)return!1;try{return(await this.balance.getBalance(a,e)).transferable<t}catch{return!0}}async getRepayFee(){return await this.api.constants.LBP.repay_fee()}async getPoolFees(e,t){let a=this.store.pools.find(s=>s.address===t);return{repayFee:await this.getRepayFee(),exchangeFee:a.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe(ii(({value:e})=>e),ai(e=>e!==void 0),ti((e,t)=>e.relay_parent_number===t.relay_parent_number),this.watchGuard("parachainSystem.ValidationData")).subscribe(({relay_parent_number:e})=>{this.store.update(async t=>{let a=[];for(let i of t){let s=this.poolsData.get(i.address);if(s){let{assets:n,repay_target:r,fee_collector:o}=s,[c]=n,[l,p]=this.getPoolWeights(s,e),[m,d]=i.tokens,g=[{...m,weight:l},{...d,weight:p}],b=await this.isRepayFeeApplied(c,r,o.toString());a.push({...i,tokens:g,repayFeeApply:b})}}return a})})}subscribeUpdates(){let e=new ei;return e.add(this.subscribeValidationData()),e}};var St={};F(St,{OmniMath:()=>h,OmniPool:()=>ue,OmniPoolClient:()=>pe,OmniPoolFee:()=>q,getEmaKey:()=>Fe,getEmaPair:()=>z});import{calculate_in_given_out as si,calculate_lrna_in_given_out as ni,calculate_out_given_in as ri,calculate_out_given_lrna_in as oi,calculate_spot_price as li,calculate_lrna_spot_price as ci,calculate_shares as ui,calculate_liquidity_out as pi,calculate_liquidity_lrna_out as mi,verify_asset_cap as di,calculate_liquidity_hub_in as gi,is_sell_allowed as bi,is_buy_allowed as hi,is_add_liquidity_allowed as yi,is_remove_liquidity_allowed as fi,recalculate_asset_fee as Pi,recalculate_protocol_fee as vi}from"@galacticcouncil/math-omnipool";import K from"big.js";var h=class{static calculateSpotPrice(e,t,a,i){return li(e,t,a,i)}static calculateLrnaSpotPrice(e,t){return ci(e,t)}static calculateInGivenOut(e,t,a,i,s,n,r,o,c,l){return si(e,t,a,i,s,n,r,o,c,l)}static calculateLrnaInGivenOut(e,t,a,i,s,n){return ni(e,t,a,i,s,n)}static calculateOutGivenIn(e,t,a,i,s,n,r,o,c,l){return ri(e,t,a,i,s,n,r,o,c,l)}static calculateOutGivenLrnaIn(e,t,a,i,s,n){return oi(e,t,a,i,s,n)}static calculateShares(e,t,a,i){return ui(e,t,a,i)}static calculateLiquidityOut(e,t,a,i,s,n,r,o){return pi(e,t,a,i,s,n,r,o)}static calculateLiquidityLRNAOut(e,t,a,i,s,n,r,o){return mi(e,t,a,i,s,n,r,o)}static calculateCapDifference(e,t,a,i){let s=K(t),n=K(e),r=K(i),o=K(a),c=K(10).pow(18),l=o.div(c);if(s.div(r).lt(l)){let m=l.times(r).minus(s).times(n),d=s.times(K(1).minus(l));return m.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(e,t,a,i){return gi(e,t,a,i)}static isSellAllowed(e){return bi(e)}static isBuyAllowed(e){return hi(e)}static isAddLiquidityAllowed(e){return yi(e)}static isRemoveLiquidityAllowed(e){return fi(e)}static recalculateAssetFee(e,t,a,i,s,n,r,o,c,l,p){return Pi(e,t,a,i,s,n,r,o,c,l,p)}static recalculateProtocolFee(e,t,a,i,s,n,r,o,c,l,p){return vi(e,t,a,i,s,n,r,o,c,l,p)}static verifyAssetCap(e,t,a,i){return di(e,t,a,i)}};import{big as Si}from"@galacticcouncil/common";var{FeeUtils:R}=y,ue=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,hubReservesIn:i.hubReserves,hubReservesOut:s.hubReserves,sharesIn:i.shares,sharesOut:s.shares,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,tradeableIn:i.tradeable,tradeableOut:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=this.calculateInGivenOut(e,t,a),n=i===0n?0:L.calculateBuyFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetInEd)&&r.push("InsufficientTradingAmount");let l=e.balanceOut/this.maxOutRatio;t>l&&r.push("MaxOutRatioExceeded");let p=e.balanceIn/this.maxInRatio;return s>p&&r.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:t,feePct:n,errors:r}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=this.calculateOutGivenIn(e,t,a),n=L.calculateSellFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetOutEd)&&r.push("InsufficientTradingAmount");let l=e.balanceIn/this.maxInRatio;t>l&&r.push("MaxInRatioExceeded");let p=e.balanceOut/this.maxOutRatio;return s>p&&r.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:s,feePct:n,errors:r}}calculateInGivenOut(e,t,a){if(e.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(e,t,a);let i=h.calculateInGivenOut(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.protocolFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateLrnaInGivenOut(e,t,a){let i=h.calculateLrnaInGivenOut(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(e,t,a){if(e.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(e,t,a);let i=h.calculateOutGivenIn(e.balanceIn.toString(),e.hubReservesIn.toString(),e.sharesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.protocolFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenLrnaIn(e,t,a){let i=h.calculateOutGivenLrnaIn(e.balanceOut.toString(),e.hubReservesOut.toString(),e.sharesOut.toString(),t.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(e){if(e.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(e);let t=h.calculateSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString(),e.balanceIn.toString(),e.hubReservesIn.toString());return this.normalizeSpot(BigInt(t),e.decimalsOut,e.decimalsIn)}spotPriceLrnaInGivenOut(e){let t=h.calculateLrnaSpotPrice(e.hubReservesOut.toString(),e.balanceOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsOut,e.decimalsIn)}spotPriceOutGivenIn(e){if(e.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(e);let t=h.calculateSpotPrice(e.balanceIn.toString(),e.hubReservesIn.toString(),e.balanceOut.toString(),e.hubReservesOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsIn,e.decimalsOut)}spotPriceOutGivenLrnaIn(e){let t=h.calculateLrnaSpotPrice(e.balanceOut.toString(),e.hubReservesOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsIn,e.decimalsOut)}normalizeSpot(e,t,a){let i=t-a;if(i===0)return e;let s=Si.pow10(Math.abs(i));return i>0?e*s:e/s}};import{AccountId as Ti,Binary as ft,CompatibilityLevel as xi,Enum as Ai}from"polkadot-api";import{toHex as wi}from"@polkadot-api/utils";import{Subscription as Ii,distinctUntilChanged as _e,finalize as We,map as Ee,tap as Re}from"rxjs";import{HYDRATION_SS58_PREFIX as Oi}from"@galacticcouncil/common";var{FeeUtils:v}=y,q=class u{static compute(e,t,a,i,s,n,r,o){let c=e.assetIn,[l,p,m]=u.getAssetFee(e,t,a,i,n),d=0,g=0,b=0;c!==1&&([d,g,b]=u.getProtocolFee(e,t,a,s,r));let B=l+d,x=m+b;return{assetFee:v.fromPermill(p),protocolFee:v.fromPermill(g),maxSlipFee:v.fromPermill(o),min:v.fromPermill(B),max:v.fromPermill(x)}}static getAssetFee(e,t,a,i,s){let{assetOut:n,balanceOut:r}=e,{min_fee:o,max_fee:c,decay:l,amplification:p}=s;if(!a||!i)return[o,o,c];let m=v.fromPermill(o),d=v.fromPermill(c),[g]=i,{asset_fee:b,timestamp:B}=a,x=Math.max(1,t-B),A=g.volume.b_in.toString(),w=g.volume.b_out.toString(),I=g.liquidity.b.toString();n===0&&(A=g.volume.a_in.toString(),w=g.volume.a_out.toString(),I=g.liquidity.a.toString());let D=v.fromPermill(b),te=h.recalculateAssetFee(A,w,I,"9",r.toString(),v.toRaw(D).toString(),x.toString(),v.toRaw(m).toString(),v.toRaw(d).toString(),l.toString(),p.toString());return[o,Number(te)*1e6,c]}static getProtocolFee(e,t,a,i,s){let{assetIn:n,balanceIn:r}=e,{min_fee:o,max_fee:c,decay:l,amplification:p}=s;if(!a||!i)return[o,o,c];let m=v.fromPermill(o),d=v.fromPermill(c),[g]=i,{protocol_fee:b,timestamp:B}=a,x=Math.max(1,t-B),A=g.volume.b_in.toString(),w=g.volume.b_out.toString(),I=g.liquidity.b.toString();n===0&&(A=g.volume.a_in.toString(),w=g.volume.a_out.toString(),I=g.liquidity.a.toString());let D=v.fromPermill(b),te=h.recalculateProtocolFee(A,w,I,"9",r.toString(),v.toRaw(D).toString(),x.toString(),v.toRaw(m).toString(),v.toRaw(d).toString(),l.toString(),p.toString());return[o,Number(te)*1e6,c]}};var z=u=>u===0?[0,1]:[1,u],Fe=u=>z(u).join(":");var{FeeUtils:Ye}=y,Pt=ft.toHex(ft.fromText("omnipool")),vt=Ai("Short"),pe=class extends S{queryBus=new $;block=0;dynamicFeesConfig=this.queryBus.scope("DynamicFees.AssetFeeConfiguration",e=>this.api.query.DynamicFees.AssetFeeConfiguration.getValue(e,{at:this.at}),e=>String(e));dynamicFees=this.queryBus.scope("DynamicFees.AssetFee",e=>this.api.query.DynamicFees.AssetFee.getValue(e,{at:this.at}),e=>String(e),6*1e3);maxSlipFee=this.queryBus.scope("Omnipool.SlipFee",()=>this.apiNext.query.Omnipool.SlipFee.getValue({at:this.at}),()=>"slipFee");emaOracles=this.queryBus.scope("EmaOracle.Oracles.Short",e=>this.api.query.EmaOracle.Oracles.getValue(Pt,e,vt,{at:this.at}),e=>e.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let e="modlomnipool".padEnd(32,"\0"),t=new TextEncoder().encode(e),a=wi(t);return Ti(Oi).dec(a)}async getPoolLimits(){let[e,t,a]=await Promise.all([this.api.constants.Omnipool.MaxInRatio(),this.api.constants.Omnipool.MaxOutRatio(),this.api.constants.Omnipool.MinimumTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:a}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Omnipool.Assets.isCompatible(xi.BackwardsCompatible)}async loadPools(){let e=await this.api.constants.Omnipool.HubAssetId(),t=this.getPoolAddress(),[a,i,s,n,r,o]=await Promise.all([this.api.query.Omnipool.Assets.getEntries({at:this.at}),this.api.query.Omnipool.HubAssetTradability.getValue({at:this.at}),this.api.query.AssetRegistry.Assets.getValue(e,{at:this.at}),this.balance.getBalance(t,e),this.getPoolLimits(),this.api.query.System.Number.getValue({at:this.at})]);this.block=o;let c=a.map(async({keyArgs:p,value:m})=>{let[d]=p,{hub_reserve:g,shares:b,tradable:B,cap:x,protocol_shares:A}=m,[w,I]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(d,{at:this.at}),this.balance.getBalance(t,d)]);return{id:d,decimals:w?.decimals,existentialDeposit:w?.existential_deposit,balance:I.transferable,cap:x,hubReserves:g,protocolShares:A,shares:b,tradeable:B,type:w?.asset_type.type}}),l=await Promise.all(c);return l.push({id:e,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:n.transferable,tradeable:i,type:s?.asset_type.type}),[{address:t,type:"Omnipool",hubAssetId:e,tokens:l,...r}]}async getPoolFees(e){let t=e.assetOut,a=e.assetIn,s=await this.maxSlipFee.get()??0,n=await this.dynamicFeesConfig.get(t);if(n?.type==="Fixed"){let{asset_fee:m,protocol_fee:d}=n.value;return{assetFee:Ye.fromPermill(m),protocolFee:Ye.fromPermill(d),maxSlipFee:Ye.fromPermill(s)}}let[r,o,c,l,p]=await Promise.all([this.dynamicFees.get(t),this.emaOracles.get(z(t)),this.emaOracles.get(z(a)),n?n.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),n?n.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return q.compute(e,this.block,r,o,c,l,p,s)}subscribeEmaOracles(){let[e]=this.store.pools,t=new Set(e.tokens.map(a=>z(a.id).join(":")));return this.api.query.EmaOracle.Oracles.watchEntries(Pt,{at:"best"}).pipe(_e((a,i)=>!i.deltas),Ee((a,i)=>({value:a,index:i})),Re(({value:a,index:i})=>{i>0&&this.log.trace("emaOracle.Oracles",a.deltas?.upserted)}),We(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(({value:{deltas:a}})=>{a?.upserted.forEach(i=>{let[,s,n]=i.args;n.type===vt.type&&t.has(s.join(":"))&&this.emaOracles.set(i.value,s)})})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe(_e((e,t)=>!t.deltas),Ee((e,t)=>({value:e,index:t})),Re(({value:e,index:t})=>{t>0&&this.log.trace("dynamicFees.AssetFee",e.deltas?.upserted)}),We(()=>this.dynamicFees.clear()),this.watchGuard("dynamicFees.AssetFee")).subscribe(({value:{deltas:e}})=>{e?.upserted.forEach(t=>{let[a]=t.args;this.dynamicFees.set(t.value,a)})})}subscribeDynamicFeesConfig(){return this.api.query.DynamicFees.AssetFeeConfiguration.watchEntries({at:"best"}).pipe(_e((e,t)=>!t.deltas),Ee((e,t)=>({value:e,index:t})),Re(({value:e,index:t})=>{t>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",e.deltas?.upserted)}),We(()=>this.dynamicFeesConfig.clear()),this.watchGuard("dynamicFees.AssetFeeConfiguration")).subscribe(({value:{deltas:e}})=>{e?.upserted.forEach(t=>{let[a]=t.args;this.dynamicFeesConfig.set(t.value,a)})})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(e=>{this.block=e})}subscribeAssets(){return this.api.query.Omnipool.Assets.watchEntries({at:"best"}).pipe(_e((e,t)=>!t.deltas),Ee((e,t)=>({value:e,index:t})),Re(({value:e,index:t})=>{t>0&&this.log.trace("omnipool.Assets",e.deltas?.upserted)}),this.watchGuard("omnipool.Assets")).subscribe(({value:{deltas:e}})=>{this.store.update(([t])=>{let a=e?.upserted.reduce((s,n)=>{let[r]=n.args;return s.set(r,n.value),s},new Map),i=t.tokens.map(s=>{let n=a?.get(s.id);return n?this.updateTokenState(s,n):s});return[{...t,tokens:i}]})})}subscribeUpdates(){let e=new Ii;return e.add(this.subscribeAssets()),e.add(this.subscribeDynamicFees()),e.add(this.subscribeDynamicFeesConfig()),e.add(this.subscribeEmaOracles()),e.add(this.subscribeBlock()),e}updateTokenState(e,t){let{hub_reserve:a,shares:i,tradable:s,cap:n,protocol_shares:r}=t;return{...e,cap:n,hubReserves:a,protocolShares:r,shares:i,tradeable:s}}};var Et={};F(Et,{StableMath:()=>P,StableSwap:()=>G,StableSwapClient:()=>be});import{calculate_in_given_out as Bi,calculate_out_given_in as Fi,calculate_amplification as _i,calculate_add_one_asset as Ei,calculate_liquidity_out_one_asset as Ri,calculate_shares as ki,calculate_shares_for_amount as Ci,calculate_spot_price_with_fee as Mi,pool_account_name as Li,recalculate_peg as Di}from"@galacticcouncil/math-stableswap";var P=class{static getPoolAddress(e){return Li(e)}static defaultPegs(e){let t=[];for(let a=0;a<e;a++)t.push(["1","1"]);return t}static calculateAmplification(e,t,a,i,s){return _i(e,t,a,i,s)}static calculateInGivenOut(e,t,a,i,s,n,r){return Bi(e,t,a,i,s,n,r)}static calculateAddOneAsset(e,t,a,i,s,n,r){return Ei(e,t,a,i,s,n,r)}static calculateSharesForAmount(e,t,a,i,s,n,r){return Ci(e,t,a,i,s,n,r)}static calculateOutGivenIn(e,t,a,i,s,n,r){return Fi(e,t,a,i,s,n,r)}static calculateLiquidityOutOneAsset(e,t,a,i,s,n,r){return Ri(e,t,a,i,s,n,r)}static calculateShares(e,t,a,i,s,n){return ki(e,t,a,i,s,n)}static calculateSpotPriceWithFee(e,t,a,i,s,n,r,o){return Mi(e,t,a,i,s,n,r,o)}static recalculatePegs(e,t,a,i,s,n){let r=Di(e,t,a,i,s,n);return JSON.parse(r)}};import{RUNTIME_DECIMALS as Hi,big as Tt}from"@galacticcouncil/common";var{FeeUtils:j}=y,G=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(e){return new u(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.isRampPeriod=e.isRampPeriod,this.id=e.id,this.fee=e.fee,this.totalIssuance=e.totalIssuance,this.pegs=e.pegs}validatePair(e,t){return!0}parsePair(e,t){let a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,tradeableIn:this.id===e?15:i.tradeable,tradeableOut:this.id===t?15:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=this.calculateInGivenOut(e,t,a),n=i===0n?0:L.calculateBuyFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);return(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:i,amountOut:t,feePct:n,errors:r}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=this.calculateOutGivenIn(e,t,a),n=L.calculateSellFee(i,s),r=[],o=h.isSellAllowed(e.tradeableIn),c=h.isBuyAllowed(e.tradeableOut);return(!o||!c)&&r.push("TradeNotAllowed"),(t<this.minTradingLimit||i<e.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:t,calculatedOut:i,amountOut:s,feePct:n,errors:r}}calculateIn(e,t,a){let i=P.calculateInGivenOut(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),a?j.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateAddOneAsset(e,t,a){let i=P.calculateAddOneAsset(this.getReserves(),t.toString(),Number(e.assetIn),this.amplification.toString(),this.totalIssuance.toString(),a?j.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateSharesForAmount(e,t,a){let i=P.calculateSharesForAmount(this.getReserves(),Number(e.assetOut),t.toString(),this.amplification.toString(),this.totalIssuance.toString(),a?j.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateInGivenOut(e,t,a){return e.assetOut==this.id?this.calculateAddOneAsset(e,t,a):e.assetIn==this.id?this.calculateSharesForAmount(e,t,a):this.calculateIn(e,t,a)}spotPriceInGivenOut(e){let t=P.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetOut.toString(),e.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(t),e.assetOut===this.id,e.assetIn===this.id,e.decimalsOut,e.decimalsIn)}calculateOut(e,t,a){let i=P.calculateOutGivenIn(this.getReserves(),Number(e.assetIn),Number(e.assetOut),t.toString(),this.amplification.toString(),a?j.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateWithdrawOneAsset(e,t,a){let i=P.calculateLiquidityOutOneAsset(this.getReserves(),t.toString(),Number(e.assetOut),this.amplification.toString(),this.totalIssuance.toString(),a?j.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateShares(e,t,a){let i=P.calculateShares(this.getReserves(),this.getAssets(e.assetIn,t),this.amplification.toString(),this.totalIssuance.toString(),a?j.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(e,t,a){return e.assetIn==this.id?this.calculateWithdrawOneAsset(e,t,a):e.assetOut==this.id?this.calculateShares(e,t,a):this.calculateOut(e,t,a)}spotPriceOutGivenIn(e){let t=P.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),e.assetIn.toString(),e.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(t),e.assetIn===this.id,e.assetOut===this.id,e.decimalsIn,e.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let e=this.tokens.filter(t=>t.id!=this.id).map(({id:t,balance:a,decimals:i})=>({asset_id:t,amount:a,decimals:i}));return JSON.stringify(e,ae.jsonFormatter)}getAssets(e,t){let a={asset_id:Number(e),amount:t.toString()};return JSON.stringify([a],ae.jsonFormatter)}normalizeSpot(e,t,a,i,s){return t?e*Tt.pow10(Hi-s):a?e/Tt.pow10(s-i):e}};import{AccountId as qi,CompatibilityLevel as Gi}from"polkadot-api";import{toHex as Vi}from"@polkadot-api/utils";import{blake2b as Ui}from"@noble/hashes/blake2b";import{Subscription as $i,distinctUntilChanged as _t,filter as Wi,map as J,merge as Yi,tap as Ke}from"rxjs";import{HYDRATION_SS58_PREFIX as Xi,RUNTIME_DECIMALS as Ki}from"@galacticcouncil/common";import{Binary as Ni}from"polkadot-api";import{decodeEventLog as wt}from"viem";var Xe=[{inputs:[],name:"decimals",outputs:[{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"description",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"view",type:"function"},{inputs:[],name:"version",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"uint80",name:"_roundId",type:"uint80"}],name:"getRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"},{inputs:[],name:"latestRoundData",outputs:[{internalType:"uint80",name:"roundId",type:"uint80"},{internalType:"int256",name:"answer",type:"int256"},{internalType:"uint256",name:"startedAt",type:"uint256"},{internalType:"uint256",name:"updatedAt",type:"uint256"},{internalType:"uint80",name:"answeredInRound",type:"uint80"}],stateMutability:"view",type:"function"}],xt=[{anonymous:!1,inputs:[{indexed:!1,name:"key",type:"string"},{indexed:!1,name:"value",type:"uint128"},{indexed:!1,name:"timestamp",type:"uint128"}],name:"OracleUpdate",type:"event"}],At=[{anonymous:!1,inputs:[{indexed:!0,name:"roundId",type:"uint80"},{indexed:!1,name:"answer",type:"int256"},{indexed:!1,name:"timestamp",type:"uint256"}],name:"PriceUpdated",type:"event"}];var me=class{static parse(e){let{address:t,topics:a,data:i}=e.log,s=t.toLowerCase(),n=Ni.toHex(i);try{let{eventName:r,args:o}=wt({abi:At,topics:a,data:n});return{eventName:`ManagedOracle.${r}`,emitter:s,value:o.answer,timestamp:o.timestamp}}catch{}try{let{eventName:r,args:o}=wt({abi:xt,topics:a,data:n});return{eventName:`DIA.${r}`,emitter:s,key:o.key,value:o.value,timestamp:o.timestamp}}catch{}}};var de=class{adapter;constructor(e){this.adapter=e.getRPCAdapter()}async getData(e,t=6){let[a,i,s]=await Promise.all([this.adapter.readContract({abi:Xe,address:e,functionName:"latestRoundData"}),this.adapter.readContract({abi:Xe,address:e,functionName:"decimals"}),this.adapter.getBlock()]),[n,r,o,c]=a,l=s.number-(s.timestamp-c)/BigInt(t),p=Number(l);return{price:r,decimals:i,updatedAt:p<0?0:p}}};var It={"EUR/USD":"0xaa47a5662269270d3df33ae08f806e383611575c","sUSDs/USD":"0x4b32bffc6acd751446e79e8687ef3815fd7924fd","sUSDe/USD":"0x22cdea305cee63d082e79f8c5db939eecd0265d0"},Ot={"0xcfab6a4031c70da0f0cf6f31a252c16119db3611":"0xaafd758688cefd0a7b7770a825f1aad551e16185"},Bt={"bifrosto:5:15:LastBlock":"0xaafd758688cefd0a7b7770a825f1aad551e16185"};function Ft(u,e,t){let a=Buffer.from(u.replace(/^0x/,""),"hex").toString("ascii").replace(/\0+$/,""),[i,s]=[e[0],e[1]].sort((n,r)=>n-r);return`${a}:${i}:${s}:${t}`}var{FeeUtils:Q}=y,ge=class u{static compute(e,t,a,i){let s=u.getRecent(t),n=Q.fromPermill(e.fee),r=Q.fromPerbill(t.max_peg_update),o=a.map(({pair:g,updatedAt:b})=>[g,b]),c=a.find(g=>g.source),l=t.updated_at?t.updated_at.toString():c?.updatedAt;if(!l)throw new Error("Current peg unknown!");let[p,m]=P.recalculatePegs(JSON.stringify(s),l,JSON.stringify(o),i.toString(),Q.toRaw(r).toString(),Q.toRaw(n).toString()),d=Number(p)*1e6;return{pegsFee:Q.fromPermill(d),pegs:m}}static getDefault(e){return{pegsFee:Q.fromPermill(e.fee),pegs:P.defaultPegs(e.assets.length)}}static getRecent(e){let{current:t}=e;return Array.from(t.entries()).map(([a,i])=>i.map(s=>s.toString()))}};var{FeeUtils:zi}=y,ji=["ManagedOracle.PriceUpdated","DIA.OracleUpdate"],be=class extends S{poolsData=new Map([]);mmOracle=new de(this.evm);mmAddresses=new Set;mmRouting={byEmitter:new Map,byDiaKey:new Map,byEma:new Map};queryBus=new $;emaOracles=this.queryBus.scope("EmaOracle.Oracles",(e,t,a)=>this.api.query.EmaOracle.Oracles.getValue(e,t,a,{at:this.at}),(e,t,a)=>`${e.toString()}:${t.join(":")}:${a.type}`,6*1e3);mmOracles=this.queryBus.scope("MmOracle",e=>this.mmOracle.getData(e),e=>e.toLowerCase(),600*1e3);pegs=this.queryBus.scope("Stableswap.PoolPegs",e=>this.api.query.Stableswap.PoolPegs.getValue(e,{at:this.at}),e=>String(e),6*1e3);getPoolType(){return"Stableswap"}getPoolAddress(e){let t=P.getPoolAddress(e),a=Ui(t,{dkLen:32}),i=Vi(a);return qi(Xi).dec(i)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(e,t){let{initial_amplification:a,final_amplification:i,initial_block:s,final_block:n}=e,r=P.calculateAmplification(a.toString(),i.toString(),s.toString(),n.toString(),t.toString()),o=Number(r)<i;return{amplification:BigInt(r),isRampPeriod:o}}async getPoolTokens(e,t){let a=this.getPoolAddress(e),i=t.assets.map(async s=>{let[n,r,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(e,s,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.balance.getBalance(a,s)]);return{id:s,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:o.transferable,tradeable:n,type:r?.asset_type.type}});return Promise.all(i)}buildRouting(){this.mmRouting.byEmitter.clear(),this.mmRouting.byDiaKey.clear(),this.mmRouting.byEma.clear();for(let e of this.mmAddresses)this.mmRouting.byEmitter.set(e,e);for(let[e,t]of Object.entries(Ot)){let a=e.toLowerCase(),i=t.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byEmitter.set(a,i)}for(let[e,t]of Object.entries(It)){let a=t.toLowerCase();this.mmAddresses.has(a)&&this.mmRouting.byDiaKey.set(e,a)}for(let[e,t]of Object.entries(Bt)){let a=t.toLowerCase();this.mmAddresses.has(a)&&this.mmRouting.byEma.set(e,a)}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(Gi.BackwardsCompatible)}async loadPools(){let[e,t,a,i]=await Promise.all([this.api.query.Stableswap.Pools.getEntries({at:this.at}),this.api.query.Stableswap.PoolPegs.getEntries({at:this.at}),this.api.query.System.Number.getValue({at:this.at}),this.getPoolLimits()]);for(let{keyArgs:n,value:r}of t){let[o]=n;this.pegs.set(r,o);for(let c of r.source)c.type==="MMOracle"&&this.mmAddresses.add(c.value.toString().toLowerCase())}this.buildRouting();let s=e.map(async({keyArgs:n,value:r})=>{let[o]=n,c=this.getPoolAddress(o),[l,p,m,d]=await Promise.all([this.getPoolTokens(o,r),this.getPoolAmplification(r,a),this.getPoolPegs(o,r,a),this.api.query.Tokens.TotalIssuance.getValue(o,{at:this.at})]);return l.push({id:o,tradeable:15,balance:d,decimals:Ki}),this.poolsData.set(o,r),{address:c,id:o,type:"Stableswap",fee:zi.fromPermill(r.fee),tokens:l,totalIssuance:d,...m,...i,...p}});return Promise.all(s)}async getPoolFees(e,t){return{fee:this.store.pools.find(i=>i.address===t).fee}}async getPoolPegs(e,t,a){let i=await this.pegs.get(e);if(!i)return ge.getDefault(t);let s=await this.getLatestPegs(t,i,a);return ge.compute(t,i,s,a)}async getLatestPegs(e,t,a){let{source:i}=t,s=e.assets,n=i.map(async(r,o)=>{if(r.type==="Oracle"){let[c,l,p]=r.value,m=[p,s[o]].sort((x,A)=>x-A),d=await this.emaOracles.get(c,m,l);if(!d)throw new Error("EmaOracle missing for "+c+" / "+m);let[{price:g,updated_at:b}]=d;return{pair:p===m[0]?[g.n.toString(),g.d.toString()]:[g.d.toString(),g.n.toString()],updatedAt:b.toString(),source:r.type}}if(r.type==="MMOracle"){let c=r.value.toString(),{price:l,decimals:p,updatedAt:m}=await this.mmOracles.get(c),d=(10n**BigInt(p)).toString();return{pair:[l.toString(),d],updatedAt:m.toString(),source:r.type}}if(r.type==="Value")return{pair:r.value.map(l=>l.toString()),updatedAt:a.toString()};throw new Error(r+" source not supported")});return Promise.all(n)}subscribeIssuance(){let t=this.store.pools.map(a=>a.id).map(a=>this.api.query.Tokens.TotalIssuance.watchValue(a,{at:"best"}).pipe(J(({value:i})=>i),J((i,s)=>({value:i,index:s})),Ke(({index:i,value:s})=>{i>0&&this.log.trace("tokens.TotalIssuance",a,s)}),J(({value:i})=>({id:a,value:i}))));return Yi(...t).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(a=>{let{id:i,value:s}=a;this.store.update(n=>{let r=[];return n.filter(o=>o.id===i).forEach(o=>{let c=o.tokens.map(l=>l.id===i?{...l,balance:s}:l);r.push({...o,tokens:c,totalIssuance:s})}),r})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe(_t((e,t)=>!t.deltas),J((e,t)=>({value:e,index:t})),Ke(({value:e,index:t})=>{t>0&&this.log.trace("stableswap.PoolPegs",e.deltas?.upserted)}),this.watchGuard("stableswap.PoolPegs")).subscribe({error:e=>this.log.error("stableswap.PoolPegs",e),next:({value:{deltas:e}})=>{for(let{args:t,value:a}of e?.upserted??[]){let[i]=t;this.pegs.set(a,i)}}})}subscribeEmaOracles(){return this.api.query.EmaOracle.Oracles.watchEntries({at:"best"}).pipe(_t((e,t)=>!t.deltas),J((e,t)=>({value:e,index:t})),Ke(({value:e,index:t})=>{t>0&&this.log.trace("emaOracle.Oracles",e.deltas?.upserted)}),this.watchGuard("emaOracle.Oracles")).subscribe(async({value:{deltas:e}})=>{let t=new Set;for(let{args:a,value:i}of e?.upserted??[]){let[s,n,r]=a;this.emaOracles.set(i,s,n,r);let o=Ft(s,n,r.type),c=this.mmRouting.byEma.get(o);c&&t.add(c)}for(let a of t){let i=await this.mmOracle.getData(a);this.log.trace("mmOracle.Hybrid",{h160:a,fresh:i}),this.mmOracles.set(i,a)}})}subscribeMMOracles(){return this.api.event.EVM.Log.watch().pipe(J(({events:e})=>e.map(t=>me.parse(t.payload)).filter(t=>!!t).filter(({eventName:t})=>ji.includes(t))),Wi(e=>e.length>0),this.watchGuard("evm.Log")).subscribe(async e=>{let t=new Set;for(let a of e){if(console.log(a),a.eventName==="ManagedOracle.PriceUpdated"){let i=this.mmRouting.byEmitter.get(a.emitter);i&&t.add(i)}if(a.eventName==="DIA.OracleUpdate"&&a.key){let i=this.mmRouting.byDiaKey.get(a.key);i&&t.add(i)}}for(let a of t){let i=await this.mmOracle.getData(a);this.log.trace("mmOracle",{h160:a,fresh:i}),this.mmOracles.set(i,a)}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(e=>{this.store.update(async t=>{let a=[];for(let i of t){let s=this.poolsData.get(i.id);if(s){let n=await this.getPoolPegs(i.id,s,e),r=this.getPoolAmplification(s,e);a.push({...i,...n,...r})}}return a})})}subscribeUpdates(){let e=new $i;return e.add(this.subscribePoolPegs()),e.add(this.subscribeEmaOracles()),e.add(this.subscribeMMOracles()),e.add(this.subscribeIssuance()),e.add(this.subscribeBlock()),e}};var kt={};F(kt,{XykMath:()=>C,XykPool:()=>he,XykPoolClient:()=>ye});import{calculate_in_given_out as Qi,calculate_out_given_in as Ji,calculate_pool_trade_fee as Zi,get_spot_price as es,calculate_liquidity_in as ts,calculate_shares as as,calculate_spot_price as is,calculate_spot_price_with_fee as ss,calculate_liquidity_out_asset_a as ns,calculate_liquidity_out_asset_b as rs}from"@galacticcouncil/math-xyk";var C=class{static getSpotPrice(e,t,a){return es(e,t,a)}static calculateInGivenOut(e,t,a){return Qi(e,t,a)}static calculateOutGivenIn(e,t,a){return Ji(e,t,a)}static calculatePoolTradeFee(e,t,a){return Zi(e,t,a)}static calculateLiquidityIn(e,t,a){return ts(e,t,a)}static calculateSpotPrice(e,t){return is(e,t)}static calculateSpotPriceWithFee(e,t,a,i){return ss(e,t,a,i)}static calculateShares(e,t,a){return as(e,t,a)}static calculateLiquidityOutAssetA(e,t,a,i){return ns(e,t,a,i)}static calculateLiquidityOutAssetB(e,t,a,i){return rs(e,t,a,i)}};import{big as os}from"@galacticcouncil/common";var{FeeUtils:Rt}=y,he=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=this.calculateTradeFee(i,a),n=Rt.toPct(a.exchangeFee),r=i+s,o=[];(t<this.minTradingLimit||i<e.assetInEd)&&o.push("InsufficientTradingAmount");let c=e.balanceOut/this.maxOutRatio;t>c&&o.push("MaxOutRatioExceeded");let l=e.balanceIn/this.maxInRatio;return r>l&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:i,amountOut:t,feePct:n,errors:o}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=this.calculateTradeFee(i,a),n=Rt.toPct(a.exchangeFee),r=i-s,o=[];(t<this.minTradingLimit||i<e.assetOutEd)&&o.push("InsufficientTradingAmount");let c=e.balanceIn/this.maxInRatio;t>c&&o.push("MaxInRatioExceeded");let l=e.balanceOut/this.maxOutRatio;return r>l&&o.push("MaxOutRatioExceeded"),{amountIn:t,calculatedOut:i,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(e,t){let a=C.calculateInGivenOut(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(e,t){let a=C.calculateOutGivenIn(e.balanceIn.toString(),e.balanceOut.toString(),t.toString()),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(e){let t=C.calculateSpotPrice(e.balanceOut.toString(),e.balanceIn.toString());return this.normalizeSpot(BigInt(t),e.decimalsOut,e.decimalsIn)}spotPriceOutGivenIn(e){let t=C.calculateSpotPrice(e.balanceIn.toString(),e.balanceOut.toString());return this.normalizeSpot(BigInt(t),e.decimalsIn,e.decimalsOut)}calculateTradeFee(e,t){let a=C.calculatePoolTradeFee(e.toString(),t.exchangeFee[0],t.exchangeFee[1]);return BigInt(a)}normalizeSpot(e,t,a){let i=t-a;if(i===0)return e;let s=os.pow10(Math.abs(i));return i>0?e*s:e/s}};import{CompatibilityLevel as ls}from"polkadot-api";import{Subscription as cs}from"rxjs";var ye=class extends S{decimals=new Map([]);getPoolType(){return"XYK"}async withOverride(e){this.decimals=e?new Map(e.map(t=>[t.id,t.decimals])):new Map}async getPoolLimits(){let[e,t,a]=await Promise.all([this.api.constants.XYK.MaxInRatio(),this.api.constants.XYK.MaxOutRatio(),this.api.constants.XYK.MinTradingLimit()]);return{maxInRatio:e,maxOutRatio:t,minTradingLimit:a}}async isSupported(){return(await this.api.getStaticApis()).compat.query.XYK.PoolAssets.isCompatible(ls.BackwardsCompatible)}async loadPools(){let[e,t]=await Promise.all([this.api.query.XYK.PoolAssets.getEntries({at:this.at}),this.getPoolLimits()]),a=e.map(async({keyArgs:i,value:s})=>{let[n]=i,[r,o]=s,[c,l,p,m]=await Promise.all([this.balance.getBalance(n,r),this.api.query.AssetRegistry.Assets.getValue(r,{at:this.at}),this.balance.getBalance(n,o),this.api.query.AssetRegistry.Assets.getValue(o,{at:this.at})]);return{address:n,type:"XYK",tokens:[{id:r,decimals:l?.decimals||this.decimals.get(r),existentialDeposit:l?.existential_deposit,balance:c.transferable,type:l?.asset_type.type},{id:o,decimals:m?.decimals||this.decimals.get(o),existentialDeposit:m?.existential_deposit,balance:p.transferable,type:m?.asset_type.type}],...t}});return Promise.all(a)}async getPoolFees(){return{exchangeFee:await this.getExchangeFee()}}async getExchangeFee(){return await this.api.constants.XYK.GetExchangeFee()}subscribeUpdates(){return cs.EMPTY}};var Nt={};F(Nt,{AavePool:()=>fe,AavePoolClient:()=>Pe});import{big as Ct,RUNTIME_DECIMALS as Mt}from"@galacticcouncil/common";var fe=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(e){return new u(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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(e),s=a.get(t);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:e,assetOut:t,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(e,t,a){let i=this.calculateInGivenOut(e,t),s=[];return t>e.balanceOut&&s.push("TradeNotAllowed"),{amountIn:i,calculatedIn:i,amountOut:t,feePct:0,errors:s}}validateAndSell(e,t,a){let i=this.calculateOutGivenIn(e,t),s=[];return i>e.balanceOut&&s.push("TradeNotAllowed"),{amountIn:t,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateInGivenOut(e,t){return t}calculateOutGivenIn(e,t){return t}spotPriceInGivenOut(e){return Ct.toBigInt(1,Mt)}spotPriceOutGivenIn(e){return Ct.toBigInt(1,Mt)}calculateTradeFee(e,t){return 0n}};import{AccountId as gs}from"polkadot-api";import{toHex as bs}from"@polkadot-api/utils";import{Subscription as Lt,filter as je,map as Dt,mergeMap as Ht}from"rxjs";import{erc20 as hs,HYDRATION_SS58_PREFIX as ys}from"@galacticcouncil/common";var ze=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var Cu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{Binary as us}from"polkadot-api";import{decodeEventLog as ps}from"viem";var Ce=class{static parse(e){let{topics:t,data:a}=e.log,i=us.toHex(a);try{let{eventName:s,args:n}=ps({abi:ze,topics:t,data:i}),r=n.reserve.toLowerCase();return{eventName:s,reserve:r,key:`${s}:${r}`}}catch{return}}};import Ju from"big.js";import{big as ep,erc20 as ms,h160 as ds}from"@galacticcouncil/common";var{ERC20:ap}=ms,{H160:ip}=ds;var sp=10n**27n;var{ERC20:fs}=hs,Ps=["Supply","Withdraw","Repay","Borrow"],Pe=class extends S{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(e,t){let a=e+"/"+t,i=new TextEncoder().encode(a.padEnd(32,"\0")),s=bs(i);return gs(ys).dec(s)}getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:0n}}async loadPools(){let t=(await this.api.apis.AaveTradeExecutor.pools({at:this.at})).map(async({reserve:a,atoken:i,liqudity_in:s,liqudity_out:n})=>{let[r,o,c,l]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(a,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(a,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(i,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(i,{at:this.at})]);return{address:this.getPoolId(a,i),type:"Aave",tokens:[{id:a,decimals:r?.decimals,existentialDeposit:r?.existential_deposit,balance:s,location:o,type:r?.asset_type.type},{id:i,decimals:c?.decimals,existentialDeposit:c?.existential_deposit,balance:n,location:l,type:c?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(t)}async getPoolDelta(e){let[t,a]=e.tokens,{liqudity_in:i,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(t.id,a.id,{at:this.at});return e.tokens.map(n=>{let r=n.id===t.id?i:s;return{...n,balance:r}})}async getPoolFees(){return{}}getReserveH160Id(e){if(e.type==="Erc20"&&e.location){let t=e.location.interior;if(t.type==="X1"&&t.value.type==="AccountKey20"){let{value:a}=t.value;return a.key}throw new Error("Invalid aave reserve multilocation")}return fs.fromAssetId(e.id)}parseRouterLog(e){let{asset_in:t,asset_out:a}=e;return{assetIn:t,assetOut:a,key:`${t}:${a}`}}subscribeRouterExecuted(){let t=this.store.pools.map(a=>a.tokens).map(([a,i])=>i).map(a=>a.id);return this.api.event.Router.Executed.watch().pipe(Ht(({events:a})=>a),Dt(({payload:a})=>this.parseRouterLog(a)),je(({assetIn:a,assetOut:i})=>t.includes(a)||t.includes(i)),this.watchGuard("router.Execute")).subscribe(({assetIn:a,assetOut:i,key:s})=>{this.log.trace("router.Executed",s),this.store.update(async n=>{let r=[];for(let o of n){let[c,l]=o.tokens;if(l.id===a||l.id===i){let m=await this.getPoolDelta(o);r.push({...o,tokens:m})}}return r})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Ht(({events:e})=>e),Dt(({payload:e})=>Ce.parse(e)),je(e=>e!==void 0),je(({eventName:e})=>Ps.includes(e)),this.watchGuard("evm.Log")).subscribe(({reserve:e,eventName:t})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async a=>{let i=[];for(let s of a){let[n]=s.tokens;if(this.getReserveH160Id(n).toLowerCase()===e){let o=await this.getPoolDelta(s);i.push({...s,tokens:o})}}return i})})}subscribeBalances(){return Lt.EMPTY}subscribeUpdates(){let e=new Lt;return e.add(this.subscribeRouterExecuted()),e.add(this.subscribeEvmLog()),e}};var Vt={};F(Vt,{HsmMath:()=>T,HsmPool:()=>ve,HsmPoolClient:()=>Se});import{calculate_collateral_in_given_hollar_out as vs,calculate_collateral_out_given_hollar_in as Ss,calculate_hollar_in_given_collateral_out as Ts,calculate_hollar_out_given_collateral_in as xs,calculate_imbalance as As,calculate_max_price as ws,calculate_buyback_limit as Is,calculate_buyback_price_with_fee as Os}from"@galacticcouncil/math-hsm";var T=class{static calculateCollateralInGivenHollarOut(e,t,a){return vs(e,t,a)}static calculateCollateralOutGivenHollarIn(e,t,a){return Ss(e,t,a)}static calculateHollarOutGivenCollateralIn(e,t,a){return xs(e,t,a)}static calculateHollarInGivenCollateralOut(e,t,a){return Ts(e,t,a)}static calculateImbalance(e,t,a){return As(e,t,a)}static calculateBuybackLimit(e,t){return Is(e,t)}static calculateBuybackPriceWithFee(e,t,a){return Os(e,t,a)}static calculateMaxPrice(e,t){return ws(e,t)}};import{big as M,RUNTIME_DECIMALS as Me}from"@galacticcouncil/common";var{FeeUtils:Z}=y,ve=class u extends G{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(e){return new u(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,a){let i=this.parsePair(e.assetOut,e.assetIn),s=super.calculateInGivenOut(i,t,{fee:this.fee}),n=this.calculateBuybackLimit(e);t>n&&a.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(e);return this.calculateBuyPrice(e,t,s)>r&&a.push("MaxBuyPriceExceeded"),s>this.collateralBalance&&a.push("InsufficientCollateral"),a}validateTradeHollarOut(e,t,a){return this.collateralBalance+e>this.maxInHolding&&a.push("MaxHoldingExceeded"),t>this.hsmMintCapacity&&a.push("FacilitatorCapacityExceeded"),a}validateTradeConstraints(e,t,a){let i=[];return e.assetIn===this.hollarId?this.validateTradeHollarIn(e,t,i):this.validateTradeHollarOut(t,a,i)}validateAndBuy(e,t){let a=this.calculateInGivenOut(e,t),i=this.validateTradeConstraints(e,a,t);return{amountIn:a,calculatedIn:a,amountOut:t,feePct:0,errors:i}}validateAndSell(e,t){let a=this.calculateOutGivenIn(e,t),i=this.validateTradeConstraints(e,t,a);return{amountIn:t,calculatedOut:a,amountOut:a,feePct:0,errors:i}}calculateHollarInGivenCollateralOut(e,t){let a=super.calculateInGivenOut(e,t,{fee:this.fee}),i=T.calculateHollarInGivenCollateralOut(t.toString(),a.toString(),Z.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateCollateralInGivenHollarOut(e){let t=this.getCollateralPeg(),a=T.calculateCollateralInGivenHollarOut(e.toString(),JSON.stringify(t),Z.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateInGivenOut(e,t){return e.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(t):this.calculateHollarInGivenCollateralOut(e,t)}calculateCollateralOutGivenHollarIn(e,t){let a=super.calculateOutGivenIn(e,t,{fee:this.fee}),i=T.calculateCollateralOutGivenHollarIn(t.toString(),a.toString(),Z.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateHollarOutGivenCollateralIn(e){let t=this.getCollateralPeg(),a=T.calculateHollarOutGivenCollateralIn(e.toString(),JSON.stringify(t),Z.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateOutGivenIn(e,t){return e.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(e,t):this.calculateHollarOutGivenCollateralIn(t)}calculateImbalance(e){let t=this.getCollateralPeg(),a=T.calculateImbalance(e.balanceIn.toString(),JSON.stringify(t),e.balanceOut.toString());return BigInt(a)}calculateBuybackLimit(e){let t=this.calculateImbalance(e),a=T.calculateBuybackLimit(t.toString(),Z.toRaw(this.buyBackRate).toString());return BigInt(a)}calculateBuyPrice(e,t,a){let i=T.calculateBuybackPriceWithFee(a.toString(),t.toString(),Z.toRaw(this.buyBackFee).toString()),[s,n]=JSON.parse(i),r=M.pow10(e.decimalsIn+Me-e.decimalsOut);return BigInt(s)*r/BigInt(n)}calculateMaxPrice(e){let t=this.getCollateralPeg(),a=T.calculateMaxPrice(JSON.stringify(t),this.maxBuyPriceCoefficient.toString()),[i,s]=JSON.parse(a),n=M.pow10(Me-e.decimalsOut);return BigInt(i)*n/BigInt(s)}spotPriceInGivenOut(e){let t=M.toBigInt(1,e.decimalsOut),i=this.calculateInGivenOut(e,t)*M.pow10(Me-e.decimalsOut);return this.normalizeSpotPrice(i,e.decimalsOut,e.decimalsIn)}spotPriceOutGivenIn(e){let t=M.toBigInt(1,e.decimalsIn),i=this.calculateOutGivenIn(e,t)*M.pow10(Me-e.decimalsIn);return this.normalizeSpotPrice(i,e.decimalsIn,e.decimalsOut)}getCollateralPeg(){let e=this.tokens.findIndex(i=>i.id!==this.hollarId),t=this.pegs[e],a=this.tokens[e].decimals;return this.isDefaultPeg(t)?[M.toBigInt(1,18).toString(),M.toBigInt(1,a).toString()]:t}isDefaultPeg(e){let[t,a]=e;return Array.isArray(e)&&e.length===2&&t==="1"&&a==="1"}normalizeSpotPrice(e,t,a){let i=t-a;if(i===0)return e;let s=M.pow10(Math.abs(i));return i>0?e*s:e/s}};import{AccountId as _s,CompatibilityLevel as Es}from"polkadot-api";import{toHex as Rs}from"@polkadot-api/utils";import{Subscription as Qe,combineLatest as ks,filter as qt,map as Je,mergeMap as Cs,pairwise as Ms}from"rxjs";import{h160 as Ls,HYDRATION_SS58_PREFIX as Ds}from"@galacticcouncil/common";import{Binary as Bs}from"polkadot-api";import{decodeEventLog as Fs}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 De=class{static parse(e){let{topics:t,data:a}=e.log,i=Bs.toHex(a);try{let{eventName:s,args:n}=Fs({abi:Le,topics:t,data:i}),r=n.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:r,key:`${s}:${r}`}}catch{return}}};var He=class{client;constructor(e){this.client=e.getWsProvider()}async getFacilitatorCapacity(e,t){let[a,i]=await this.client.readContract({abi:Le,address:e,functionName:"getFacilitatorBucket",args:[t]});return a-i}};var{FeeUtils:Ze}=y,{H160:Gt}=Ls,Hs=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Se=class extends S{ghoClient;stableClient;constructor(e,t,a,i){super(e,t,i),this.stableClient=a,this.ghoClient=new He(t)}getPoolType(){return"HSM"}getPoolId(e){return this.getPoolAddress("hsm:"+e)}getFacilitatorAddress(){return this.getPoolAddress("modlpy/hsmod")}getHollarAddress(e){if(e){let t=e.interior;if(t.type==="X1"&&t.value.type==="AccountKey20"){let{value:a}=t.value;return a.key}}throw Error("Invalid hollar multilocation")}getPoolAddress(e){let t=e.padEnd(32,"\0"),a=new TextEncoder().encode(t),i=Rs(a);return _s(Ds).dec(i)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(Es.BackwardsCompatible)}async loadPools(){let e=await this.api.constants.HSM.HollarId(),[t,a,i]=await Promise.all([this.api.query.AssetRegistry.AssetLocations.getValue(e,{at:this.at}),this.api.query.HSM.Collaterals.getEntries({at:this.at}),this.stableClient.getPools()]);if(a.length===0)return[];let s=this.getFacilitatorAddress(),n=Gt.fromAny(s),r=this.getHollarAddress(t),o=await this.ghoClient.getFacilitatorCapacity(r,n),c=a.map(async({keyArgs:p,value:m})=>{let[d]=p,{pool_id:g,max_buy_price_coefficient:b,max_in_holding:B,purchase_fee:x,buy_back_fee:A,buyback_rate:w}=m,I=i.find(D=>D.id===g);if(I){let D=this.getPoolId(g),te=await this.balance.getBalance(s,d);return{...I,address:D,type:"HSM",tokens:I.tokens.filter(Ut=>Ut.id!==g),hsmAddress:s,hsmMintCapacity:o,hollarId:e,hollarH160:r,collateralId:d,collateralBalance:te.transferable,maxBuyPriceCoefficient:b,maxInHolding:B,purchaseFee:Ze.fromPermill(x),buyBackFee:Ze.fromPermill(A),buyBackRate:Ze.fromPerbill(w)}}});return(await Promise.all(c)).filter(p=>p!==null)}async getPoolFees(){return{}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Cs(({events:e})=>e),Je(({payload:e})=>De.parse(e)),qt(e=>e!==void 0),qt(({eventName:e})=>Hs.includes(e)),this.watchGuard("evm.Log")).subscribe(({eventName:e,facilitator:t})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async a=>{let i=[],[{hsmAddress:s,hollarH160:n}]=a,r=Gt.fromAny(s);if(r.toLowerCase()===t){let c=await this.ghoClient.getFacilitatorCapacity(n,r);for(let l of a)i.push({...l,hsmMintCapacity:c})}return i})})}subscribeCollateralBalance(){let e=[],t=[];this.store.pools.forEach(s=>{let{tokens:n,collateralId:r}=s;n.find(c=>c.id===r).type==="Erc20"?t.push(r):e.push(r)});let[{hsmAddress:a}]=this.store.pools,i=[];if(e.length>0){let s=this.balance.watchTokensBalance(a);i.push(s)}if(t.length>0){let s=this.balance.watchErc20Balance(a,t);i.push(s)}return i.length>0?ks(i).pipe(Je(s=>s.flat()),Ms(),Je(([s,n])=>this.balance.getDeltas(s,n)),this.watchGuard("balances")).subscribe(s=>{this.store.update(n=>{let r=[],o=new Map(n.map(c=>[c.collateralId,c]));return s.forEach(({id:c,balance:l})=>{let p=o.get(c);p&&(this.log.trace("balances",{id:c,balance:l}),r.push({...p,collateralBalance:l.transferable}))}),r})}):Qe.EMPTY}subscribeStableswapUpdates(){return this.stableClient.getSubscriber().pipe(this.watchGuard("stableswap.updates")).subscribe(e=>{let t=new Map(e.map(a=>[a.id,a]));this.store.update(a=>{let i=[];for(let s of a){let n=t.get(s.id);n&&i.push({...s,fee:n.fee,tokens:n.tokens.filter(r=>r.id!==s.id),totalIssuance:n.totalIssuance,pegs:n.pegs,amplification:n.amplification,isRampPeriod:n.isRampPeriod})}return i})})}subscribeBalances(){return Qe.EMPTY}subscribeUpdates(){let e=new Qe;return e.add(this.subscribeCollateralBalance()),e.add(this.subscribeStableswapUpdates()),e.add(this.subscribeEvmLog()),e}};var et=class{static get(e){switch(e.type){case"Aave":return fe.fromPool(e);case"XYK":return he.fromPool(e);case"Omnipool":return ue.fromPool(e);case"LBP":return ie.fromPool(e);case"Stableswap":return G.fromPool(e);case"HSM":return ve.fromPool(e);default:throw new Error("Pool type "+e.type+" is not supported yet")}}};import{log as Ns}from"@galacticcouncil/common";import{Subject as qs,Subscription as V,takeUntil as Gs}from"rxjs";var ee=class extends Error{constructor(e){super(),this.message=`${e} pool invalid`,this.name="PoolNotFound"}};var{logger:Vs}=Ns,tt=class extends _{evm;aave;omnipool;stableswap;hsm;xyk;lbp;active=new Set([]);pools=new Map([]);clients=[];aaveSub=V.EMPTY;omniSub=V.EMPTY;stableSub=V.EMPTY;hsmSub=V.EMPTY;xykSub=V.EMPTY;lbpSub=V.EMPTY;isReady=!1;isDestroyed=new qs;constructor(e,t,a){super(e,a),this.evm=t,this.aave=new Pe(e,t,a),this.omnipool=new pe(e,t,a),this.stableswap=new be(e,t,a),this.hsm=new Se(e,t,this.stableswap,a),this.xyk=new ye(e,t,a),this.lbp=new ce(e,t,a),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(e){return this.isHistorical?V.EMPTY:e.getSubscriber().pipe(Gs(this.isDestroyed)).subscribe(t=>{t.forEach(a=>{this.pools.set(a.address,a)})})}withAave(){return this.aaveSub.unsubscribe(),this.aaveSub=this.subscribe(this.aave),this.active.add("Aave"),this}withOmnipool(){return this.omniSub.unsubscribe(),this.omniSub=this.subscribe(this.omnipool),this.active.add("Omnipool"),this}withStableswap(){return this.stableSub.unsubscribe(),this.stableSub=this.subscribe(this.stableswap),this.active.add("Stableswap"),this}withHsm(){return this.active.has("Stableswap")||(Vs.info("[PoolContextProvider] auto-activating stableswap"),this.withStableswap()),this.hsmSub.unsubscribe(),this.hsmSub=this.subscribe(this.hsm),this.active.add("HSM"),this}withXyk(e){return this.xyk.withOverride(e),this.xykSub.unsubscribe(),this.xykSub=this.subscribe(this.xyk),this.active.add("XYK"),this}withLbp(){return this.lbpSub.unsubscribe(),this.lbpSub=this.subscribe(this.lbp),this.active.add("LBP"),this}destroy(){this.isDestroyed.next(!0),this.isDestroyed.complete(),this.active.clear(),this.pools.clear(),this.isReady=!1}async getPools(){if(this.isReady){let t=this.pools.values();return Array.from(t)}let e=await Promise.all(this.clients.filter(t=>this.active.has(t.getPoolType())).map(t=>t.getPools()));return this.isReady=!0,e.flat()}async getPoolFees(e,t){let a=this.clients.find(i=>i.getPoolType()===t.type);if(a)return a.getPoolFees(e,t.address);throw new ee(t.type)}};var at=class{constructor(e){this.snapshot=e;let{aave:t,xyk:a,lbp:i,stable:s,omni:n}=e.pools;this.flat=[...t,...a,...i,...s,...n]}flat;async getPools(){return this.flat}async getPoolFees(e,t){let{block:a,states:i}=this.snapshot;switch(t.type){case"Aave":return{};case"XYK":{let{exchangeFee:s}=i.xyk;return{exchangeFee:s}}case"LBP":{let{repayFee:s}=i.lbp;return{exchangeFee:t.fee,repayFee:s}}case"Stableswap":return{fee:t.fee};case"Omnipool":{let s=e.assetOut,n=e.assetIn,{dynamicFees:r,emaOracles:o,assetFeeParams:c,protocolFeeParams:l,maxSlipFee:p}=i.omni,m=r.find(({asset:b})=>b===s)?.fee,d=o.find(({pair:b})=>b.join(":")===Fe(s))?.oracle,g=o.find(({pair:b})=>b.join(":")===Fe(n))?.oracle;return q.compute(e,a,m,d,g,c,l,p)}default:throw new ee(t.type)}}};export{tt as PoolContextProvider,H as PoolError,et as PoolFactory,f as PoolType,at as SnapshotPoolCtxProvider,Nt as aave,Vt as hsm,yt as lbp,St as omni,Et as stable,kt as xyk};
|