@galacticcouncil/sdk-next 0.41.0 → 0.41.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- var Wt=Object.defineProperty;var X=(u,t)=>{for(var e in t)Wt(u,e,{get:t[e],enumerable:!0})};import Ut from"buffer";typeof window<"u"&&(window.Buffer=Ut.Buffer);var Y=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $t=10,z=class{isNotVisited(t,e){let s=!0;return e.forEach(a=>{(a[0]===t[0]||a[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let a=[],i=new Y,n=[];for(n.push([e,""]),i.enqueue(n);i.size()>0;){let r=i.dequeue();if(!r||r.length>$t)continue;let o=r[r.length-1];(s===null||o[0]===s)&&a.push(r),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let m=[...r];m.push(c),i.enqueue(m)}})}return a}findShortestPaths(t,e,s){let a=[],i=new Y,n=[];n.push([e,""]),i.enqueue(n);let r=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===s){o.length<r?(r=o.length,a.length=0,a.push(o)):o.length===r&&a.push(o);continue}let c=t.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&i.enqueue([...o,m])}return a}buildAndPopulateGraph(t,e){let s=new Map;for(let a of t)s.set(parseInt(a),[]);for(let[a,i,n]of e)s.get(i)?.push([n,a]);return s}};function mt(u){let t={};for(let e of u){let s=e.tokens.length;for(let a=0;a<s;a++){t[e.tokens[a].id]||(t[e.tokens[a].id]=[]);for(let i=0;i<s;i++){if(a==i)continue;let n=[e.address,e.tokens[a].id,e.tokens[i].id];t[e.tokens[a].id].push(n)}}}return t}import{calculate_in_given_out as Xt,calculate_out_given_in as Yt,calculate_linear_weights as zt,calculate_pool_trade_fee as Kt,get_spot_price as jt}from"@galacticcouncil/math-lbp";var E=class{static getSpotPrice(t,e,s,a,i){return jt(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i){return Xt(t,e,s,a,i)}static calculateOutGivenIn(t,e,s,a,i){return Yt(t,e,s,a,i)}static calculateLinearWeights(t,e,s,a,i){return zt(t,e,s,a,i)}static calculatePoolTradeFee(t,e,s){return Kt(t,e,s)}};import{big as wt,RUNTIME_DECIMALS as Ot}from"@galacticcouncil/common";var at={};X(at,{withTimeout:()=>Qt});function Qt(u,t,e="timeout"){return new Promise((s,a)=>{let i=setTimeout(()=>a(new Error(e)),t);u.then(n=>{clearTimeout(i),s(n)},n=>{clearTimeout(i),a(n)})})}var A={};X(A,{divSpot:()=>Zt,getFraction:()=>te,mulScaled:()=>St,mulSpot:()=>Jt});import{RUNTIME_DECIMALS as ft}from"@galacticcouncil/common";function St(u,t,e,s,a){let i=e+s-a,n=u*t;return i>0?n/BigInt(10)**BigInt(i):i<0?n*BigInt(10)**BigInt(-i):n}function Jt(u,t,e,s){return St(u,t,e,ft,s)}function Zt(u,t,e,s){if(t===0n)return 0n;let a=BigInt(10)**BigInt(ft+s-e);return u*a/t}function te(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let s=BigInt(10)**BigInt(e),a=BigInt(Math.round(t*Number(s)));return u*a/(BigInt(100)*s)}var S={};X(S,{FeeUtils:()=>dt,shiftNeg:()=>ae});import se from"big.js";var dt=class u{static toPct(t){let[e,s]=t;return u.safeDivide(e*100,s)}static toRaw(t){let[e,s]=t;return u.safeDivide(e,s)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,s=12){let a=10**s;return Math.round(t*a/e)/a}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ae(u,t){let e=se(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var K={};X(K,{findNestedKey:()=>ie,findNestedObj:()=>ne,jsonFormatter:()=>re});var ie=(u,t)=>{let e=[];return JSON.stringify(u,(s,a)=>(a&&a[t]&&e.push(a),a)),e[0]},ne=(u,t,e)=>{let s;return JSON.stringify(u,(a,i)=>(i&&i[t]===e&&(s=i),i)),s},re=(u,t)=>typeof t=="bigint"?t.toString():t;var T={};X(T,{calculateBuyFee:()=>ue,calculateDiffToAvg:()=>oe,calculateDiffToRef:()=>le,calculateSellFee:()=>ce});import k from"big.js";function oe(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function le(u,t){if(t===0n)return 0;let e=k(u.toString()),s=k(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function ce(u,t){if(u===0n)return 0;let e=k(u.toString()),s=k(t.toString());return k(1).minus(s.div(e)).mul(100).round(2).toNumber()}function ue(u,t){if(u===0n)return 0;let e=k(u.toString());return k(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as Ys}from"@thi.ng/cache";var{FeeUtils:Tt}=S,it=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,weightIn:a.weight,weightOut:i.weight}}validateAndBuy(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&i.push("MaxOutRatioExceeded"),a===t.assetOut){let r=this.calculateTradeFee(e,s),o=Tt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:i}}else{let r=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return r>o&&i.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&i.push("MaxInRatioExceeded"),a===t.assetIn){let r=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return r>o&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:i}}else{let r=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(r,s),l=Tt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=r-o,m=t.balanceOut/this.maxOutRatio;return c>m&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let s=E.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=E.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=E.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),wt.toBigInt(1,Ot).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=E.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),wt.toBigInt(1,Ot).toString());return BigInt(e)}calculateTradeFee(t,e){let s=E.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as tr}from"polkadot-api";import{Subscription as sr,distinctUntilChanged as ar,filter as ir}from"rxjs";import{memoize1 as pn}from"@thi.ng/memoize";import{TLRUCache as dn}from"@thi.ng/cache";import{ReplaySubject as Pn,Subscription as yn,combineLatest as fn,defer as Sn,from as In,merge as wn,of as On,EMPTY as Tn}from"rxjs";import{bufferCount as xn,bufferTime as Bn,catchError as An,filter as Fn,finalize as _n,map as Rn,pairwise as En,repeat as kn,skip as Cn,share as Mn,startWith as Ln,switchMap as Dn,tap as Hn,throttleTime as qn}from"rxjs/operators";import{hydration as Va,hydrationNext as Wa}from"@galacticcouncil/descriptors";import{log as pe}from"@galacticcouncil/common";import{shareReplay as Ca,tap as Ma}from"rxjs";import{defer as ba,from as ha,of as Pa,timer as ya}from"rxjs";import{catchError as Sa,distinctUntilChanged as Ia,expand as wa,map as Oa,shareReplay as Ta,skip as va,switchMap as xa,timeout as Ba}from"rxjs/operators";var{logger:Da}=pe;import{getWsProvider as za}from"polkadot-api/ws-provider";import{withLogsRecorder as ja}from"polkadot-api/logs-provider";import{withLegacy as Ja}from"@polkadot-api/legacy-provider";import{getSmProvider as si}from"polkadot-api/sm-provider";import{log as me}from"@galacticcouncil/common";import{combineLatest as fi,concat as Si,defer as Ii,from as wi}from"rxjs";import{bufferCount as Ti,distinctUntilChanged as vi,debounceTime as xi,map as Bi,retry as Ai,startWith as Fi,switchMap as _i,tap as Ri,take as Ei,skip as ki,connect as Ci}from"rxjs/operators";var{logger:Di}=me;import{BehaviorSubject as Qi}from"rxjs";import{log as ge}from"@galacticcouncil/common";var an={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:nn}=ge;var{withTimeout:jn}=at;import{calculate_in_given_out as he,calculate_lrna_in_given_out as Pe,calculate_out_given_in as ye,calculate_out_given_lrna_in as fe,calculate_spot_price as Se,calculate_lrna_spot_price as Ie,calculate_shares as we,calculate_liquidity_out as Oe,calculate_liquidity_lrna_out as Te,verify_asset_cap as ve,calculate_liquidity_hub_in as xe,is_sell_allowed as Be,is_buy_allowed as Ae,is_add_liquidity_allowed as Fe,is_remove_liquidity_allowed as _e,recalculate_asset_fee as Re,recalculate_protocol_fee as Ee}from"@galacticcouncil/math-omnipool";import G from"big.js";var f=class{static calculateSpotPrice(t,e,s,a){return Se(t,e,s,a)}static calculateLrnaSpotPrice(t,e){return Ie(t,e)}static calculateInGivenOut(t,e,s,a,i,n,r,o,l,c){return he(t,e,s,a,i,n,r,o,l,c)}static calculateLrnaInGivenOut(t,e,s,a,i,n){return Pe(t,e,s,a,i,n)}static calculateOutGivenIn(t,e,s,a,i,n,r,o,l,c){return ye(t,e,s,a,i,n,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,s,a,i,n){return fe(t,e,s,a,i,n)}static calculateShares(t,e,s,a){return we(t,e,s,a)}static calculateLiquidityOut(t,e,s,a,i,n,r,o){return Oe(t,e,s,a,i,n,r,o)}static calculateLiquidityLRNAOut(t,e,s,a,i,n,r,o){return Te(t,e,s,a,i,n,r,o)}static calculateCapDifference(t,e,s,a){let i=G(e),n=G(t),r=G(a),o=G(s),l=G(10).pow(18),c=o.div(l);if(i.div(r).lt(c)){let b=c.times(r).minus(i).times(n),d=i.times(G(1).minus(c));return b.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,s,a){return xe(t,e,s,a)}static isSellAllowed(t){return Be(t)}static isBuyAllowed(t){return Ae(t)}static isAddLiquidityAllowed(t){return Fe(t)}static isRemoveLiquidityAllowed(t){return _e(t)}static recalculateAssetFee(t,e,s,a,i,n,r,o,l,c,m){return Re(t,e,s,a,i,n,r,o,l,c,m)}static recalculateProtocolFee(t,e,s,a,i,n,r,o,l,c,m){return Ee(t,e,s,a,i,n,r,o,l,c,m)}static verifyAssetCap(t,e,s,a){return ve(t,e,s,a)}};import{big as ke}from"@galacticcouncil/common";var{FeeUtils:R}=S,rt=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:a.hubReserves,hubReservesOut:i.hubReserves,sharesIn:a.shares,sharesOut:i.shares,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,tradeableIn:a.tradeable,tradeableOut:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),n=a===0n?0:T.calculateBuyFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return i>m&&r.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),n=T.calculateSellFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return i>m&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:n,errors:r}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let a=f.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.protocolFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,s){let a=f.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let a=f.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.protocolFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,s){let a=f.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=f.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=f.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=f.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=f.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,s){let a=e-s;if(a===0)return t;let i=ke.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as qr,Binary as Ce,CompatibilityLevel as Nr,Enum as Me}from"polkadot-api";import{toHex as Vr}from"@polkadot-api/utils";import{Subscription as Ur,distinctUntilChanged as $r,filter as Xr,finalize as Yr,map as zr,merge as Kr,tap as jr}from"rxjs";import{HYDRATION_SS58_PREFIX as Jr}from"@galacticcouncil/common";var{FeeUtils:oo}=S,lo=Ce.fromText("omnipool"),co=Me("Short");import{calculate_in_given_out as De,calculate_out_given_in as He,calculate_amplification as qe,calculate_add_one_asset as Ne,calculate_liquidity_out_one_asset as Ge,calculate_shares as Ve,calculate_shares_for_amount as We,calculate_spot_price_with_fee as Ue,pool_account_name as $e,recalculate_peg as Xe}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return $e(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,a,i){return qe(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i,n,r){return De(t,e,s,a,i,n,r)}static calculateAddOneAsset(t,e,s,a,i,n,r){return Ne(t,e,s,a,i,n,r)}static calculateSharesForAmount(t,e,s,a,i,n,r){return We(t,e,s,a,i,n,r)}static calculateOutGivenIn(t,e,s,a,i,n,r){return He(t,e,s,a,i,n,r)}static calculateLiquidityOutOneAsset(t,e,s,a,i,n,r){return Ge(t,e,s,a,i,n,r)}static calculateShares(t,e,s,a,i,n){return Ve(t,e,s,a,i,n)}static calculateSpotPriceWithFee(t,e,s,a,i,n,r,o){return Ue(t,e,s,a,i,n,r,o)}static recalculatePegs(t,e,s,a,i,n){let r=Xe(t,e,s,a,i,n);return JSON.parse(r)}};import{RUNTIME_DECIMALS as Ye,big as vt}from"@galacticcouncil/common";var{FeeUtils:V}=S,W=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:a.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),n=a===0n?0:T.calculateBuyFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),n=T.calculateSellFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:n,errors:r}}calculateIn(t,e,s){let a=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateAddOneAsset(t,e,s){let a=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateSharesForAmount(t,e,s){let a=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateInGivenOut(t,e,s){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,s):t.assetIn==this.id?this.calculateSharesForAmount(t,e,s):this.calculateIn(t,e,s)}spotPriceInGivenOut(t){let e=B.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,s){let a=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,s){let a=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateShares(t,e,s){let a=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,s):t.assetOut==this.id?this.calculateShares(t,e,s):this.calculateOut(t,e,s)}spotPriceOutGivenIn(t){let e=B.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:s,decimals:a})=>({asset_id:e,amount:s,decimals:a}));return JSON.stringify(t,K.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],K.jsonFormatter)}normalizeSpot(t,e,s,a,i){return e?t*vt.pow10(Ye-i):s?t/vt.pow10(i-a):t}};import{AccountId as Ho,CompatibilityLevel as qo}from"polkadot-api";import{toHex as Go}from"@polkadot-api/utils";import{blake2b as Wo}from"@noble/hashes/blake2b";import{Subscription as $o,distinctUntilChanged as Xo,map as Yo,merge as zo,tap as Ko}from"rxjs";import{HYDRATION_SS58_PREFIX as Qo,RUNTIME_DECIMALS as Jo}from"@galacticcouncil/common";var{FeeUtils:cl}=S;import{calculate_in_given_out as Ke,calculate_out_given_in as je,calculate_pool_trade_fee as Qe,get_spot_price as Je,calculate_liquidity_in as Ze,calculate_shares as ts,calculate_spot_price as es,calculate_spot_price_with_fee as ss,calculate_liquidity_out_asset_a as as,calculate_liquidity_out_asset_b as is}from"@galacticcouncil/math-xyk";var L=class{static getSpotPrice(t,e,s){return Je(t,e,s)}static calculateInGivenOut(t,e,s){return Ke(t,e,s)}static calculateOutGivenIn(t,e,s){return je(t,e,s)}static calculatePoolTradeFee(t,e,s){return Qe(t,e,s)}static calculateLiquidityIn(t,e,s){return Ze(t,e,s)}static calculateSpotPrice(t,e){return es(t,e)}static calculateSpotPriceWithFee(t,e,s,a){return ss(t,e,s,a)}static calculateShares(t,e,s){return ts(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,a){return as(t,e,s,a)}static calculateLiquidityOutAssetB(t,e,s,a){return is(t,e,s,a)}};import{big as ns}from"@galacticcouncil/common";var{FeeUtils:xt}=S,ot=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(a,s),n=xt.toPct(s.exchangeFee),r=a+i,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 r>c&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:a,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(a,s),n=xt.toPct(s.exchangeFee),r=a-i,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 r>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(t,e){let s=L.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=L.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=L.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=L.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let s=L.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}normalizeSpot(t,e,s){let a=e-s;if(a===0)return t;let i=ns.pow10(Math.abs(a));return a>0?t*i:t/i}};import{CompatibilityLevel as Ml}from"polkadot-api";import{Subscription as Dl}from"rxjs";import{big as Bt,RUNTIME_DECIMALS as At}from"@galacticcouncil/common";var lt=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=[];return a>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Bt.toBigInt(1,At)}spotPriceOutGivenIn(t){return Bt.toBigInt(1,At)}calculateTradeFee(t,e){return 0n}};import{AccountId as dc}from"polkadot-api";import{toHex as bc}from"@polkadot-api/utils";import{Subscription as Pc,filter as yc,map as fc}from"rxjs";import{decodeEventLog as Ic}from"viem";import{erc20 as os,HYDRATION_SS58_PREFIX as Oc}from"@galacticcouncil/common";var{ERC20:_c}=os;import{calculate_collateral_in_given_hollar_out as cs,calculate_collateral_out_given_hollar_in as us,calculate_hollar_in_given_collateral_out as ps,calculate_hollar_out_given_collateral_in as ms,calculate_imbalance as ds,calculate_max_price as gs,calculate_buyback_limit as bs,calculate_buyback_price_with_fee as hs}from"@galacticcouncil/math-hsm";var F=class{static calculateCollateralInGivenHollarOut(t,e,s){return cs(t,e,s)}static calculateCollateralOutGivenHollarIn(t,e,s){return us(t,e,s)}static calculateHollarOutGivenCollateralIn(t,e,s){return ms(t,e,s)}static calculateHollarInGivenCollateralOut(t,e,s){return ps(t,e,s)}static calculateImbalance(t,e,s){return ds(t,e,s)}static calculateBuybackLimit(t,e){return bs(t,e)}static calculateBuybackPriceWithFee(t,e,s){return hs(t,e,s)}static calculateMaxPrice(t,e){return gs(t,e)}};import{big as C,RUNTIME_DECIMALS as ct}from"@galacticcouncil/common";var{FeeUtils:U}=S,ut=class u extends W{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,s){let a=this.parsePair(t.assetOut,t.assetIn),i=super.calculateInGivenOut(a,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&s.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,i)>r&&s.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(t,e,s){return this.collateralBalance+t>this.maxInHolding&&s.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&s.push("FacilitatorCapacityExceeded"),s}validateTradeConstraints(t,e,s){let a=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,a):this.validateTradeHollarOut(e,s,a)}validateAndBuy(t,e){let s=this.calculateInGivenOut(t,e),a=this.validateTradeConstraints(t,s,e);return{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e){let s=this.calculateOutGivenIn(t,e),a=this.validateTradeConstraints(t,e,s);return{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateHollarInGivenCollateralOut(t,e){let s=super.calculateInGivenOut(t,e,{fee:this.fee}),a=F.calculateHollarInGivenCollateralOut(e.toString(),s.toString(),U.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),s=F.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),U.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let s=super.calculateOutGivenIn(t,e,{fee:this.fee}),a=F.calculateCollateralOutGivenHollarIn(e.toString(),s.toString(),U.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),s=F.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),U.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),s=F.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(s)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),s=F.calculateBuybackLimit(e.toString(),U.toRaw(this.buyBackRate).toString());return BigInt(s)}calculateBuyPrice(t,e,s){let a=F.calculateBuybackPriceWithFee(s.toString(),e.toString(),U.toRaw(this.buyBackFee).toString()),[i,n]=JSON.parse(a),r=C.pow10(t.decimalsIn+ct-t.decimalsOut);return BigInt(i)*r/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),s=F.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[a,i]=JSON.parse(s),n=C.pow10(ct-t.decimalsOut);return BigInt(a)*n/BigInt(i)}spotPriceInGivenOut(t){let e=C.toBigInt(1,t.decimalsOut),a=this.calculateInGivenOut(t,e)*C.pow10(ct-t.decimalsOut);return this.normalizeSpotPrice(a,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=C.toBigInt(1,t.decimalsIn),a=this.calculateOutGivenIn(t,e)*C.pow10(ct-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],s=this.tokens[t].decimals;return this.isDefaultPeg(e)?[C.toBigInt(1,18).toString(),C.toBigInt(1,s).toString()]:e}isDefaultPeg(t){let[e,s]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&s==="1"}normalizeSpotPrice(t,e,s){let a=e-s;if(a===0)return t;let i=C.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as lu,CompatibilityLevel as cu}from"polkadot-api";import{toHex as mu}from"@polkadot-api/utils";import{Subscription as bu,combineLatest as hu,filter as Pu,map as yu,pairwise as fu}from"rxjs";import{decodeEventLog as Iu}from"viem";import{h160 as ys,HYDRATION_SS58_PREFIX as Ou}from"@galacticcouncil/common";var{FeeUtils:_u}=S,{H160:Ru}=ys;var J=class{static get(t){switch(t.type){case"Aave":return lt.fromPool(t);case"XYK":return ot.fromPool(t);case"Omnipool":return rt.fromPool(t);case"LBP":return it.fromPool(t);case"Stableswap":return W.fromPool(t);case"HSM":return ut.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as Ss}from"@galacticcouncil/common";import{Subject as up,Subscription as pp,takeUntil as mp}from"rxjs";var pt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var{logger:Ap}=Ss;var Z=class{getProposals(t,e,s){let a=s.filter(p=>p.type==="XYK"),i=s.filter(p=>p.type!=="XYK"),n=new Set(i.map(p=>p.tokens).flat().map(p=>p.id)),r=n.has(t),o=n.has(e),l=new z,c=p=>{let h=mt(p),P=Object.keys(h),_=P.flatMap(x=>h[x]);return l.buildAndPopulateGraph(P,_)};if(!r&&!o){let p=a.filter(_=>_.tokens.find(x=>x.id===t)||_.tokens.find(x=>x.id===e)),h=c(p),P=l.findPaths(h,t,e);return this.parsePaths(P)}if(r&&o){let p=c(i),h=l.findPaths(p,t,e);return this.parsePaths(h)}let m=r?e:t,b=a.filter(p=>p.tokens.some(h=>h.id===m));if(b.length===0)return[];let d=[...i,...b],y=c(d),g=l.findPaths(y,t,e);return this.parsePaths(g)}parsePaths(t){let e=[];for(let s of t){let a=[];for(let i=0;i<s.length;i++){let n=s[i],r=s[i+1];if(r==null)break;a.push(this.toEdge(n,r))}e.push(a)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var tt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Z,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,s){return`${t}->${e}::${s.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:s=[]}=this.filter,a=new Set(e),i=new Set(s);return t.filter(n=>i.has(n.type)?!1:a.size>0?a.has(n.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let s=await this.getPools();return this.validateInput(t,e,s),this.getPaths(t,e,s)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(a=>a!==t).map(a=>this.getRoutes(a,t)))).filter(a=>a.length>0).map(([a])=>a[0].assetIn).sort()}validateInput(t,e,s){if(s.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let a=this.getAssets(s);if(!a.has(t))throw new Error(t+" is not supported asset");if(!a.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(a=>a.id)).flat().sort((s,a)=>s>a?1:-1);return new Set(e)}getPaths(t,e,s){let a=this.toPoolsMap(s);return this.getProposals(t,e,s).filter(n=>this.validPath(n,a)).map(n=>this.toHops(n,a))}getProposals(t,e,s){let a=this.buildRouteKey(t,e,s);if(this.routeProposals.has(a))return this.routeProposals.get(a);let i=this.routeSuggester.getProposals(t,e,s);return this.routeProposals.set(a,i),i}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,a)=>s&&a)}validEdge([t,e,s],a){return a.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,J.get(e)]))}toHops(t,e){return t.map(([s,a,i])=>{let n=e.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:a,assetOut:i}})}};import{big as w,RUNTIME_DECIMALS as $}from"@galacticcouncil/common";var _t=(e=>(e.Buy="Buy",e.Sell="Sell",e))(_t||{}),Rt=(s=>(s.Dca="Dca",s.TwapSell="TwapSell",s.TwapBuy="TwapBuy",s))(Rt||{}),Et=(s=>(s.OrderTooSmall="OrderTooSmall",s.OrderTooBig="OrderTooBig",s.OrderImpactTooBig="OrderImpactTooBig",s))(Et||{});var{FeeUtils:kt}=S,et=class extends tt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,s){let a=super.validateInput(t,e,s),i=super.getPaths(t,e,s);if(!i.length)throw new pt(t,e);return{paths:i,pools:s,poolsMap:a}}async withCtx(t,e,s){let a=await super.getPools(),i=this.buildCtxSync(t,e,a);return s(i)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,a)=>{let i=s[s.length-1].amountOut,n=a[a.length-1].amountOut;return i>n?-1:1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),a=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,a]}}getPoolFeeRange(t,e){let s=t.min?kt.toPct(t.min):void 0,a=t.max?kt.toPct(t.max):void 0;if(s&&a)return[s,Math.max(a,e)]}async getBestSell(t,e,s){return this.getSell(t,e,s)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:n})=>{let r;if(a)r=await this.toSellSwaps(s,a,n);else{let o=i.map(c=>this.toSellSwaps(s,c,n)),l=await Promise.all(o);r=this.findBestSellRoute(l)}return this.buildSell(n,r)})}async getSells(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let n=a.map(o=>this.toSellSwaps(s,o,i));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(i,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let s=e[0],a=e[e.length-1],i=this.isDirectTrade(e),n=this.getSellSpot(e),r=a.amountOut,o=i?a.calculatedOut:this.calculateDelta0Y(s.amountIn,e,t),l=o-r,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:T.calculateSellFee(o,r),b=A.mulSpot(s.amountIn,n,s.assetInDecimals,a.assetOutDecimals),d=T.calculateDiffToRef(o,b);return{type:"Sell",amountIn:s.amountIn,amountOut:a.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:w.toDecimal(s.amountIn,s.assetInDecimals),amountOut:w.toDecimal(a.amountOut,a.assetOutDecimals),spotPrice:w.toDecimal(n,$),tradeFee:w.toDecimal(l,a.assetOutDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(y=>y.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,s)=>e*s/10n**BigInt($))}calculateDelta0Y(t,e,s){let a=[];for(let i=0;i<e.length;i++){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i>0?l=a[i-1]:l=t;let c=r.calculateOutGivenIn(o,l);a.push(c)}return a[a.length-1]}async calculateMostLiquidRoute(t,e,s){let{paths:a,pools:i,poolsMap:n}=s,l=i.filter(g=>g.tokens.some(p=>p.id===t)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(p=>p.id===t)).map(g=>g.map(p=>p.balance).reduce((p,h)=>p+h)).sort((g,p)=>p<g?-1:1)[0],c=A.getFraction(l,.1),m=await Promise.all(a.map(g=>this.toSellSwaps(c,g,n))),d=this.findBestSellRoute(m).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut})),y=this.buildRouteKey(t,e,i);return this.mlr.set(y,d),d}async toSellSwaps(t,e,s){let a=[];for(let i=0;i<e.length;i++){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i>0?l=a[i-1].amountOut:l=typeof t=="string"?w.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r),{amountOut:m,calculatedOut:b,feePct:d,errors:y}=r.validateAndSell(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceOutGivenIn(o),h=A.mulSpot(l,p,o.decimalsIn,o.decimalsOut),P=T.calculateDiffToRef(b,h);a.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:b,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y,isSupply(){return r.type==="Aave"&&r.tokens[0].id===n.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:w.toDecimal(l,o.decimalsIn),amountOut:w.toDecimal(m,o.decimalsOut),calculatedOut:w.toDecimal(b,o.decimalsOut),spotPrice:w.toDecimal(p,$),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y}}})}return a}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async s=>{let a=this.buildRouteKey(t,e,s.pools),i=this.mlr.get(a);return i||this.calculateMostLiquidRoute(t,e,s)})}async getSpotPrice(t,e){return this.withCtx(t,e,async s=>{let{pools:a,poolsMap:i}=s,n=this.buildRouteKey(t,e,a),r=this.mlr.get(n);r||(r=await this.calculateMostLiquidRoute(t,e,s));let o=await this.toSellSwaps("1",r,i);return{amount:this.getSellSpot(o),decimals:$}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((s,a)=>{let i=s[0].amountIn,n=a[0].amountIn;return i>n?1:-1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}async getBestBuy(t,e,s){return this.getBuy(t,e,s)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:n})=>{let r;if(a)r=await this.toBuySwaps(s,a,n);else{let o=i.map(c=>this.toBuySwaps(s,c,n)),l=await Promise.all(o);r=this.findBestBuyRoute(l)}return this.buildBuy(n,r)})}async getBuys(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let n=a.map(o=>this.toBuySwaps(s,o,i));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(i,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let s=e[e.length-1],a=e[0],i=this.isDirectTrade(e),n=this.getBuySpot(e),r=a.amountIn,o=i?a.calculatedIn:this.calculateDelta0X(s.amountOut,e,t),l=r-o,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:T.calculateBuyFee(o,r),b=A.mulSpot(s.amountOut,n,s.assetOutDecimals,a.assetInDecimals),d;return o===0n?d=-100:d=T.calculateDiffToRef(b,o),{type:"Buy",amountOut:s.amountOut,amountIn:a.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:w.toDecimal(s.amountOut,s.assetOutDecimals),amountIn:w.toDecimal(a.amountIn,a.assetInDecimals),spotPrice:w.toDecimal(n,$),tradeFee:w.toDecimal(l,a.assetInDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0X(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i==e.length-1?l=t:l=a[0];let c=r.calculateInGivenOut(o,l);a.unshift(c)}return a[0]}async toBuySwaps(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i==e.length-1?l=typeof t=="string"?w.toBigInt(t,o.decimalsOut):t:l=a[0].amountIn;let c=await this.ctx.getPoolFees(o,r),{amountIn:m,calculatedIn:b,feePct:d,errors:y}=r.validateAndBuy(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceInGivenOut(o),h=A.mulSpot(l,p,o.decimalsOut,o.decimalsIn),P;b===0n?P=-100:P=T.calculateDiffToRef(h,b),a.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:m,calculatedIn:b,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y,isSupply(){return r.type==="Aave"&&r.tokens[0].id===n.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===n.assetIn},toHuman(){return{...n,amountOut:w.toDecimal(l,o.decimalsOut),amountIn:w.toDecimal(m,o.decimalsIn),calculatedIn:w.toDecimal(b,o.decimalsIn),spotPrice:w.toDecimal(p,$),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y}}})}return a}};import{big as O}from"@galacticcouncil/common";var Ct=6e3,Mt=1000000000000000n,st=6,bt=-5,ht=216e5,_m=3,Lt=.1,Dt=6;import{Enum as Ht}from"polkadot-api";var D=class{static build(t){return t.map(({assetIn:e,assetOut:s,pool:a,poolId:i})=>a==="Stableswap"?{pool:Ht("Stableswap",i),asset_in:e,asset_out:s}:{pool:Ht(a),asset_in:e,asset_out:s})}};var Pt=class{schedulerOptions;router;constructor(t,e={}){this.router=new et(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Mt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,s,a,i){let n=await this.router.getBestSell(t,e,s),{amountIn:r,swaps:o,priceImpactPct:l}=n,c=o[0],m=o[o.length-1],{assetInDecimals:b}=c,{assetOutDecimals:d}=m,y=Math.abs(l),g=await this.getMinimumOrderBudget(t,b),p=this.getOptimalTradeCount(y),h=this.getMaximumTradeCount(r,g,a),P=i||Math.min(p,h),_=Math.round(a/P),x=r/BigInt(P),v=await this.router.getBestSell(t,e,x),H=r<g,q=[];H&&q.push("OrderTooSmall");let M=v.amountOut*BigInt(P),Nt=this.toBlockPeriod(_),Gt=v.tradeFee*BigInt(P),Vt=D.build(o),yt={assetIn:t,assetOut:e,errors:q,maxTradeCount:h,tradeCount:P,tradeFee:Gt,tradeImpactPct:v.priceImpactPct,tradePeriod:Nt,tradeRoute:Vt,type:"Dca"};return{...yt,amountIn:r,amountOut:M,tradeAmountIn:v.amountIn,tradeAmountOut:v.amountOut,toHuman(){return{...yt,amountIn:O.toDecimal(r,b),amountOut:O.toDecimal(M,d),tradeAmountIn:O.toDecimal(v.amountIn,b),tradeAmountOut:O.toDecimal(v.amountOut,d)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let s=await this.router.getSpotPrice(0,t);if(s)return A.mulSpot(this.minOrderBudget,s.amount,12,e);let a=await this.router.getSpotPrice(t,0);if(a)return A.divSpot(this.minOrderBudget,a.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,s){let a=e*2n/10n;if(a===0n)return 0;let i=Number(t/a),n=Math.floor(s/this.blockTime),r=Math.max(0,Math.floor(n*(1-.1)));return Math.min(i,r)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,s,a){let i=await this.router.getBestSell(t,e,s),{swaps:n}=i,r=n[0],o=n[n.length-1],{assetInDecimals:l}=r,{assetOutDecimals:c}=o,m=await this.getMinimumOrderBudget(t,l),b=i.amountIn<m,d=[];b&&d.push("OrderTooSmall");let y=this.toBlockPeriod(a),g=D.build(n),p={assetIn:t,assetOut:e,errors:d,maxTradeCount:0,tradeCount:0,tradeFee:i.tradeFee,tradeImpactPct:i.priceImpactPct,tradePeriod:y,tradeRoute:g,type:"Dca"};return{...p,amountIn:0n,amountOut:0n,tradeAmountIn:i.amountIn,tradeAmountOut:i.amountOut,toHuman(){return{...p,amountIn:"0",amountOut:"0",tradeAmountIn:O.toDecimal(i.amountIn,l),tradeAmountOut:O.toDecimal(i.amountOut,c)}}}}async getTwapSellOrder(t,e,s){let a=await this.router.getBestSell(t,e,s),{amountIn:i,swaps:n,priceImpactPct:r}=a,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),y=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestSell(o.assetIn,l.assetOut,y)]),h=d===1,P=i<g,_=p.priceImpactPct<-5,x=[];P||h?x.push("OrderTooSmall"):_&&x.push("OrderImpactTooBig");let v=p.amountOut*BigInt(d),H=p.tradeFee*BigInt(d),q=D.build(n),M={assetIn:t,assetOut:e,errors:x,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:q,type:"TwapSell"};return{...M,amountIn:i,amountOut:v,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(i,c),amountOut:O.toDecimal(v,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(H,m)}}}}async getTwapBuyOrder(t,e,s){let a=await this.router.getBestBuy(t,e,s),{amountOut:i,swaps:n,priceImpactPct:r}=a,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),y=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestBuy(o.assetIn,l.assetOut,y)]),h=p.amountIn*BigInt(d),P=d===1,_=h<g,x=p.priceImpactPct<-5,v=[];_||P?v.push("OrderTooSmall"):x&&v.push("OrderImpactTooBig");let H=p.tradeFee*BigInt(d),q=D.build(n),M={assetIn:t,assetOut:e,errors:v,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:q,type:"TwapBuy"};return{...M,amountIn:h,amountOut:i,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(h,c),amountOut:O.toDecimal(i,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(H,c)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let a=216e5/(this.blockTime*6);return Math.round(a)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,s=Math.round(e);return Math.max(s,6)}};export{Lt as DCA_TIME_RESERVE,Ct as DEFAULT_BLOCK_TIME,Mt as DEFAULT_MIN_BUDGET,Dt as ORDER_MIN_BLOCK_PERIOD,tt as Router,st as TWAP_EXECUTION_INTERVAL,ht as TWAP_MAX_DURATION,bt as TWAP_MAX_PRICE_IMPACT,_m as TWAP_TX_MULTIPLIER,Et as TradeOrderError,Rt as TradeOrderType,D as TradeRouteBuilder,et as TradeRouter,Pt as TradeScheduler,_t as TradeType};
1
+ var Wt=Object.defineProperty;var X=(u,t)=>{for(var e in t)Wt(u,e,{get:t[e],enumerable:!0})};import Ut from"buffer";typeof window<"u"&&(window.Buffer=Ut.Buffer);var Y=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var $t=10,z=class{isNotVisited(t,e){let s=!0;return e.forEach(a=>{(a[0]===t[0]||a[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let a=[],i=new Y,n=[];for(n.push([e,""]),i.enqueue(n);i.size()>0;){let r=i.dequeue();if(!r||r.length>$t)continue;let o=r[r.length-1];(s===null||o[0]===s)&&a.push(r),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let m=[...r];m.push(c),i.enqueue(m)}})}return a}findShortestPaths(t,e,s){let a=[],i=new Y,n=[];n.push([e,""]),i.enqueue(n);let r=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===s){o.length<r?(r=o.length,a.length=0,a.push(o)):o.length===r&&a.push(o);continue}let c=t.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&i.enqueue([...o,m])}return a}buildAndPopulateGraph(t,e){let s=new Map;for(let a of t)s.set(parseInt(a),[]);for(let[a,i,n]of e)s.get(i)?.push([n,a]);return s}};function mt(u){let t={};for(let e of u){let s=e.tokens.length;for(let a=0;a<s;a++){t[e.tokens[a].id]||(t[e.tokens[a].id]=[]);for(let i=0;i<s;i++){if(a==i)continue;let n=[e.address,e.tokens[a].id,e.tokens[i].id];t[e.tokens[a].id].push(n)}}}return t}import{calculate_in_given_out as Xt,calculate_out_given_in as Yt,calculate_linear_weights as zt,calculate_pool_trade_fee as Kt,get_spot_price as jt}from"@galacticcouncil/math-lbp";var E=class{static getSpotPrice(t,e,s,a,i){return jt(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i){return Xt(t,e,s,a,i)}static calculateOutGivenIn(t,e,s,a,i){return Yt(t,e,s,a,i)}static calculateLinearWeights(t,e,s,a,i){return zt(t,e,s,a,i)}static calculatePoolTradeFee(t,e,s){return Kt(t,e,s)}};import{big as wt,RUNTIME_DECIMALS as Ot}from"@galacticcouncil/common";var at={};X(at,{withTimeout:()=>Qt});function Qt(u,t,e="timeout"){return new Promise((s,a)=>{let i=setTimeout(()=>a(new Error(e)),t);u.then(n=>{clearTimeout(i),s(n)},n=>{clearTimeout(i),a(n)})})}var A={};X(A,{divSpot:()=>Zt,getFraction:()=>te,mulScaled:()=>St,mulSpot:()=>Jt});import{RUNTIME_DECIMALS as ft}from"@galacticcouncil/common";function St(u,t,e,s,a){let i=e+s-a,n=u*t;return i>0?n/BigInt(10)**BigInt(i):i<0?n*BigInt(10)**BigInt(-i):n}function Jt(u,t,e,s){return St(u,t,e,ft,s)}function Zt(u,t,e,s){if(t===0n)return 0n;let a=BigInt(10)**BigInt(ft+s-e);return u*a/t}function te(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let s=BigInt(10)**BigInt(e),a=BigInt(Math.round(t*Number(s)));return u*a/(BigInt(100)*s)}var S={};X(S,{FeeUtils:()=>dt,shiftNeg:()=>ae});import se from"big.js";var dt=class u{static toPct(t){let[e,s]=t;return u.safeDivide(e*100,s)}static toRaw(t){let[e,s]=t;return u.safeDivide(e,s)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,s=12){let a=10**s;return Math.round(t*a/e)/a}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ae(u,t){let e=se(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var K={};X(K,{findNestedKey:()=>ie,findNestedObj:()=>ne,jsonFormatter:()=>re});var ie=(u,t)=>{let e=[];return JSON.stringify(u,(s,a)=>(a&&a[t]&&e.push(a),a)),e[0]},ne=(u,t,e)=>{let s;return JSON.stringify(u,(a,i)=>(i&&i[t]===e&&(s=i),i)),s},re=(u,t)=>typeof t=="bigint"?t.toString():t;var T={};X(T,{calculateBuyFee:()=>ue,calculateDiffToAvg:()=>oe,calculateDiffToRef:()=>le,calculateSellFee:()=>ce});import k from"big.js";function oe(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function le(u,t){if(t===0n)return 0;let e=k(u.toString()),s=k(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function ce(u,t){if(u===0n)return 0;let e=k(u.toString()),s=k(t.toString());return k(1).minus(s.div(e)).mul(100).round(2).toNumber()}function ue(u,t){if(u===0n)return 0;let e=k(u.toString());return k(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as Ys}from"@thi.ng/cache";var{FeeUtils:Tt}=S,it=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,weightIn:a.weight,weightOut:i.weight}}validateAndBuy(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&i.push("MaxOutRatioExceeded"),a===t.assetOut){let r=this.calculateTradeFee(e,s),o=Tt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:i}}else{let r=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return r>o&&i.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&i.push("MaxInRatioExceeded"),a===t.assetIn){let r=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return r>o&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:i}}else{let r=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(r,s),l=Tt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=r-o,m=t.balanceOut/this.maxOutRatio;return c>m&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let s=E.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=E.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=E.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),wt.toBigInt(1,Ot).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=E.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),wt.toBigInt(1,Ot).toString());return BigInt(e)}calculateTradeFee(t,e){let s=E.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as er}from"polkadot-api";import{Subscription as ar,distinctUntilChanged as ir,filter as nr}from"rxjs";import{memoize1 as pn}from"@thi.ng/memoize";import{TLRUCache as dn}from"@thi.ng/cache";import{ReplaySubject as Pn,Subscription as yn,combineLatest as fn,defer as Sn,from as In,interval as wn,merge as On,of as Tn,EMPTY as vn}from"rxjs";import{bufferCount as Bn,bufferTime as An,catchError as Fn,filter as _n,finalize as Rn,map as En,pairwise as kn,repeat as Cn,skip as Mn,share as Ln,startWith as Dn,switchMap as Hn,tap as qn,throttleTime as Nn}from"rxjs/operators";import{hydration as Va,hydrationNext as Wa}from"@galacticcouncil/descriptors";import{log as pe}from"@galacticcouncil/common";import{shareReplay as Ca,tap as Ma}from"rxjs";import{defer as ha,from as ba,of as Pa,timer as ya}from"rxjs";import{catchError as Sa,distinctUntilChanged as Ia,expand as wa,map as Oa,shareReplay as Ta,skip as va,switchMap as xa,timeout as Ba}from"rxjs/operators";var{logger:Da}=pe;import{getWsProvider as za}from"polkadot-api/ws-provider";import{withLogsRecorder as ja}from"polkadot-api/logs-provider";import{withLegacy as Ja}from"@polkadot-api/legacy-provider";import{getSmProvider as si}from"polkadot-api/sm-provider";import{log as me}from"@galacticcouncil/common";import{combineLatest as fi,concat as Si,defer as Ii,from as wi}from"rxjs";import{bufferCount as Ti,distinctUntilChanged as vi,debounceTime as xi,map as Bi,retry as Ai,startWith as Fi,switchMap as _i,tap as Ri,take as Ei,skip as ki,connect as Ci}from"rxjs/operators";var{logger:Di}=me;import{BehaviorSubject as Qi}from"rxjs";import{log as ge}from"@galacticcouncil/common";var an={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:nn}=ge;var{withTimeout:Qn}=at;import{calculate_in_given_out as be,calculate_lrna_in_given_out as Pe,calculate_out_given_in as ye,calculate_out_given_lrna_in as fe,calculate_spot_price as Se,calculate_lrna_spot_price as Ie,calculate_shares as we,calculate_liquidity_out as Oe,calculate_liquidity_lrna_out as Te,verify_asset_cap as ve,calculate_liquidity_hub_in as xe,is_sell_allowed as Be,is_buy_allowed as Ae,is_add_liquidity_allowed as Fe,is_remove_liquidity_allowed as _e,recalculate_asset_fee as Re,recalculate_protocol_fee as Ee}from"@galacticcouncil/math-omnipool";import G from"big.js";var f=class{static calculateSpotPrice(t,e,s,a){return Se(t,e,s,a)}static calculateLrnaSpotPrice(t,e){return Ie(t,e)}static calculateInGivenOut(t,e,s,a,i,n,r,o,l,c){return be(t,e,s,a,i,n,r,o,l,c)}static calculateLrnaInGivenOut(t,e,s,a,i,n){return Pe(t,e,s,a,i,n)}static calculateOutGivenIn(t,e,s,a,i,n,r,o,l,c){return ye(t,e,s,a,i,n,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,s,a,i,n){return fe(t,e,s,a,i,n)}static calculateShares(t,e,s,a){return we(t,e,s,a)}static calculateLiquidityOut(t,e,s,a,i,n,r,o){return Oe(t,e,s,a,i,n,r,o)}static calculateLiquidityLRNAOut(t,e,s,a,i,n,r,o){return Te(t,e,s,a,i,n,r,o)}static calculateCapDifference(t,e,s,a){let i=G(e),n=G(t),r=G(a),o=G(s),l=G(10).pow(18),c=o.div(l);if(i.div(r).lt(c)){let h=c.times(r).minus(i).times(n),d=i.times(G(1).minus(c));return h.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,s,a){return xe(t,e,s,a)}static isSellAllowed(t){return Be(t)}static isBuyAllowed(t){return Ae(t)}static isAddLiquidityAllowed(t){return Fe(t)}static isRemoveLiquidityAllowed(t){return _e(t)}static recalculateAssetFee(t,e,s,a,i,n,r,o,l,c,m){return Re(t,e,s,a,i,n,r,o,l,c,m)}static recalculateProtocolFee(t,e,s,a,i,n,r,o,l,c,m){return Ee(t,e,s,a,i,n,r,o,l,c,m)}static verifyAssetCap(t,e,s,a){return ve(t,e,s,a)}};import{big as ke}from"@galacticcouncil/common";var{FeeUtils:R}=S,rt=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:a.hubReserves,hubReservesOut:i.hubReserves,sharesIn:a.shares,sharesOut:i.shares,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,tradeableIn:a.tradeable,tradeableOut:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),n=a===0n?0:T.calculateBuyFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return i>m&&r.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),n=T.calculateSellFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return i>m&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:n,errors:r}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let a=f.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.protocolFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,s){let a=f.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let a=f.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.protocolFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,s){let a=f.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=f.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=f.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=f.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=f.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,s){let a=e-s;if(a===0)return t;let i=ke.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as Nr,Binary as Ce,CompatibilityLevel as Gr,Enum as Me}from"polkadot-api";import{toHex as Wr}from"@polkadot-api/utils";import{Subscription as $r,distinctUntilChanged as Xr,filter as Yr,finalize as zr,map as Kr,merge as jr,tap as Qr}from"rxjs";import{HYDRATION_SS58_PREFIX as Zr}from"@galacticcouncil/common";var{FeeUtils:lo}=S,co=Ce.fromText("omnipool"),uo=Me("Short");import{calculate_in_given_out as De,calculate_out_given_in as He,calculate_amplification as qe,calculate_add_one_asset as Ne,calculate_liquidity_out_one_asset as Ge,calculate_shares as Ve,calculate_shares_for_amount as We,calculate_spot_price_with_fee as Ue,pool_account_name as $e,recalculate_peg as Xe}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return $e(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,a,i){return qe(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i,n,r){return De(t,e,s,a,i,n,r)}static calculateAddOneAsset(t,e,s,a,i,n,r){return Ne(t,e,s,a,i,n,r)}static calculateSharesForAmount(t,e,s,a,i,n,r){return We(t,e,s,a,i,n,r)}static calculateOutGivenIn(t,e,s,a,i,n,r){return He(t,e,s,a,i,n,r)}static calculateLiquidityOutOneAsset(t,e,s,a,i,n,r){return Ge(t,e,s,a,i,n,r)}static calculateShares(t,e,s,a,i,n){return Ve(t,e,s,a,i,n)}static calculateSpotPriceWithFee(t,e,s,a,i,n,r,o){return Ue(t,e,s,a,i,n,r,o)}static recalculatePegs(t,e,s,a,i,n){let r=Xe(t,e,s,a,i,n);return JSON.parse(r)}};import{RUNTIME_DECIMALS as Ye,big as vt}from"@galacticcouncil/common";var{FeeUtils:V}=S,W=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:a.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),n=a===0n?0:T.calculateBuyFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),n=T.calculateSellFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:n,errors:r}}calculateIn(t,e,s){let a=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateAddOneAsset(t,e,s){let a=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateSharesForAmount(t,e,s){let a=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateInGivenOut(t,e,s){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,s):t.assetIn==this.id?this.calculateSharesForAmount(t,e,s):this.calculateIn(t,e,s)}spotPriceInGivenOut(t){let e=B.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,s){let a=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,s){let a=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateShares(t,e,s){let a=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,s):t.assetOut==this.id?this.calculateShares(t,e,s):this.calculateOut(t,e,s)}spotPriceOutGivenIn(t){let e=B.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:s,decimals:a})=>({asset_id:e,amount:s,decimals:a}));return JSON.stringify(t,K.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],K.jsonFormatter)}normalizeSpot(t,e,s,a,i){return e?t*vt.pow10(Ye-i):s?t/vt.pow10(i-a):t}};import{AccountId as qo,CompatibilityLevel as No}from"polkadot-api";import{toHex as Vo}from"@polkadot-api/utils";import{blake2b as Uo}from"@noble/hashes/blake2b";import{Subscription as Xo,distinctUntilChanged as Yo,map as zo,merge as Ko,tap as jo}from"rxjs";import{HYDRATION_SS58_PREFIX as Jo,RUNTIME_DECIMALS as Zo}from"@galacticcouncil/common";var{FeeUtils:ul}=S;import{calculate_in_given_out as Ke,calculate_out_given_in as je,calculate_pool_trade_fee as Qe,get_spot_price as Je,calculate_liquidity_in as Ze,calculate_shares as ts,calculate_spot_price as es,calculate_spot_price_with_fee as ss,calculate_liquidity_out_asset_a as as,calculate_liquidity_out_asset_b as is}from"@galacticcouncil/math-xyk";var L=class{static getSpotPrice(t,e,s){return Je(t,e,s)}static calculateInGivenOut(t,e,s){return Ke(t,e,s)}static calculateOutGivenIn(t,e,s){return je(t,e,s)}static calculatePoolTradeFee(t,e,s){return Qe(t,e,s)}static calculateLiquidityIn(t,e,s){return Ze(t,e,s)}static calculateSpotPrice(t,e){return es(t,e)}static calculateSpotPriceWithFee(t,e,s,a){return ss(t,e,s,a)}static calculateShares(t,e,s){return ts(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,a){return as(t,e,s,a)}static calculateLiquidityOutAssetB(t,e,s,a){return is(t,e,s,a)}};import{big as ns}from"@galacticcouncil/common";var{FeeUtils:xt}=S,ot=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(a,s),n=xt.toPct(s.exchangeFee),r=a+i,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 r>c&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:a,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(a,s),n=xt.toPct(s.exchangeFee),r=a-i,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 r>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(t,e){let s=L.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=L.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=L.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=L.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let s=L.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}normalizeSpot(t,e,s){let a=e-s;if(a===0)return t;let i=ns.pow10(Math.abs(a));return a>0?t*i:t/i}};import{CompatibilityLevel as Ll}from"polkadot-api";import{Subscription as Hl}from"rxjs";import{big as Bt,RUNTIME_DECIMALS as At}from"@galacticcouncil/common";var lt=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 s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=[];return a>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Bt.toBigInt(1,At)}spotPriceOutGivenIn(t){return Bt.toBigInt(1,At)}calculateTradeFee(t,e){return 0n}};import{AccountId as gc}from"polkadot-api";import{toHex as bc}from"@polkadot-api/utils";import{Subscription as yc,filter as fc,map as Sc}from"rxjs";import{decodeEventLog as wc}from"viem";import{erc20 as os,HYDRATION_SS58_PREFIX as Tc}from"@galacticcouncil/common";var{ERC20:Rc}=os;import{calculate_collateral_in_given_hollar_out as cs,calculate_collateral_out_given_hollar_in as us,calculate_hollar_in_given_collateral_out as ps,calculate_hollar_out_given_collateral_in as ms,calculate_imbalance as ds,calculate_max_price as gs,calculate_buyback_limit as hs,calculate_buyback_price_with_fee as bs}from"@galacticcouncil/math-hsm";var F=class{static calculateCollateralInGivenHollarOut(t,e,s){return cs(t,e,s)}static calculateCollateralOutGivenHollarIn(t,e,s){return us(t,e,s)}static calculateHollarOutGivenCollateralIn(t,e,s){return ms(t,e,s)}static calculateHollarInGivenCollateralOut(t,e,s){return ps(t,e,s)}static calculateImbalance(t,e,s){return ds(t,e,s)}static calculateBuybackLimit(t,e){return hs(t,e)}static calculateBuybackPriceWithFee(t,e,s){return bs(t,e,s)}static calculateMaxPrice(t,e){return gs(t,e)}};import{big as C,RUNTIME_DECIMALS as ct}from"@galacticcouncil/common";var{FeeUtils:U}=S,ut=class u extends W{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,s){let a=this.parsePair(t.assetOut,t.assetIn),i=super.calculateInGivenOut(a,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&s.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,i)>r&&s.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(t,e,s){return this.collateralBalance+t>this.maxInHolding&&s.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&s.push("FacilitatorCapacityExceeded"),s}validateTradeConstraints(t,e,s){let a=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,a):this.validateTradeHollarOut(e,s,a)}validateAndBuy(t,e){let s=this.calculateInGivenOut(t,e),a=this.validateTradeConstraints(t,s,e);return{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e){let s=this.calculateOutGivenIn(t,e),a=this.validateTradeConstraints(t,e,s);return{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateHollarInGivenCollateralOut(t,e){let s=super.calculateInGivenOut(t,e,{fee:this.fee}),a=F.calculateHollarInGivenCollateralOut(e.toString(),s.toString(),U.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),s=F.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),U.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let s=super.calculateOutGivenIn(t,e,{fee:this.fee}),a=F.calculateCollateralOutGivenHollarIn(e.toString(),s.toString(),U.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),s=F.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),U.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),s=F.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(s)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),s=F.calculateBuybackLimit(e.toString(),U.toRaw(this.buyBackRate).toString());return BigInt(s)}calculateBuyPrice(t,e,s){let a=F.calculateBuybackPriceWithFee(s.toString(),e.toString(),U.toRaw(this.buyBackFee).toString()),[i,n]=JSON.parse(a),r=C.pow10(t.decimalsIn+ct-t.decimalsOut);return BigInt(i)*r/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),s=F.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[a,i]=JSON.parse(s),n=C.pow10(ct-t.decimalsOut);return BigInt(a)*n/BigInt(i)}spotPriceInGivenOut(t){let e=C.toBigInt(1,t.decimalsOut),a=this.calculateInGivenOut(t,e)*C.pow10(ct-t.decimalsOut);return this.normalizeSpotPrice(a,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=C.toBigInt(1,t.decimalsIn),a=this.calculateOutGivenIn(t,e)*C.pow10(ct-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],s=this.tokens[t].decimals;return this.isDefaultPeg(e)?[C.toBigInt(1,18).toString(),C.toBigInt(1,s).toString()]:e}isDefaultPeg(t){let[e,s]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&s==="1"}normalizeSpotPrice(t,e,s){let a=e-s;if(a===0)return t;let i=C.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as cu,CompatibilityLevel as uu}from"polkadot-api";import{toHex as du}from"@polkadot-api/utils";import{Subscription as bu,combineLatest as Pu,filter as yu,map as fu,pairwise as Su}from"rxjs";import{decodeEventLog as wu}from"viem";import{h160 as ys,HYDRATION_SS58_PREFIX as Tu}from"@galacticcouncil/common";var{FeeUtils:Ru}=S,{H160:Eu}=ys;var J=class{static get(t){switch(t.type){case"Aave":return lt.fromPool(t);case"XYK":return ot.fromPool(t);case"Omnipool":return rt.fromPool(t);case"LBP":return it.fromPool(t);case"Stableswap":return W.fromPool(t);case"HSM":return ut.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as Ss}from"@galacticcouncil/common";import{Subject as pp,Subscription as mp,takeUntil as dp}from"rxjs";var pt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var{logger:Fp}=Ss;var Z=class{getProposals(t,e,s){let a=s.filter(p=>p.type==="XYK"),i=s.filter(p=>p.type!=="XYK"),n=new Set(i.map(p=>p.tokens).flat().map(p=>p.id)),r=n.has(t),o=n.has(e),l=new z,c=p=>{let b=mt(p),P=Object.keys(b),_=P.flatMap(x=>b[x]);return l.buildAndPopulateGraph(P,_)};if(!r&&!o){let p=a.filter(_=>_.tokens.find(x=>x.id===t)||_.tokens.find(x=>x.id===e)),b=c(p),P=l.findPaths(b,t,e);return this.parsePaths(P)}if(r&&o){let p=c(i),b=l.findPaths(p,t,e);return this.parsePaths(b)}let m=r?e:t,h=a.filter(p=>p.tokens.some(b=>b.id===m));if(h.length===0)return[];let d=[...i,...h],y=c(d),g=l.findPaths(y,t,e);return this.parsePaths(g)}parsePaths(t){let e=[];for(let s of t){let a=[];for(let i=0;i<s.length;i++){let n=s[i],r=s[i+1];if(r==null)break;a.push(this.toEdge(n,r))}e.push(a)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var tt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Z,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,s){return`${t}->${e}::${s.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:s=[]}=this.filter,a=new Set(e),i=new Set(s);return t.filter(n=>i.has(n.type)?!1:a.size>0?a.has(n.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let s=await this.getPools();return this.validateInput(t,e,s),this.getPaths(t,e,s)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(a=>a!==t).map(a=>this.getRoutes(a,t)))).filter(a=>a.length>0).map(([a])=>a[0].assetIn).sort()}validateInput(t,e,s){if(s.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let a=this.getAssets(s);if(!a.has(t))throw new Error(t+" is not supported asset");if(!a.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(a=>a.id)).flat().sort((s,a)=>s>a?1:-1);return new Set(e)}getPaths(t,e,s){let a=this.toPoolsMap(s);return this.getProposals(t,e,s).filter(n=>this.validPath(n,a)).map(n=>this.toHops(n,a))}getProposals(t,e,s){let a=this.buildRouteKey(t,e,s);if(this.routeProposals.has(a))return this.routeProposals.get(a);let i=this.routeSuggester.getProposals(t,e,s);return this.routeProposals.set(a,i),i}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,a)=>s&&a)}validEdge([t,e,s],a){return a.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,J.get(e)]))}toHops(t,e){return t.map(([s,a,i])=>{let n=e.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:a,assetOut:i}})}};import{big as w,RUNTIME_DECIMALS as $}from"@galacticcouncil/common";var _t=(e=>(e.Buy="Buy",e.Sell="Sell",e))(_t||{}),Rt=(s=>(s.Dca="Dca",s.TwapSell="TwapSell",s.TwapBuy="TwapBuy",s))(Rt||{}),Et=(s=>(s.OrderTooSmall="OrderTooSmall",s.OrderTooBig="OrderTooBig",s.OrderImpactTooBig="OrderImpactTooBig",s))(Et||{});var{FeeUtils:kt}=S,et=class extends tt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,s){let a=super.validateInput(t,e,s),i=super.getPaths(t,e,s);if(!i.length)throw new pt(t,e);return{paths:i,pools:s,poolsMap:a}}async withCtx(t,e,s){let a=await super.getPools(),i=this.buildCtxSync(t,e,a);return s(i)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,a)=>{let i=s[s.length-1].amountOut,n=a[a.length-1].amountOut;return i>n?-1:1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),a=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,a]}}getPoolFeeRange(t,e){let s=t.min?kt.toPct(t.min):void 0,a=t.max?kt.toPct(t.max):void 0;if(s&&a)return[s,Math.max(a,e)]}async getBestSell(t,e,s){return this.getSell(t,e,s)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:n})=>{let r;if(a)r=await this.toSellSwaps(s,a,n);else{let o=i.map(c=>this.toSellSwaps(s,c,n)),l=await Promise.all(o);r=this.findBestSellRoute(l)}return this.buildSell(n,r)})}async getSells(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let n=a.map(o=>this.toSellSwaps(s,o,i));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(i,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let s=e[0],a=e[e.length-1],i=this.isDirectTrade(e),n=this.getSellSpot(e),r=a.amountOut,o=i?a.calculatedOut:this.calculateDelta0Y(s.amountIn,e,t),l=o-r,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:T.calculateSellFee(o,r),h=A.mulSpot(s.amountIn,n,s.assetInDecimals,a.assetOutDecimals),d=T.calculateDiffToRef(o,h);return{type:"Sell",amountIn:s.amountIn,amountOut:a.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:w.toDecimal(s.amountIn,s.assetInDecimals),amountOut:w.toDecimal(a.amountOut,a.assetOutDecimals),spotPrice:w.toDecimal(n,$),tradeFee:w.toDecimal(l,a.assetOutDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(y=>y.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,s)=>e*s/10n**BigInt($))}calculateDelta0Y(t,e,s){let a=[];for(let i=0;i<e.length;i++){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i>0?l=a[i-1]:l=t;let c=r.calculateOutGivenIn(o,l);a.push(c)}return a[a.length-1]}async calculateMostLiquidRoute(t,e,s){let{paths:a,pools:i,poolsMap:n}=s,l=i.filter(g=>g.tokens.some(p=>p.id===t)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(p=>p.id===t)).map(g=>g.map(p=>p.balance).reduce((p,b)=>p+b)).sort((g,p)=>p<g?-1:1)[0],c=A.getFraction(l,.1),m=await Promise.all(a.map(g=>this.toSellSwaps(c,g,n))),d=this.findBestSellRoute(m).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut})),y=this.buildRouteKey(t,e,i);return this.mlr.set(y,d),d}async toSellSwaps(t,e,s){let a=[];for(let i=0;i<e.length;i++){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i>0?l=a[i-1].amountOut:l=typeof t=="string"?w.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r),{amountOut:m,calculatedOut:h,feePct:d,errors:y}=r.validateAndSell(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceOutGivenIn(o),b=A.mulSpot(l,p,o.decimalsIn,o.decimalsOut),P=T.calculateDiffToRef(h,b);a.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:h,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y,isSupply(){return r.type==="Aave"&&r.tokens[0].id===n.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:w.toDecimal(l,o.decimalsIn),amountOut:w.toDecimal(m,o.decimalsOut),calculatedOut:w.toDecimal(h,o.decimalsOut),spotPrice:w.toDecimal(p,$),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y}}})}return a}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async s=>{let a=this.buildRouteKey(t,e,s.pools),i=this.mlr.get(a);return i||this.calculateMostLiquidRoute(t,e,s)})}async getSpotPrice(t,e){return this.withCtx(t,e,async s=>{let{pools:a,poolsMap:i}=s,n=this.buildRouteKey(t,e,a),r=this.mlr.get(n);r||(r=await this.calculateMostLiquidRoute(t,e,s));let o=await this.toSellSwaps("1",r,i);return{amount:this.getSellSpot(o),decimals:$}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((s,a)=>{let i=s[0].amountIn,n=a[0].amountIn;return i>n?1:-1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}async getBestBuy(t,e,s){return this.getBuy(t,e,s)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:n})=>{let r;if(a)r=await this.toBuySwaps(s,a,n);else{let o=i.map(c=>this.toBuySwaps(s,c,n)),l=await Promise.all(o);r=this.findBestBuyRoute(l)}return this.buildBuy(n,r)})}async getBuys(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let n=a.map(o=>this.toBuySwaps(s,o,i));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(i,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let s=e[e.length-1],a=e[0],i=this.isDirectTrade(e),n=this.getBuySpot(e),r=a.amountIn,o=i?a.calculatedIn:this.calculateDelta0X(s.amountOut,e,t),l=r-o,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:T.calculateBuyFee(o,r),h=A.mulSpot(s.amountOut,n,s.assetOutDecimals,a.assetInDecimals),d;return o===0n?d=-100:d=T.calculateDiffToRef(h,o),{type:"Buy",amountOut:s.amountOut,amountIn:a.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:w.toDecimal(s.amountOut,s.assetOutDecimals),amountIn:w.toDecimal(a.amountIn,a.assetInDecimals),spotPrice:w.toDecimal(n,$),tradeFee:w.toDecimal(l,a.assetInDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0X(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i==e.length-1?l=t:l=a[0];let c=r.calculateInGivenOut(o,l);a.unshift(c)}return a[0]}async toBuySwaps(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i==e.length-1?l=typeof t=="string"?w.toBigInt(t,o.decimalsOut):t:l=a[0].amountIn;let c=await this.ctx.getPoolFees(o,r),{amountIn:m,calculatedIn:h,feePct:d,errors:y}=r.validateAndBuy(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceInGivenOut(o),b=A.mulSpot(l,p,o.decimalsOut,o.decimalsIn),P;h===0n?P=-100:P=T.calculateDiffToRef(b,h),a.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:m,calculatedIn:h,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y,isSupply(){return r.type==="Aave"&&r.tokens[0].id===n.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===n.assetIn},toHuman(){return{...n,amountOut:w.toDecimal(l,o.decimalsOut),amountIn:w.toDecimal(m,o.decimalsIn),calculatedIn:w.toDecimal(h,o.decimalsIn),spotPrice:w.toDecimal(p,$),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y}}})}return a}};import{big as O}from"@galacticcouncil/common";var Ct=6e3,Mt=1000000000000000n,st=6,ht=-5,bt=216e5,Rm=3,Lt=.1,Dt=6;import{Enum as Ht}from"polkadot-api";var D=class{static build(t){return t.map(({assetIn:e,assetOut:s,pool:a,poolId:i})=>a==="Stableswap"?{pool:Ht("Stableswap",i),asset_in:e,asset_out:s}:{pool:Ht(a),asset_in:e,asset_out:s})}};var Pt=class{schedulerOptions;router;constructor(t,e={}){this.router=new et(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Mt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,s,a,i){let n=await this.router.getBestSell(t,e,s),{amountIn:r,swaps:o,priceImpactPct:l}=n,c=o[0],m=o[o.length-1],{assetInDecimals:h}=c,{assetOutDecimals:d}=m,y=Math.abs(l),g=await this.getMinimumOrderBudget(t,h),p=this.getOptimalTradeCount(y),b=this.getMaximumTradeCount(r,g,a),P=i||Math.min(p,b),_=Math.round(a/P),x=r/BigInt(P),v=await this.router.getBestSell(t,e,x),H=r<g,q=[];H&&q.push("OrderTooSmall");let M=v.amountOut*BigInt(P),Nt=this.toBlockPeriod(_),Gt=v.tradeFee*BigInt(P),Vt=D.build(o),yt={assetIn:t,assetOut:e,errors:q,maxTradeCount:b,tradeCount:P,tradeFee:Gt,tradeImpactPct:v.priceImpactPct,tradePeriod:Nt,tradeRoute:Vt,type:"Dca"};return{...yt,amountIn:r,amountOut:M,tradeAmountIn:v.amountIn,tradeAmountOut:v.amountOut,toHuman(){return{...yt,amountIn:O.toDecimal(r,h),amountOut:O.toDecimal(M,d),tradeAmountIn:O.toDecimal(v.amountIn,h),tradeAmountOut:O.toDecimal(v.amountOut,d)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let s=await this.router.getSpotPrice(0,t);if(s)return A.mulSpot(this.minOrderBudget,s.amount,12,e);let a=await this.router.getSpotPrice(t,0);if(a)return A.divSpot(this.minOrderBudget,a.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,s){let a=e*2n/10n;if(a===0n)return 0;let i=Number(t/a),n=Math.floor(s/this.blockTime),r=Math.max(0,Math.floor(n*(1-.1)));return Math.min(i,r)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,s,a){let i=await this.router.getBestSell(t,e,s),{swaps:n}=i,r=n[0],o=n[n.length-1],{assetInDecimals:l}=r,{assetOutDecimals:c}=o,m=await this.getMinimumOrderBudget(t,l),h=i.amountIn<m,d=[];h&&d.push("OrderTooSmall");let y=this.toBlockPeriod(a),g=D.build(n),p={assetIn:t,assetOut:e,errors:d,maxTradeCount:0,tradeCount:0,tradeFee:i.tradeFee,tradeImpactPct:i.priceImpactPct,tradePeriod:y,tradeRoute:g,type:"Dca"};return{...p,amountIn:0n,amountOut:0n,tradeAmountIn:i.amountIn,tradeAmountOut:i.amountOut,toHuman(){return{...p,amountIn:"0",amountOut:"0",tradeAmountIn:O.toDecimal(i.amountIn,l),tradeAmountOut:O.toDecimal(i.amountOut,c)}}}}async getTwapSellOrder(t,e,s){let a=await this.router.getBestSell(t,e,s),{amountIn:i,swaps:n,priceImpactPct:r}=a,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,h=Math.abs(r),d=this.getTwapTradeCount(h),y=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestSell(o.assetIn,l.assetOut,y)]),b=d===1,P=i<g,_=p.priceImpactPct<-5,x=[];P||b?x.push("OrderTooSmall"):_&&x.push("OrderImpactTooBig");let v=p.amountOut*BigInt(d),H=p.tradeFee*BigInt(d),q=D.build(n),M={assetIn:t,assetOut:e,errors:x,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:q,type:"TwapSell"};return{...M,amountIn:i,amountOut:v,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(i,c),amountOut:O.toDecimal(v,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(H,m)}}}}async getTwapBuyOrder(t,e,s){let a=await this.router.getBestBuy(t,e,s),{amountOut:i,swaps:n,priceImpactPct:r}=a,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,h=Math.abs(r),d=this.getTwapTradeCount(h),y=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestBuy(o.assetIn,l.assetOut,y)]),b=p.amountIn*BigInt(d),P=d===1,_=b<g,x=p.priceImpactPct<-5,v=[];_||P?v.push("OrderTooSmall"):x&&v.push("OrderImpactTooBig");let H=p.tradeFee*BigInt(d),q=D.build(n),M={assetIn:t,assetOut:e,errors:v,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:q,type:"TwapBuy"};return{...M,amountIn:b,amountOut:i,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(b,c),amountOut:O.toDecimal(i,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(H,c)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let a=216e5/(this.blockTime*6);return Math.round(a)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,s=Math.round(e);return Math.max(s,6)}};export{Lt as DCA_TIME_RESERVE,Ct as DEFAULT_BLOCK_TIME,Mt as DEFAULT_MIN_BUDGET,Dt as ORDER_MIN_BLOCK_PERIOD,tt as Router,st as TWAP_EXECUTION_INTERVAL,bt as TWAP_MAX_DURATION,ht as TWAP_MAX_PRICE_IMPACT,Rm as TWAP_TX_MULTIPLIER,Et as TradeOrderError,Rt as TradeOrderType,D as TradeRouteBuilder,et as TradeRouter,Pt as TradeScheduler,_t as TradeType};
@@ -1 +1 @@
1
- "use strict";var ce=Object.create;var Q=Object.defineProperty;var ue=Object.getOwnPropertyDescriptor;var pe=Object.getOwnPropertyNames;var me=Object.getPrototypeOf,de=Object.prototype.hasOwnProperty;var J=(o,t)=>{for(var e in t)Q(o,e,{get:t[e],enumerable:!0})},At=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of pe(t))!de.call(o,s)&&s!==e&&Q(o,s,{get:()=>t[s],enumerable:!(a=ue(t,s))||a.enumerable});return o};var Z=(o,t,e)=>(e=o!=null?ce(me(o)):{},At(t||!o||!o.__esModule?Q(e,"default",{value:o,enumerable:!0}):e,o)),ge=o=>At(Q({},"__esModule",{value:!0}),o);var pa={};J(pa,{TxBuilderFactory:()=>mt});module.exports=ge(pa);var $=require("@galacticcouncil/math-lbp");var Et=require("@galacticcouncil/common");var tt={};J(tt,{withTimeout:()=>he});function he(o,t,e="timeout"){return new Promise((a,s)=>{let n=setTimeout(()=>s(new Error(e)),t);o.then(i=>{clearTimeout(n),a(i)},i=>{clearTimeout(n),s(i)})})}var w={};J(w,{divSpot:()=>ye,getFraction:()=>Pe,mulScaled:()=>Bt,mulSpot:()=>be});var gt=require("@galacticcouncil/common");function Bt(o,t,e,a,s){let n=e+a-s,i=o*t;return n>0?i/BigInt(10)**BigInt(n):n<0?i*BigInt(10)**BigInt(-n):i}function be(o,t,e,a){return Bt(o,t,e,gt.RUNTIME_DECIMALS,a)}function ye(o,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(gt.RUNTIME_DECIMALS+a-e);return o*s/t}function Pe(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(a)));return o*s/(BigInt(100)*a)}var m={};J(m,{FeeUtils:()=>ht,shiftNeg:()=>Te});var Rt=Z(require("big.js"));var ht=class o{static toPct(t){let[e,a]=t;return o.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return o.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let s=10**a;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Te(o,t){let e=(0,Rt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Se=Z(require("big.js"));var{FeeUtils:Ha}=m;var _e=require("polkadot-api"),bt=require("rxjs");var k=require("rxjs"),f=require("rxjs/operators");var nt=require("@galacticcouncil/descriptors");var kt=require("@galacticcouncil/common"),st=require("rxjs");var F=require("rxjs"),h=require("rxjs/operators");function Ct(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,h.timeout)({first:e}),(0,h.map)(()=>"online"),(0,h.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,h.expand)(n=>(0,F.timer)(n.delayMs).pipe((0,h.switchMap)(a),(0,h.map)(i=>({state:i,delayMs:t})))),(0,h.skip)(1),(0,h.map)(n=>n.state),(0,h.distinctUntilChanged)(),(0,h.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:we}=kt.log,at=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Ct(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,st.tap)({error:a=>we.error(t,a)}),(0,st.shareReplay)({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(nt.hydration),this.apiNext=this.client.getTypedApi(nt.hydrationNext),this.watcher=at.getInstance(this.client)}};var xe=require("polkadot-api/ws-provider"),Ie=require("polkadot-api/logs-provider"),Oe=require("@polkadot-api/legacy-provider");var Ae=require("polkadot-api/sm-provider");var Dt=require("@galacticcouncil/common"),S=require("rxjs"),c=require("rxjs/operators");var{logger:q}=Dt.log,N=class extends O{erc20Ids=null;constructor(t){super(t)}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:a}=await e.getValue(t,{at:"best"});return this.getBreakdown(a)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,S.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,S.combineLatest)([e,a,s]).pipe((0,c.connect)(n=>(0,S.concat)(n.pipe((0,c.take)(1)),n.pipe((0,c.skip)(1),(0,c.debounceTime)(250)))))}).pipe((0,c.map)(e=>e.flat()),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([e,a],s)=>s===0?a:this.getDeltas(e,a))).pipe((0,c.tap)({subscribe:()=>q.debug("balance: subscribe",t),error:e=>q.error("balance",e)}),(0,c.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,S.defer)(()=>e.watchValue(t,"best")).pipe((0,c.map)(a=>({id:0,balance:this.getBreakdown(a.data)})),(0,c.tap)({error:a=>q.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,S.defer)(()=>a.watchValue(t,e,"best")).pipe((0,c.map)(s=>({id:e,balance:this.getBreakdown(s)})),(0,c.tap)({error:s=>q.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,S.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,c.distinctUntilChanged)((a,s)=>!s.deltas),(0,c.map)(({deltas:a})=>{let s=[];return a?.deleted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),(0,c.tap)({error:a=>q.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,u])=>({id:r,balance:u}));return(0,S.defer)(()=>(0,S.from)(e?Promise.resolve(e):a()).pipe((0,c.switchMap)(n=>this.watcher.bestBlock$.pipe((0,c.switchMap)(()=>(0,S.from)(s(n))))),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([n,i],r)=>r===0?i.filter(u=>u.balance.total>0n):this.getDeltas(n,i)),(0,c.distinctUntilChanged)((n,i)=>i.length===0),(0,c.tap)({error:n=>q.error("balance(erc20)",n)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(n,i)=>n!==void 0&&i!==void 0&&n.transferable===i.transferable&&n.total===i.total,s=t.reduce((n,i)=>(n.set(i.id,i.balance),n),new Map);return e.filter(n=>!a(n.balance,s.get(n.id)))}};var Be=require("rxjs");var Mt=require("@galacticcouncil/common");var Ps={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:fs}=Mt.log;var{withTimeout:Ds}=tt;var y=require("@galacticcouncil/math-omnipool"),Fe=Z(require("big.js"));var Ee=require("@galacticcouncil/common");var{FeeUtils:on}=m;var G=require("polkadot-api"),Ce=require("@polkadot-api/utils"),H=require("rxjs"),ke=require("@galacticcouncil/common");var{FeeUtils:fn}=m,Tn=G.Binary.fromText("omnipool"),Sn=(0,G.Enum)("Short");var A=require("@galacticcouncil/math-stableswap");var Ht=require("@galacticcouncil/common");var{FeeUtils:Gn}=m;var qt=require("polkadot-api"),He=require("@polkadot-api/utils"),qe=require("@noble/hashes/blake2b"),K=require("rxjs"),Nt=require("@galacticcouncil/common");var{FeeUtils:Zn}=m;var B=require("@galacticcouncil/math-xyk");var Ge=require("@galacticcouncil/common");var{FeeUtils:Pi}=m;var Ue=require("polkadot-api"),Ve=require("rxjs");var Gt=require("@galacticcouncil/common");var $e=require("polkadot-api"),Xe=require("@polkadot-api/utils"),yt=require("rxjs"),Ye=require("viem"),Pt=require("@galacticcouncil/common");var{ERC20:Ki}=Pt.erc20;var D=require("@galacticcouncil/math-hsm");var Ut=require("@galacticcouncil/common");var{FeeUtils:pr}=m;var Wt=require("polkadot-api"),Qe=require("@polkadot-api/utils"),j=require("rxjs"),Je=require("viem"),ft=require("@galacticcouncil/common");var{FeeUtils:Ar}=m,{H160:Br}=ft.h160;var $t=require("@galacticcouncil/common"),Tt=require("rxjs");var{logger:vo}=$t.log;var Xt=require("@galacticcouncil/common");var{FeeUtils:bl}=m;var la=require("@galacticcouncil/common");var St=require("polkadot-api");var M=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:(0,St.Enum)("Stableswap",n),asset_in:e,asset_out:a}:{pool:(0,St.Enum)(s),asset_in:e,asset_out:a})}};var Ot=require("polkadot-api");var Yt=[{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 vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var zt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",wt="0x112b087b60C1a166130d59266363C45F8aa99db0",xt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Kt=1000000n;var ec=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var it=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:wt,args:[xt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:vt,address:wt,args:[xt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:Yt,address:zt,args:[t],functionName:"getUserAccountData"})}};var g=Z(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:U}=v.erc20,{H160:It}=v.h160,ca=1.01,ua=31536000n,jt=4,rt=-1,ot=10n**27n,lt=class{client;constructor(t){this.client=new it(t)}async getSummary(t){let e=It.fromAny(t),[a,s,n,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[u,p]=s,[l,b,P,E,x,I]=n,_=v.big.toDecimal(I,18),C=[];for(let R of u){let L=R.underlyingAsset.toLowerCase(),T=r.find(({underlyingAsset:le})=>le.toLowerCase()===L);if(!T)throw new Error("Missing pool reserve for "+L);let dt=R.scaledATokenBalance,W=T.liquidityIndex,Jt=T.liquidityRate,Zt=T.availableLiquidity,te=T.priceInMarketReferenceCurrency,ee=i+6,ae=this.calculateLinearInterest(Jt,T.lastUpdateTimestamp,ee),se=W*ae/ot,ne=dt*se/ot,ie=Number(p!==0&&p===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,re=T.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,oe=U.toAssetId(L);C.push({aTokenBalance:ne,availableLiquidity:Zt,decimals:Number(T.decimals),isCollateral:re,priceInRef:te,reserveId:oe,reserveAsset:L,reserveLiquidationThreshold:ie})}return{healthFactor:Number(_),currentLiquidationThreshold:Number(v.big.toDecimal(E,jt)),totalCollateral:l,totalDebt:b,reserves:C}}async hasBorrowPositions(t){let e=It.fromAny(t),a=await this.client.getUserAccountData(e),[s,n]=a;return n>0n}async getHealthFactor(t){let e=It.fromAny(t),a=await this.client.getUserAccountData(e),[s,n,i,r,u,p]=a;return this.calculateHealthFactorFromBalances(n,s,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return rt;let u=U.fromAssetId(e),p=i.find(L=>L.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,isCollateral:b,priceInRef:P,reserveLiquidationThreshold:E}=p,x=v.big.toBigInt(a,l),I=b?x*P/10n**BigInt(l):0n,_=s-I;if(_<=0n)return 0;let C=(0,g.default)(s.toString()).mul(r).minus((0,g.default)(I.toString()).mul(E)).div(_.toString()),R=(0,g.default)(_.toString()).mul(C).div(n.toString()).toFixed(6,g.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return rt;let u=U.fromAssetId(e),p=i.find(R=>R.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,priceInRef:b,reserveLiquidationThreshold:P}=p,x=v.big.toBigInt(a,l)*b/10n**BigInt(l),I=s+x;if(I<=0n)return 0;let _=(0,g.default)(s.toString()).mul(r).plus((0,g.default)(x.toString()).mul(P)).div(I.toString()),C=(0,g.default)(I.toString()).mul(_).div(n.toString()).toFixed(6,g.default.roundDown);return Number(C)}async getHealthFactorAfterSwap(t,e,a,s,n){let{totalDebt:i,reserves:r,healthFactor:u}=await this.getSummary(t);if(i===0n)return rt;let p=U.fromAssetId(a),l=U.fromAssetId(n),b=r.find(W=>W.reserveAsset===p),P=r.find(W=>W.reserveAsset===l);if(!b)throw new Error(`Missing reserve ctx for ${p}`);if(!P)throw new Error(`Missing reserve ctx for ${P}`);let E=v.big.toBigInt(e,b.decimals),x=v.big.toBigInt(s,P.decimals),I=E*b.priceInRef/10n**BigInt(b.decimals),_=x*P.priceInRef/10n**BigInt(P.decimals),C=b.isCollateral?(0,g.default)(I.toString()).mul(b.reserveLiquidationThreshold):(0,g.default)(0),T=(P.isCollateral?(0,g.default)(_.toString()).mul(P.reserveLiquidationThreshold):(0,g.default)(0)).minus(C).div(i.toString()),dt=(0,g.default)(u).plus(T).toFixed(6,g.default.roundDown);return Number(dt)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(t),i=U.fromAssetId(e),r=s.find(u=>u.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,n)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:s}=await this.getSummary(t),n={};for(let i of a){let r=this.calculateWithdrawMax(i,e,s);i.reserveId&&(n[i.reserveId]=r)}return n}calculateWithdrawMax(t,e,a){let{aTokenBalance:s,availableLiquidity:n,decimals:i,priceInRef:r,reserveLiquidationThreshold:u,isCollateral:p}=t,l=s;if(p&&e>0n){let P=a-ca;if(P>0){let E=(0,g.default)(P).mul(e.toString()).div(u).toFixed(0,g.default.roundDown),x=(0,g.default)(E).div(r.toString()).mul(10**i).toFixed(0,g.default.roundDown);l=s<BigInt(x)?s:BigInt(x)}else l=0n}return{amount:l<n?l:n,decimals:i}}calculateLinearInterest(t,e,a){let s=a-e;if(s<=0)return ot;let n=t*BigInt(s)/ua;return ot+n}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return rt;let s=e*a/t,n=v.big.toDecimal(s,jt);return Number(n)}};function Qt(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var V=class extends O{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new N(t),this.aaveUtils=new lt(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Kt})}async dryRun(t,e){let a=(0,Ot.Enum)("Signed",t),s=(0,Ot.Enum)("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let u=Qt(r.value);throw new Error("Dry run execution error!",{cause:u})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var ct=class extends V{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],n=await this.balance.getBalance(this.beneficiary,s);return t>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=w.getFraction(t,this.slippagePct),r=s.assetIn,u=n.assetOut,p=t+i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.buy({asset_in:r,asset_out:u,amount:e,max_sell_amount:p}):l=this.api.tx.Router.buy({asset_in:r,asset_out:u,amount_out:e,max_amount_in:p,route:M.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=w.getFraction(e,this.slippagePct),r=s.assetIn,u=n.assetOut,p=e-i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.sell({asset_in:r,asset_out:u,amount:t,min_buy_amount:p}):l=this.api.tx.Router.sell({asset_in:r,asset_out:u,amount_in:t,min_amount_out:p,route:M.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],s=e[e.length-1],n=w.getFraction(t,this.slippagePct),i=a.assetIn,r=s.assetOut,u=t-n,p=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:u,route:M.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("RouterSellAll",p)}};var ut=require("polkadot-api");var pt=class extends V{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradePeriod:n,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ut.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(r=await this.dispatchWithExtraGas(r)),this.wrapTx("DcaSchedule",r)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=w.getFraction(n,this.slippagePct),p=n-u,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ut.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:p,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapSell",l)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=w.getFraction(s,this.slippagePct),p=s+u,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ut.Enum)("Buy",{asset_in:e,asset_out:a,amount_out:n,max_amount_in:p,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapBuy",l)}};var mt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new ct(this.client,this.evmClient).setTrade(t)}order(t){return new pt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
1
+ "use strict";var ct=Object.create;var Q=Object.defineProperty;var ut=Object.getOwnPropertyDescriptor;var pt=Object.getOwnPropertyNames;var mt=Object.getPrototypeOf,dt=Object.prototype.hasOwnProperty;var J=(o,e)=>{for(var t in e)Q(o,t,{get:e[t],enumerable:!0})},Ae=(o,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of pt(e))!dt.call(o,s)&&s!==t&&Q(o,s,{get:()=>e[s],enumerable:!(a=ut(e,s))||a.enumerable});return o};var Z=(o,e,t)=>(t=o!=null?ct(mt(o)):{},Ae(e||!o||!o.__esModule?Q(t,"default",{value:o,enumerable:!0}):t,o)),gt=o=>Ae(Q({},"__esModule",{value:!0}),o);var pa={};J(pa,{TxBuilderFactory:()=>me});module.exports=gt(pa);var $=require("@galacticcouncil/math-lbp");var Ee=require("@galacticcouncil/common");var ee={};J(ee,{withTimeout:()=>ht});function ht(o,e,t="timeout"){return new Promise((a,s)=>{let n=setTimeout(()=>s(new Error(t)),e);o.then(i=>{clearTimeout(n),a(i)},i=>{clearTimeout(n),s(i)})})}var w={};J(w,{divSpot:()=>yt,getFraction:()=>Pt,mulScaled:()=>Be,mulSpot:()=>bt});var ge=require("@galacticcouncil/common");function Be(o,e,t,a,s){let n=t+a-s,i=o*e;return n>0?i/BigInt(10)**BigInt(n):n<0?i*BigInt(10)**BigInt(-n):i}function bt(o,e,t,a){return Be(o,e,t,ge.RUNTIME_DECIMALS,a)}function yt(o,e,t,a){if(e===0n)return 0n;let s=BigInt(10)**BigInt(ge.RUNTIME_DECIMALS+a-t);return o*s/e}function Pt(o,e,t=2){if(e<.01||e>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(t),s=BigInt(Math.round(e*Number(a)));return o*s/(BigInt(100)*a)}var m={};J(m,{FeeUtils:()=>he,shiftNeg:()=>Tt});var Re=Z(require("big.js"));var he=class o{static toPct(e){let[t,a]=e;return o.safeDivide(t*100,a)}static toRaw(e){let[t,a]=e;return o.safeDivide(t,a)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,a=12){let s=10**a;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};function Tt(o,e){let t=(0,Re.default)(typeof o=="bigint"?o.toString():o);return e===0?t.toString():t.div(Math.pow(10,e)).toString()}var St=Z(require("big.js"));var{FeeUtils:Ha}=m;var _t=require("polkadot-api"),be=require("rxjs");var E=require("rxjs"),f=require("rxjs/operators");var ne=require("@galacticcouncil/descriptors");var ke=require("@galacticcouncil/common"),se=require("rxjs");var F=require("rxjs"),h=require("rxjs/operators");function Ce(o,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let a=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,h.timeout)({first:t}),(0,h.map)(()=>"online"),(0,h.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,h.expand)(n=>(0,F.timer)(n.delayMs).pipe((0,h.switchMap)(a),(0,h.map)(i=>({state:i,delayMs:e})))),(0,h.skip)(1),(0,h.map)(n=>n.state),(0,h.distinctUntilChanged)(),(0,h.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:wt}=ke.log,ae=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Ce(e))}static getInstance(e){return this.instance||(this.instance=new o(e)),this.instance}watched(e,t){return t.pipe((0,se.tap)({error:a=>wt.error(e,a)}),(0,se.shareReplay)({bufferSize:1,refCount:!0}))}};var O=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(ne.hydration),this.apiNext=this.client.getTypedApi(ne.hydrationNext),this.watcher=ae.getInstance(this.client)}};var xt=require("polkadot-api/ws-provider"),It=require("polkadot-api/logs-provider"),Ot=require("@polkadot-api/legacy-provider");var At=require("polkadot-api/sm-provider");var De=require("@galacticcouncil/common"),S=require("rxjs"),c=require("rxjs/operators");var{logger:q}=De.log,N=class extends O{erc20Ids=null;constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:a}=await t.getValue(e,{at:"best"});return this.getBreakdown(a)}async getTokenBalance(e,t){let s=await this.api.query.Tokens.Accounts.getValue(e,t,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return(0,S.defer)(()=>{let t=this.watchSystemBalance(e),a=this.watchTokensBalance(e),s=this.watchErc20Balance(e);return(0,S.combineLatest)([t,a,s]).pipe((0,c.connect)(n=>(0,S.concat)(n.pipe((0,c.take)(1)),n.pipe((0,c.skip)(1),(0,c.debounceTime)(250)))))}).pipe((0,c.map)(t=>t.flat()),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([t,a],s)=>s===0?a:this.getDeltas(t,a))).pipe((0,c.tap)({subscribe:()=>q.debug("balance: subscribe",e),error:t=>q.error("balance",t)}),(0,c.retry)({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return(0,S.defer)(()=>t.watchValue(e,"best")).pipe((0,c.map)(a=>({id:0,balance:this.getBreakdown(a.data)})),(0,c.tap)({error:a=>q.error("balance(system)",a)}))}watchTokenBalance(e,t){let a=this.api.query.Tokens.Accounts;return(0,S.defer)(()=>a.watchValue(e,t,"best")).pipe((0,c.map)(s=>({id:t,balance:this.getBreakdown(s)})),(0,c.tap)({error:s=>q.error("balance(token)",s)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return(0,S.defer)(()=>t.watchEntries(e,{at:"best"})).pipe((0,c.distinctUntilChanged)((a,s)=>!s.deltas),(0,c.map)(({deltas:a})=>{let s=[];return a?.deleted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),(0,c.tap)({error:a=>q.error("balance(tokens)",a)}))}watchErc20Balance(e,t){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(e,r)]))).map(([r,u])=>({id:r,balance:u}));return(0,S.defer)(()=>(0,S.from)(t?Promise.resolve(t):a()).pipe((0,c.switchMap)(n=>this.watcher.bestBlock$.pipe((0,c.switchMap)(()=>(0,S.from)(s(n))))),(0,c.startWith)([]),(0,c.bufferCount)(2,1),(0,c.map)(([n,i],r)=>r===0?i.filter(u=>u.balance.total>0n):this.getDeltas(n,i)),(0,c.distinctUntilChanged)((n,i)=>i.length===0),(0,c.tap)({error:n=>q.error("balance(erc20)",n)})))}async getBalanceData(e,t){let a=await this.api.apis.CurrenciesApi.account(t,e,{at:"best"});return this.getBreakdown(a)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,a=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:a,transferable:t}}getDeltas(e,t){let a=(n,i)=>n!==void 0&&i!==void 0&&n.transferable===i.transferable&&n.total===i.total,s=e.reduce((n,i)=>(n.set(i.id,i.balance),n),new Map);return t.filter(n=>!a(n.balance,s.get(n.id)))}};var Bt=require("rxjs");var Me=require("@galacticcouncil/common");var Ps={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:fs}=Me.log;var{withTimeout:Ds}=ee;var y=require("@galacticcouncil/math-omnipool"),Ft=Z(require("big.js"));var Et=require("@galacticcouncil/common");var{FeeUtils:on}=m;var G=require("polkadot-api"),Ct=require("@polkadot-api/utils"),H=require("rxjs"),kt=require("@galacticcouncil/common");var{FeeUtils:fn}=m,Tn=G.Binary.fromText("omnipool"),Sn=(0,G.Enum)("Short");var A=require("@galacticcouncil/math-stableswap");var He=require("@galacticcouncil/common");var{FeeUtils:Gn}=m;var qe=require("polkadot-api"),Ht=require("@polkadot-api/utils"),qt=require("@noble/hashes/blake2b"),K=require("rxjs"),Ne=require("@galacticcouncil/common");var{FeeUtils:Zn}=m;var B=require("@galacticcouncil/math-xyk");var Gt=require("@galacticcouncil/common");var{FeeUtils:Pi}=m;var Ut=require("polkadot-api"),Vt=require("rxjs");var Ge=require("@galacticcouncil/common");var $t=require("polkadot-api"),Xt=require("@polkadot-api/utils"),ye=require("rxjs"),Yt=require("viem"),Pe=require("@galacticcouncil/common");var{ERC20:Ki}=Pe.erc20;var D=require("@galacticcouncil/math-hsm");var Ue=require("@galacticcouncil/common");var{FeeUtils:pr}=m;var We=require("polkadot-api"),Qt=require("@polkadot-api/utils"),j=require("rxjs"),Jt=require("viem"),fe=require("@galacticcouncil/common");var{FeeUtils:Ar}=m,{H160:Br}=fe.h160;var $e=require("@galacticcouncil/common"),Te=require("rxjs");var{logger:vo}=$e.log;var Xe=require("@galacticcouncil/common");var{FeeUtils:bl}=m;var la=require("@galacticcouncil/common");var Se=require("polkadot-api");var M=class{static build(e){return e.map(({assetIn:t,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:(0,Se.Enum)("Stableswap",n),asset_in:t,asset_out:a}:{pool:(0,Se.Enum)(s),asset_in:t,asset_out:a})}};var Oe=require("polkadot-api");var Ye=[{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 ve=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var ze="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",we="0x112b087b60C1a166130d59266363C45F8aa99db0",xe="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Ke=1000000n;var tc=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ie=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:ve,address:we,args:[xe],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:ve,address:we,args:[xe,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:Ye,address:ze,args:[e],functionName:"getUserAccountData"})}};var g=Z(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:U}=v.erc20,{H160:Ie}=v.h160,ca=1.01,ua=31536000n,je=4,re=-1,oe=10n**27n,le=class{client;constructor(e){this.client=new ie(e)}async getSummary(e){let t=Ie.fromAny(e),[a,s,n,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[r]=a,[u,p]=s,[l,b,P,C,x,I]=n,_=v.big.toDecimal(I,18),k=[];for(let R of u){let L=R.underlyingAsset.toLowerCase(),T=r.find(({underlyingAsset:lt})=>lt.toLowerCase()===L);if(!T)throw new Error("Missing pool reserve for "+L);let de=R.scaledATokenBalance,W=T.liquidityIndex,Je=T.liquidityRate,Ze=T.availableLiquidity,et=T.priceInMarketReferenceCurrency,tt=i+6,at=this.calculateLinearInterest(Je,T.lastUpdateTimestamp,tt),st=W*at/oe,nt=de*st/oe,it=Number(p!==0&&p===T.eModeCategoryId?T.eModeLiquidationThreshold:T.reserveLiquidationThreshold)/1e4,rt=T.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,ot=U.toAssetId(L);k.push({aTokenBalance:nt,availableLiquidity:Ze,decimals:Number(T.decimals),isCollateral:rt,priceInRef:et,reserveId:ot,reserveAsset:L,reserveLiquidationThreshold:it})}return{healthFactor:Number(_),currentLiquidationThreshold:Number(v.big.toDecimal(C,je)),totalCollateral:l,totalDebt:b,reserves:k}}async hasBorrowPositions(e){let t=Ie.fromAny(e),a=await this.client.getUserAccountData(t),[s,n]=a;return n>0n}async getHealthFactor(e){let t=Ie.fromAny(e),a=await this.client.getUserAccountData(t),[s,n,i,r,u,p]=a;return this.calculateHealthFactorFromBalances(n,s,r)}async getHealthFactorAfterWithdraw(e,t,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(e);if(n===0n)return re;let u=U.fromAssetId(t),p=i.find(L=>L.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,isCollateral:b,priceInRef:P,reserveLiquidationThreshold:C}=p,x=v.big.toBigInt(a,l),I=b?x*P/10n**BigInt(l):0n,_=s-I;if(_<=0n)return 0;let k=(0,g.default)(s.toString()).mul(r).minus((0,g.default)(I.toString()).mul(C)).div(_.toString()),R=(0,g.default)(_.toString()).mul(k).div(n.toString()).toFixed(6,g.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(e,t,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(e);if(n===0n)return re;let u=U.fromAssetId(t),p=i.find(R=>R.reserveAsset===u);if(!p)throw new Error("Missing reserve ctx for "+u);let{decimals:l,priceInRef:b,reserveLiquidationThreshold:P}=p,x=v.big.toBigInt(a,l)*b/10n**BigInt(l),I=s+x;if(I<=0n)return 0;let _=(0,g.default)(s.toString()).mul(r).plus((0,g.default)(x.toString()).mul(P)).div(I.toString()),k=(0,g.default)(I.toString()).mul(_).div(n.toString()).toFixed(6,g.default.roundDown);return Number(k)}async getHealthFactorAfterSwap(e,t,a,s,n){let{totalDebt:i,reserves:r,healthFactor:u}=await this.getSummary(e);if(i===0n)return re;let p=U.fromAssetId(a),l=U.fromAssetId(n),b=r.find(W=>W.reserveAsset===p),P=r.find(W=>W.reserveAsset===l);if(!b)throw new Error(`Missing reserve ctx for ${p}`);if(!P)throw new Error(`Missing reserve ctx for ${P}`);let C=v.big.toBigInt(t,b.decimals),x=v.big.toBigInt(s,P.decimals),I=C*b.priceInRef/10n**BigInt(b.decimals),_=x*P.priceInRef/10n**BigInt(P.decimals),k=b.isCollateral?(0,g.default)(I.toString()).mul(b.reserveLiquidationThreshold):(0,g.default)(0),T=(P.isCollateral?(0,g.default)(_.toString()).mul(P.reserveLiquidationThreshold):(0,g.default)(0)).minus(k).div(i.toString()),de=(0,g.default)(u).plus(T).toFixed(6,g.default.roundDown);return Number(de)}async getMaxWithdraw(e,t){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(e),i=U.fromAssetId(t),r=s.find(u=>u.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,n)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:a,healthFactor:s}=await this.getSummary(e),n={};for(let i of a){let r=this.calculateWithdrawMax(i,t,s);i.reserveId&&(n[i.reserveId]=r)}return n}calculateWithdrawMax(e,t,a){let{aTokenBalance:s,availableLiquidity:n,decimals:i,priceInRef:r,reserveLiquidationThreshold:u,isCollateral:p}=e,l=s;if(p&&t>0n){let P=a-ca;if(P>0){let C=(0,g.default)(P).mul(t.toString()).div(u).toFixed(0,g.default.roundDown),x=(0,g.default)(C).div(r.toString()).mul(10**i).toFixed(0,g.default.roundDown);l=s<BigInt(x)?s:BigInt(x)}else l=0n}return{amount:l<n?l:n,decimals:i}}calculateLinearInterest(e,t,a){let s=a-t;if(s<=0)return oe;let n=e*BigInt(s)/ua;return oe+n}calculateHealthFactorFromBalances(e,t,a){if(e===0n)return re;let s=t*a/e,n=v.big.toDecimal(s,je);return Number(n)}};function Qe(o){let e=[],t=o;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var V=class extends O{evm;evmClient;balance;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balance=new N(e),this.aaveUtils=new le(t)}wrapTx(e,t){return{name:e,get:()=>t,dryRun:a=>this.dryRun(a,t)}}async dispatchWithExtraGas(e){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:e.decodedCall,extra_gas:Ke})}async dryRun(e,t){let a=(0,Oe.Enum)("Signed",e),s=(0,Oe.Enum)("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,t.decodedCall),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let u=Qe(r.value);throw new Error("Dry run execution error!",{cause:u})}return i}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var ce=class extends V{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=t[0],n=await this.balance.getBalance(this.beneficiary,s);return e>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=w.getFraction(e,this.slippagePct),r=s.assetIn,u=n.assetOut,p=e+i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.buy({asset_in:r,asset_out:u,amount:t,max_sell_amount:p}):l=this.api.tx.Router.buy({asset_in:r,asset_out:u,amount_out:t,max_amount_in:p,route:M.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterBuy",l)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=w.getFraction(t,this.slippagePct),r=s.assetIn,u=n.assetOut,p=t-i,l;return this.isDirectOmnipoolTrade(a)?l=this.api.tx.Omnipool.sell({asset_in:r,asset_out:u,amount:e,min_buy_amount:p}):l=this.api.tx.Router.sell({asset_in:r,asset_out:u,amount_in:e,min_amount_out:p,route:M.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("RouterSell",l)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,a=t[0],s=t[t.length-1],n=w.getFraction(e,this.slippagePct),i=a.assetIn,r=s.assetOut,u=e-n,p=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:u,route:M.build(t)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("RouterSellAll",p)}};var ue=require("polkadot-api");var pe=class extends V{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}async buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:a,tradeAmountIn:s,tradePeriod:n,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ue.Enum)("Sell",{asset_in:t,asset_out:a,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(r=await this.dispatchWithExtraGas(r)),this.wrapTx("DcaSchedule",r)}async buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=w.getFraction(n,this.slippagePct),p=n-u,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ue.Enum)("Sell",{asset_in:t,asset_out:a,amount_in:s,min_amount_out:p,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapSell",l)}async buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,u=w.getFraction(s,this.slippagePct),p=s+u,l=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,ue.Enum)("Buy",{asset_in:t,asset_out:a,amount_out:n,max_amount_in:p,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("DcaSchedule.twapBuy",l)}};var me=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t}trade(e){return new ce(this.client,this.evmClient).setTrade(e)}order(e){return new pe(this.client,this.evmClient).setOrder(e)}};0&&(module.exports={TxBuilderFactory});
@@ -1 +1 @@
1
- var Dt=Object.defineProperty;var K=(l,t)=>{for(var e in t)Dt(l,e,{get:t[e],enumerable:!0})};import Mt from"buffer";typeof window<"u"&&(window.Buffer=Mt.Buffer);import{calculate_in_given_out as aa,calculate_out_given_in as na,calculate_linear_weights as sa,calculate_pool_trade_fee as ia,get_spot_price as ra}from"@galacticcouncil/math-lbp";import{big as Fa,RUNTIME_DECIMALS as Ea}from"@galacticcouncil/common";var q={};K(q,{withTimeout:()=>Lt});function Lt(l,t,e="timeout"){return new Promise((a,s)=>{let n=setTimeout(()=>s(new Error(e)),t);l.then(i=>{clearTimeout(n),a(i)},i=>{clearTimeout(n),s(i)})})}var y={};K(y,{divSpot:()=>qt,getFraction:()=>Nt,mulScaled:()=>it,mulSpot:()=>Ht});import{RUNTIME_DECIMALS as st}from"@galacticcouncil/common";function it(l,t,e,a,s){let n=e+a-s,i=l*t;return n>0?i/BigInt(10)**BigInt(n):n<0?i*BigInt(10)**BigInt(-n):i}function Ht(l,t,e,a){return it(l,t,e,st,a)}function qt(l,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(st+a-e);return l*s/t}function Nt(l,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),s=BigInt(Math.round(t*Number(a)));return l*s/(BigInt(100)*a)}var p={};K(p,{FeeUtils:()=>j,shiftNeg:()=>Vt});import Ut from"big.js";var j=class l{static toPct(t){let[e,a]=t;return l.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return l.safeDivide(e,a)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,a=12){let s=10**a;return Math.round(t*s/e)/s}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Vt(l,t){let e=Ut(typeof l=="bigint"?l.toString():l);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}import Sa from"big.js";import{TLRUCache as xa}from"@thi.ng/cache";var{FeeUtils:Wa}=p;import{CompatibilityLevel as Zs}from"polkadot-api";import{Subscription as ei,distinctUntilChanged as ai,filter as ni}from"rxjs";import{memoize1 as us}from"@thi.ng/memoize";import{TLRUCache as ms}from"@thi.ng/cache";import{ReplaySubject as bs,Subscription as ys,combineLatest as fs,defer as Ps,from as Ts,merge as Ss,of as vs,EMPTY as ws}from"rxjs";import{bufferCount as Is,bufferTime as Os,catchError as As,filter as Bs,finalize as _s,map as Rs,pairwise as Fs,repeat as Es,skip as Cs,share as ks,startWith as Ds,switchMap as Ms,tap as Ls,throttleTime as Hs}from"rxjs/operators";import{hydration as ie,hydrationNext as re}from"@galacticcouncil/descriptors";import{log as ee}from"@galacticcouncil/common";import{shareReplay as ae,tap as ne}from"rxjs";import{defer as $t,from as Xt,of as lt,timer as Yt}from"rxjs";import{catchError as zt,distinctUntilChanged as Kt,expand as jt,map as Q,shareReplay as Qt,skip as Jt,switchMap as Zt,timeout as te}from"rxjs/operators";function ct(l,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>$t(()=>Xt(l._request("system_health",[]))).pipe(te({first:e}),Q(()=>"online"),zt(()=>lt("offline")));return lt({state:"offline",delayMs:0}).pipe(jt(n=>Yt(n.delayMs).pipe(Zt(a),Q(i=>({state:i,delayMs:t})))),Jt(1),Q(n=>n.state),Kt(),Qt({bufferSize:1,refCount:!0}))}var{logger:se}=ee,G=class l{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ct(t))}static getInstance(t){return this.instance||(this.instance=new l(t)),this.instance}watched(t,e){return e.pipe(ne({error:a=>se.error(t,a)}),ae({bufferSize:1,refCount:!0}))}};var T=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(ie),this.apiNext=this.client.getTypedApi(re),this.watcher=G.getInstance(this.client)}};import{getWsProvider as un}from"polkadot-api/ws-provider";import{withLogsRecorder as mn}from"polkadot-api/logs-provider";import{withLegacy as gn}from"@polkadot-api/legacy-provider";import{getSmProvider as fn}from"polkadot-api/sm-provider";import{log as oe}from"@galacticcouncil/common";import{combineLatest as le,concat as ce,defer as D,from as ut}from"rxjs";import{bufferCount as pt,distinctUntilChanged as mt,debounceTime as ue,map as B,retry as pe,startWith as dt,switchMap as gt,tap as M,take as me,skip as de,connect as ge}from"rxjs/operators";var{logger:_}=oe,R=class extends T{erc20Ids=null;constructor(t){super(t)}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:a}=await e.getValue(t,{at:"best"});return this.getBreakdown(a)}async getTokenBalance(t,e){let s=await this.api.query.Tokens.Accounts.getValue(t,e,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return D(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return le([e,a,s]).pipe(ge(n=>ce(n.pipe(me(1)),n.pipe(de(1),ue(250)))))}).pipe(B(e=>e.flat()),dt([]),pt(2,1),B(([e,a],s)=>s===0?a:this.getDeltas(e,a))).pipe(M({subscribe:()=>_.debug("balance: subscribe",t),error:e=>_.error("balance",e)}),pe({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return D(()=>e.watchValue(t,"best")).pipe(B(a=>({id:0,balance:this.getBreakdown(a.data)})),M({error:a=>_.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return D(()=>a.watchValue(t,e,"best")).pipe(B(s=>({id:e,balance:this.getBreakdown(s)})),M({error:s=>_.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return D(()=>e.watchEntries(t,{at:"best"})).pipe(mt((a,s)=>!s.deltas),B(({deltas:a})=>{let s=[];return a?.deleted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),M({error:a=>_.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,c])=>({id:r,balance:c}));return D(()=>ut(e?Promise.resolve(e):a()).pipe(gt(n=>this.watcher.bestBlock$.pipe(gt(()=>ut(s(n))))),dt([]),pt(2,1),B(([n,i],r)=>r===0?i.filter(c=>c.balance.total>0n):this.getDeltas(n,i)),mt((n,i)=>i.length===0),M({error:n=>_.error("balance(erc20)",n)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:"best"});return this.getBreakdown(a)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,a=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:a,transferable:e}}getDeltas(t,e){let a=(n,i)=>n!==void 0&&i!==void 0&&n.transferable===i.transferable&&n.total===i.total,s=t.reduce((n,i)=>(n.set(i.id,i.balance),n),new Map);return e.filter(n=>!a(n.balance,s.get(n.id)))}};import{BehaviorSubject as Qn}from"rxjs";import{log as he}from"@galacticcouncil/common";var ns={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:ss}=he;var{withTimeout:Ks}=q;import{calculate_in_given_out as fi,calculate_lrna_in_given_out as Pi,calculate_out_given_in as Ti,calculate_out_given_lrna_in as Si,calculate_spot_price as vi,calculate_lrna_spot_price as wi,calculate_shares as xi,calculate_liquidity_out as Ii,calculate_liquidity_lrna_out as Oi,verify_asset_cap as Ai,calculate_liquidity_hub_in as Bi,is_sell_allowed as _i,is_buy_allowed as Ri,is_add_liquidity_allowed as Fi,is_remove_liquidity_allowed as Ei,recalculate_asset_fee as Ci,recalculate_protocol_fee as ki}from"@galacticcouncil/math-omnipool";import Mi from"big.js";import{big as Ni}from"@galacticcouncil/common";var{FeeUtils:Ji}=p;import{AccountId as sr,Binary as ye,CompatibilityLevel as ir,Enum as fe}from"polkadot-api";import{toHex as or}from"@polkadot-api/utils";import{Subscription as cr,distinctUntilChanged as ur,filter as pr,finalize as mr,map as dr,merge as gr,tap as hr}from"rxjs";import{HYDRATION_SS58_PREFIX as yr}from"@galacticcouncil/common";var{FeeUtils:Or}=p,Ar=ye.fromText("omnipool"),Br=fe("Short");import{calculate_in_given_out as Mr,calculate_out_given_in as Lr,calculate_amplification as Hr,calculate_add_one_asset as qr,calculate_liquidity_out_one_asset as Nr,calculate_shares as Gr,calculate_shares_for_amount as Ur,calculate_spot_price_with_fee as Vr,pool_account_name as Wr,recalculate_peg as $r}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as Kr,big as jr}from"@galacticcouncil/common";var{FeeUtils:po}=p;import{AccountId as bo,CompatibilityLevel as yo}from"polkadot-api";import{toHex as Po}from"@polkadot-api/utils";import{blake2b as So}from"@noble/hashes/blake2b";import{Subscription as wo,distinctUntilChanged as xo,map as Io,merge as Oo,tap as Ao}from"rxjs";import{HYDRATION_SS58_PREFIX as _o,RUNTIME_DECIMALS as Ro}from"@galacticcouncil/common";var{FeeUtils:Go}=p;import{calculate_in_given_out as Ko,calculate_out_given_in as jo,calculate_pool_trade_fee as Qo,get_spot_price as Jo,calculate_liquidity_in as Zo,calculate_shares as tl,calculate_spot_price as el,calculate_spot_price_with_fee as al,calculate_liquidity_out_asset_a as nl,calculate_liquidity_out_asset_b as sl}from"@galacticcouncil/math-xyk";import{big as ul}from"@galacticcouncil/common";var{FeeUtils:vl}=p;import{CompatibilityLevel as Ol}from"polkadot-api";import{Subscription as Bl}from"rxjs";import{big as Wl,RUNTIME_DECIMALS as $l}from"@galacticcouncil/common";import{AccountId as rc}from"polkadot-api";import{toHex as lc}from"@polkadot-api/utils";import{Subscription as uc,filter as pc,map as mc}from"rxjs";import{decodeEventLog as gc}from"viem";import{erc20 as xe,HYDRATION_SS58_PREFIX as bc}from"@galacticcouncil/common";var{ERC20:wc}=xe;import{calculate_collateral_in_given_hollar_out as Rc,calculate_collateral_out_given_hollar_in as Fc,calculate_hollar_in_given_collateral_out as Ec,calculate_hollar_out_given_collateral_in as Cc,calculate_imbalance as kc,calculate_max_price as Dc,calculate_buyback_limit as Mc,calculate_buyback_price_with_fee as Lc}from"@galacticcouncil/math-hsm";import{big as Uc,RUNTIME_DECIMALS as Vc}from"@galacticcouncil/common";var{FeeUtils:tu}=p;import{AccountId as du,CompatibilityLevel as gu}from"polkadot-api";import{toHex as yu}from"@polkadot-api/utils";import{Subscription as Tu,combineLatest as Su,filter as vu,map as wu,pairwise as xu}from"rxjs";import{decodeEventLog as Ou}from"viem";import{h160 as Be,HYDRATION_SS58_PREFIX as Bu}from"@galacticcouncil/common";var{FeeUtils:Du}=p,{H160:Mu}=Be;import{log as Re}from"@galacticcouncil/common";import{Subject as Tp,Subscription as Sp,takeUntil as vp}from"rxjs";var{logger:Hp}=Re;import{big as Im,RUNTIME_DECIMALS as Om}from"@galacticcouncil/common";var{FeeUtils:Gm}=p;import{big as od}from"@galacticcouncil/common";import{Enum as yt}from"polkadot-api";var I=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:yt("Stableswap",n),asset_in:e,asset_out:a}:{pool:yt(s),asset_in:e,asset_out:a})}};import{Enum as wt}from"polkadot-api";var ft=[{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 J=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Pt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Z="0x112b087b60C1a166130d59266363C45F8aa99db0",tt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Tt=1000000n;var Ld=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var U=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:J,address:Z,args:[tt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:J,address:Z,args:[tt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:ft,address:Pt,args:[t],functionName:"getUserAccountData"})}};import d from"big.js";import{big as A,erc20 as qe,h160 as Ne}from"@galacticcouncil/common";var{ERC20:F}=qe,{H160:et}=Ne,Ge=1.01,Ue=31536000n,St=4,V=-1,W=10n**27n,$=class{client;constructor(t){this.client=new U(t)}async getSummary(t){let e=et.fromAny(t),[a,s,n,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[c,u]=s,[o,g,h,w,f,P]=n,S=A.toDecimal(P,18),x=[];for(let v of c){let O=v.underlyingAsset.toLowerCase(),b=r.find(({underlyingAsset:kt})=>kt.toLowerCase()===O);if(!b)throw new Error("Missing pool reserve for "+O);let z=v.scaledATokenBalance,C=b.liquidityIndex,xt=b.liquidityRate,It=b.availableLiquidity,Ot=b.priceInMarketReferenceCurrency,At=i+6,Bt=this.calculateLinearInterest(xt,b.lastUpdateTimestamp,At),_t=C*Bt/W,Rt=z*_t/W,Ft=Number(u!==0&&u===b.eModeCategoryId?b.eModeLiquidationThreshold:b.reserveLiquidationThreshold)/1e4,Et=b.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,Ct=F.toAssetId(O);x.push({aTokenBalance:Rt,availableLiquidity:It,decimals:Number(b.decimals),isCollateral:Et,priceInRef:Ot,reserveId:Ct,reserveAsset:O,reserveLiquidationThreshold:Ft})}return{healthFactor:Number(S),currentLiquidationThreshold:Number(A.toDecimal(w,St)),totalCollateral:o,totalDebt:g,reserves:x}}async hasBorrowPositions(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[s,n]=a;return n>0n}async getHealthFactor(t){let e=et.fromAny(t),a=await this.client.getUserAccountData(e),[s,n,i,r,c,u]=a;return this.calculateHealthFactorFromBalances(n,s,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return V;let c=F.fromAssetId(e),u=i.find(O=>O.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,isCollateral:g,priceInRef:h,reserveLiquidationThreshold:w}=u,f=A.toBigInt(a,o),P=g?f*h/10n**BigInt(o):0n,S=s-P;if(S<=0n)return 0;let x=d(s.toString()).mul(r).minus(d(P.toString()).mul(w)).div(S.toString()),v=d(S.toString()).mul(x).div(n.toString()).toFixed(6,d.roundDown);return Number(v)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return V;let c=F.fromAssetId(e),u=i.find(v=>v.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,priceInRef:g,reserveLiquidationThreshold:h}=u,f=A.toBigInt(a,o)*g/10n**BigInt(o),P=s+f;if(P<=0n)return 0;let S=d(s.toString()).mul(r).plus(d(f.toString()).mul(h)).div(P.toString()),x=d(P.toString()).mul(S).div(n.toString()).toFixed(6,d.roundDown);return Number(x)}async getHealthFactorAfterSwap(t,e,a,s,n){let{totalDebt:i,reserves:r,healthFactor:c}=await this.getSummary(t);if(i===0n)return V;let u=F.fromAssetId(a),o=F.fromAssetId(n),g=r.find(C=>C.reserveAsset===u),h=r.find(C=>C.reserveAsset===o);if(!g)throw new Error(`Missing reserve ctx for ${u}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let w=A.toBigInt(e,g.decimals),f=A.toBigInt(s,h.decimals),P=w*g.priceInRef/10n**BigInt(g.decimals),S=f*h.priceInRef/10n**BigInt(h.decimals),x=g.isCollateral?d(P.toString()).mul(g.reserveLiquidationThreshold):d(0),b=(h.isCollateral?d(S.toString()).mul(h.reserveLiquidationThreshold):d(0)).minus(x).div(i.toString()),z=d(c).plus(b).toFixed(6,d.roundDown);return Number(z)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(t),i=F.fromAssetId(e),r=s.find(c=>c.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,n)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:s}=await this.getSummary(t),n={};for(let i of a){let r=this.calculateWithdrawMax(i,e,s);i.reserveId&&(n[i.reserveId]=r)}return n}calculateWithdrawMax(t,e,a){let{aTokenBalance:s,availableLiquidity:n,decimals:i,priceInRef:r,reserveLiquidationThreshold:c,isCollateral:u}=t,o=s;if(u&&e>0n){let h=a-Ge;if(h>0){let w=d(h).mul(e.toString()).div(c).toFixed(0,d.roundDown),f=d(w).div(r.toString()).mul(10**i).toFixed(0,d.roundDown);o=s<BigInt(f)?s:BigInt(f)}else o=0n}return{amount:o<n?o:n,decimals:i}}calculateLinearInterest(t,e,a){let s=a-e;if(s<=0)return W;let n=t*BigInt(s)/Ue;return W+n}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return V;let s=e*a/t,n=A.toDecimal(s,St);return Number(n)}};function vt(l){let t=[],e=l;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var E=class extends T{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new R(t),this.aaveUtils=new $(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:Tt})}async dryRun(t,e){let a=wt("Signed",t),s=wt("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let c=vt(r.value);throw new Error("Dry run execution error!",{cause:c})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var X=class extends E{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=e[0],n=await this.balance.getBalance(this.beneficiary,s);return t>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=y.getFraction(t,this.slippagePct),r=s.assetIn,c=n.assetOut,u=t+i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.buy({asset_in:r,asset_out:c,amount:e,max_sell_amount:u}):o=this.api.tx.Router.buy({asset_in:r,asset_out:c,amount_out:e,max_amount_in:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterBuy",o)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=y.getFraction(e,this.slippagePct),r=s.assetIn,c=n.assetOut,u=e-i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.sell({asset_in:r,asset_out:c,amount:t,min_buy_amount:u}):o=this.api.tx.Router.sell({asset_in:r,asset_out:c,amount_in:t,min_amount_out:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterSell",o)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],s=e[e.length-1],n=y.getFraction(t,this.slippagePct),i=a.assetIn,r=s.assetOut,c=t-n,u=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:c,route:I.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};import{Enum as at}from"polkadot-api";var Y=class extends E{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradePeriod:n,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:at("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(r=await this.dispatchWithExtraGas(r)),this.wrapTx("DcaSchedule",r)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(n,this.slippagePct),u=n-c,o=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:at("Sell",{asset_in:e,asset_out:a,amount_in:s,min_amount_out:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapSell",o)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(s,this.slippagePct),u=s+c,o=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:at("Buy",{asset_in:e,asset_out:a,amount_out:n,max_amount_in:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapBuy",o)}};var nt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new X(this.client,this.evmClient).setTrade(t)}order(t){return new Y(this.client,this.evmClient).setOrder(t)}};export{nt as TxBuilderFactory};
1
+ var De=Object.defineProperty;var K=(l,e)=>{for(var t in e)De(l,t,{get:e[t],enumerable:!0})};import Me from"buffer";typeof window<"u"&&(window.Buffer=Me.Buffer);import{calculate_in_given_out as aa,calculate_out_given_in as na,calculate_linear_weights as sa,calculate_pool_trade_fee as ia,get_spot_price as ra}from"@galacticcouncil/math-lbp";import{big as Fa,RUNTIME_DECIMALS as Ea}from"@galacticcouncil/common";var q={};K(q,{withTimeout:()=>Le});function Le(l,e,t="timeout"){return new Promise((a,s)=>{let n=setTimeout(()=>s(new Error(t)),e);l.then(i=>{clearTimeout(n),a(i)},i=>{clearTimeout(n),s(i)})})}var y={};K(y,{divSpot:()=>qe,getFraction:()=>Ne,mulScaled:()=>ie,mulSpot:()=>He});import{RUNTIME_DECIMALS as se}from"@galacticcouncil/common";function ie(l,e,t,a,s){let n=t+a-s,i=l*e;return n>0?i/BigInt(10)**BigInt(n):n<0?i*BigInt(10)**BigInt(-n):i}function He(l,e,t,a){return ie(l,e,t,se,a)}function qe(l,e,t,a){if(e===0n)return 0n;let s=BigInt(10)**BigInt(se+a-t);return l*s/e}function Ne(l,e,t=2){if(e<.01||e>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(t),s=BigInt(Math.round(e*Number(a)));return l*s/(BigInt(100)*a)}var p={};K(p,{FeeUtils:()=>j,shiftNeg:()=>Ve});import Ue from"big.js";var j=class l{static toPct(e){let[t,a]=e;return l.safeDivide(t*100,a)}static toRaw(e){let[t,a]=e;return l.safeDivide(t,a)}static fromPermill(e){return[e,1e6]}static fromPerbill(e){return[e,1e9]}static fromRate(e,t){return[e,t]}static safeDivide(e,t,a=12){let s=10**a;return Math.round(e*s/t)/s}static safeRound(e){return parseFloat(e.toPrecision(15))}};function Ve(l,e){let t=Ue(typeof l=="bigint"?l.toString():l);return e===0?t.toString():t.div(Math.pow(10,e)).toString()}import Sa from"big.js";import{TLRUCache as xa}from"@thi.ng/cache";var{FeeUtils:Wa}=p;import{CompatibilityLevel as ei}from"polkadot-api";import{Subscription as ai,distinctUntilChanged as ni,filter as si}from"rxjs";import{memoize1 as us}from"@thi.ng/memoize";import{TLRUCache as ms}from"@thi.ng/cache";import{ReplaySubject as bs,Subscription as ys,combineLatest as fs,defer as Ps,from as Ts,interval as Ss,merge as vs,of as ws,EMPTY as xs}from"rxjs";import{bufferCount as Os,bufferTime as As,catchError as Bs,filter as _s,finalize as Rs,map as Fs,pairwise as Es,repeat as Cs,skip as ks,share as Ds,startWith as Ms,switchMap as Ls,tap as Hs,throttleTime as qs}from"rxjs/operators";import{hydration as it,hydrationNext as rt}from"@galacticcouncil/descriptors";import{log as tt}from"@galacticcouncil/common";import{shareReplay as at,tap as nt}from"rxjs";import{defer as $e,from as Xe,of as le,timer as Ye}from"rxjs";import{catchError as ze,distinctUntilChanged as Ke,expand as je,map as Q,shareReplay as Qe,skip as Je,switchMap as Ze,timeout as et}from"rxjs/operators";function ce(l,{intervalMs:e=5e3,rpcTimeoutMs:t=1e4}={}){let a=()=>$e(()=>Xe(l._request("system_health",[]))).pipe(et({first:t}),Q(()=>"online"),ze(()=>le("offline")));return le({state:"offline",delayMs:0}).pipe(je(n=>Ye(n.delayMs).pipe(Ze(a),Q(i=>({state:i,delayMs:e})))),Je(1),Q(n=>n.state),Ke(),Qe({bufferSize:1,refCount:!0}))}var{logger:st}=tt,G=class l{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(e){this.bestBlock$=this.watched("watcher(bestBlock)",e.getUnsafeApi().query.System.Number.watchValue("best")),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",e.finalizedBlock$),this.connection$=this.watched("watcher(connection)",ce(e))}static getInstance(e){return this.instance||(this.instance=new l(e)),this.instance}watched(e,t){return t.pipe(nt({error:a=>st.error(e,a)}),at({bufferSize:1,refCount:!0}))}};var T=class{client;api;apiNext;watcher;constructor(e){this.client=e,this.api=this.client.getTypedApi(it),this.apiNext=this.client.getTypedApi(rt),this.watcher=G.getInstance(this.client)}};import{getWsProvider as un}from"polkadot-api/ws-provider";import{withLogsRecorder as mn}from"polkadot-api/logs-provider";import{withLegacy as gn}from"@polkadot-api/legacy-provider";import{getSmProvider as fn}from"polkadot-api/sm-provider";import{log as ot}from"@galacticcouncil/common";import{combineLatest as lt,concat as ct,defer as D,from as ue}from"rxjs";import{bufferCount as pe,distinctUntilChanged as me,debounceTime as ut,map as B,retry as pt,startWith as de,switchMap as ge,tap as M,take as mt,skip as dt,connect as gt}from"rxjs/operators";var{logger:_}=ot,R=class extends T{erc20Ids=null;constructor(e){super(e)}async getBalance(e,t){return t===0?this.getSystemBalance(e):this.getBalanceData(e,t)}async getSystemBalance(e){let t=this.api.query.System.Account,{data:a}=await t.getValue(e,{at:"best"});return this.getBreakdown(a)}async getTokenBalance(e,t){let s=await this.api.query.Tokens.Accounts.getValue(e,t,{at:"best"});return this.getBreakdown(s)}async getErc20Balance(e,t){return this.getBalanceData(e,t)}watchBalance(e){return D(()=>{let t=this.watchSystemBalance(e),a=this.watchTokensBalance(e),s=this.watchErc20Balance(e);return lt([t,a,s]).pipe(gt(n=>ct(n.pipe(mt(1)),n.pipe(dt(1),ut(250)))))}).pipe(B(t=>t.flat()),de([]),pe(2,1),B(([t,a],s)=>s===0?a:this.getDeltas(t,a))).pipe(M({subscribe:()=>_.debug("balance: subscribe",e),error:t=>_.error("balance",t)}),pt({delay:1e3}))}watchSystemBalance(e){let t=this.api.query.System.Account;return D(()=>t.watchValue(e,"best")).pipe(B(a=>({id:0,balance:this.getBreakdown(a.data)})),M({error:a=>_.error("balance(system)",a)}))}watchTokenBalance(e,t){let a=this.api.query.Tokens.Accounts;return D(()=>a.watchValue(e,t,"best")).pipe(B(s=>({id:t,balance:this.getBreakdown(s)})),M({error:s=>_.error("balance(token)",s)}))}watchTokensBalance(e){let t=this.api.query.Tokens.Accounts;return D(()=>t.watchEntries(e,{at:"best"})).pipe(me((a,s)=>!s.deltas),B(({deltas:a})=>{let s=[];return a?.deleted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(n=>{let[i,r]=n.args;s.push({id:r,balance:this.getBreakdown(n.value)})}),s}),M({error:a=>_.error("balance(tokens)",a)}))}watchErc20Balance(e,t){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let n=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=n.filter(({value:i})=>i.asset_type.type==="Erc20").map(({keyArgs:i})=>{let[r]=i;return r}),this.erc20Ids},s=async n=>(await Promise.all(n.map(async r=>[r,await this.getBalanceData(e,r)]))).map(([r,c])=>({id:r,balance:c}));return D(()=>ue(t?Promise.resolve(t):a()).pipe(ge(n=>this.watcher.bestBlock$.pipe(ge(()=>ue(s(n))))),de([]),pe(2,1),B(([n,i],r)=>r===0?i.filter(c=>c.balance.total>0n):this.getDeltas(n,i)),me((n,i)=>i.length===0),M({error:n=>_.error("balance(erc20)",n)})))}async getBalanceData(e,t){let a=await this.api.apis.CurrenciesApi.account(t,e,{at:"best"});return this.getBreakdown(a)}getBreakdown(e){let t=e.free>=e.frozen?e.free-e.frozen:0n,a=e.free+e.reserved;return{free:e.free,reserved:e.reserved,frozen:e.frozen,total:a,transferable:t}}getDeltas(e,t){let a=(n,i)=>n!==void 0&&i!==void 0&&n.transferable===i.transferable&&n.total===i.total,s=e.reduce((n,i)=>(n.set(i.id,i.balance),n),new Map);return t.filter(n=>!a(n.balance,s.get(n.id)))}};import{BehaviorSubject as Qn}from"rxjs";import{log as ht}from"@galacticcouncil/common";var ns={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:ss}=ht;var{withTimeout:js}=q;import{calculate_in_given_out as Pi,calculate_lrna_in_given_out as Ti,calculate_out_given_in as Si,calculate_out_given_lrna_in as vi,calculate_spot_price as wi,calculate_lrna_spot_price as xi,calculate_shares as Ii,calculate_liquidity_out as Oi,calculate_liquidity_lrna_out as Ai,verify_asset_cap as Bi,calculate_liquidity_hub_in as _i,is_sell_allowed as Ri,is_buy_allowed as Fi,is_add_liquidity_allowed as Ei,is_remove_liquidity_allowed as Ci,recalculate_asset_fee as ki,recalculate_protocol_fee as Di}from"@galacticcouncil/math-omnipool";import Li from"big.js";import{big as Gi}from"@galacticcouncil/common";var{FeeUtils:Zi}=p;import{AccountId as ir,Binary as yt,CompatibilityLevel as rr,Enum as ft}from"polkadot-api";import{toHex as lr}from"@polkadot-api/utils";import{Subscription as ur,distinctUntilChanged as pr,filter as mr,finalize as dr,map as gr,merge as hr,tap as br}from"rxjs";import{HYDRATION_SS58_PREFIX as fr}from"@galacticcouncil/common";var{FeeUtils:Ar}=p,Br=yt.fromText("omnipool"),_r=ft("Short");import{calculate_in_given_out as Lr,calculate_out_given_in as Hr,calculate_amplification as qr,calculate_add_one_asset as Nr,calculate_liquidity_out_one_asset as Gr,calculate_shares as Ur,calculate_shares_for_amount as Vr,calculate_spot_price_with_fee as Wr,pool_account_name as $r,recalculate_peg as Xr}from"@galacticcouncil/math-stableswap";import{RUNTIME_DECIMALS as jr,big as Qr}from"@galacticcouncil/common";var{FeeUtils:mo}=p;import{AccountId as yo,CompatibilityLevel as fo}from"polkadot-api";import{toHex as To}from"@polkadot-api/utils";import{blake2b as vo}from"@noble/hashes/blake2b";import{Subscription as xo,distinctUntilChanged as Io,map as Oo,merge as Ao,tap as Bo}from"rxjs";import{HYDRATION_SS58_PREFIX as Ro,RUNTIME_DECIMALS as Fo}from"@galacticcouncil/common";var{FeeUtils:Uo}=p;import{calculate_in_given_out as jo,calculate_out_given_in as Qo,calculate_pool_trade_fee as Jo,get_spot_price as Zo,calculate_liquidity_in as el,calculate_shares as tl,calculate_spot_price as al,calculate_spot_price_with_fee as nl,calculate_liquidity_out_asset_a as sl,calculate_liquidity_out_asset_b as il}from"@galacticcouncil/math-xyk";import{big as pl}from"@galacticcouncil/common";var{FeeUtils:wl}=p;import{CompatibilityLevel as Al}from"polkadot-api";import{Subscription as _l}from"rxjs";import{big as $l,RUNTIME_DECIMALS as Xl}from"@galacticcouncil/common";import{AccountId as oc}from"polkadot-api";import{toHex as cc}from"@polkadot-api/utils";import{Subscription as pc,filter as mc,map as dc}from"rxjs";import{decodeEventLog as hc}from"viem";import{erc20 as xt,HYDRATION_SS58_PREFIX as yc}from"@galacticcouncil/common";var{ERC20:xc}=xt;import{calculate_collateral_in_given_hollar_out as Fc,calculate_collateral_out_given_hollar_in as Ec,calculate_hollar_in_given_collateral_out as Cc,calculate_hollar_out_given_collateral_in as kc,calculate_imbalance as Dc,calculate_max_price as Mc,calculate_buyback_limit as Lc,calculate_buyback_price_with_fee as Hc}from"@galacticcouncil/math-hsm";import{big as Vc,RUNTIME_DECIMALS as Wc}from"@galacticcouncil/common";var{FeeUtils:tu}=p;import{AccountId as gu,CompatibilityLevel as hu}from"polkadot-api";import{toHex as fu}from"@polkadot-api/utils";import{Subscription as Su,combineLatest as vu,filter as wu,map as xu,pairwise as Iu}from"rxjs";import{decodeEventLog as Au}from"viem";import{h160 as Bt,HYDRATION_SS58_PREFIX as _u}from"@galacticcouncil/common";var{FeeUtils:Mu}=p,{H160:Lu}=Bt;import{log as Rt}from"@galacticcouncil/common";import{Subject as Sp,Subscription as vp,takeUntil as wp}from"rxjs";var{logger:qp}=Rt;import{big as Om,RUNTIME_DECIMALS as Am}from"@galacticcouncil/common";var{FeeUtils:Um}=p;import{big as ld}from"@galacticcouncil/common";import{Enum as ye}from"polkadot-api";var I=class{static build(e){return e.map(({assetIn:t,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:ye("Stableswap",n),asset_in:t,asset_out:a}:{pool:ye(s),asset_in:t,asset_out:a})}};import{Enum as we}from"polkadot-api";var fe=[{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 J=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Pe="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",Z="0x112b087b60C1a166130d59266363C45F8aa99db0",ee="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",Te=1000000n;var Hd=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var U=class{client;constructor(e){this.client=e.getWsProvider()}async getBlockTimestamp(){let e=await this.client.getBlock();return Number(e.timestamp)}async getReservesData(){return await this.client.readContract({abi:J,address:Z,args:[ee],functionName:"getReservesData"})}async getUserReservesData(e){return await this.client.readContract({abi:J,address:Z,args:[ee,e],functionName:"getUserReservesData"})}async getUserAccountData(e){return await this.client.readContract({abi:fe,address:Pe,args:[e],functionName:"getUserAccountData"})}};import d from"big.js";import{big as A,erc20 as qt,h160 as Nt}from"@galacticcouncil/common";var{ERC20:F}=qt,{H160:te}=Nt,Gt=1.01,Ut=31536000n,Se=4,V=-1,W=10n**27n,$=class{client;constructor(e){this.client=new U(e)}async getSummary(e){let t=te.fromAny(e),[a,s,n,i]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(t),this.client.getUserAccountData(t),this.client.getBlockTimestamp()]),[r]=a,[c,u]=s,[o,g,h,w,f,P]=n,S=A.toDecimal(P,18),x=[];for(let v of c){let O=v.underlyingAsset.toLowerCase(),b=r.find(({underlyingAsset:ke})=>ke.toLowerCase()===O);if(!b)throw new Error("Missing pool reserve for "+O);let z=v.scaledATokenBalance,C=b.liquidityIndex,xe=b.liquidityRate,Ie=b.availableLiquidity,Oe=b.priceInMarketReferenceCurrency,Ae=i+6,Be=this.calculateLinearInterest(xe,b.lastUpdateTimestamp,Ae),_e=C*Be/W,Re=z*_e/W,Fe=Number(u!==0&&u===b.eModeCategoryId?b.eModeLiquidationThreshold:b.reserveLiquidationThreshold)/1e4,Ee=b.usageAsCollateralEnabled&&v.usageAsCollateralEnabledOnUser&&v.scaledATokenBalance>0n,Ce=F.toAssetId(O);x.push({aTokenBalance:Re,availableLiquidity:Ie,decimals:Number(b.decimals),isCollateral:Ee,priceInRef:Oe,reserveId:Ce,reserveAsset:O,reserveLiquidationThreshold:Fe})}return{healthFactor:Number(S),currentLiquidationThreshold:Number(A.toDecimal(w,Se)),totalCollateral:o,totalDebt:g,reserves:x}}async hasBorrowPositions(e){let t=te.fromAny(e),a=await this.client.getUserAccountData(t),[s,n]=a;return n>0n}async getHealthFactor(e){let t=te.fromAny(e),a=await this.client.getUserAccountData(t),[s,n,i,r,c,u]=a;return this.calculateHealthFactorFromBalances(n,s,r)}async getHealthFactorAfterWithdraw(e,t,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(e);if(n===0n)return V;let c=F.fromAssetId(t),u=i.find(O=>O.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,isCollateral:g,priceInRef:h,reserveLiquidationThreshold:w}=u,f=A.toBigInt(a,o),P=g?f*h/10n**BigInt(o):0n,S=s-P;if(S<=0n)return 0;let x=d(s.toString()).mul(r).minus(d(P.toString()).mul(w)).div(S.toString()),v=d(S.toString()).mul(x).div(n.toString()).toFixed(6,d.roundDown);return Number(v)}async getHealthFactorAfterSupply(e,t,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(e);if(n===0n)return V;let c=F.fromAssetId(t),u=i.find(v=>v.reserveAsset===c);if(!u)throw new Error("Missing reserve ctx for "+c);let{decimals:o,priceInRef:g,reserveLiquidationThreshold:h}=u,f=A.toBigInt(a,o)*g/10n**BigInt(o),P=s+f;if(P<=0n)return 0;let S=d(s.toString()).mul(r).plus(d(f.toString()).mul(h)).div(P.toString()),x=d(P.toString()).mul(S).div(n.toString()).toFixed(6,d.roundDown);return Number(x)}async getHealthFactorAfterSwap(e,t,a,s,n){let{totalDebt:i,reserves:r,healthFactor:c}=await this.getSummary(e);if(i===0n)return V;let u=F.fromAssetId(a),o=F.fromAssetId(n),g=r.find(C=>C.reserveAsset===u),h=r.find(C=>C.reserveAsset===o);if(!g)throw new Error(`Missing reserve ctx for ${u}`);if(!h)throw new Error(`Missing reserve ctx for ${h}`);let w=A.toBigInt(t,g.decimals),f=A.toBigInt(s,h.decimals),P=w*g.priceInRef/10n**BigInt(g.decimals),S=f*h.priceInRef/10n**BigInt(h.decimals),x=g.isCollateral?d(P.toString()).mul(g.reserveLiquidationThreshold):d(0),b=(h.isCollateral?d(S.toString()).mul(h.reserveLiquidationThreshold):d(0)).minus(x).div(i.toString()),z=d(c).plus(b).toFixed(6,d.roundDown);return Number(z)}async getMaxWithdraw(e,t){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(e),i=F.fromAssetId(t),r=s.find(c=>c.reserveAsset===i);if(!r)throw new Error("Missing reserve ctx for "+i);return this.calculateWithdrawMax(r,a,n)}async getMaxWithdrawAll(e){let{totalDebt:t,reserves:a,healthFactor:s}=await this.getSummary(e),n={};for(let i of a){let r=this.calculateWithdrawMax(i,t,s);i.reserveId&&(n[i.reserveId]=r)}return n}calculateWithdrawMax(e,t,a){let{aTokenBalance:s,availableLiquidity:n,decimals:i,priceInRef:r,reserveLiquidationThreshold:c,isCollateral:u}=e,o=s;if(u&&t>0n){let h=a-Gt;if(h>0){let w=d(h).mul(t.toString()).div(c).toFixed(0,d.roundDown),f=d(w).div(r.toString()).mul(10**i).toFixed(0,d.roundDown);o=s<BigInt(f)?s:BigInt(f)}else o=0n}return{amount:o<n?o:n,decimals:i}}calculateLinearInterest(e,t,a){let s=a-t;if(s<=0)return W;let n=e*BigInt(s)/Ut;return W+n}calculateHealthFactorFromBalances(e,t,a){if(e===0n)return V;let s=t*a/e,n=A.toDecimal(s,Se);return Number(n)}};function ve(l){let e=[],t=l;for(;t&&typeof t=="object"&&"type"in t;)e.push(t.type),t=t.value;return e.join(".")}var E=class extends T{evm;evmClient;balance;aaveUtils;constructor(e,t){super(e),this.evm=t,this.evmClient=t.getWsProvider(),this.balance=new R(e),this.aaveUtils=new $(t)}wrapTx(e,t){return{name:e,get:()=>t,dryRun:a=>this.dryRun(a,t)}}async dispatchWithExtraGas(e){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:e.decodedCall,extra_gas:Te})}async dryRun(e,t){let a=we("Signed",e),s=we("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,t.decodedCall),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let c=ve(r.value);throw new Error("Dry run execution error!",{cause:c})}return i}isDirectOmnipoolTrade(e){return e.length===1&&e[0].pool==="Omnipool"}};var X=class extends E{_trade;_beneficiary;_slippagePct=1;setTrade(e){return this._trade=e,this}withBeneficiary(e){return this._beneficiary=e,this}withSlippage(e){return this._slippagePct=e,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:e,swaps:t,type:a}=this.trade;if(a==="Buy")return this.buildBuyTx();let{assetIn:s}=t[0],n=await this.balance.getBalance(this.beneficiary,s);return e>=n.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:e,amountOut:t,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=y.getFraction(e,this.slippagePct),r=s.assetIn,c=n.assetOut,u=e+i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.buy({asset_in:r,asset_out:c,amount:t,max_sell_amount:u}):o=this.api.tx.Router.buy({asset_in:r,asset_out:c,amount_out:t,max_amount_in:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterBuy",o)}async buildSellTx(){let{amountIn:e,amountOut:t,swaps:a}=this.trade,s=a[0],n=a[a.length-1],i=y.getFraction(t,this.slippagePct),r=s.assetIn,c=n.assetOut,u=t-i,o;return this.isDirectOmnipoolTrade(a)?o=this.api.tx.Omnipool.sell({asset_in:r,asset_out:c,amount:e,min_buy_amount:u}):o=this.api.tx.Router.sell({asset_in:r,asset_out:c,amount_in:e,min_amount_out:u,route:I.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("RouterSell",o)}async buildSellAllTx(){let{amountOut:e,swaps:t}=this.trade,a=t[0],s=t[t.length-1],n=y.getFraction(e,this.slippagePct),i=a.assetIn,r=s.assetOut,c=e-n,u=this.api.tx.Router.sell_all({asset_in:i,asset_out:r,min_amount_out:c,route:I.build(t)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};import{Enum as ae}from"polkadot-api";var Y=class extends E{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(e){return this._order=e,this}withBeneficiary(e){return this._beneficiary=e,this}withMaxRetries(e){return this._maxRetries=e,this}withSlippage(e){return this._slippagePct=e,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:e}=this.order;switch(e){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${e}`)}}async buildDcaTx(){let{amountIn:e,assetIn:t,assetOut:a,tradeAmountIn:s,tradePeriod:n,tradeRoute:i}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:n,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ae("Sell",{asset_in:t,asset_out:a,amount_in:s,min_amount_out:0n,route:i})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(r=await this.dispatchWithExtraGas(r)),this.wrapTx("DcaSchedule",r)}async buildTwapSellTx(){let{amountIn:e,assetIn:t,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(n,this.slippagePct),u=n-c,o=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ae("Sell",{asset_in:t,asset_out:a,amount_in:s,min_amount_out:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapSell",o)}async buildTwapBuyTx(){let{amountIn:e,assetIn:t,assetOut:a,tradeAmountIn:s,tradeAmountOut:n,tradePeriod:i,tradeRoute:r}=this.order,c=y.getFraction(s,this.slippagePct),u=s+c,o=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:i,max_retries:this.maxRetries,total_amount:e,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:ae("Buy",{asset_in:t,asset_out:a,amount_out:n,max_amount_in:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(o=await this.dispatchWithExtraGas(o)),this.wrapTx("DcaSchedule.twapBuy",o)}};var ne=class{client;evmClient;constructor(e,t){this.client=e,this.evmClient=t}trade(e){return new X(this.client,this.evmClient).setTrade(e)}order(e){return new Y(this.client,this.evmClient).setOrder(e)}};export{ne as TxBuilderFactory};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@galacticcouncil/sdk-next",
3
- "version": "0.41.0",
3
+ "version": "0.41.1",
4
4
  "description": "Galactic next gen sdk (papi)",
5
5
  "author": "GalacticCouncil",
6
6
  "repository": {