@galacticcouncil/sdk-next 1.1.0 → 1.2.0

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