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