@galacticcouncil/sdk-next 1.0.0 → 1.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/client/index.cjs +1 -1
- package/build/client/index.mjs +1 -1
- package/build/farm/index.cjs +1 -1
- package/build/farm/index.mjs +1 -1
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.mjs +1 -1
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/staking/index.cjs +1 -1
- package/build/staking/index.mjs +1 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +1 -1
package/build/sor/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var Ut=Object.defineProperty;var X=(u,t)=>{for(var e in t)Ut(u,e,{get:t[e],enumerable:!0})};import $t from"buffer";typeof window<"u"&&(window.Buffer=$t.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 Xt=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>Xt)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 Yt,calculate_out_given_in as zt,calculate_linear_weights as Kt,calculate_pool_trade_fee as jt,get_spot_price as Qt}from"@galacticcouncil/math-lbp";var E=class{static getSpotPrice(t,e,s,a,i){return Qt(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i){return Yt(t,e,s,a,i)}static calculateOutGivenIn(t,e,s,a,i){return zt(t,e,s,a,i)}static calculateLinearWeights(t,e,s,a,i){return Kt(t,e,s,a,i)}static calculatePoolTradeFee(t,e,s){return jt(t,e,s)}};import{big as wt,RUNTIME_DECIMALS as Ot}from"@galacticcouncil/common";var at={};X(at,{withTimeout:()=>Jt});function Jt(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:()=>te,getFraction:()=>ee,mulScaled:()=>St,mulSpot:()=>Zt});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 Zt(u,t,e,s){return St(u,t,e,ft,s)}function te(u,t,e,s){if(t===0n)return 0n;let a=BigInt(10)**BigInt(ft+s-e);return u*a/t}function ee(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:()=>ie});import ae 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 ie(u,t){let e=ae(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var K={};X(K,{findNestedKey:()=>ne,findNestedObj:()=>re,jsonFormatter:()=>oe});var ne=(u,t)=>{let e=[];return JSON.stringify(u,(s,a)=>(a&&a[t]&&e.push(a),a)),e[0]},re=(u,t,e)=>{let s;return JSON.stringify(u,(a,i)=>(i&&i[t]===e&&(s=i),i)),s},oe=(u,t)=>typeof t=="bigint"?t.toString():t;var v={};X(v,{calculateBuyFee:()=>pe,calculateDiffToAvg:()=>le,calculateDiffToRef:()=>ce,calculateSellFee:()=>ue});import k from"big.js";function le(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 ce(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 ue(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 pe(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:vt}=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=vt.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=vt.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 ar}from"polkadot-api";import{Subscription as nr,distinctUntilChanged as rr,filter as or,map as lr}from"rxjs";import{memoize1 as dn}from"@thi.ng/memoize";import{TLRUCache as hn}from"@thi.ng/cache";import{ReplaySubject as fn,Subscription as Sn,combineLatest as In,defer as wn,from as On,interval as vn,merge as Tn,of as xn,EMPTY as Bn}from"rxjs";import{bufferCount as Fn,bufferTime as _n,catchError as Rn,filter as En,finalize as kn,map as Cn,pairwise as Mn,repeat as Ln,skip as Dn,share as Hn,startWith as Nn,switchMap as qn,tap as Gn,throttleTime as Vn}from"rxjs/operators";import{hydration as Wa,hydrationNext as Ua}from"@galacticcouncil/descriptors";import{log as me}from"@galacticcouncil/common";import{map as Ca,shareReplay as Ma,tap as La}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 va,skip as Ta,switchMap as xa,timeout as Ba}from"rxjs/operators";var{logger:Ha}=me;import{getWsProvider as Ka}from"polkadot-api/ws";import{withLogsRecorder as Qa}from"polkadot-api/logs-provider";import{getSmProvider as ei}from"polkadot-api/sm-provider";import{Binary as gi}from"polkadot-api";import{log as de}from"@galacticcouncil/common";import{combineLatest as Ii,concat as wi,defer as Oi,from as vi}from"rxjs";import{bufferCount as xi,distinctUntilChanged as Bi,debounceTime as Ai,map as Fi,retry as _i,startWith as Ri,switchMap as Ei,tap as ki,take as Ci,skip as Mi,connect as Li}from"rxjs/operators";var{logger:Ni}=de;import{BehaviorSubject as Zi}from"rxjs";import{log as he}from"@galacticcouncil/common";var rn={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:on}=he;var{withTimeout:Zn}=at;import{calculate_in_given_out as Pe,calculate_lrna_in_given_out as ye,calculate_out_given_in as fe,calculate_out_given_lrna_in as Se,calculate_spot_price as Ie,calculate_lrna_spot_price as we,calculate_shares as Oe,calculate_liquidity_out as ve,calculate_liquidity_lrna_out as Te,verify_asset_cap as xe,calculate_liquidity_hub_in as Be,is_sell_allowed as Ae,is_buy_allowed as Fe,is_add_liquidity_allowed as _e,is_remove_liquidity_allowed as Re,recalculate_asset_fee as Ee,recalculate_protocol_fee as ke}from"@galacticcouncil/math-omnipool";import G from"big.js";var f=class{static calculateSpotPrice(t,e,s,a){return Ie(t,e,s,a)}static calculateLrnaSpotPrice(t,e){return we(t,e)}static calculateInGivenOut(t,e,s,a,i,n,r,o,l,c){return Pe(t,e,s,a,i,n,r,o,l,c)}static calculateLrnaInGivenOut(t,e,s,a,i,n){return ye(t,e,s,a,i,n)}static calculateOutGivenIn(t,e,s,a,i,n,r,o,l,c){return fe(t,e,s,a,i,n,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,s,a,i,n){return Se(t,e,s,a,i,n)}static calculateShares(t,e,s,a){return Oe(t,e,s,a)}static calculateLiquidityOut(t,e,s,a,i,n,r,o){return ve(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 Be(t,e,s,a)}static isSellAllowed(t){return Ae(t)}static isBuyAllowed(t){return Fe(t)}static isAddLiquidityAllowed(t){return _e(t)}static isRemoveLiquidityAllowed(t){return Re(t)}static recalculateAssetFee(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 recalculateProtocolFee(t,e,s,a,i,n,r,o,l,c,m){return ke(t,e,s,a,i,n,r,o,l,c,m)}static verifyAssetCap(t,e,s,a){return xe(t,e,s,a)}};import{big as Ce}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:v.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=v.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=Ce.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as Wr,Binary as Tt,CompatibilityLevel as Ur,Enum as Me}from"polkadot-api";import{toHex as Yr}from"@polkadot-api/utils";import{Subscription as Kr,distinctUntilChanged as jr,filter as Qr,finalize as Jr,map as Zr,merge as to,tap as eo}from"rxjs";import{HYDRATION_SS58_PREFIX as ao}from"@galacticcouncil/common";var{FeeUtils:mo}=S,go=Tt.toHex(Tt.fromText("omnipool")),ho=Me("Short");import{calculate_in_given_out as De,calculate_out_given_in as He,calculate_amplification as Ne,calculate_add_one_asset as qe,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 Ne(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 qe(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 xt}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:v.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=v.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*xt.pow10(Ye-i):s?t/xt.pow10(i-a):t}};import{AccountId as Wo,CompatibilityLevel as Uo}from"polkadot-api";import{toHex as Xo}from"@polkadot-api/utils";import{blake2b as zo}from"@noble/hashes/blake2b";import{Subscription as jo,distinctUntilChanged as Qo,map as Jo,merge as Zo,tap as tl}from"rxjs";import{HYDRATION_SS58_PREFIX as sl,RUNTIME_DECIMALS as al}from"@galacticcouncil/common";var{FeeUtils:gl}=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:Bt}=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=Bt.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=Bt.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 ql}from"polkadot-api";import{Subscription as Vl}from"rxjs";import{big as At,RUNTIME_DECIMALS as Ft}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 At.toBigInt(1,Ft)}spotPriceOutGivenIn(t){return At.toBigInt(1,Ft)}calculateTradeFee(t,e){return 0n}};import{AccountId as yc,Binary as fc}from"polkadot-api";import{toHex as Ic}from"@polkadot-api/utils";import{Subscription as Oc,filter as vc,map as Tc,mergeMap as xc}from"rxjs";import{decodeEventLog as Ac}from"viem";import{erc20 as os,HYDRATION_SS58_PREFIX as _c}from"@galacticcouncil/common";var{ERC20:Dc}=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 hu,Binary as bu,CompatibilityLevel as Pu}from"polkadot-api";import{toHex as Su}from"@polkadot-api/utils";import{Subscription as Ou,combineLatest as vu,filter as Tu,map as xu,mergeMap as Bu,pairwise as Au}from"rxjs";import{decodeEventLog as _u}from"viem";import{h160 as ys,HYDRATION_SS58_PREFIX as Eu}from"@galacticcouncil/common";var{FeeUtils:Nu}=S,{H160:qu}=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 fp,Subscription as Sp,takeUntil as Ip}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:Dp}=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 Rt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Rt||{}),Et=(s=>(s.Dca="Dca",s.TwapSell="TwapSell",s.TwapBuy="TwapBuy",s))(Et||{}),kt=(s=>(s.OrderTooSmall="OrderTooSmall",s.OrderTooBig="OrderTooBig",s.OrderImpactTooBig="OrderImpactTooBig",s))(kt||{});var{FeeUtils:Ct}=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?Ct.toPct(t.min):void 0,a=t.max?Ct.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:v.calculateSellFee(o,r),h=A.mulSpot(s.amountIn,n,s.assetInDecimals,a.assetOutDecimals),d=v.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=v.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:v.calculateBuyFee(o,r),h=A.mulSpot(s.amountOut,n,s.assetOutDecimals,a.assetInDecimals),d;return o===0n?d=-100:d=v.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=v.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 Mt=6e3,Lt=1000000000000000n,st=6,ht=-5,bt=216e5,Nm=3,Dt=.1,Ht=6;import{Enum as Nt}from"polkadot-api";var D=class{static build(t){return t.map(({assetIn:e,assetOut:s,pool:a,poolId:i})=>a==="Stableswap"?{pool:Nt("Stableswap",i),asset_in:e,asset_out:s}:{pool:Nt(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??Lt})}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),T=await this.router.getBestSell(t,e,x),H=r<g,N=[];H&&N.push("OrderTooSmall");let M=T.amountOut*BigInt(P),Gt=this.toBlockPeriod(_),Vt=T.tradeFee*BigInt(P),Wt=D.build(o),yt={assetIn:t,assetOut:e,errors:N,maxTradeCount:b,tradeCount:P,tradeFee:Vt,tradeImpactPct:T.priceImpactPct,tradePeriod:Gt,tradeRoute:Wt,type:"Dca"};return{...yt,amountIn:r,amountOut:M,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...yt,amountIn:O.toDecimal(r,h),amountOut:O.toDecimal(M,d),tradeAmountIn:O.toDecimal(T.amountIn,h),tradeAmountOut:O.toDecimal(T.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 T=p.amountOut*BigInt(d),H=p.tradeFee*BigInt(d),N=D.build(n),M={assetIn:t,assetOut:e,errors:x,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapSell"};return{...M,amountIn:i,amountOut:T,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(i,c),amountOut:O.toDecimal(T,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,T=[];_||P?T.push("OrderTooSmall"):x&&T.push("OrderImpactTooBig");let H=p.tradeFee*BigInt(d),N=D.build(n),M={assetIn:t,assetOut:e,errors:T,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:N,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{Dt as DCA_TIME_RESERVE,Mt as DEFAULT_BLOCK_TIME,Lt as DEFAULT_MIN_BUDGET,Ht as ORDER_MIN_BLOCK_PERIOD,tt as Router,st as TWAP_EXECUTION_INTERVAL,bt as TWAP_MAX_DURATION,ht as TWAP_MAX_PRICE_IMPACT,Nm as TWAP_TX_MULTIPLIER,kt as TradeOrderError,Et as TradeOrderType,D as TradeRouteBuilder,et as TradeRouter,Pt as TradeScheduler,Rt as TradeType};
|
|
1
|
+
var Ut=Object.defineProperty;var X=(u,t)=>{for(var e in t)Ut(u,e,{get:t[e],enumerable:!0})};import $t from"buffer";typeof window<"u"&&(window.Buffer=$t.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 Xt=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>Xt)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 Yt,calculate_out_given_in as zt,calculate_linear_weights as Kt,calculate_pool_trade_fee as jt,get_spot_price as Qt}from"@galacticcouncil/math-lbp";var E=class{static getSpotPrice(t,e,s,a,i){return Qt(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i){return Yt(t,e,s,a,i)}static calculateOutGivenIn(t,e,s,a,i){return zt(t,e,s,a,i)}static calculateLinearWeights(t,e,s,a,i){return Kt(t,e,s,a,i)}static calculatePoolTradeFee(t,e,s){return jt(t,e,s)}};import{big as wt,RUNTIME_DECIMALS as Ot}from"@galacticcouncil/common";var at={};X(at,{withTimeout:()=>Jt});function Jt(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:()=>te,getFraction:()=>ee,mulScaled:()=>St,mulSpot:()=>Zt});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 Zt(u,t,e,s){return St(u,t,e,ft,s)}function te(u,t,e,s){if(t===0n)return 0n;let a=BigInt(10)**BigInt(ft+s-e);return u*a/t}function ee(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:()=>ie});import ae 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 ie(u,t){let e=ae(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var K={};X(K,{findNestedKey:()=>ne,findNestedObj:()=>re,jsonFormatter:()=>oe});var ne=(u,t)=>{let e=[];return JSON.stringify(u,(s,a)=>(a&&a[t]&&e.push(a),a)),e[0]},re=(u,t,e)=>{let s;return JSON.stringify(u,(a,i)=>(i&&i[t]===e&&(s=i),i)),s},oe=(u,t)=>typeof t=="bigint"?t.toString():t;var v={};X(v,{calculateBuyFee:()=>pe,calculateDiffToAvg:()=>le,calculateDiffToRef:()=>ce,calculateSellFee:()=>ue});import k from"big.js";function le(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 ce(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 ue(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 pe(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:vt}=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=vt.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=vt.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,map as rr}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 vn,EMPTY as Tn}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 Nn,throttleTime as qn}from"rxjs/operators";import{hydration as Wa,hydrationNext as Ua}from"@galacticcouncil/descriptors";import{log as me}from"@galacticcouncil/common";import{map as Ca,shareReplay as Ma,tap as La}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 va,skip as Ta,switchMap as xa,timeout as Ba}from"rxjs/operators";var{logger:Ha}=me;import{getWsProvider as Ka}from"polkadot-api/ws";import{withLogsRecorder as Qa}from"polkadot-api/logs-provider";import{Binary as mi}from"polkadot-api";import{log as de}from"@galacticcouncil/common";import{combineLatest as fi,concat as Si,defer as Ii,from as wi}from"rxjs";import{bufferCount as vi,distinctUntilChanged as Ti,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}=de;import{BehaviorSubject as Qi}from"rxjs";import{log as he}from"@galacticcouncil/common";var an={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:nn}=he;var{withTimeout:Qn}=at;import{calculate_in_given_out as Pe,calculate_lrna_in_given_out as ye,calculate_out_given_in as fe,calculate_out_given_lrna_in as Se,calculate_spot_price as Ie,calculate_lrna_spot_price as we,calculate_shares as Oe,calculate_liquidity_out as ve,calculate_liquidity_lrna_out as Te,verify_asset_cap as xe,calculate_liquidity_hub_in as Be,is_sell_allowed as Ae,is_buy_allowed as Fe,is_add_liquidity_allowed as _e,is_remove_liquidity_allowed as Re,recalculate_asset_fee as Ee,recalculate_protocol_fee as ke}from"@galacticcouncil/math-omnipool";import G from"big.js";var f=class{static calculateSpotPrice(t,e,s,a){return Ie(t,e,s,a)}static calculateLrnaSpotPrice(t,e){return we(t,e)}static calculateInGivenOut(t,e,s,a,i,n,r,o,l,c){return Pe(t,e,s,a,i,n,r,o,l,c)}static calculateLrnaInGivenOut(t,e,s,a,i,n){return ye(t,e,s,a,i,n)}static calculateOutGivenIn(t,e,s,a,i,n,r,o,l,c){return fe(t,e,s,a,i,n,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,s,a,i,n){return Se(t,e,s,a,i,n)}static calculateShares(t,e,s,a){return Oe(t,e,s,a)}static calculateLiquidityOut(t,e,s,a,i,n,r,o){return ve(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 Be(t,e,s,a)}static isSellAllowed(t){return Ae(t)}static isBuyAllowed(t){return Fe(t)}static isAddLiquidityAllowed(t){return _e(t)}static isRemoveLiquidityAllowed(t){return Re(t)}static recalculateAssetFee(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 recalculateProtocolFee(t,e,s,a,i,n,r,o,l,c,m){return ke(t,e,s,a,i,n,r,o,l,c,m)}static verifyAssetCap(t,e,s,a){return xe(t,e,s,a)}};import{big as Ce}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:v.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=v.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=Ce.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as Gr,Binary as Tt,CompatibilityLevel as Vr,Enum as Me}from"polkadot-api";import{toHex as $r}from"@polkadot-api/utils";import{Subscription as Yr,distinctUntilChanged as zr,filter as Kr,finalize as jr,map as Qr,merge as Jr,tap as Zr}from"rxjs";import{HYDRATION_SS58_PREFIX as eo}from"@galacticcouncil/common";var{FeeUtils:uo}=S,po=Tt.toHex(Tt.fromText("omnipool")),mo=Me("Short");import{calculate_in_given_out as De,calculate_out_given_in as He,calculate_amplification as Ne,calculate_add_one_asset as qe,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 Ne(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 qe(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 xt}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:v.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=v.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*xt.pow10(Ye-i):s?t/xt.pow10(i-a):t}};import{AccountId as Go,CompatibilityLevel as Vo}from"polkadot-api";import{toHex as Uo}from"@polkadot-api/utils";import{blake2b as Xo}from"@noble/hashes/blake2b";import{Subscription as zo,distinctUntilChanged as Ko,map as jo,merge as Qo,tap as Jo}from"rxjs";import{HYDRATION_SS58_PREFIX as tl,RUNTIME_DECIMALS as el}from"@galacticcouncil/common";var{FeeUtils:ml}=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:Bt}=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=Bt.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=Bt.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 Hl}from"polkadot-api";import{Subscription as ql}from"rxjs";import{big as At,RUNTIME_DECIMALS as Ft}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 At.toBigInt(1,Ft)}spotPriceOutGivenIn(t){return At.toBigInt(1,Ft)}calculateTradeFee(t,e){return 0n}};import{AccountId as bc,Binary as Pc}from"polkadot-api";import{toHex as fc}from"@polkadot-api/utils";import{Subscription as Ic,filter as wc,map as Oc,mergeMap as vc}from"rxjs";import{decodeEventLog as xc}from"viem";import{erc20 as os,HYDRATION_SS58_PREFIX as Ac}from"@galacticcouncil/common";var{ERC20:Mc}=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 du,Binary as gu,CompatibilityLevel as hu}from"polkadot-api";import{toHex as yu}from"@polkadot-api/utils";import{Subscription as Iu,combineLatest as wu,filter as Ou,map as vu,mergeMap as Tu,pairwise as xu}from"rxjs";import{decodeEventLog as Au}from"viem";import{h160 as ys,HYDRATION_SS58_PREFIX as _u}from"@galacticcouncil/common";var{FeeUtils:Du}=S,{H160:Hu}=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 yp,takeUntil as fp}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:Mp}=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 Rt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Rt||{}),Et=(s=>(s.Dca="Dca",s.TwapSell="TwapSell",s.TwapBuy="TwapBuy",s))(Et||{}),kt=(s=>(s.OrderTooSmall="OrderTooSmall",s.OrderTooBig="OrderTooBig",s.OrderImpactTooBig="OrderImpactTooBig",s))(kt||{});var{FeeUtils:Ct}=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?Ct.toPct(t.min):void 0,a=t.max?Ct.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:v.calculateSellFee(o,r),h=A.mulSpot(s.amountIn,n,s.assetInDecimals,a.assetOutDecimals),d=v.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=v.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:v.calculateBuyFee(o,r),h=A.mulSpot(s.amountOut,n,s.assetOutDecimals,a.assetInDecimals),d;return o===0n?d=-100:d=v.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=v.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 Mt=6e3,Lt=1000000000000000n,st=6,ht=-5,bt=216e5,Dm=3,Dt=.1,Ht=6;import{Enum as Nt}from"polkadot-api";var D=class{static build(t){return t.map(({assetIn:e,assetOut:s,pool:a,poolId:i})=>a==="Stableswap"?{pool:Nt("Stableswap",i),asset_in:e,asset_out:s}:{pool:Nt(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??Lt})}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),T=await this.router.getBestSell(t,e,x),H=r<g,N=[];H&&N.push("OrderTooSmall");let M=T.amountOut*BigInt(P),Gt=this.toBlockPeriod(_),Vt=T.tradeFee*BigInt(P),Wt=D.build(o),yt={assetIn:t,assetOut:e,errors:N,maxTradeCount:b,tradeCount:P,tradeFee:Vt,tradeImpactPct:T.priceImpactPct,tradePeriod:Gt,tradeRoute:Wt,type:"Dca"};return{...yt,amountIn:r,amountOut:M,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...yt,amountIn:O.toDecimal(r,h),amountOut:O.toDecimal(M,d),tradeAmountIn:O.toDecimal(T.amountIn,h),tradeAmountOut:O.toDecimal(T.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 T=p.amountOut*BigInt(d),H=p.tradeFee*BigInt(d),N=D.build(n),M={assetIn:t,assetOut:e,errors:x,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapSell"};return{...M,amountIn:i,amountOut:T,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(i,c),amountOut:O.toDecimal(T,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,T=[];_||P?T.push("OrderTooSmall"):x&&T.push("OrderImpactTooBig");let H=p.tradeFee*BigInt(d),N=D.build(n),M={assetIn:t,assetOut:e,errors:T,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:N,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{Dt as DCA_TIME_RESERVE,Mt as DEFAULT_BLOCK_TIME,Lt as DEFAULT_MIN_BUDGET,Ht as ORDER_MIN_BLOCK_PERIOD,tt as Router,st as TWAP_EXECUTION_INTERVAL,bt as TWAP_MAX_DURATION,ht as TWAP_MAX_PRICE_IMPACT,Dm as TWAP_TX_MULTIPLIER,kt as TradeOrderError,Et as TradeOrderType,D as TradeRouteBuilder,et as TradeRouter,Pt as TradeScheduler,Rt as TradeType};
|
package/build/staking/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var et=Object.create;var v=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var rt=(n,t)=>{for(var e in t)v(n,e,{get:t[e],enumerable:!0})},$=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of ot(t))!at.call(n,c)&&c!==e&&v(n,c,{get:()=>t[c],enumerable:!(o=nt(t,c))||o.enumerable});return n};var st=(n,t,e)=>(e=n!=null?et(it(n)):{},$(t||!n||!n.__esModule?v(e,"default",{value:n,enumerable:!0}):e,n)),ct=n=>$(v({},"__esModule",{value:!0}),n);var
|
|
1
|
+
"use strict";var et=Object.create;var v=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var rt=(n,t)=>{for(var e in t)v(n,e,{get:t[e],enumerable:!0})},$=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of ot(t))!at.call(n,c)&&c!==e&&v(n,c,{get:()=>t[c],enumerable:!(o=nt(t,c))||o.enumerable});return n};var st=(n,t,e)=>(e=n!=null?et(it(n)):{},$(t||!n||!n.__esModule?v(e,"default",{value:n,enumerable:!0}):e,n)),ct=n=>$(v({},"__esModule",{value:!0}),n);var gt={};rt(gt,{BIG_10:()=>G,BIG_BILL:()=>N,StakingApi:()=>O,StakingClient:()=>E});module.exports=ct(gt);var l=require("@galacticcouncil/math-staking"),d=st(require("big.js"));var b={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},z=n=>Object.keys(b).includes(n);var F=require("polkadot-api"),Y=require("@polkadot-api/utils"),j=require("@galacticcouncil/common");function X(n){let t=("modl"+n).padEnd(32,"\0"),e=new TextEncoder().encode(t),o=(0,Y.toHex)(e);return(0,F.AccountId)(j.HYDRATION_SS58_PREFIX).dec(o)}var x="20000000000000000",A="2000",G=(0,d.default)(10),N=(0,d.default)(G.pow(12)),O=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=X(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,o]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let c=e.created_at,i=await o.reduce(async(a,[p,r])=>{let g=await a,S=p,P=r.amount,h=r.conviction.type.toLowerCase(),u=await this.client.getReferendumInfo(S);return u&&(u.type==="Approved"||u.type==="Rejected")&&z(h)&&g.push({id:S,amount:P,conviction:h}),g},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:c,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:i}}async getStake(t){let e=await this.client.getNFTCollectionId(),[o,c]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),i=c.find(a=>a)?.itemId;return{totalStake:o?.total_stake,accumulatedRewardPerStake:o?.accumulated_reward_per_stake,potReservedBalance:o?.pot_reserved_balance,positionId:i,stakePosition:i?await this.getStakingPosition(i):void 0}}getCurrentActionPoints(t,e,o,c){let i=(0,d.default)(0),a=(0,d.default)(0),p=b.locked6x,r=(0,d.default)(o.toString()).mul(p),g=100,S=[];t.forEach(u=>{let f=b[u.conviction],k=c.includes(u.id.toString());k&&S.push(u.id.toString());let w=(0,d.default)(u.amount.toString()).mul(g).div(r);i=i.plus(Math.floor(w.mul(f).toNumber())),a=a.plus(Math.floor(w.mul(k?p:f).toNumber()))});let P=Math.floor((0,d.default)(o.toString()).mul(p).mul(g).div(r).toNumber());c.forEach(u=>{S.includes(u)||(a=a.plus(P))});let h={democracyVote:1};return i=i.mul(h.democracyVote),i=i.plus(e.toString()||"0"),a=a.mul(h.democracyVote),a=a.plus(e.toString()||"0"),{currentActionPoints:i.toString(),maxActionPoints:a.toString()}}async getRewards(t,e,o){let c=await this.getStake(t),{potReservedBalance:i,accumulatedRewardPerStake:a,totalStake:p,stakePosition:r}=c;if(!r)return;let[g,S,P,h,u,f,k]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),w=(0,d.default)(g.transferable.toString()).minus(i.toString()),Q=w.gt(0)&&p>0?(0,l.calculate_accumulated_rps)(a.toString(),w.toString(),p.toString()):a.toString(),I=(0,l.calculate_period_number)(S.toString(),o,k),R=(0,l.calculate_period_number)(S.toString(),r.createdAt.toString(),k),Z=(0,l.calculate_rewards)(Q,r.rewardPerStake.toString(),r.stake.toString()),L=this.getCurrentActionPoints(r.votes,r.actionPoints,r.stake,e),M=(0,l.calculate_points)(R,I,h.toString(),u.toString(),L.currentActionPoints,f.toString(),r.accumulatedSlashPoints.toString()),B=(0,l.sigmoid)(M,x,A),W=(()=>{if(!e.length)return;let tt=(0,l.calculate_points)(R,I,h.toString(),u.toString(),L.maxActionPoints.toString(),f.toString(),r.accumulatedSlashPoints.toString());return(0,l.sigmoid)(tt,x,A)})(),q=(0,d.default)(Z).plus(r.accumulatedUnpaidRewards.toString()).plus(r.accumulatedLockedRewards.toString());if((0,d.default)(I).minus(R).lte(P.toString()))return{rewards:"0",payablePercentage:B,extraPayablePercentage:W,constants:{a:x,b:A}};let D=(0,l.calculate_percentage_amount)(q.toString(),B),U=(0,d.default)(r.accumulatedLockedRewards.toString()),H=U.gt(D)?U:(0,d.default)(D);return{rewards:H.div(N).toString(),maxRewards:q.div(N).toString(),allocatedRewardsPercentage:H.div(q).mul(100).toNumber(),points:M,payablePercentage:B,extraPayablePercentage:W,constants:{a:x,b:A}}}};var V=require("polkadot-api");var T=require("@galacticcouncil/descriptors");var K=require("@galacticcouncil/common"),y=require("rxjs");var m=require("rxjs"),s=require("rxjs/operators");function J(n,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let o=()=>(0,m.defer)(()=>(0,m.from)(n._request("system_health",[]))).pipe((0,s.timeout)({first:e}),(0,s.map)(()=>"online"),(0,s.catchError)(()=>(0,m.of)("offline")));return(0,m.of)({state:"offline",delayMs:0}).pipe((0,s.expand)(i=>(0,m.timer)(i.delayMs).pipe((0,s.switchMap)(o),(0,s.map)(a=>({state:a,delayMs:t})))),(0,s.skip)(1),(0,s.map)(i=>i.state),(0,s.distinctUntilChanged)(),(0,s.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:ut}=K.log,_=class n{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,y.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",J(t))}static getInstance(t){return this.instance||(this.instance=new n(t)),this.instance}watched(t,e){return e.pipe((0,y.tap)({error:o=>ut.error(t,o)}),(0,y.shareReplay)({bufferSize:1,refCount:!0}))}};var C=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(T.hydration),this.apiNext=this.client.getTypedApi(T.hydrationNext),this.watcher=_.getInstance(this.client)}};var dt=require("polkadot-api/ws"),pt=require("polkadot-api/logs-provider");var E=class extends C{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return V.Binary.toText(V.Binary.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:a})=>{let[p,r,g]=a;return{address:p,collectionId:r,itemId:g}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};0&&(module.exports={BIG_10,BIG_BILL,StakingApi,StakingClient});
|
package/build/staking/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import X from"buffer";typeof window<"u"&&(window.Buffer=X.Buffer);import{calculate_accumulated_rps as Z,calculate_percentage_amount as tt,calculate_period_number as E,calculate_points as L,calculate_rewards as et,sigmoid as M}from"@galacticcouncil/math-staking";import s from"big.js";var y={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},O=c=>Object.keys(y).includes(c);import{AccountId as G}from"polkadot-api";import{toHex as J}from"@polkadot-api/utils";import{HYDRATION_SS58_PREFIX as K}from"@galacticcouncil/common";function V(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=J(e);return G(K).dec(n)}var P="20000000000000000",k="2000",nt=s(10),W=s(nt.pow(12)),D=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=V(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let l=e.created_at,o=await n.reduce(async(i,[u,a])=>{let d=await i,p=u,m=a.amount,g=a.conviction.type.toLowerCase(),r=await this.client.getReferendumInfo(p);return r&&(r.type==="Approved"||r.type==="Rejected")&&O(g)&&d.push({id:p,amount:m,conviction:g}),d},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:l,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:o}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,l]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),o=l.find(i=>i)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:o,stakePosition:o?await this.getStakingPosition(o):void 0}}getCurrentActionPoints(t,e,n,l){let o=s(0),i=s(0),u=y.locked6x,a=s(n.toString()).mul(u),d=100,p=[];t.forEach(r=>{let S=y[r.conviction],f=l.includes(r.id.toString());f&&p.push(r.id.toString());let h=s(r.amount.toString()).mul(d).div(a);o=o.plus(Math.floor(h.mul(S).toNumber())),i=i.plus(Math.floor(h.mul(f?u:S).toNumber()))});let m=Math.floor(s(n.toString()).mul(u).mul(d).div(a).toNumber());l.forEach(r=>{p.includes(r)||(i=i.plus(m))});let g={democracyVote:1};return o=o.mul(g.democracyVote),o=o.plus(e.toString()||"0"),i=i.mul(g.democracyVote),i=i.plus(e.toString()||"0"),{currentActionPoints:o.toString(),maxActionPoints:i.toString()}}async getRewards(t,e,n){let l=await this.getStake(t),{potReservedBalance:o,accumulatedRewardPerStake:i,totalStake:u,stakePosition:a}=l;if(!a)return;let[d,p,m,g,r,S,f]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=s(d.transferable.toString()).minus(o.toString()),F=h.gt(0)&&u>0?Z(i.toString(),h.toString(),u.toString()):i.toString(),b=E(p.toString(),n,f),x=E(p.toString(),a.createdAt.toString(),f),Y=et(F,a.rewardPerStake.toString(),a.stake.toString()),T=this.getCurrentActionPoints(a.votes,a.actionPoints,a.stake,e),I=L(x,b,g.toString(),r.toString(),T.currentActionPoints,S.toString(),a.accumulatedSlashPoints.toString()),A=M(I,P,k),R=(()=>{if(!e.length)return;let j=L(x,b,g.toString(),r.toString(),T.maxActionPoints.toString(),S.toString(),a.accumulatedSlashPoints.toString());return M(j,P,k)})(),_=s(Y).plus(a.accumulatedUnpaidRewards.toString()).plus(a.accumulatedLockedRewards.toString());if(s(b).minus(x).lte(m.toString()))return{rewards:"0",payablePercentage:A,extraPayablePercentage:R,constants:{a:P,b:k}};let B=tt(_.toString(),A),q=s(a.accumulatedLockedRewards.toString()),N=q.gt(B)?q:s(B);return{rewards:N.div(W).toString(),maxRewards:_.div(W).toString(),allocatedRewardsPercentage:N.div(_).mul(100).toNumber(),points:I,payablePercentage:A,extraPayablePercentage:R,constants:{a:P,b:k}}}};import{Binary as $}from"polkadot-api";import{hydration as yt,hydrationNext as Pt}from"@galacticcouncil/descriptors";import{log as gt}from"@galacticcouncil/common";import{map as mt,shareReplay as St,tap as ft}from"rxjs";import{defer as ot,from as it,of as U,timer as at}from"rxjs";import{catchError as rt,distinctUntilChanged as st,expand as ct,map as C,shareReplay as lt,skip as ut,switchMap as dt,timeout as pt}from"rxjs/operators";function H(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let n=()=>ot(()=>it(c._request("system_health",[]))).pipe(pt({first:e}),C(()=>"online"),rt(()=>U("offline")));return U({state:"offline",delayMs:0}).pipe(ct(o=>at(o.delayMs).pipe(dt(n),C(i=>({state:i,delayMs:t})))),ut(1),C(o=>o.state),st(),lt({bufferSize:1,refCount:!0}))}var{logger:ht}=gt,w=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(mt(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",H(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe(ft({error:n=>ht.error(t,n)}),St({bufferSize:1,refCount:!0}))}};var v=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(yt),this.apiNext=this.client.getTypedApi(Pt),this.watcher=w.getInstance(this.client)}};import{getWsProvider as te}from"polkadot-api/ws";import{withLogsRecorder as ne}from"polkadot-api/logs-provider";
|
|
1
|
+
import X from"buffer";typeof window<"u"&&(window.Buffer=X.Buffer);import{calculate_accumulated_rps as Z,calculate_percentage_amount as tt,calculate_period_number as E,calculate_points as L,calculate_rewards as et,sigmoid as M}from"@galacticcouncil/math-staking";import s from"big.js";var y={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},O=c=>Object.keys(y).includes(c);import{AccountId as G}from"polkadot-api";import{toHex as J}from"@polkadot-api/utils";import{HYDRATION_SS58_PREFIX as K}from"@galacticcouncil/common";function V(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=J(e);return G(K).dec(n)}var P="20000000000000000",k="2000",nt=s(10),W=s(nt.pow(12)),D=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=V(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let l=e.created_at,o=await n.reduce(async(i,[u,a])=>{let d=await i,p=u,m=a.amount,g=a.conviction.type.toLowerCase(),r=await this.client.getReferendumInfo(p);return r&&(r.type==="Approved"||r.type==="Rejected")&&O(g)&&d.push({id:p,amount:m,conviction:g}),d},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:l,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:o}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,l]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),o=l.find(i=>i)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:o,stakePosition:o?await this.getStakingPosition(o):void 0}}getCurrentActionPoints(t,e,n,l){let o=s(0),i=s(0),u=y.locked6x,a=s(n.toString()).mul(u),d=100,p=[];t.forEach(r=>{let S=y[r.conviction],f=l.includes(r.id.toString());f&&p.push(r.id.toString());let h=s(r.amount.toString()).mul(d).div(a);o=o.plus(Math.floor(h.mul(S).toNumber())),i=i.plus(Math.floor(h.mul(f?u:S).toNumber()))});let m=Math.floor(s(n.toString()).mul(u).mul(d).div(a).toNumber());l.forEach(r=>{p.includes(r)||(i=i.plus(m))});let g={democracyVote:1};return o=o.mul(g.democracyVote),o=o.plus(e.toString()||"0"),i=i.mul(g.democracyVote),i=i.plus(e.toString()||"0"),{currentActionPoints:o.toString(),maxActionPoints:i.toString()}}async getRewards(t,e,n){let l=await this.getStake(t),{potReservedBalance:o,accumulatedRewardPerStake:i,totalStake:u,stakePosition:a}=l;if(!a)return;let[d,p,m,g,r,S,f]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=s(d.transferable.toString()).minus(o.toString()),F=h.gt(0)&&u>0?Z(i.toString(),h.toString(),u.toString()):i.toString(),b=E(p.toString(),n,f),x=E(p.toString(),a.createdAt.toString(),f),Y=et(F,a.rewardPerStake.toString(),a.stake.toString()),T=this.getCurrentActionPoints(a.votes,a.actionPoints,a.stake,e),I=L(x,b,g.toString(),r.toString(),T.currentActionPoints,S.toString(),a.accumulatedSlashPoints.toString()),A=M(I,P,k),R=(()=>{if(!e.length)return;let j=L(x,b,g.toString(),r.toString(),T.maxActionPoints.toString(),S.toString(),a.accumulatedSlashPoints.toString());return M(j,P,k)})(),_=s(Y).plus(a.accumulatedUnpaidRewards.toString()).plus(a.accumulatedLockedRewards.toString());if(s(b).minus(x).lte(m.toString()))return{rewards:"0",payablePercentage:A,extraPayablePercentage:R,constants:{a:P,b:k}};let B=tt(_.toString(),A),q=s(a.accumulatedLockedRewards.toString()),N=q.gt(B)?q:s(B);return{rewards:N.div(W).toString(),maxRewards:_.div(W).toString(),allocatedRewardsPercentage:N.div(_).mul(100).toNumber(),points:I,payablePercentage:A,extraPayablePercentage:R,constants:{a:P,b:k}}}};import{Binary as $}from"polkadot-api";import{hydration as yt,hydrationNext as Pt}from"@galacticcouncil/descriptors";import{log as gt}from"@galacticcouncil/common";import{map as mt,shareReplay as St,tap as ft}from"rxjs";import{defer as ot,from as it,of as U,timer as at}from"rxjs";import{catchError as rt,distinctUntilChanged as st,expand as ct,map as C,shareReplay as lt,skip as ut,switchMap as dt,timeout as pt}from"rxjs/operators";function H(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let n=()=>ot(()=>it(c._request("system_health",[]))).pipe(pt({first:e}),C(()=>"online"),rt(()=>U("offline")));return U({state:"offline",delayMs:0}).pipe(ct(o=>at(o.delayMs).pipe(dt(n),C(i=>({state:i,delayMs:t})))),ut(1),C(o=>o.state),st(),lt({bufferSize:1,refCount:!0}))}var{logger:ht}=gt,w=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(mt(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",H(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe(ft({error:n=>ht.error(t,n)}),St({bufferSize:1,refCount:!0}))}};var v=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(yt),this.apiNext=this.client.getTypedApi(Pt),this.watcher=w.getInstance(this.client)}};import{getWsProvider as te}from"polkadot-api/ws";import{withLogsRecorder as ne}from"polkadot-api/logs-provider";var z=class extends v{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return $.toText($.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:i})=>{let[u,a,d]=i;return{address:u,collectionId:a,itemId:d}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};export{nt as BIG_10,W as BIG_BILL,D as StakingApi,z as StakingClient};
|
package/build/tx/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ue=Object.create;var J=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var Z=(o,t)=>{for(var e in t)J(o,e,{get:t[e],enumerable:!0})},Bt=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of me(t))!ge.call(o,s)&&s!==e&&J(o,s,{get:()=>t[s],enumerable:!(a=pe(t,s))||a.enumerable});return o};var tt=(o,t,e)=>(e=o!=null?ue(de(o)):{},Bt(t||!o||!o.__esModule?J(e,"default",{value:o,enumerable:!0}):e,o)),he=o=>Bt(J({},"__esModule",{value:!0}),o);var pa={};Z(pa,{TxBuilderFactory:()=>gt});module.exports=he(pa);var Y=require("@galacticcouncil/math-lbp");var Ct=require("@galacticcouncil/common");var et={};Z(et,{withTimeout:()=>be});function be(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={};Z(w,{divSpot:()=>Pe,getFraction:()=>fe,mulScaled:()=>_t,mulSpot:()=>ye});var bt=require("@galacticcouncil/common");function _t(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 ye(o,t,e,a){return _t(o,t,e,bt.RUNTIME_DECIMALS,a)}function Pe(o,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(bt.RUNTIME_DECIMALS+a-e);return o*s/t}function fe(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={};Z(m,{FeeUtils:()=>yt,shiftNeg:()=>Te});var Ft=tt(require("big.js"));var yt=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,Ft.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var ve=tt(require("big.js"));var{FeeUtils:Ha}=m;var Re=require("polkadot-api"),it=require("rxjs");var E=require("rxjs"),f=require("rxjs/operators");var nt=require("@galacticcouncil/descriptors");var Mt=require("@galacticcouncil/common"),q=require("rxjs");var F=require("rxjs"),h=require("rxjs/operators");function kt(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:xe}=Mt.log,st=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,q.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",kt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,q.tap)({error:a=>xe.error(t,a)}),(0,q.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=st.getInstance(this.client)}};var Ie=require("polkadot-api/ws"),Oe=require("polkadot-api/logs-provider");var Ae=require("polkadot-api/sm-provider");var Be=require("polkadot-api");var Dt=require("@galacticcouncil/common"),T=require("rxjs"),c=require("rxjs/operators");var{logger:G}=Dt.log,U=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,T.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,T.combineLatest)([e,a,s]).pipe((0,c.connect)(n=>(0,T.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:()=>G.debug("balance: subscribe",t),error:e=>G.error("balance",e)}),(0,c.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,T.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,c.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,c.tap)({error:a=>G.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,T.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,c.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,c.tap)({error:s=>G.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,T.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=>G.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,T.defer)(()=>(0,T.from)(e?Promise.resolve(e):a()).pipe((0,c.switchMap)(n=>this.watcher.bestBlock$.pipe((0,c.switchMap)(()=>(0,T.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=>G.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 _e=require("rxjs");var Lt=require("@galacticcouncil/common");var fs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ss}=Lt.log;var{withTimeout:Ds}=et;var y=require("@galacticcouncil/math-omnipool"),Ee=tt(require("big.js"));var Ce=require("@galacticcouncil/common");var{FeeUtils:ln}=m;var H=require("polkadot-api"),ke=require("@polkadot-api/utils"),N=require("rxjs"),Me=require("@galacticcouncil/common");var{FeeUtils:Tn}=m,vn=H.Binary.toHex(H.Binary.fromText("omnipool")),wn=(0,H.Enum)("Short");var A=require("@galacticcouncil/math-stableswap");var Nt=require("@galacticcouncil/common");var{FeeUtils:Vn}=m;var qt=require("polkadot-api"),Ne=require("@polkadot-api/utils"),qe=require("@noble/hashes/blake2b"),Q=require("rxjs"),Gt=require("@galacticcouncil/common");var{FeeUtils:ei}=m;var B=require("@galacticcouncil/math-xyk");var Ue=require("@galacticcouncil/common");var{FeeUtils:Si}=m;var Ve=require("polkadot-api"),We=require("rxjs");var Ut=require("@galacticcouncil/common");var Vt=require("polkadot-api"),Xe=require("@polkadot-api/utils"),rt=require("rxjs"),Ye=require("viem"),Pt=require("@galacticcouncil/common");var{ERC20:Qi}=Pt.erc20;var M=require("@galacticcouncil/math-hsm");var Wt=require("@galacticcouncil/common");var{FeeUtils:dr}=m;var ft=require("polkadot-api"),Qe=require("@polkadot-api/utils"),V=require("rxjs"),Je=require("viem"),St=require("@galacticcouncil/common");var{FeeUtils:_r}=m,{H160:Rr}=St.h160;var Xt=require("@galacticcouncil/common"),Tt=require("rxjs");var{logger:xo}=Xt.log;var Yt=require("@galacticcouncil/common");var{FeeUtils:Pl}=m;var la=require("@galacticcouncil/common");var vt=require("polkadot-api");var D=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:(0,vt.Enum)("Stableswap",n),asset_in:e,asset_out:a}:{pool:(0,vt.Enum)(s),asset_in:e,asset_out:a})}};var At=require("polkadot-api");var zt=[{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 wt=[{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 Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",It="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",jt=1000000n;var sc=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ot=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:wt,address:xt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:wt,address:xt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:zt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var g=tt(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:W}=v.erc20,{H160:Ot}=v.h160,ca=1.01,ua=31536000n,Qt=4,lt=-1,ct=10n**27n,ut=class{client;constructor(t){this.client=new ot(t)}async getSummary(t){let e=Ot.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,C,x,I]=n,_=v.big.toDecimal(I,18),k=[];for(let R of u){let L=R.underlyingAsset.toLowerCase(),S=r.find(({underlyingAsset:ce})=>ce.toLowerCase()===L);if(!S)throw new Error("Missing pool reserve for "+L);let ht=R.scaledATokenBalance,X=S.liquidityIndex,Zt=S.liquidityRate,te=S.availableLiquidity,ee=S.priceInMarketReferenceCurrency,ae=i+6,se=this.calculateLinearInterest(Zt,S.lastUpdateTimestamp,ae),ne=X*se/ct,ie=ht*ne/ct,re=Number(p!==0&&p===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,oe=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,le=W.toAssetId(L);k.push({aTokenBalance:ie,availableLiquidity:te,decimals:Number(S.decimals),isCollateral:oe,priceInRef:ee,reserveId:le,reserveAsset:L,reserveLiquidationThreshold:re})}return{healthFactor:Number(_),currentLiquidationThreshold:Number(v.big.toDecimal(C,Qt)),totalCollateral:l,totalDebt:b,reserves:k}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[s,n]=a;return n>0n}async getHealthFactor(t){let e=Ot.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 lt;let u=W.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: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(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return lt;let u=W.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()),k=(0,g.default)(I.toString()).mul(_).div(n.toString()).toFixed(6,g.default.roundDown);return Number(k)}async getHealthFactorAfterSwap(t,e,a,s,n){let{totalDebt:i,reserves:r,healthFactor:u}=await this.getSummary(t);if(i===0n)return lt;let p=W.fromAssetId(a),l=W.fromAssetId(n),b=r.find(X=>X.reserveAsset===p),P=r.find(X=>X.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(e,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),S=(P.isCollateral?(0,g.default)(_.toString()).mul(P.reserveLiquidationThreshold):(0,g.default)(0)).minus(k).div(i.toString()),ht=(0,g.default)(u).plus(S).toFixed(6,g.default.roundDown);return Number(ht)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(t),i=W.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 C=(0,g.default)(P).mul(e.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(t,e,a){let s=a-e;if(s<=0)return ct;let n=t*BigInt(s)/ua;return ct+n}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return lt;let s=e*a/t,n=v.big.toDecimal(s,Qt);return Number(n)}};function Jt(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var $=class extends O{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new U(t),this.aaveUtils=new ut(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:jt})}async dryRun(t,e){let a=(0,At.Enum)("Signed",t),s=(0,At.Enum)("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall,4),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let u=r.type==="Module"?Jt(r.value):r.type;throw new Error("Dry run execution error!",{cause:u})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends ${_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:D.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:D.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:D.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("RouterSellAll",p)}};var mt=require("polkadot-api");var dt=class extends ${_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,mt.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,mt.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,mt.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 gt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new pt(this.client,this.evmClient).setTrade(t)}order(t){return new dt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
|
|
1
|
+
"use strict";var ue=Object.create;var J=Object.defineProperty;var pe=Object.getOwnPropertyDescriptor;var me=Object.getOwnPropertyNames;var de=Object.getPrototypeOf,ge=Object.prototype.hasOwnProperty;var Z=(o,t)=>{for(var e in t)J(o,e,{get:t[e],enumerable:!0})},Bt=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of me(t))!ge.call(o,s)&&s!==e&&J(o,s,{get:()=>t[s],enumerable:!(a=pe(t,s))||a.enumerable});return o};var tt=(o,t,e)=>(e=o!=null?ue(de(o)):{},Bt(t||!o||!o.__esModule?J(e,"default",{value:o,enumerable:!0}):e,o)),he=o=>Bt(J({},"__esModule",{value:!0}),o);var ua={};Z(ua,{TxBuilderFactory:()=>gt});module.exports=he(ua);var Y=require("@galacticcouncil/math-lbp");var Ct=require("@galacticcouncil/common");var et={};Z(et,{withTimeout:()=>be});function be(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={};Z(w,{divSpot:()=>Pe,getFraction:()=>fe,mulScaled:()=>_t,mulSpot:()=>ye});var bt=require("@galacticcouncil/common");function _t(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 ye(o,t,e,a){return _t(o,t,e,bt.RUNTIME_DECIMALS,a)}function Pe(o,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(bt.RUNTIME_DECIMALS+a-e);return o*s/t}function fe(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={};Z(m,{FeeUtils:()=>yt,shiftNeg:()=>Te});var Ft=tt(require("big.js"));var yt=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,Ft.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var ve=tt(require("big.js"));var{FeeUtils:La}=m;var _e=require("polkadot-api"),it=require("rxjs");var E=require("rxjs"),f=require("rxjs/operators");var nt=require("@galacticcouncil/descriptors");var Mt=require("@galacticcouncil/common"),q=require("rxjs");var F=require("rxjs"),h=require("rxjs/operators");function kt(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:xe}=Mt.log,st=class o{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,q.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",kt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,q.tap)({error:a=>xe.error(t,a)}),(0,q.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=st.getInstance(this.client)}};var Ie=require("polkadot-api/ws"),Oe=require("polkadot-api/logs-provider");var Ae=require("polkadot-api");var Dt=require("@galacticcouncil/common"),T=require("rxjs"),c=require("rxjs/operators");var{logger:G}=Dt.log,U=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,T.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),s=this.watchErc20Balance(t);return(0,T.combineLatest)([e,a,s]).pipe((0,c.connect)(n=>(0,T.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:()=>G.debug("balance: subscribe",t),error:e=>G.error("balance",e)}),(0,c.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,T.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,c.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,c.tap)({error:a=>G.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,T.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,c.map)(({value:s})=>({id:e,balance:this.getBreakdown(s)})),(0,c.tap)({error:s=>G.error("balance(token)",s)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,T.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=>G.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,T.defer)(()=>(0,T.from)(e?Promise.resolve(e):a()).pipe((0,c.switchMap)(n=>this.watcher.bestBlock$.pipe((0,c.switchMap)(()=>(0,T.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=>G.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 Lt=require("@galacticcouncil/common");var Ps={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:fs}=Lt.log;var{withTimeout:Ms}=et;var y=require("@galacticcouncil/math-omnipool"),Fe=tt(require("big.js"));var Ee=require("@galacticcouncil/common");var{FeeUtils:on}=m;var H=require("polkadot-api"),Ce=require("@polkadot-api/utils"),N=require("rxjs"),ke=require("@galacticcouncil/common");var{FeeUtils:Sn}=m,Tn=H.Binary.toHex(H.Binary.fromText("omnipool")),vn=(0,H.Enum)("Short");var A=require("@galacticcouncil/math-stableswap");var Nt=require("@galacticcouncil/common");var{FeeUtils:Un}=m;var qt=require("polkadot-api"),He=require("@polkadot-api/utils"),Ne=require("@noble/hashes/blake2b"),Q=require("rxjs"),Gt=require("@galacticcouncil/common");var{FeeUtils:ti}=m;var B=require("@galacticcouncil/math-xyk");var Ge=require("@galacticcouncil/common");var{FeeUtils:fi}=m;var Ue=require("polkadot-api"),Ve=require("rxjs");var Ut=require("@galacticcouncil/common");var Vt=require("polkadot-api"),$e=require("@polkadot-api/utils"),rt=require("rxjs"),Xe=require("viem"),Pt=require("@galacticcouncil/common");var{ERC20:ji}=Pt.erc20;var M=require("@galacticcouncil/math-hsm");var Wt=require("@galacticcouncil/common");var{FeeUtils:mr}=m;var ft=require("polkadot-api"),je=require("@polkadot-api/utils"),V=require("rxjs"),Qe=require("viem"),St=require("@galacticcouncil/common");var{FeeUtils:Br}=m,{H160:_r}=St.h160;var Xt=require("@galacticcouncil/common"),Tt=require("rxjs");var{logger:wo}=Xt.log;var Yt=require("@galacticcouncil/common");var{FeeUtils:yl}=m;var oa=require("@galacticcouncil/common");var vt=require("polkadot-api");var D=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:(0,vt.Enum)("Stableswap",n),asset_in:e,asset_out:a}:{pool:(0,vt.Enum)(s),asset_in:e,asset_out:a})}};var At=require("polkadot-api");var zt=[{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 wt=[{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 Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",It="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",jt=1000000n;var ac=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var ot=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:wt,address:xt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:wt,address:xt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:zt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var g=tt(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:W}=v.erc20,{H160:Ot}=v.h160,la=1.01,ca=31536000n,Qt=4,lt=-1,ct=10n**27n,ut=class{client;constructor(t){this.client=new ot(t)}async getSummary(t){let e=Ot.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,C,x,I]=n,_=v.big.toDecimal(I,18),k=[];for(let R of u){let L=R.underlyingAsset.toLowerCase(),S=r.find(({underlyingAsset:ce})=>ce.toLowerCase()===L);if(!S)throw new Error("Missing pool reserve for "+L);let ht=R.scaledATokenBalance,X=S.liquidityIndex,Zt=S.liquidityRate,te=S.availableLiquidity,ee=S.priceInMarketReferenceCurrency,ae=i+6,se=this.calculateLinearInterest(Zt,S.lastUpdateTimestamp,ae),ne=X*se/ct,ie=ht*ne/ct,re=Number(p!==0&&p===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,oe=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,le=W.toAssetId(L);k.push({aTokenBalance:ie,availableLiquidity:te,decimals:Number(S.decimals),isCollateral:oe,priceInRef:ee,reserveId:le,reserveAsset:L,reserveLiquidationThreshold:re})}return{healthFactor:Number(_),currentLiquidationThreshold:Number(v.big.toDecimal(C,Qt)),totalCollateral:l,totalDebt:b,reserves:k}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[s,n]=a;return n>0n}async getHealthFactor(t){let e=Ot.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 lt;let u=W.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: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(t,e,a){let{totalCollateral:s,totalDebt:n,reserves:i,currentLiquidationThreshold:r}=await this.getSummary(t);if(n===0n)return lt;let u=W.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()),k=(0,g.default)(I.toString()).mul(_).div(n.toString()).toFixed(6,g.default.roundDown);return Number(k)}async getHealthFactorAfterSwap(t,e,a,s,n){let{totalDebt:i,reserves:r,healthFactor:u}=await this.getSummary(t);if(i===0n)return lt;let p=W.fromAssetId(a),l=W.fromAssetId(n),b=r.find(X=>X.reserveAsset===p),P=r.find(X=>X.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(e,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),S=(P.isCollateral?(0,g.default)(_.toString()).mul(P.reserveLiquidationThreshold):(0,g.default)(0)).minus(k).div(i.toString()),ht=(0,g.default)(u).plus(S).toFixed(6,g.default.roundDown);return Number(ht)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:s,healthFactor:n}=await this.getSummary(t),i=W.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-la;if(P>0){let C=(0,g.default)(P).mul(e.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(t,e,a){let s=a-e;if(s<=0)return ct;let n=t*BigInt(s)/ca;return ct+n}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return lt;let s=e*a/t,n=v.big.toDecimal(s,Qt);return Number(n)}};function Jt(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var $=class extends O{evm;evmClient;balance;aaveUtils;constructor(t,e){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new U(t),this.aaveUtils=new ut(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:jt})}async dryRun(t,e){let a=(0,At.Enum)("Signed",t),s=(0,At.Enum)("system",a),i=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(s,e.decodedCall,4),r=i.success&&!i.value.execution_result.success?i.value.execution_result.value.error:null;if(r){let u=r.type==="Module"?Jt(r.value):r.type;throw new Error("Dry run execution error!",{cause:u})}return i}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends ${_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:D.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:D.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:D.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(p=await this.dispatchWithExtraGas(p)),this.wrapTx("RouterSellAll",p)}};var mt=require("polkadot-api");var dt=class extends ${_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,mt.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,mt.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,mt.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 gt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new pt(this.client,this.evmClient).setTrade(t)}order(t){return new dt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
|