@galacticcouncil/sdk-next 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/aave/AaveLog.d.ts +4 -0
- package/build/aave/index.cjs +1 -1
- package/build/aave/index.d.ts +2 -0
- package/build/aave/index.mjs +1 -1
- package/build/aave/types.d.ts +7 -0
- package/build/evm/adapter.d.ts +3 -1
- package/build/evm/client.d.ts +3 -1
- package/build/evm/index.cjs +1 -1
- package/build/evm/index.mjs +1 -1
- package/build/gho/GhoTokenLog.d.ts +4 -0
- package/build/gho/index.d.ts +4 -2
- package/build/{pool/hsm → gho}/types.d.ts +1 -1
- package/build/index.cjs +1 -1
- package/build/index.d.ts +1 -0
- package/build/index.mjs +1 -1
- package/build/indexer/BlockFetcher.d.ts +10 -0
- package/build/indexer/Indexer.d.ts +19 -0
- package/build/indexer/IndexerStats.d.ts +33 -0
- package/build/indexer/RpcPool.d.ts +12 -0
- package/build/indexer/Semaphore.d.ts +9 -0
- package/build/indexer/index.cjs +1 -0
- package/build/indexer/index.d.ts +9 -0
- package/build/indexer/index.mjs +1 -0
- package/build/indexer/scale.d.ts +1 -0
- package/build/indexer/types.d.ts +17 -0
- package/build/oracle/MmOracleClient.d.ts +1 -1
- package/build/oracle/MmOracleLog.d.ts +4 -0
- package/build/oracle/abi.d.ts +11 -84
- package/build/oracle/index.d.ts +2 -0
- package/build/oracle/mappings.d.ts +25 -0
- package/build/oracle/types.d.ts +11 -0
- package/build/pool/PoolContextProvider.d.ts +4 -0
- package/build/pool/aave/AavePoolClient.d.ts +0 -1
- package/build/pool/aave/types.d.ts +0 -6
- package/build/pool/hsm/HsmPoolClient.d.ts +0 -1
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.d.ts +1 -0
- package/build/pool/index.mjs +1 -1
- package/build/pool/stable/StableSwap.d.ts +1 -1
- package/build/pool/stable/StableSwapClient.d.ts +12 -3
- package/build/pool/stable/StableSwapPeg.d.ts +7 -0
- package/build/pool/stable/types.d.ts +12 -1
- package/build/pool/types.d.ts +3 -1
- package/build/pool/uniswapv3/UniswapV3Math.d.ts +7 -0
- package/build/pool/uniswapv3/UniswapV3Pool.d.ts +46 -0
- package/build/pool/uniswapv3/UniswapV3PoolClient.d.ts +45 -0
- package/build/pool/uniswapv3/abi.d.ts +111 -0
- package/build/pool/uniswapv3/const.d.ts +7 -0
- package/build/pool/uniswapv3/index.d.ts +5 -0
- package/build/pool/uniswapv3/types.d.ts +21 -0
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/tx/TxBuilder.d.ts +2 -2
- package/build/tx/TxBuilderFactory.d.ts +3 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +9 -1
- package/build/pool/aave/AaveAbi.d.ts +0 -126
package/build/pool/index.mjs
CHANGED
|
@@ -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 di=Object.defineProperty;var F=(u,t)=>{for(var e in t)di(u,e,{get:t[e],enumerable:!0})};import gi from"buffer";typeof window<"u"&&(window.Buffer=gi.Buffer);var Fe={};F(Fe,{LbpMath:()=>E,LbpPool:()=>ct,LbpPoolClient:()=>bt});import{calculate_in_given_out as bi,calculate_out_given_in as hi,calculate_linear_weights as yi,calculate_pool_trade_fee as fi,get_spot_price as Pi}from"@galacticcouncil/math-lbp";var E=class{static getSpotPrice(t,e,i,a,s){return Pi(t,e,i,a,s)}static calculateInGivenOut(t,e,i,a,s){return bi(t,e,i,a,s)}static calculateOutGivenIn(t,e,i,a,s){return hi(t,e,i,a,s)}static calculateLinearWeights(t,e,i,a,s){return yi(t,e,i,a,s)}static calculatePoolTradeFee(t,e,i){return fi(t,e,i)}};import{big as fe,RUNTIME_DECIMALS as Pe}from"@galacticcouncil/common";var P=(n=>(n.Aave="Aave",n.LBP="LBP",n.Omni="Omnipool",n.Stable="Stableswap",n.XYK="XYK",n.HSM="HSM",n.V3="UniswapV3",n))(P||{}),V=(c=>(c.UnknownError="UnknownError",c.FacilitatorCapacityExceeded="FacilitatorCapacityExceeded",c.InsufficientTradingAmount="InsufficientTradingAmount",c.InsufficientCollateral="InsufficientCollateral",c.MaxHoldingExceeded="MaxHoldingExceeded",c.MaxInRatioExceeded="MaxInRatioExceeded",c.MaxOutRatioExceeded="MaxOutRatioExceeded",c.TradeNotAllowed="TradeNotAllowed",c.MaxBuyBackExceeded="MaxBuyBackExceeded",c.MaxBuyPriceExceeded="MaxBuyPriceExceeded",c))(V||{});var Ft={};F(Ft,{withTimeout:()=>Si});function Si(u,t,e="timeout"){return new Promise((i,a)=>{let s=setTimeout(()=>a(new Error(e)),t);u.then(r=>{clearTimeout(s),i(r)},r=>{clearTimeout(s),a(r)})})}import{RUNTIME_DECIMALS as Dn}from"@galacticcouncil/common";var f={};F(f,{FeeUtils:()=>Yt,shiftNeg:()=>Ii});import xi from"big.js";var Yt=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 a=10**i;return Math.round(t*a/e)/a}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ii(u,t){let e=xi(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var lt={};F(lt,{findNestedKey:()=>wi,findNestedObj:()=>Ai,jsonFormatter:()=>Oi});var wi=(u,t)=>{let e=[];return JSON.stringify(u,(i,a)=>(a&&a[t]&&e.push(a),a)),e[0]},Ai=(u,t,e)=>{let i;return JSON.stringify(u,(a,s)=>(s&&s[t]===e&&(i=s),s)),i},Oi=(u,t)=>typeof t=="bigint"?t.toString():t;var R={};F(R,{calculateBuyFee:()=>Fi,calculateDiffToAvg:()=>Bi,calculateDiffToRef:()=>_i,calculateSellFee:()=>ki});import D from"big.js";function Bi(u,t){let e=D(u.toString()),i=D(t.toString());return e.minus(i).abs().div(e.plus(i).div(2)).mul(100).round(2).toNumber()}function _i(u,t){if(t===0n)return 0;let e=D(u.toString()),i=D(t.toString());return e.minus(i).div(i).mul(100).round(2).toNumber()}function ki(u,t){if(u===0n)return 0;let e=D(u.toString()),i=D(t.toString());return D(1).minus(i.div(e)).mul(100).round(2).toNumber()}function Fi(u,t){if(u===0n)return 0;let e=D(u.toString());return D(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as ye}from"@thi.ng/cache";var z=class{debug;constructor(t){this.debug=t||!1}log(t,e,i){this.debug&&console.log(t,e,i)}scope(t,e,i,a){let s=new Map,r=a!==void 0?new ye(null,{ttl:a}):new ye;return{get:(...c)=>{let m=i(...c);if(s.has(m)){this.log("[live]",t,m);let p=s.get(m);return Promise.resolve(p)}if(r.has(m))return this.log("[memo]",t,m),r.get(m);this.log("[fetch]",t,m);let g=e(...c).catch(p=>{throw r.delete(m),p});return r.set(m,g),g},set:(c,...m)=>{let g=i(...m);this.log("[set-live]",t,g),s.set(g,c)},clear:()=>{this.log("[clear]",t),s.clear(),r.release()}}}};var{FeeUtils:Se}=f,ct=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(r=>[r.id,r])),a=i.get(t),s=i.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,weightIn:a.weight,weightOut:s.weight}}validateAndBuy(t,e,i){let a=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let r=t.balanceOut/this.maxOutRatio;if(e>r&&s.push("MaxOutRatioExceeded"),a===t.assetOut){let n=this.calculateTradeFee(e,i),o=Se.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),l=e+n,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&s.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:s}}else{let n=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return n>o&&s.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:n,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,i){let a=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let r=t.balanceIn/this.maxInRatio;if(e>r&&s.push("MaxInRatioExceeded"),a===t.assetIn){let n=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return n>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:n,feePct:0,errors:s}}else{let n=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(n,i),l=Se.toPct(this.repayFeeApply?i.repayFee:i.exchangeFee),c=n-o,m=t.balanceOut/this.maxOutRatio;return c>m&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:n,amountOut:c,feePct:l,errors:s}}}calculateInGivenOut(t,e){let i=E.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(i);return a<0n?0n:a}calculateOutGivenIn(t,e){let i=E.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(i);return a<0n?0n:a}spotPriceInGivenOut(t){let e=E.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),fe.toBigInt(1,Pe).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=E.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),fe.toBigInt(1,Pe).toString());return BigInt(e)}calculateTradeFee(t,e){let i=E.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 Ta}from"polkadot-api";import{Subscription as xa,distinctUntilChanged as Ia,filter as wa,map as Aa}from"rxjs";import{memoize1 as oa}from"@thi.ng/memoize";import{TLRUCache as la}from"@thi.ng/cache";import{ReplaySubject as Be,Subscription as _e,combineLatest as ca,defer as ua,from as ma,interval as pa,merge as zt,of as da,EMPTY as dt}from"rxjs";import{bufferCount as ga,bufferTime as ba,catchError as gt,filter as Lt,finalize as jt,map as J,pairwise as Qt,repeat as Jt,skip as ha,share as ya,startWith as fa,switchMap as ke,tap as $,throttleTime as Pa}from"rxjs/operators";import{hydration as Yi,hydrationNext as Ki,hydrationIce as zi}from"@galacticcouncil/descriptors";import{log as Hi}from"@galacticcouncil/common";import{map as Ui,shareReplay as $i,tap as Wi}from"rxjs";import{defer as Ei,from as Ri,of as ve,timer as Ci}from"rxjs";import{catchError as Mi,distinctUntilChanged as Li,expand as Di,map as Kt,shareReplay as qi,skip as Ni,switchMap as Vi,timeout as Gi}from"rxjs/operators";function Te(u,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>Ei(()=>Ri(u._request("system_health",[]))).pipe(Gi({first:e}),Kt(()=>"online"),Mi(()=>ve("offline")));return ve({state:"offline",delayMs:0}).pipe(Di(s=>Ci(s.delayMs).pipe(Vi(i),Kt(r=>({state:r,delayMs:t})))),Ni(1),Kt(s=>s.state),Li(),qi({bufferSize:1,refCount:!0}))}var{logger:Xi}=Hi,Et=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(Ui(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Te(t))}static getInstance(t){return this.instance||(this.instance=new u(t)),this.instance}watched(t,e){return e.pipe(Wi({error:i=>Xi.error(t,i)}),$i({bufferSize:1,refCount:!0}))}};var C=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(Yi),this.apiNext=this.client.getTypedApi(Ki),this.apiIce=this.client.getTypedApi(zi),this.watcher=Et.getInstance(this.client),this.at=e??"best"}};import{getWsProvider as _r}from"polkadot-api/ws";import{withLogsRecorder as Fr}from"polkadot-api/logs-provider";import{Binary as Xr}from"polkadot-api";import{log as ji}from"@galacticcouncil/common";import{combineLatest as Qi,concat as Ji,defer as ut,from as xe}from"rxjs";import{bufferCount as Ie,distinctUntilChanged as we,debounceTime as Zi,map as j,retry as ta,startWith as Ae,switchMap as Oe,tap as mt,take as ea,skip as ia,connect as aa}from"rxjs/operators";var{logger:Q}=ji,pt=class extends C{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 a=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(a)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return ut(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),a=this.watchErc20Balance(t);return Qi([e,i,a]).pipe(aa(s=>Ji(s.pipe(ea(1)),s.pipe(ia(1),Zi(250)))))}).pipe(j(e=>e.flat()),Ae([]),Ie(2,1),j(([e,i],a)=>a===0?i:this.getDeltas(e,i))).pipe(mt({subscribe:()=>Q.debug("balance: subscribe",t),error:e=>Q.error("balance",e)}),ta({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return ut(()=>e.watchValue(t,{at:"best"})).pipe(j(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),mt({error:i=>Q.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return ut(()=>i.watchValue(t,e,{at:"best"})).pipe(j(({value:a})=>({id:e,balance:this.getBreakdown(a)})),mt({error:a=>Q.error("balance(token)",a)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return ut(()=>e.watchEntries(t,{at:"best"})).pipe(we((i,a)=>!a.deltas),j(({deltas:i})=>{let a=[];return i?.deleted.forEach(s=>{let[r,n]=s.args;a.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(s=>{let[r,n]=s.args;a.push({id:n,balance:this.getBreakdown(s.value)})}),a}),mt({error:i=>Q.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},a=async s=>(await Promise.all(s.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,o])=>({id:n,balance:o}));return ut(()=>xe(e?Promise.resolve(e):i()).pipe(Oe(s=>this.watcher.bestBlock$.pipe(Oe(()=>xe(a(s))))),Ae([]),Ie(2,1),j(([s,r],n)=>n===0?r.filter(o=>o.balance.total>0n):this.getDeltas(s,r)),we((s,r)=>r.length===0),mt({error:s=>Q.error("balance(erc20)",s)})))}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=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,a=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!i(s.balance,a.get(s.id)))}};import{BehaviorSubject as sa}from"rxjs";var Rt=class{store$=new sa([]);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((n,o)=>[n.address,o])),a=await t(e),s=e.slice(),r=new Set;for(let n of a){let o=i.get(n.address);o===void 0?(i.set(n.address,s.length),s.push(n)):s[o]=n,r.add(n.address)}this.changeset=r,this.store$.next(s)}).catch(console.error)}destroy(){this.store$.complete()}};import{log as na}from"@galacticcouncil/common";var ra={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM",UniswapV3:"UNIV3"},{logger:Ct}=na,Mt=class{type;constructor(t){this.type=t}prefix(){return this.pad(`pool(${ra[this.type]})`,10)}trace(t,...e){Ct.trace(`${this.prefix()} ${t} :`,...e)}debug(t,...e){Ct.debug(`${this.prefix()} ${t} :`,...e)}info(t,...e){Ct.info(`${this.prefix()} ${t} :`,...e)}error(t,...e){Ct.error(`${this.prefix()} ${t} :`,...e)}pad(t,e){return t.length>=e?t:t+" ".repeat(e-t.length)}};var{withTimeout:Sa}=Ft,va=3e3,w=class extends C{evm;balance;store=new Rt;log;shared$;resync$=new Be(1);resyncAt=0;resyncPending=!1;mem=0;memPoolsCache=new la(null,{ttl:6*1e3});memPools=oa(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 pt(t,i),this.log=new Mt(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(fa([]),ga(2,1),J(([t,e])=>t.length===0?e:this.store.applyChangeset(e)),Lt(t=>t.length>0),Pa(1e3,void 0,{leading:!0,trailing:!0}))}subscribeStore(){return ua(()=>{let t=new _e;return t.add(this.startWatchdog()),this.resync$.next(),this.resync$.pipe(ke(()=>{let e=new _e;return ma(Sa(this.getMemPools(),6e4,"getMemPools stalled")).pipe($(()=>this.log.info("pool_synced",{mem:this.mem})),J(a=>a.filter(s=>this.hasValidAssets(s))),$(a=>this.store.set(a)),gt(()=>(this.log.error("pool_seed_error",{mem:this.mem}),this.requestResync(),dt))).pipe($(()=>{e.add(this.subscribeBalances()),e.add(this.subscribeUpdates())}),ke(a=>zt(da(a),this.store.asObservable().pipe(ha(1)))),jt(()=>{e.unsubscribe()}))}),jt(()=>t.unsubscribe()))}).pipe(ya({connector:()=>new Be(1),resetOnRefCountZero:!0}))}subscribeBalances(){let t=this.store.pools.map(e=>{let{address:i}=e,a=[this.balance.watchTokensBalance(i)];if(this.hasSystemAsset(e)){let s=this.balance.watchSystemBalance(i);a.push(s)}if(this.hasErc20Asset(e)){let s=e.tokens.filter(n=>n.type==="Erc20").map(n=>n.id),r=this.balance.watchErc20Balance(i,s);a.push(r)}return ca(a).pipe(J(s=>s.flat()),Qt(),J(([s,r])=>this.balance.getDeltas(s,r)),Lt(s=>s.length>0),J(s=>[i,s]))});return zt(...t).pipe(ba(250),Lt(e=>e.length>0),J(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=[],a=new Map(t.map(s=>[s.address,s]));for(let[s,r]of e){let n=a.get(s);if(n){let o=n.tokens.map(l=>{let c=r.find(m=>m.id===l.id);return c&&l.id!==n.id?{...l,balance:c.balance.transferable}:l});i.push({...n,tokens:o})}}return i};resync(t=!1){let e=Date.now();!t&&e-this.resyncAt<va||(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 a=this.watcher.connection$.pipe(Qt(),Lt(([n,o])=>n==="offline"&&o==="online"),$(()=>{this.log.debug("watchdog_recover_online",{mem:this.mem}),this.requestResync()}),gt(n=>(this.log.error("watchdog_recovery_error",n),dt)),Jt({delay:1e3})),s=this.watcher.finalizedBlock$.pipe(Qt(),$(([n,o])=>{let l=Number(n.number),c=Number(o.number),m=c-l;m>=3&&(this.log.debug("watchdog_gap",{from:l,to:c,gap:m}),this.requestResync())}),gt(n=>(this.log.error("watchdog_gap_error",n),dt)),Jt({delay:1e3})),r=pa(36e5).pipe($(()=>{this.log.debug("watchdog_periodic",{mem:this.mem}),this.requestResync()}),gt(n=>(this.log.error("watchdog_periodic_error",n),dt)),Jt({delay:1e3}));return zt(a,s,r).subscribe()}watchGuard(t){return e=>e.pipe($({error:i=>{this.log.error(t,i),this.requestResync(!0)}}),jt(()=>{this.log.debug(t,"unsub")}),gt(()=>dt))}};var bt=class extends w{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:a,initial_weight:s,final_weight:r}=t,n=E.calculateLinearWeights(i?i.toString():"0",a?a.toString():"0",s.toString(),r.toString(),e.toString()),o=BigInt(n),l=this.MAX_FINAL_WEIGHT-BigInt(o);return[o,l]}async isSupported(){return(await this.api.getStaticApis()).compat.query.LBP.PoolData.isCompatible(Ta.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()]),a=e?.relay_parent_number||0,s=t.filter(({value:r})=>e&&this.isActivePool(r,a)).map(async({keyArgs:r,value:n})=>{let[o]=r,l=o.toString(),c=await this.getPoolDelta(l,n,a);return{address:l,type:"LBP",fee:n.fee,...c,...i}});return Promise.all(s)}async getPoolDelta(t,e,i){let{assets:a,repay_target:s,fee_collector:r}=e,[n,o]=this.getPoolWeights(e,i),[l,c]=a,[m,g,p,d,b]=await Promise.all([this.isRepayFeeApplied(l,s,r.toString()),this.balance.getBalance(t,l),this.api.query.AssetRegistry.Assets.getValue(l,{at:this.at}),this.balance.getBalance(t,c),this.api.query.AssetRegistry.Assets.getValue(c,{at:this.at})]);return{repayFeeApply:m,tokens:[{id:l,decimals:p?.decimals,existentialDeposit:p?.existential_deposit,balance:g.transferable,weight:n,type:p?.asset_type.type},{id:c,decimals:b?.decimals,existentialDeposit:b?.existential_deposit,balance:d.transferable,weight:o,type:b?.asset_type.type}]}}isActivePool(t,e){let{start:i,end:a}=t;return i&&a?e>=i&&e<a:!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(s=>s.address===e);return{repayFee:await this.getRepayFee(),exchangeFee:i.fee}}subscribeValidationData(){return this.api.query.ParachainSystem.ValidationData.watchValue({at:"best"}).pipe(Aa(({value:t})=>t),wa(t=>t!==void 0),Ia((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 a of e){let s=this.poolsData.get(a.address);if(s){let{assets:r,repay_target:n,fee_collector:o}=s,[l]=r,[c,m]=this.getPoolWeights(s,t),[g,p]=a.tokens,d=[{...g,weight:c},{...p,weight:m}],b=await this.isRepayFeeApplied(l,n,o.toString());i.push({...a,tokens:d,repayFeeApply:b})}}return i})})}subscribeUpdates(){let t=new xa;return t.add(this.subscribeValidationData()),t}};var Me={};F(Me,{OmniMath:()=>y,OmniPool:()=>ht,OmniPoolClient:()=>yt,OmniPoolFee:()=>W,getEmaKey:()=>qt,getEmaPair:()=>tt});import{calculate_in_given_out as Oa,calculate_lrna_in_given_out as Ba,calculate_out_given_in as _a,calculate_out_given_lrna_in as ka,calculate_spot_price as Fa,calculate_lrna_spot_price as Ea,calculate_shares as Ra,calculate_liquidity_out as Ca,calculate_liquidity_lrna_out as Ma,verify_asset_cap as La,calculate_liquidity_hub_in as Da,is_sell_allowed as qa,is_buy_allowed as Na,is_add_liquidity_allowed as Va,is_remove_liquidity_allowed as Ga,recalculate_asset_fee as Ha,recalculate_protocol_fee as Ua}from"@galacticcouncil/math-omnipool";import Z from"big.js";var y=class{static calculateSpotPrice(t,e,i,a){return Fa(t,e,i,a)}static calculateLrnaSpotPrice(t,e){return Ea(t,e)}static calculateInGivenOut(t,e,i,a,s,r,n,o,l,c){return Oa(t,e,i,a,s,r,n,o,l,c)}static calculateLrnaInGivenOut(t,e,i,a,s,r){return Ba(t,e,i,a,s,r)}static calculateOutGivenIn(t,e,i,a,s,r,n,o,l,c){return _a(t,e,i,a,s,r,n,o,l,c)}static calculateOutGivenLrnaIn(t,e,i,a,s,r){return ka(t,e,i,a,s,r)}static calculateShares(t,e,i,a){return Ra(t,e,i,a)}static calculateLiquidityOut(t,e,i,a,s,r,n,o){return Ca(t,e,i,a,s,r,n,o)}static calculateLiquidityLRNAOut(t,e,i,a,s,r,n,o){return Ma(t,e,i,a,s,r,n,o)}static calculateCapDifference(t,e,i,a){let s=Z(e),r=Z(t),n=Z(a),o=Z(i),l=Z(10).pow(18),c=o.div(l);if(s.div(n).lt(c)){let g=c.times(n).minus(s).times(r),p=s.times(Z(1).minus(c));return g.div(p).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,i,a){return Da(t,e,i,a)}static isSellAllowed(t){return qa(t)}static isBuyAllowed(t){return Na(t)}static isAddLiquidityAllowed(t){return Va(t)}static isRemoveLiquidityAllowed(t){return Ga(t)}static recalculateAssetFee(t,e,i,a,s,r,n,o,l,c,m){return Ha(t,e,i,a,s,r,n,o,l,c,m)}static recalculateProtocolFee(t,e,i,a,s,r,n,o,l,c,m){return Ua(t,e,i,a,s,r,n,o,l,c,m)}static verifyAssetCap(t,e,i,a){return La(t,e,i,a)}};import{big as $a}from"@galacticcouncil/common";var{FeeUtils:L}=f,ht=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(r=>[r.id,r])),a=i.get(t),s=i.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:a.hubReserves,hubReservesOut:s.hubReserves,sharesIn:a.shares,sharesOut:s.shares,decimalsIn:a.decimals,decimalsOut:s.decimals,balanceIn:a.balance,balanceOut:s.balance,tradeableIn:a.tradeable,tradeableOut:s.tradeable,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let a=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),r=a===0n?0:R.calculateBuyFee(a,s),n=[],o=y.isSellAllowed(t.tradeableIn),l=y.isBuyAllowed(t.tradeableOut);(!o||!l)&&n.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&n.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&n.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return s>m&&n.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:a,amountOut:e,feePct:r,errors:n}}validateAndSell(t,e,i){let a=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),r=R.calculateSellFee(a,s),n=[],o=y.isSellAllowed(t.tradeableIn),l=y.isBuyAllowed(t.tradeableOut);(!o||!l)&&n.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&n.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&n.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return s>m&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:s,feePct:r,errors:n}}calculateInGivenOut(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,i);let a=y.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?L.toRaw(i.assetFee).toString():"0",i?L.toRaw(i.protocolFee).toString():"0",i?L.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,i){let a=y.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?L.toRaw(i.assetFee).toString():"0",i?L.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateOutGivenIn(t,e,i){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,i);let a=y.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?L.toRaw(i.assetFee).toString():"0",i?L.toRaw(i.protocolFee).toString():"0",i?L.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,i){let a=y.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),i?L.toRaw(i.assetFee).toString():"0",i?L.toRaw(i.maxSlipFee).toString():"0"),s=BigInt(a);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=y.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=y.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=y.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=y.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,i){let a=e-i;if(a===0)return t;let s=$a.pow10(Math.abs(a));return a>0?t*s:t/s}};import{AccountId as Wa,Binary as Ee,CompatibilityLevel as Xa,Enum as Ya}from"polkadot-api";import{toHex as Ka}from"@polkadot-api/utils";import{Subscription as za,distinctUntilChanged as Zt,filter as ja,finalize as te,map as et,merge as Qa,tap as Nt}from"rxjs";import{HYDRATION_SS58_PREFIX as Ja}from"@galacticcouncil/common";var{FeeUtils:I}=f,W=class u{static compute(t,e,i,a,s,r,n,o){let l=t.assetIn,[c,m,g]=u.getAssetFee(t,e,i,a,r),p=0,d=0,b=0;l!==1&&([p,d,b]=u.getProtocolFee(t,e,i,s,n));let O=c+p,S=g+b;return{assetFee:I.fromPermill(m),protocolFee:I.fromPermill(d),maxSlipFee:I.fromPermill(o),min:I.fromPermill(O),max:I.fromPermill(S)}}static getAssetFee(t,e,i,a,s){let{assetOut:r,balanceOut:n}=t,{min_fee:o,max_fee:l,decay:c,amplification:m}=s;if(!i||!a)return[o,o,l];let g=I.fromPermill(o),p=I.fromPermill(l),[d]=a,{asset_fee:b,timestamp:O}=i,S=Math.max(1,e-O),A=d.volume.b_in.toString(),x=d.volume.b_out.toString(),v=d.liquidity.b.toString();r===0&&(A=d.volume.a_in.toString(),x=d.volume.a_out.toString(),v=d.liquidity.a.toString());let B=I.fromPermill(b),k=y.recalculateAssetFee(A,x,v,"9",n.toString(),I.toRaw(B).toString(),S.toString(),I.toRaw(g).toString(),I.toRaw(p).toString(),c.toString(),m.toString());return[o,Number(k)*1e6,l]}static getProtocolFee(t,e,i,a,s){let{assetIn:r,balanceIn:n}=t,{min_fee:o,max_fee:l,decay:c,amplification:m}=s;if(!i||!a)return[o,o,l];let g=I.fromPermill(o),p=I.fromPermill(l),[d]=a,{protocol_fee:b,timestamp:O}=i,S=Math.max(1,e-O),A=d.volume.b_in.toString(),x=d.volume.b_out.toString(),v=d.liquidity.b.toString();r===0&&(A=d.volume.a_in.toString(),x=d.volume.a_out.toString(),v=d.liquidity.a.toString());let B=I.fromPermill(b),k=y.recalculateProtocolFee(A,x,v,"9",n.toString(),I.toRaw(B).toString(),S.toString(),I.toRaw(g).toString(),I.toRaw(p).toString(),c.toString(),m.toString());return[o,Number(k)*1e6,l]}};var tt=u=>u===0?[0,1]:[1,u],qt=u=>tt(u).join(":");var{FeeUtils:ee}=f,Re=Ee.toHex(Ee.fromText("omnipool")),Ce=Ya("Short"),yt=class extends w{queryBus=new z;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(Re,t,Ce,{at:this.at}),t=>t.join(":"),6*1e3);getPoolType(){return"Omnipool"}getPoolAddress(){let t="modlomnipool".padEnd(32,"\0"),e=new TextEncoder().encode(t),i=Ka(e);return Wa(Ja).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(Xa.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.Omnipool.HubAssetId(),e=this.getPoolAddress(),[i,a,s,r,n,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 l=i.map(async({keyArgs:m,value:g})=>{let[p]=m,{hub_reserve:d,shares:b,tradable:O,cap:S,protocol_shares:A}=g,[x,v]=await Promise.all([this.api.query.AssetRegistry.Assets.getValue(p,{at:this.at}),this.balance.getBalance(e,p)]);return{id:p,decimals:x?.decimals,existentialDeposit:x?.existential_deposit,balance:v.transferable,cap:S,hubReserves:d,protocolShares:A,shares:b,tradeable:O,type:x?.asset_type.type}}),c=await Promise.all(l);return c.push({id:t,decimals:s?.decimals,existentialDeposit:s?.existential_deposit,balance:r.transferable,tradeable:a,type:s?.asset_type.type}),[{address:e,type:"Omnipool",hubAssetId:t,tokens:c,...n}]}async getPoolFees(t){let e=t.assetOut,i=t.assetIn,s=await this.maxSlipFee.get()??0,r=await this.dynamicFeesConfig.get(e);if(r?.type==="Fixed"){let{asset_fee:g,protocol_fee:p}=r.value;return{assetFee:ee.fromPermill(g),protocolFee:ee.fromPermill(p),maxSlipFee:ee.fromPermill(s)}}let[n,o,l,c,m]=await Promise.all([this.dynamicFees.get(e),this.emaOracles.get(tt(e)),this.emaOracles.get(tt(i)),r?r.value.asset_fee_params:this.api.constants.DynamicFees.AssetFeeParameters(),r?r.value.protocol_fee_params:this.api.constants.DynamicFees.ProtocolFeeParameters()]);return W.compute(t,this.block,n,o,l,c,m,s)}subscribeEmaOracles(){let[t]=this.store.pools,i=t.tokens.map(a=>a.id).map(a=>tt(a)).map(a=>this.api.query.EmaOracle.Oracles.watchValue(Re,a,Ce,{at:"best"}).pipe(et(({value:s})=>s),ja(s=>s!==void 0),et((s,r)=>({value:s,index:r})),Nt(({index:s})=>{s>0&&this.log.trace("emaOracle.Oracles",a.join(":"))}),et(({value:s})=>({pair:a,value:s}))));return Qa(...i).pipe(te(()=>this.emaOracles.clear()),this.watchGuard("emaOracle.Oracles")).subscribe(a=>{let{pair:s,value:r}=a;this.emaOracles.set(r,s)})}subscribeDynamicFees(){return this.api.query.DynamicFees.AssetFee.watchEntries({at:"best"}).pipe(Zt((t,e)=>!e.deltas),et((t,e)=>({value:t,index:e})),Nt(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFee",t.deltas?.upserted)}),te(()=>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(Zt((t,e)=>!e.deltas),et((t,e)=>({value:t,index:e})),Nt(({value:t,index:e})=>{e>0&&this.log.trace("dynamicFees.AssetFeeConfiguration",t.deltas?.upserted)}),te(()=>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(Zt((t,e)=>!e.deltas),et((t,e)=>({value:t,index:e})),Nt(({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((s,r)=>{let[n]=r.args;return s.set(n,r.value),s},new Map),a=e.tokens.map(s=>{let r=i?.get(s.id);return r?this.updateTokenState(s,r):s});return[{...e,tokens:a}]})})}subscribeUpdates(){let t=new za;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:a,tradable:s,cap:r,protocol_shares:n}=e;return{...t,cap:r,hubReserves:i,protocolShares:n,shares:a,tradeable:s}}};var We={};F(We,{StableMath:()=>T,StableSwap:()=>X,StableSwapClient:()=>vt});import{calculate_in_given_out as Za,calculate_out_given_in as ts,calculate_amplification as es,calculate_add_one_asset as is,calculate_liquidity_out_one_asset as as,calculate_shares as ss,calculate_shares_for_amount as ns,calculate_spot_price_with_fee as rs,pool_account_name as os,recalculate_peg as ls}from"@galacticcouncil/math-stableswap";var T=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,a,s){return es(t,e,i,a,s)}static calculateInGivenOut(t,e,i,a,s,r,n){return Za(t,e,i,a,s,r,n)}static calculateAddOneAsset(t,e,i,a,s,r,n){return is(t,e,i,a,s,r,n)}static calculateSharesForAmount(t,e,i,a,s,r,n){return ns(t,e,i,a,s,r,n)}static calculateOutGivenIn(t,e,i,a,s,r,n){return ts(t,e,i,a,s,r,n)}static calculateLiquidityOutOneAsset(t,e,i,a,s,r,n){return as(t,e,i,a,s,r,n)}static calculateShares(t,e,i,a,s,r){return ss(t,e,i,a,s,r)}static calculateSpotPriceWithFee(t,e,i,a,s,r,n,o){return rs(t,e,i,a,s,r,n,o)}static recalculatePegs(t,e,i,a,s,r){let n=ls(t,e,i,a,s,r);return JSON.parse(n)}};import{RUNTIME_DECIMALS as cs,big as Le}from"@galacticcouncil/common";var{FeeUtils:it}=f,X=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(r=>[r.id,r])),a=i.get(t),s=i.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:a.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let a=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,i),r=a===0n?0:R.calculateBuyFee(a,s),n=[],o=y.isSellAllowed(t.tradeableIn),l=y.isBuyAllowed(t.tradeableOut);return(!o||!l)&&n.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&n.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:a,amountOut:e,feePct:r,errors:n}}validateAndSell(t,e,i){let a=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,i),r=R.calculateSellFee(a,s),n=[],o=y.isSellAllowed(t.tradeableIn),l=y.isBuyAllowed(t.tradeableOut);return(!o||!l)&&n.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&n.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:a,amountOut:s,feePct:r,errors:n}}calculateIn(t,e,i){let a=T.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?it.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateAddOneAsset(t,e,i){let a=T.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),i?it.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateSharesForAmount(t,e,i){let a=T.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),i?it.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}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=T.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 a=T.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),i?it.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,i){let a=T.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),i?it.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}calculateShares(t,e,i){let a=T.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),i?it.toRaw(i.fee).toString():"0",this.getPegs()),s=BigInt(a);return s<0n?0n:s}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=T.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:a})=>({asset_id:e,amount:i,decimals:a}));return JSON.stringify(t,lt.jsonFormatter)}getAssets(t,e){let i={asset_id:Number(t),amount:e.toString()};return JSON.stringify([i],lt.jsonFormatter)}normalizeSpot(t,e,i,a,s){return e?t*Le.pow10(cs-s):i?t/Le.pow10(s-a):t}};import{AccountId as ms,CompatibilityLevel as ps}from"polkadot-api";import{toHex as ds}from"@polkadot-api/utils";import{blake2b as gs}from"@noble/hashes/blake2b";import{Subscription as bs,distinctUntilChanged as $e,filter as hs,map as st,merge as ys,tap as ae}from"rxjs";import{HYDRATION_SS58_PREFIX as fs,RUNTIME_DECIMALS as Ps}from"@galacticcouncil/common";import{Binary as us}from"polkadot-api";import{decodeEventLog as Ne}from"viem";var ie=[{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"}],De=[{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"}],qe=[{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 ft=class{static parse(t){let{address:e,topics:i,data:a}=t.log,s=e.toLowerCase(),r=us.toHex(a);try{let{eventName:n,args:o}=Ne({abi:qe,topics:i,data:r});return{eventName:`ManagedOracle.${n}`,emitter:s,value:o.answer,timestamp:o.timestamp}}catch{}try{let{eventName:n,args:o}=Ne({abi:De,topics:i,data:r});return{eventName:`DIA.${n}`,emitter:s,key:o.key,value:o.value,timestamp:o.timestamp}}catch{}}};var Pt=class{adapter;constructor(t){this.adapter=t.getRPCAdapter()}async getData(t,e=6){let[i,a,s]=await Promise.all([this.adapter.readContract({abi:ie,address:t,functionName:"latestRoundData"}),this.adapter.readContract({abi:ie,address:t,functionName:"decimals"}),this.adapter.getBlock()]),[r,n,o,l]=i,c=s.number-(s.timestamp-l)/BigInt(e),m=Number(c);return{price:n,decimals:a,updatedAt:m<0?0:m}}};var Ve={"EUR/USD":"0xaa47a5662269270d3df33ae08f806e383611575c","sUSDs/USD":"0x4b32bffc6acd751446e79e8687ef3815fd7924fd","sUSDe/USD":"0x22cdea305cee63d082e79f8c5db939eecd0265d0"},Ge={"0xcfab6a4031c70da0f0cf6f31a252c16119db3611":"0xaafd758688cefd0a7b7770a825f1aad551e16185"},He={"bifrosto:5:15:LastBlock":"0xaafd758688cefd0a7b7770a825f1aad551e16185"};function Ue(u,t,e){let i=Buffer.from(u.replace(/^0x/,""),"hex").toString("ascii").replace(/\0+$/,""),[a,s]=[t[0],t[1]].sort((r,n)=>r-n);return`${i}:${a}:${s}:${e}`}var{FeeUtils:at}=f,St=class u{static compute(t,e,i,a){let s=u.getRecent(e),r=at.fromPermill(t.fee),n=at.fromPerbill(e.max_peg_update),o=i.map(({pair:d,updatedAt:b})=>[d,b]),l=i.find(d=>d.source),c=e.updated_at?e.updated_at.toString():l?.updatedAt;if(!c)throw new Error("Current peg unknown!");let[m,g]=T.recalculatePegs(JSON.stringify(s),c,JSON.stringify(o),a.toString(),at.toRaw(n).toString(),at.toRaw(r).toString()),p=Number(m)*1e6;return{pegsFee:at.fromPermill(p),pegs:g}}static getDefault(t){return{pegsFee:at.fromPermill(t.fee),pegs:T.defaultPegs(t.assets.length)}}static getRecent(t){let{current:e}=t;return Array.from(e.entries()).map(([i,a])=>a.map(s=>s.toString()))}};var{FeeUtils:Ss}=f,vs=["ManagedOracle.PriceUpdated","DIA.OracleUpdate"],vt=class extends w{poolsData=new Map([]);mmOracle=new Pt(this.evm);mmAddresses=new Set;mmRouting={byEmitter:new Map,byDiaKey:new Map,byEma:new Map};queryBus=new z;emaOracles=this.queryBus.scope("EmaOracle.Oracles",(t,e,i)=>this.api.query.EmaOracle.Oracles.getValue(t,e,i,{at:this.at}),(t,e,i)=>`${t.toString()}:${e.join(":")}:${i.type}`,6*1e3);mmOracles=this.queryBus.scope("MmOracle",t=>this.mmOracle.getData(t),t=>t.toLowerCase(),600*1e3);pegs=this.queryBus.scope("Stableswap.PoolPegs",t=>this.api.query.Stableswap.PoolPegs.getValue(t,{at:this.at}),t=>String(t),6*1e3);getPoolType(){return"Stableswap"}getPoolAddress(t){let e=T.getPoolAddress(t),i=gs(e,{dkLen:32}),a=ds(i);return ms(fs).dec(a)}async getPoolLimits(){return{maxInRatio:0n,maxOutRatio:0n,minTradingLimit:await this.api.constants.Stableswap.MinTradingLimit()}}getPoolAmplification(t,e){let{initial_amplification:i,final_amplification:a,initial_block:s,final_block:r}=t,n=T.calculateAmplification(i.toString(),a.toString(),s.toString(),r.toString(),e.toString()),o=Number(n)<a;return{amplification:BigInt(n),isRampPeriod:o}}async getPoolTokens(t,e){let i=this.getPoolAddress(t),a=e.assets.map(async s=>{let[r,n,o]=await Promise.all([this.api.query.Stableswap.AssetTradability.getValue(t,s,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(s,{at:this.at}),this.balance.getBalance(i,s)]);return{id:s,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:o.transferable,tradeable:r,type:n?.asset_type.type}});return Promise.all(a)}buildRouting(){this.mmRouting.byEmitter.clear(),this.mmRouting.byDiaKey.clear(),this.mmRouting.byEma.clear();for(let t of this.mmAddresses)this.mmRouting.byEmitter.set(t,t);for(let[t,e]of Object.entries(Ge)){let i=t.toLowerCase(),a=e.toLowerCase();this.mmAddresses.has(a)&&this.mmRouting.byEmitter.set(i,a)}for(let[t,e]of Object.entries(Ve)){let i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byDiaKey.set(t,i)}for(let[t,e]of Object.entries(He)){let i=e.toLowerCase();this.mmAddresses.has(i)&&this.mmRouting.byEma.set(t,i)}}async isSupported(){return(await this.api.getStaticApis()).compat.query.Stableswap.Pools.isCompatible(ps.BackwardsCompatible)}async loadPools(){let[t,e,i,a]=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:r,value:n}of e){let[o]=r;this.pegs.set(n,o);for(let l of n.source)l.type==="MMOracle"&&this.mmAddresses.add(l.value.toString().toLowerCase())}this.buildRouting();let s=t.map(async({keyArgs:r,value:n})=>{let[o]=r,l=this.getPoolAddress(o),[c,m,g,p]=await Promise.all([this.getPoolTokens(o,n),this.getPoolAmplification(n,i),this.getPoolPegs(o,n,i),this.api.query.Tokens.TotalIssuance.getValue(o,{at:this.at})]);return c.push({id:o,tradeable:15,balance:p,decimals:Ps}),this.poolsData.set(o,n),{address:l,id:o,type:"Stableswap",fee:Ss.fromPermill(n.fee),tokens:c,totalIssuance:p,...g,...a,...m}});return Promise.all(s)}async getPoolFees(t,e){return{fee:this.store.pools.find(a=>a.address===e).fee}}async getPoolPegs(t,e,i){let a=await this.pegs.get(t);if(!a)return St.getDefault(e);let s=await this.getLatestPegs(e,a,i);return St.compute(e,a,s,i)}async getLatestPegs(t,e,i){let{source:a}=e,s=t.assets,r=a.map(async(n,o)=>{if(n.type==="Oracle"){let[l,c,m]=n.value,g=[m,s[o]].sort((S,A)=>S-A),p=await this.emaOracles.get(l,g,c);if(!p)throw new Error("EmaOracle missing for "+l+" / "+g);let[{price:d,updated_at:b}]=p;return{pair:m===g[0]?[d.n.toString(),d.d.toString()]:[d.d.toString(),d.n.toString()],updatedAt:b.toString(),source:n.type}}if(n.type==="MMOracle"){let l=n.value.toString(),{price:c,decimals:m,updatedAt:g}=await this.mmOracles.get(l),p=(10n**BigInt(m)).toString();return{pair:[c.toString(),p],updatedAt:g.toString(),source:n.type}}if(n.type==="Value")return{pair:n.value.map(c=>c.toString()),updatedAt:i.toString()};throw new Error(n+" source not supported")});return Promise.all(r)}subscribeIssuance(){let e=this.store.pools.map(i=>i.id).map(i=>this.api.query.Tokens.TotalIssuance.watchValue(i,{at:"best"}).pipe(st(({value:a})=>a),st((a,s)=>({value:a,index:s})),ae(({index:a,value:s})=>{a>0&&this.log.trace("tokens.TotalIssuance",i,s)}),st(({value:a})=>({id:i,value:a}))));return ys(...e).pipe(this.watchGuard("tokens.TotalIssuance")).subscribe(i=>{let{id:a,value:s}=i;this.store.update(r=>{let n=[];return r.filter(o=>o.id===a).forEach(o=>{let l=o.tokens.map(c=>c.id===a?{...c,balance:s}:c);n.push({...o,tokens:l,totalIssuance:s})}),n})})}subscribePoolPegs(){return this.api.query.Stableswap.PoolPegs.watchEntries({at:"best"}).pipe($e((t,e)=>!e.deltas),st((t,e)=>({value:t,index:e})),ae(({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}})=>{for(let{args:e,value:i}of t?.upserted??[]){let[a]=e;this.pegs.set(i,a)}}})}subscribeEmaOracles(){return this.api.query.EmaOracle.Oracles.watchEntries({at:"best"}).pipe($e((t,e)=>!e.deltas),st((t,e)=>({value:t,index:e})),ae(({value:t,index:e})=>{e>0&&this.log.trace("emaOracle.Oracles",t.deltas?.upserted)}),this.watchGuard("emaOracle.Oracles")).subscribe(async({value:{deltas:t}})=>{let e=new Set;for(let{args:i,value:a}of t?.upserted??[]){let[s,r,n]=i;this.emaOracles.set(a,s,r,n);let o=Ue(s,r,n.type),l=this.mmRouting.byEma.get(o);l&&e.add(l)}for(let i of e){let a=await this.mmOracle.getData(i);this.log.trace("mmOracle.Hybrid",{h160:i,fresh:a}),this.mmOracles.set(a,i)}})}subscribeMMOracles(){return this.api.event.EVM.Log.watch().pipe(st(({events:t})=>t.map(e=>ft.parse(e.payload)).filter(e=>!!e).filter(({eventName:e})=>vs.includes(e))),hs(t=>t.length>0),this.watchGuard("evm.Log")).subscribe(async t=>{let e=new Set;for(let i of t){if(console.log(i),i.eventName==="ManagedOracle.PriceUpdated"){let a=this.mmRouting.byEmitter.get(i.emitter);a&&e.add(a)}if(i.eventName==="DIA.OracleUpdate"&&i.key){let a=this.mmRouting.byDiaKey.get(i.key);a&&e.add(a)}}for(let i of e){let a=await this.mmOracle.getData(i);this.log.trace("mmOracle",{h160:i,fresh:a}),this.mmOracles.set(a,i)}})}subscribeBlock(){return this.watcher.bestBlock$.pipe(this.watchGuard("watcher.bestBlock")).subscribe(t=>{this.store.update(async e=>{let i=[];for(let a of e){let s=this.poolsData.get(a.id);if(s){let r=await this.getPoolPegs(a.id,s,t),n=this.getPoolAmplification(s,t);i.push({...a,...r,...n})}}return i})})}subscribeUpdates(){let t=new bs;return t.add(this.subscribePoolPegs()),t.add(this.subscribeEmaOracles()),t.add(this.subscribeMMOracles()),t.add(this.subscribeIssuance()),t.add(this.subscribeBlock()),t}};var Ye={};F(Ye,{XykMath:()=>q,XykPool:()=>Tt,XykPoolClient:()=>xt});import{calculate_in_given_out as Ts,calculate_out_given_in as xs,calculate_pool_trade_fee as Is,get_spot_price as ws,calculate_liquidity_in as As,calculate_shares as Os,calculate_spot_price as Bs,calculate_spot_price_with_fee as _s,calculate_liquidity_out_asset_a as ks,calculate_liquidity_out_asset_b as Fs}from"@galacticcouncil/math-xyk";var q=class{static getSpotPrice(t,e,i){return ws(t,e,i)}static calculateInGivenOut(t,e,i){return Ts(t,e,i)}static calculateOutGivenIn(t,e,i){return xs(t,e,i)}static calculatePoolTradeFee(t,e,i){return Is(t,e,i)}static calculateLiquidityIn(t,e,i){return As(t,e,i)}static calculateSpotPrice(t,e){return Bs(t,e)}static calculateSpotPriceWithFee(t,e,i,a){return _s(t,e,i,a)}static calculateShares(t,e,i){return Os(t,e,i)}static calculateLiquidityOutAssetA(t,e,i,a){return ks(t,e,i,a)}static calculateLiquidityOutAssetB(t,e,i,a){return Fs(t,e,i,a)}};import{big as Es}from"@galacticcouncil/common";var{FeeUtils:Xe}=f,Tt=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(r=>[r.id,r])),a=i.get(t),s=i.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:a.decimals,decimalsOut:s.decimals,balanceIn:a.balance,balanceOut:s.balance,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,i){let a=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(a,i),r=Xe.toPct(i.exchangeFee),n=a+s,o=[];(e<this.minTradingLimit||a<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return n>c&&o.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:a,amountOut:e,feePct:r,errors:o}}validateAndSell(t,e,i){let a=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(a,i),r=Xe.toPct(i.exchangeFee),n=a-s,o=[];(e<this.minTradingLimit||a<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return n>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:n,feePct:r,errors:o}}calculateInGivenOut(t,e){let i=q.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(i);return a<0n?0n:a}calculateOutGivenIn(t,e){let i=q.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(i);return a<0n?0n:a}spotPriceInGivenOut(t){let e=q.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=q.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let i=q.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(i)}normalizeSpot(t,e,i){let a=e-i;if(a===0)return t;let s=Es.pow10(Math.abs(a));return a>0?t*s:t/s}};import{CompatibilityLevel as Rs}from"polkadot-api";import{Subscription as Cs}from"rxjs";var xt=class extends w{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(Rs.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:a,value:s})=>{let[r]=a,[n,o]=s,[l,c,m,g]=await Promise.all([this.balance.getBalance(r,n),this.api.query.AssetRegistry.Assets.getValue(n,{at:this.at}),this.balance.getBalance(r,o),this.api.query.AssetRegistry.Assets.getValue(o,{at:this.at})]);return{address:r,type:"XYK",tokens:[{id:n,decimals:c?.decimals||this.decimals.get(n),existentialDeposit:c?.existential_deposit,balance:l.transferable,type:c?.asset_type.type},{id:o,decimals:g?.decimals||this.decimals.get(o),existentialDeposit:g?.existential_deposit,balance:m.transferable,type:g?.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 Cs.EMPTY}};var Ze={};F(Ze,{AavePool:()=>It,AavePoolClient:()=>wt});import{big as Ke,RUNTIME_DECIMALS as ze}from"@galacticcouncil/common";var It=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(r=>[r.id,r])),a=i.get(t),s=i.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:s.balance,decimalsIn:a.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,i){let a=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,i){let a=this.calculateOutGivenIn(t,e),s=[];return a>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Ke.toBigInt(1,ze)}spotPriceOutGivenIn(t){return Ke.toBigInt(1,ze)}calculateTradeFee(t,e){return 0n}};import{AccountId as Ns}from"polkadot-api";import{toHex as Vs}from"@polkadot-api/utils";import{Subscription as je,filter as ne,map as Qe,mergeMap as Je}from"rxjs";import{erc20 as Gs,HYDRATION_SS58_PREFIX as Hs}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"},{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 fm=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{Binary as Ms}from"polkadot-api";import{decodeEventLog as Ls}from"viem";var Gt=class{static parse(t){let{topics:e,data:i}=t.log,a=Ms.toHex(i);try{let{eventName:s,args:r}=Ls({abi:se,topics:e,data:a}),n=r.reserve.toLowerCase();return{eventName:s,reserve:n,key:`${s}:${n}`}}catch{return}}};import Lm from"big.js";import{big as qm,erc20 as Ds,h160 as qs}from"@galacticcouncil/common";var{ERC20:Vm}=Ds,{H160:Gm}=qs;var Hm=10n**27n;var{ERC20:Us}=Gs,$s=["Supply","Withdraw","Repay","Borrow"],wt=class extends w{getPoolType(){return"Aave"}async isSupported(){return!0}getPoolId(t,e){let i=t+"/"+e,a=new TextEncoder().encode(i.padEnd(32,"\0")),s=Vs(a);return Ns(Hs).dec(s)}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:a,liqudity_in:s,liqudity_out:r})=>{let[n,o,l,c]=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(a,{at:this.at}),this.api.query.AssetRegistry.AssetLocations.getValue(a,{at:this.at})]);return{address:this.getPoolId(i,a),type:"Aave",tokens:[{id:i,decimals:n?.decimals,existentialDeposit:n?.existential_deposit,balance:s,location:o,type:n?.asset_type.type},{id:a,decimals:l?.decimals,existentialDeposit:l?.existential_deposit,balance:r,location:c,type:l?.asset_type.type}],...this.getPoolLimits()}});return Promise.all(e)}async getPoolDelta(t){let[e,i]=t.tokens,{liqudity_in:a,liqudity_out:s}=await this.api.apis.AaveTradeExecutor.pool(e.id,i.id,{at:this.at});return t.tokens.map(r=>{let n=r.id===e.id?a:s;return{...r,balance:n}})}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 Us.fromAssetId(t.id)}parseRouterLog(t){let{asset_in:e,asset_out:i}=t;return{assetIn:e,assetOut:i,key:`${e}:${i}`}}subscribeRouterExecuted(){let e=this.store.pools.map(i=>i.tokens).map(([i,a])=>a).map(i=>i.id);return this.api.event.Router.Executed.watch().pipe(Je(({events:i})=>i),Qe(({payload:i})=>this.parseRouterLog(i)),ne(({assetIn:i,assetOut:a})=>e.includes(i)||e.includes(a)),this.watchGuard("router.Execute")).subscribe(({assetIn:i,assetOut:a,key:s})=>{this.log.trace("router.Executed",s),this.store.update(async r=>{let n=[];for(let o of r){let[l,c]=o.tokens;if(c.id===i||c.id===a){let g=await this.getPoolDelta(o);n.push({...o,tokens:g})}}return n})})}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(Je(({events:t})=>t),Qe(({payload:t})=>Gt.parse(t)),ne(t=>t!==void 0),ne(({eventName:t})=>$s.includes(t)),this.watchGuard("evm.Log")).subscribe(({reserve:t,eventName:e})=>{this.log.trace(`evm.Log.${e}`,t),this.store.update(async i=>{let a=[];for(let s of i){let[r]=s.tokens;if(this.getReserveH160Id(r).toLowerCase()===t){let o=await this.getPoolDelta(s);a.push({...s,tokens:o})}}return a})})}subscribeBalances(){return je.EMPTY}subscribeUpdates(){let t=new je;return t.add(this.subscribeRouterExecuted()),t.add(this.subscribeEvmLog()),t}};var ii={};F(ii,{HsmMath:()=>_,HsmPool:()=>At,HsmPoolClient:()=>Ot});import{calculate_collateral_in_given_hollar_out as Ws,calculate_collateral_out_given_hollar_in as Xs,calculate_hollar_in_given_collateral_out as Ys,calculate_hollar_out_given_collateral_in as Ks,calculate_imbalance as zs,calculate_max_price as js,calculate_buyback_limit as Qs,calculate_buyback_price_with_fee as Js}from"@galacticcouncil/math-hsm";var _=class{static calculateCollateralInGivenHollarOut(t,e,i){return Ws(t,e,i)}static calculateCollateralOutGivenHollarIn(t,e,i){return Xs(t,e,i)}static calculateHollarOutGivenCollateralIn(t,e,i){return Ks(t,e,i)}static calculateHollarInGivenCollateralOut(t,e,i){return Ys(t,e,i)}static calculateImbalance(t,e,i){return zs(t,e,i)}static calculateBuybackLimit(t,e){return Qs(t,e)}static calculateBuybackPriceWithFee(t,e,i){return Js(t,e,i)}static calculateMaxPrice(t,e){return js(t,e)}};import{big as N,RUNTIME_DECIMALS as Ht}from"@galacticcouncil/common";var{FeeUtils:nt}=f,At=class u extends X{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 a=this.parsePair(t.assetOut,t.assetIn),s=super.calculateInGivenOut(a,e,{fee:this.fee}),r=this.calculateBuybackLimit(t);e>r&&i.push("MaxBuyBackExceeded");let n=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,s)>n&&i.push("MaxBuyPriceExceeded"),s>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 a=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,a):this.validateTradeHollarOut(e,i,a)}validateAndBuy(t,e){let i=this.calculateInGivenOut(t,e),a=this.validateTradeConstraints(t,i,e);return{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e){let i=this.calculateOutGivenIn(t,e),a=this.validateTradeConstraints(t,e,i);return{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:a}}calculateHollarInGivenCollateralOut(t,e){let i=super.calculateInGivenOut(t,e,{fee:this.fee}),a=_.calculateHollarInGivenCollateralOut(e.toString(),i.toString(),nt.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),i=_.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),nt.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}),a=_.calculateCollateralOutGivenHollarIn(e.toString(),i.toString(),nt.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),i=_.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),nt.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=_.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(i)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),i=_.calculateBuybackLimit(e.toString(),nt.toRaw(this.buyBackRate).toString());return BigInt(i)}calculateBuyPrice(t,e,i){let a=_.calculateBuybackPriceWithFee(i.toString(),e.toString(),nt.toRaw(this.buyBackFee).toString()),[s,r]=JSON.parse(a),n=N.pow10(t.decimalsIn+Ht-t.decimalsOut);return BigInt(s)*n/BigInt(r)}calculateMaxPrice(t){let e=this.getCollateralPeg(),i=_.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[a,s]=JSON.parse(i),r=N.pow10(Ht-t.decimalsOut);return BigInt(a)*r/BigInt(s)}spotPriceInGivenOut(t){let e=N.toBigInt(1,t.decimalsOut),a=this.calculateInGivenOut(t,e)*N.pow10(Ht-t.decimalsOut);return this.normalizeSpotPrice(a,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=N.toBigInt(1,t.decimalsIn),a=this.calculateOutGivenIn(t,e)*N.pow10(Ht-t.decimalsIn);return this.normalizeSpotPrice(a,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(a=>a.id!==this.hollarId),e=this.pegs[t],i=this.tokens[t].decimals;return this.isDefaultPeg(e)?[N.toBigInt(1,18).toString(),N.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 a=e-i;if(a===0)return t;let s=N.pow10(Math.abs(a));return a>0?t*s:t/s}};import{AccountId as en,CompatibilityLevel as an}from"polkadot-api";import{toHex as sn}from"@polkadot-api/utils";import{Subscription as re,combineLatest as nn,filter as ti,map as oe,mergeMap as rn,pairwise as on}from"rxjs";import{h160 as ln,HYDRATION_SS58_PREFIX as cn}from"@galacticcouncil/common";import{Binary as Zs}from"polkadot-api";import{decodeEventLog as tn}from"viem";var Ut=[{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 $t=class{static parse(t){let{topics:e,data:i}=t.log,a=Zs.toHex(i);try{let{eventName:s,args:r}=tn({abi:Ut,topics:e,data:a}),n=r.facilitatorAddress.toLowerCase();return{eventName:s,facilitator:n,key:`${s}:${n}`}}catch{return}}};var Wt=class{client;constructor(t){this.client=t.getWsProvider()}async getFacilitatorCapacity(t,e){let[i,a]=await this.client.readContract({abi:Ut,address:t,functionName:"getFacilitatorBucket",args:[e]});return i-a}};var{FeeUtils:le}=f,{H160:ei}=ln,un=["FacilitatorBucketCapacityUpdated","FacilitatorBucketLevelUpdated"],Ot=class extends w{ghoClient;stableClient;constructor(t,e,i,a){super(t,e,a),this.stableClient=i,this.ghoClient=new Wt(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),a=sn(i);return en(cn).dec(a)}async isSupported(){return(await this.api.getStaticApis()).compat.query.HSM.Collaterals.isCompatible(an.BackwardsCompatible)}async loadPools(){let t=await this.api.constants.HSM.HollarId(),[e,i,a]=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 s=this.getFacilitatorAddress(),r=ei.fromAny(s),n=this.getHollarAddress(e),o=await this.ghoClient.getFacilitatorCapacity(n,r),l=i.map(async({keyArgs:m,value:g})=>{let[p]=m,{pool_id:d,max_buy_price_coefficient:b,max_in_holding:O,purchase_fee:S,buy_back_fee:A,buyback_rate:x}=g,v=a.find(B=>B.id===d);if(v){let B=this.getPoolId(d),k=await this.balance.getBalance(s,p);return{...v,address:B,type:"HSM",tokens:v.tokens.filter(U=>U.id!==d),hsmAddress:s,hsmMintCapacity:o,hollarId:t,hollarH160:n,collateralId:p,collateralBalance:k.transferable,maxBuyPriceCoefficient:b,maxInHolding:O,purchaseFee:le.fromPermill(S),buyBackFee:le.fromPermill(A),buyBackRate:le.fromPerbill(x)}}});return(await Promise.all(l)).filter(m=>m!==null)}async getPoolFees(){return{}}subscribeEvmLog(){return this.api.event.EVM.Log.watch().pipe(rn(({events:t})=>t),oe(({payload:t})=>$t.parse(t)),ti(t=>t!==void 0),ti(({eventName:t})=>un.includes(t)),this.watchGuard("evm.Log")).subscribe(({eventName:t,facilitator:e})=>{this.log.trace(`evm.Log.${t}`,e),this.store.update(async i=>{let a=[],[{hsmAddress:s,hollarH160:r}]=i,n=ei.fromAny(s);if(n.toLowerCase()===e){let l=await this.ghoClient.getFacilitatorCapacity(r,n);for(let c of i)a.push({...c,hsmMintCapacity:l})}return a})})}subscribeCollateralBalance(){let t=[],e=[];this.store.pools.forEach(s=>{let{tokens:r,collateralId:n}=s;r.find(l=>l.id===n).type==="Erc20"?e.push(n):t.push(n)});let[{hsmAddress:i}]=this.store.pools,a=[];if(t.length>0){let s=this.balance.watchTokensBalance(i);a.push(s)}if(e.length>0){let s=this.balance.watchErc20Balance(i,e);a.push(s)}return a.length>0?nn(a).pipe(oe(s=>s.flat()),on(),oe(([s,r])=>this.balance.getDeltas(s,r)),this.watchGuard("balances")).subscribe(s=>{this.store.update(r=>{let n=[],o=new Map(r.map(l=>[l.collateralId,l]));return s.forEach(({id:l,balance:c})=>{let m=o.get(l);m&&(this.log.trace("balances",{id:l,balance:c}),n.push({...m,collateralBalance:c.transferable}))}),n})}):re.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 a=[];for(let s of i){let r=e.get(s.id);r&&a.push({...s,fee:r.fee,tokens:r.tokens.filter(n=>n.id!==s.id),totalIssuance:r.totalIssuance,pegs:r.pegs,amplification:r.amplification,isRampPeriod:r.isRampPeriod})}return a})})}subscribeBalances(){return re.EMPTY}subscribeUpdates(){let t=new re;return t.add(this.subscribeCollateralBalance()),t.add(this.subscribeStableswapUpdates()),t.add(this.subscribeEvmLog()),t}};var pi={};F(pi,{UNISWAP_V3_FACTORY:()=>ce,UniswapV3Math:()=>rt,UniswapV3Pool:()=>Bt,UniswapV3PoolClient:()=>kt,V3_POOLS:()=>ue,ticksInWord:()=>mi});var ce="0x9fE46736679d2D9a65F0992F2272dE9f3c7fa6e0",ue=[{assetA:16,assetB:9,fee:3e3},{assetA:16,assetB:9,fee:500}];import h from"jsbi";import{LiquidityMath as mn,SwapMath as pn,Tick as dn,TickList as ai,TickMath as G}from"@uniswap/v3-sdk";var me=h.BigInt(0),si=h.BigInt(1),pe=h.BigInt(-1),rt=class u{static calculateOutGivenIn(t,e,i){if(i<=0n||t.liquidity<=0n)return 0n;let a=u.computeSwap(t,e,h.BigInt(i.toString())),s=h.multiply(a.amountCalculated,pe);return BigInt(s.toString())}static calculateInGivenOut(t,e,i){if(i<=0n||t.liquidity<=0n)return 0n;let a=u.computeSwap(t,e,h.multiply(h.BigInt(i.toString()),pe));return BigInt(a.amountCalculated.toString())}static computeSwap(t,e,i){let a=u.buildTicks(t.ticks),s=t.tickSpacing,r=t.fee,n=e?h.add(G.MIN_SQRT_RATIO,si):h.subtract(G.MAX_SQRT_RATIO,si),o=h.greaterThanOrEqual(i,me),l=i,c=me,m=h.BigInt(t.sqrtPriceX96.toString()),g=t.tick,p=h.BigInt(t.liquidity.toString());for(;h.notEqual(l,me)&&h.notEqual(m,n);){let d=m,[b,O]=ai.nextInitializedTickWithinOneWord(a,g,e,s);b<G.MIN_TICK?b=G.MIN_TICK:b>G.MAX_TICK&&(b=G.MAX_TICK);let S=G.getSqrtRatioAtTick(b),A=(e?h.lessThan(S,n):h.greaterThan(S,n))?n:S,[x,v,B,k]=pn.computeSwapStep(m,A,p,l,r);if(m=x,o?(l=h.subtract(l,h.add(v,k)),c=h.subtract(c,B)):(l=h.add(l,B),c=h.add(c,h.add(v,k))),h.equal(m,S)){if(O){let U=ai.getTick(a,b).liquidityNet;e&&(U=h.multiply(U,pe)),p=mn.addDelta(p,U)}g=e?b-1:b}else h.notEqual(m,d)&&(g=G.getTickAtSqrtRatio(m))}return{amountCalculated:c,sqrtPriceX96:m,liquidity:p,tick:g}}static buildTicks(t){return t.map(e=>new dn({index:e.index,liquidityGross:e.liquidityGross.toString(),liquidityNet:e.liquidityNet.toString()})).sort((e,i)=>e.index-i.index)}};import{RUNTIME_DECIMALS as gn}from"@galacticcouncil/common";var bn=1e6,ni=10n**BigInt(gn),ri=192n,Bt=class u{type;address;id;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;token0;token1;sqrtPriceX96;tick;liquidity;tickSpacing;ticks;static fromPool(t){return new u(t)}constructor(t){this.type="UniswapV3",this.address=t.address,this.id=t.id,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.token0=t.token0,this.token1=t.token1,this.sqrtPriceX96=t.sqrtPriceX96,this.tick=t.tick,this.liquidity=t.liquidity,this.tickSpacing=t.tickSpacing,this.ticks=t.ticks}validatePair(t,e){let i=a=>a===this.token0||a===this.token1;return i(t)&&i(e)&&t!==e}parsePair(t,e){let i=new Map(this.tokens.map(r=>[r.id,r])),a=i.get(t),s=i.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:a.decimals,decimalsOut:s.decimals,balanceIn:a.balance,balanceOut:s.balance,assetInEd:a.existentialDeposit,assetOutEd:s.existentialDeposit}}calculateInGivenOut(t,e,i){return rt.calculateInGivenOut(this.toState(i!=null),this.isZeroForOne(t.assetIn),e)}calculateOutGivenIn(t,e,i){return rt.calculateOutGivenIn(this.toState(i!=null),this.isZeroForOne(t.assetIn),e)}spotPriceOutGivenIn(t){let e=this.spotOutPerIn(this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsIn,t.decimalsOut)}spotPriceInGivenOut(t){let e=this.spotOutPerIn(!this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsOut,t.decimalsIn)}validateAndSell(t,e,i){let a=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,this.fees()),r=R.calculateSellFee(a,s),n=[];(e<this.minTradingLimit||a<t.assetOutEd)&&n.push("InsufficientTradingAmount");let o=t.balanceIn/this.maxInRatio;e>o&&n.push("MaxInRatioExceeded");let l=t.balanceOut/this.maxOutRatio;return s>l&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:s,feePct:r,errors:n}}validateAndBuy(t,e,i){let a=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,this.fees()),r=R.calculateBuyFee(a,s),n=[];(e<this.minTradingLimit||a<t.assetInEd)&&n.push("InsufficientTradingAmount");let o=t.balanceOut/this.maxOutRatio;e>o&&n.push("MaxOutRatioExceeded");let l=t.balanceIn/this.maxInRatio;return s>l&&n.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:a,amountOut:e,feePct:r,errors:n}}fees(){return{fee:[this.fee,bn]}}isZeroForOne(t){return t===this.token0}toState(t){return{fee:t?this.fee:0,sqrtPriceX96:this.sqrtPriceX96,tick:this.tick,liquidity:this.liquidity,tickSpacing:this.tickSpacing,ticks:this.ticks}}spotOutPerIn(t){let e=this.sqrtPriceX96*this.sqrtPriceX96;if(e===0n)return 0n;let i=e*ni>>ri;return t?i:(ni<<ri)/e}normalizeSpot(t,e,i){let a=e-i;if(a===0)return t;let s=10n**BigInt(Math.abs(a));return a>0?t*s:t/s}};import{Subscription as hn,filter as yn,map as fn,mergeMap as Pn}from"rxjs";import{erc20 as Sn}from"@galacticcouncil/common";import{TICK_SPACINGS as vn,TickMath as li,nearestUsableTick as ci}from"@uniswap/v3-sdk";import{parseAbi as de}from"viem";var oi=de(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)"]),Y=de(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickBitmap(int16 wordPosition) view returns (uint256)","function ticks(int24 tick) view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized)"]),_t=de(["function balanceOf(address account) view returns (uint256)"]);var{ERC20:Xt}=Sn,Tn="0x0000000000000000000000000000000000000000",xn=1e6,ui=5;function mi(u,t,e){let i=[];for(let a=0;a<256;a++)u>>BigInt(a)&1n&&i.push((t*256+a)*e);return i}var kt=class extends w{getPoolType(){return"UniswapV3"}async isSupported(){return!0}async getPoolFees(t,e){let i=this.store.pools.find(s=>s.address===e);return{fee:[i?i.fee:0,xn]}}async loadPools(){let t=this.evm.getWsProvider();return(await Promise.all(ue.map(i=>this.loadPool(t,i)))).filter(i=>i!==void 0)}async loadPool(t,e){try{let{assetA:i,assetB:a,fee:s}=e,r=vn[s];if(r===void 0)return;let n=Xt.fromAssetId(i).toLowerCase(),o=Xt.fromAssetId(a).toLowerCase(),l=n<o,c=l?i:a,m=l?a:i,g=l?n:o,p=l?o:n,d=await t.readContract({abi:oi,address:ce,functionName:"getPool",args:[g,p,s]});if(d.toLowerCase()===Tn)return;let[b,O,S,A,x,v]=await Promise.all([t.readContract({abi:Y,address:d,functionName:"slot0"}),t.readContract({abi:Y,address:d,functionName:"liquidity"}),t.readContract({abi:_t,address:g,functionName:"balanceOf",args:[d]}),t.readContract({abi:_t,address:p,functionName:"balanceOf",args:[d]}),this.api.query.AssetRegistry.Assets.getValue(c,{at:this.at}),this.api.query.AssetRegistry.Assets.getValue(m,{at:this.at})]),B=b[0],k=b[1],U=await this.loadTicks(t,d,k,r);return{address:d,type:"UniswapV3",token0:c,token1:m,fee:s,sqrtPriceX96:B,tick:k,liquidity:O,tickSpacing:r,ticks:U,tokens:[{id:c,decimals:x?.decimals,existentialDeposit:x?.existential_deposit??0n,balance:S,type:x?.asset_type.type},{id:m,decimals:v?.decimals,existentialDeposit:v?.existential_deposit??0n,balance:A,type:v?.asset_type.type}],maxInRatio:3n,maxOutRatio:3n,minTradingLimit:0n}}catch(i){this.log.error("v3_load_pool",e,i);return}}async loadTicks(t,e,i,a){let s=Math.floor(i/a)>>8,r=[];for(let p=s-ui;p<=s+ui;p++)r.push(p);let n=await Promise.all(r.map(p=>t.readContract({abi:Y,address:e,functionName:"tickBitmap",args:[p]}))),o=r.flatMap((p,d)=>mi(n[d],p,a)),l=await Promise.all(o.map(p=>t.readContract({abi:Y,address:e,functionName:"ticks",args:[p]}))),c=o.map((p,d)=>({index:p,liquidityGross:l[d][0],liquidityNet:l[d][1]})),m=ci(li.MIN_TICK,a),g=ci(li.MAX_TICK,a);return c.some(p=>p.index===m)||c.push({index:m,liquidityNet:0n,liquidityGross:0n}),c.some(p=>p.index===g)||c.push({index:g,liquidityNet:0n,liquidityGross:0n}),c.sort((p,d)=>p.index-d.index),c}async refreshPool(t,e){let i=e.address,a=Xt.fromAssetId(e.token0).toLowerCase(),s=Xt.fromAssetId(e.token1).toLowerCase(),[r,n,o,l]=await Promise.all([t.readContract({abi:Y,address:i,functionName:"slot0"}),t.readContract({abi:Y,address:i,functionName:"liquidity"}),t.readContract({abi:_t,address:a,functionName:"balanceOf",args:[i]}),t.readContract({abi:_t,address:s,functionName:"balanceOf",args:[i]})]),c=r[1],m=await this.loadTicks(t,i,c,e.tickSpacing),g=e.tokens.map(p=>p.id===e.token0?{...p,balance:o}:{...p,balance:l});return{...e,sqrtPriceX96:r[0],tick:c,liquidity:n,ticks:m,tokens:g}}subscribeBalances(){return hn.EMPTY}subscribeUpdates(){let t=new Set(this.store.pools.map(e=>e.address.toLowerCase()));return this.api.event.EVM.Log.watch().pipe(Pn(({events:e})=>e),fn(({payload:e})=>e.log.address.toLowerCase()),yn(e=>t.has(e)),this.watchGuard("evm.Log")).subscribe(e=>{this.log.trace("evm.Log",e),this.store.update(async i=>{let a=this.evm.getWsProvider(),s=[];for(let r of i)r.address.toLowerCase()===e&&s.push(await this.refreshPool(a,r));return s})})}};var ge=class{static get(t){switch(t.type){case"Aave":return It.fromPool(t);case"XYK":return Tt.fromPool(t);case"Omnipool":return ht.fromPool(t);case"LBP":return ct.fromPool(t);case"Stableswap":return X.fromPool(t);case"HSM":return At.fromPool(t);case"UniswapV3":return Bt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as In}from"@galacticcouncil/common";import{Subject as wn,Subscription as H,takeUntil as An}from"rxjs";var ot=class extends Error{constructor(t){super(),this.message=`${t} pool invalid`,this.name="PoolNotFound"}};var{logger:On}=In,be=class extends C{evm;aave;omnipool;stableswap;hsm;xyk;lbp;uniswapv3;active=new Set([]);pools=new Map([]);clients=[];aaveSub=H.EMPTY;omniSub=H.EMPTY;stableSub=H.EMPTY;hsmSub=H.EMPTY;xykSub=H.EMPTY;lbpSub=H.EMPTY;v3Sub=H.EMPTY;isReady=!1;isDestroyed=new wn;constructor(t,e,i){super(t,i),this.evm=e,this.aave=new wt(t,e,i),this.omnipool=new yt(t,e,i),this.stableswap=new vt(t,e,i),this.hsm=new Ot(t,e,this.stableswap,i),this.xyk=new xt(t,e,i),this.lbp=new bt(t,e,i),this.uniswapv3=new kt(t,e,i),this.clients=[this.aave,this.omnipool,this.stableswap,this.hsm,this.xyk,this.lbp,this.uniswapv3]}get isHistorical(){return this.at!=="best"&&this.at!=="finalized"}subscribe(t){return this.isHistorical?H.EMPTY:t.getSubscriber().pipe(An(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")||(On.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}withV3(){return this.v3Sub.unsubscribe(),this.v3Sub=this.subscribe(this.uniswapv3),this.active.add("UniswapV3"),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(a=>a.getPoolType()===e.type);if(i)return i.getPoolFees(t,e.address);throw new ot(e.type)}};var he=class{constructor(t){this.snapshot=t;let{aave:e,xyk:i,lbp:a,stable:s,omni:r}=t.pools;this.flat=[...e,...i,...a,...s,...r]}flat;async getPools(){return this.flat}async getPoolFees(t,e){let{block:i,states:a}=this.snapshot;switch(e.type){case"Aave":return{};case"XYK":{let{exchangeFee:s}=a.xyk;return{exchangeFee:s}}case"LBP":{let{repayFee:s}=a.lbp;return{exchangeFee:e.fee,repayFee:s}}case"Stableswap":return{fee:e.fee};case"Omnipool":{let s=t.assetOut,r=t.assetIn,{dynamicFees:n,emaOracles:o,assetFeeParams:l,protocolFeeParams:c,maxSlipFee:m}=a.omni,g=n.find(({asset:b})=>b===s)?.fee,p=o.find(({pair:b})=>b.join(":")===qt(s))?.oracle,d=o.find(({pair:b})=>b.join(":")===qt(r))?.oracle;return W.compute(t,i,g,p,d,l,c,m)}default:throw new ot(e.type)}}};export{be as PoolContextProvider,V as PoolError,ge as PoolFactory,P as PoolType,he as SnapshotPoolCtxProvider,Ze as aave,ii as hsm,Fe as lbp,Me as omni,We as stable,pi as uniswapv3,Ye 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:
|
|
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
|
|
17
|
-
private
|
|
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'];
|
package/build/pool/types.d.ts
CHANGED
|
@@ -9,7 +9,8 @@ export declare enum PoolType {
|
|
|
9
9
|
Omni = "Omnipool",
|
|
10
10
|
Stable = "Stableswap",
|
|
11
11
|
XYK = "XYK",
|
|
12
|
-
HSM = "HSM"
|
|
12
|
+
HSM = "HSM",
|
|
13
|
+
V3 = "UniswapV3"
|
|
13
14
|
}
|
|
14
15
|
export declare enum PoolError {
|
|
15
16
|
UnknownError = "UnknownError",
|
|
@@ -90,6 +91,7 @@ export type Hop = {
|
|
|
90
91
|
pool: PoolType;
|
|
91
92
|
poolAddress: string;
|
|
92
93
|
poolId?: number;
|
|
94
|
+
fee?: number;
|
|
93
95
|
assetIn: number;
|
|
94
96
|
assetOut: number;
|
|
95
97
|
};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { V3PoolState } from './types';
|
|
2
|
+
export declare class UniswapV3Math {
|
|
3
|
+
static calculateOutGivenIn(state: V3PoolState, zeroForOne: boolean, amountIn: bigint): bigint;
|
|
4
|
+
static calculateInGivenOut(state: V3PoolState, zeroForOne: boolean, amountOut: bigint): bigint;
|
|
5
|
+
private static computeSwap;
|
|
6
|
+
private static buildTicks;
|
|
7
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { BuyCtx, Pool, PoolFees, PoolPair, PoolToken, PoolType, SellCtx } from '../types';
|
|
2
|
+
import { UniswapV3PoolBase, UniswapV3PoolFees, V3Tick } from './types';
|
|
3
|
+
/**
|
|
4
|
+
* Concrete Uniswap v3 pool. Implements the synchronous router `Pool` interface
|
|
5
|
+
* by delegating swap math to `UniswapV3Math` (a tick-walk over the pool's
|
|
6
|
+
* loaded concentrated liquidity) and deriving the spot price from `sqrtPriceX96`.
|
|
7
|
+
*
|
|
8
|
+
* The v3 fee is taken inside the swap, so — mirroring `OmniPool`/`StableSwap` —
|
|
9
|
+
* `calculate*` returns the gross (fee-less) amount when called without `fees`
|
|
10
|
+
* and the net amount when called with them; `validateAndSell/Buy` use the two
|
|
11
|
+
* to report the effective fee.
|
|
12
|
+
*/
|
|
13
|
+
export declare class UniswapV3Pool implements Pool {
|
|
14
|
+
type: PoolType;
|
|
15
|
+
address: string;
|
|
16
|
+
id?: number;
|
|
17
|
+
tokens: PoolToken[];
|
|
18
|
+
maxInRatio: bigint;
|
|
19
|
+
maxOutRatio: bigint;
|
|
20
|
+
minTradingLimit: bigint;
|
|
21
|
+
fee: number;
|
|
22
|
+
token0: number;
|
|
23
|
+
token1: number;
|
|
24
|
+
sqrtPriceX96: bigint;
|
|
25
|
+
tick: number;
|
|
26
|
+
liquidity: bigint;
|
|
27
|
+
tickSpacing: number;
|
|
28
|
+
ticks: V3Tick[];
|
|
29
|
+
static fromPool(pool: UniswapV3PoolBase): UniswapV3Pool;
|
|
30
|
+
constructor(pool: UniswapV3PoolBase);
|
|
31
|
+
validatePair(tokenIn: number, tokenOut: number): boolean;
|
|
32
|
+
parsePair(tokenIn: number, tokenOut: number): PoolPair;
|
|
33
|
+
/** Input required for `amountOut`; gross (fee-less) unless `fees` is given. */
|
|
34
|
+
calculateInGivenOut(poolPair: PoolPair, amountOut: bigint, fees?: UniswapV3PoolFees): bigint;
|
|
35
|
+
/** Output for `amountIn`; gross (fee-less) unless `fees` is given. */
|
|
36
|
+
calculateOutGivenIn(poolPair: PoolPair, amountIn: bigint, fees?: UniswapV3PoolFees): bigint;
|
|
37
|
+
spotPriceOutGivenIn(poolPair: PoolPair): bigint;
|
|
38
|
+
spotPriceInGivenOut(poolPair: PoolPair): bigint;
|
|
39
|
+
validateAndSell(poolPair: PoolPair, amountIn: bigint, _dynamicFees: PoolFees | null): SellCtx;
|
|
40
|
+
validateAndBuy(poolPair: PoolPair, amountOut: bigint, _dynamicFees: PoolFees | null): BuyCtx;
|
|
41
|
+
private fees;
|
|
42
|
+
private isZeroForOne;
|
|
43
|
+
private toState;
|
|
44
|
+
private spotOutPerIn;
|
|
45
|
+
private normalizeSpot;
|
|
46
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import { Subscription } from 'rxjs';
|
|
2
|
+
import { PoolFees, PoolPair, PoolType } from '../types';
|
|
3
|
+
import { PoolClient } from '../PoolClient';
|
|
4
|
+
import { UniswapV3PoolBase } from './types';
|
|
5
|
+
/**
|
|
6
|
+
* Decode one tick-bitmap word into the absolute tick indices it marks
|
|
7
|
+
* initialized. Bit `i` of the word at `wordPos` is compressed tick
|
|
8
|
+
* `wordPos * 256 + i`, i.e. absolute tick `(wordPos * 256 + i) * tickSpacing`.
|
|
9
|
+
*/
|
|
10
|
+
export declare function ticksInWord(bitmap: bigint, wordPos: number, tickSpacing: number): number[];
|
|
11
|
+
/**
|
|
12
|
+
* Router venue for Uniswap v3 pools on Hydration's EVM.
|
|
13
|
+
*
|
|
14
|
+
* Pools come from a curated per-chain config (`V3_POOLS`) and are resolved via
|
|
15
|
+
* the v3 factory — mirroring the on-chain design where v3 routes are
|
|
16
|
+
* governance-gated rather than permissionless. Concentrated-liquidity state
|
|
17
|
+
* (`slot0`, `liquidity`, and initialized ticks via the tick bitmap) is read
|
|
18
|
+
* directly over the EVM; quoting itself is client-side in
|
|
19
|
+
* `UniswapV3Pool`/`UniswapV3Math`.
|
|
20
|
+
*/
|
|
21
|
+
export declare class UniswapV3PoolClient extends PoolClient<UniswapV3PoolBase> {
|
|
22
|
+
getPoolType(): PoolType;
|
|
23
|
+
isSupported(): Promise<boolean>;
|
|
24
|
+
/** Fixed per-pool fee tier as a `[numerator, denominator]` fraction. */
|
|
25
|
+
getPoolFees(_pair: PoolPair, address: string): Promise<PoolFees>;
|
|
26
|
+
/** Resolve and load every configured pool; pools that fail to load are skipped. */
|
|
27
|
+
loadPools(): Promise<UniswapV3PoolBase[]>;
|
|
28
|
+
private loadPool;
|
|
29
|
+
/**
|
|
30
|
+
* Read the initialized ticks in a bounded window around the current tick via
|
|
31
|
+
* the pool's tick bitmap, plus the usable min/max ticks as zero-liquidity
|
|
32
|
+
* sentinels so the swap walk is always bounded (a full-range pool with no
|
|
33
|
+
* ticks in range simply yields the two sentinels).
|
|
34
|
+
*/
|
|
35
|
+
private loadTicks;
|
|
36
|
+
private refreshPool;
|
|
37
|
+
/**
|
|
38
|
+
* The base balance watcher targets substrate accounts, but a v3 pool is an
|
|
39
|
+
* EVM contract — its reserves, price and ticks are refreshed via EVM reads in
|
|
40
|
+
* `subscribeUpdates`/`loadPools` instead (mirrors `AavePoolClient`).
|
|
41
|
+
*/
|
|
42
|
+
protected subscribeBalances(): Subscription;
|
|
43
|
+
/** Re-sync a pool's state whenever it emits an EVM log (swap/mint/burn). */
|
|
44
|
+
protected subscribeUpdates(): Subscription;
|
|
45
|
+
}
|