@galacticcouncil/sdk-next 1.3.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.cjs +1 -1
- package/build/index.mjs +1 -1
- package/build/pool/PoolContextProvider.d.ts +4 -0
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.d.ts +1 -0
- package/build/pool/index.mjs +1 -1
- package/build/pool/types.d.ts +3 -1
- package/build/pool/uniswapv3/UniswapV3Math.d.ts +7 -0
- package/build/pool/uniswapv3/UniswapV3Pool.d.ts +46 -0
- package/build/pool/uniswapv3/UniswapV3PoolClient.d.ts +45 -0
- package/build/pool/uniswapv3/abi.d.ts +111 -0
- package/build/pool/uniswapv3/const.d.ts +7 -0
- package/build/pool/uniswapv3/index.d.ts +5 -0
- package/build/pool/uniswapv3/types.d.ts +21 -0
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +4 -1
package/build/sor/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var $t=Object.defineProperty;var X=(u,t)=>{for(var e in t)$t(u,e,{get:t[e],enumerable:!0})};import Wt from"buffer";typeof window<"u"&&(window.Buffer=Wt.Buffer);var K=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 Yt=10,z=class{isNotVisited(t,e){let a=!0;return e.forEach(s=>{(s[0]===t[0]||s[1]===t[1])&&(a=!1)}),a}findPaths(t,e,a){let s=[],n=new K,i=[];for(i.push([e,""]),n.enqueue(i);n.size()>0;){let r=n.dequeue();if(!r||r.length>Yt)continue;let o=r[r.length-1];(a===null||o[0]===a)&&s.push(r),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let p=[...r];p.push(c),n.enqueue(p)}})}return s}findShortestPaths(t,e,a){let s=[],n=new K,i=[];i.push([e,""]),n.enqueue(i);let r=1/0;for(;n.size()>0;){let o=n.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===a){o.length<r?(r=o.length,s.length=0,s.push(o)):o.length===r&&s.push(o);continue}let c=t.get(l[0]);for(let p of c??[])this.isNotVisited(p,o)&&n.enqueue([...o,p])}return s}buildAndPopulateGraph(t,e){let a=new Map;for(let s of t)a.set(parseInt(s),[]);for(let[s,n,i]of e)a.get(n)?.push([i,s]);return a}};function dt(u){let t={};for(let e of u){let a=e.tokens.length;for(let s=0;s<a;s++){t[e.tokens[s].id]||(t[e.tokens[s].id]=[]);for(let n=0;n<a;n++){if(s==n)continue;let i=[e.address,e.tokens[s].id,e.tokens[n].id];t[e.tokens[s].id].push(i)}}}return t}import{calculate_in_given_out as Xt,calculate_out_given_in as Kt,calculate_linear_weights as zt,calculate_pool_trade_fee as jt,get_spot_price as Qt}from"@galacticcouncil/math-lbp";var _=class{static getSpotPrice(t,e,a,s,n){return Qt(t,e,a,s,n)}static calculateInGivenOut(t,e,a,s,n){return Xt(t,e,a,s,n)}static calculateOutGivenIn(t,e,a,s,n){return Kt(t,e,a,s,n)}static calculateLinearWeights(t,e,a,s,n){return zt(t,e,a,s,n)}static calculatePoolTradeFee(t,e,a){return jt(t,e,a)}};import{big as wt,RUNTIME_DECIMALS as It}from"@galacticcouncil/common";var nt={};X(nt,{withTimeout:()=>Jt});function Jt(u,t,e="timeout"){return new Promise((a,s)=>{let n=setTimeout(()=>s(new Error(e)),t);u.then(i=>{clearTimeout(n),a(i)},i=>{clearTimeout(n),s(i)})})}var B={};X(B,{divSpot:()=>te,getFraction:()=>ee,mulScaled:()=>vt,mulSpot:()=>Zt});import{RUNTIME_DECIMALS as Tt}from"@galacticcouncil/common";function vt(u,t,e,a,s){let n=e+a-s,i=u*t;return n>0?i/BigInt(10)**BigInt(n):n<0?i*BigInt(10)**BigInt(-n):i}function Zt(u,t,e,a){return vt(u,t,e,Tt,a)}function te(u,t,e,a){if(t===0n)return 0n;let s=BigInt(10)**BigInt(Tt+a-e);return u*s/t}function ee(u,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 u*s/(BigInt(100)*a)}var y={};X(y,{FeeUtils:()=>gt,shiftNeg:()=>ne});import se from"big.js";var gt=class u{static toPct(t){let[e,a]=t;return u.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return u.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 ne(u,t){let e=se(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var j={};X(j,{findNestedKey:()=>ie,findNestedObj:()=>re,jsonFormatter:()=>oe});var ie=(u,t)=>{let e=[];return JSON.stringify(u,(a,s)=>(s&&s[t]&&e.push(s),s)),e[0]},re=(u,t,e)=>{let a;return JSON.stringify(u,(s,n)=>(n&&n[t]===e&&(a=n),n)),a},oe=(u,t)=>typeof t=="bigint"?t.toString():t;var I={};X(I,{calculateBuyFee:()=>me,calculateDiffToAvg:()=>le,calculateDiffToRef:()=>ce,calculateSellFee:()=>ue});import C from"big.js";function le(u,t){let e=C(u.toString()),a=C(t.toString());return e.minus(a).abs().div(e.plus(a).div(2)).mul(100).round(2).toNumber()}function ce(u,t){if(t===0n)return 0;let e=C(u.toString()),a=C(t.toString());return e.minus(a).div(a).mul(100).round(2).toNumber()}function ue(u,t){if(u===0n)return 0;let e=C(u.toString()),a=C(t.toString());return C(1).minus(a.div(e)).mul(100).round(2).toNumber()}function me(u,t){if(u===0n)return 0;let e=C(u.toString());return C(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as as}from"@thi.ng/cache";var{FeeUtils:xt}=y,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 a=new Map(this.tokens.map(i=>[i.id,i])),s=a.get(t),n=a.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,weightIn:s.weight,weightOut:n.weight}}validateAndBuy(t,e,a){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let i=t.balanceOut/this.maxOutRatio;if(e>i&&n.push("MaxOutRatioExceeded"),s===t.assetOut){let r=this.calculateTradeFee(e,a),o=xt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),p=t.balanceIn/this.maxInRatio;return c>p&&n.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:n}}else{let r=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return r>o&&n.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:n}}}validateAndSell(t,e,a){let s=this.tokens[0].id,n=[];e<this.minTradingLimit&&n.push("InsufficientTradingAmount");let i=t.balanceIn/this.maxInRatio;if(e>i&&n.push("MaxInRatioExceeded"),s===t.assetIn){let r=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return r>o&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:n}}else{let r=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(r,a),l=xt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),c=r-o,p=t.balanceOut/this.maxOutRatio;return c>p&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:n}}}calculateInGivenOut(t,e){let a=_.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(a);return s<0n?0n:s}calculateOutGivenIn(t,e){let a=_.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),s=BigInt(a);return s<0n?0n:s}spotPriceInGivenOut(t){let e=_.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),wt.toBigInt(1,It).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=_.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),wt.toBigInt(1,It).toString());return BigInt(e)}calculateTradeFee(t,e){let a=_.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(a)}};import{CompatibilityLevel as dr}from"polkadot-api";import{Subscription as br,distinctUntilChanged as hr,filter as yr,map as Pr}from"rxjs";import{memoize1 as vi}from"@thi.ng/memoize";import{TLRUCache as Ii}from"@thi.ng/cache";import{ReplaySubject as Bi,Subscription as Ei,combineLatest as Fi,defer as Ri,from as _i,interval as Ci,merge as ki,of as Mi,EMPTY as Di}from"rxjs";import{bufferCount as Hi,bufferTime as Ni,catchError as qi,filter as Gi,finalize as Ui,map as Vi,pairwise as $i,repeat as Wi,skip as Yi,share as Xi,startWith as Ki,switchMap as zi,tap as ji,throttleTime as Qi}from"rxjs/operators";import{hydration as Js,hydrationNext as Zs,hydrationIce as tn}from"@galacticcouncil/descriptors";import{log as pe}from"@galacticcouncil/common";import{map as Vs,shareReplay as $s,tap as Ws}from"rxjs";import{defer as Is,from as xs,of as Os,timer as As}from"rxjs";import{catchError as Es,distinctUntilChanged as Fs,expand as Rs,map as _s,shareReplay as Cs,skip as ks,switchMap as Ms,timeout as Ds}from"rxjs/operators";var{logger:Xs}=pe;import{getWsProvider as rn}from"polkadot-api/ws";import{withLogsRecorder as ln}from"polkadot-api/logs-provider";import{Binary as wn}from"polkadot-api";import{log as de}from"@galacticcouncil/common";import{combineLatest as Fn,concat as Rn,defer as _n,from as Cn}from"rxjs";import{bufferCount as Mn,distinctUntilChanged as Dn,debounceTime as Ln,map as Hn,retry as Nn,startWith as qn,switchMap as Gn,tap as Un,take as Vn,skip as $n,connect as Wn}from"rxjs/operators";var{logger:zn}=de;import{BehaviorSubject as ci}from"rxjs";import{log as be}from"@galacticcouncil/common";var bi={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:hi}=be;var{withTimeout:cr}=nt;import{calculate_in_given_out as ye,calculate_lrna_in_given_out as Pe,calculate_out_given_in as fe,calculate_out_given_lrna_in as Se,calculate_spot_price as Te,calculate_lrna_spot_price as ve,calculate_shares as we,calculate_liquidity_out as Ie,calculate_liquidity_lrna_out as xe,verify_asset_cap as Oe,calculate_liquidity_hub_in as Ae,is_sell_allowed as Be,is_buy_allowed as Ee,is_add_liquidity_allowed as Fe,is_remove_liquidity_allowed as Re,recalculate_asset_fee as _e,recalculate_protocol_fee as Ce}from"@galacticcouncil/math-omnipool";import U from"big.js";var S=class{static calculateSpotPrice(t,e,a,s){return Te(t,e,a,s)}static calculateLrnaSpotPrice(t,e){return ve(t,e)}static calculateInGivenOut(t,e,a,s,n,i,r,o,l,c){return ye(t,e,a,s,n,i,r,o,l,c)}static calculateLrnaInGivenOut(t,e,a,s,n,i){return Pe(t,e,a,s,n,i)}static calculateOutGivenIn(t,e,a,s,n,i,r,o,l,c){return fe(t,e,a,s,n,i,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,a,s,n,i){return Se(t,e,a,s,n,i)}static calculateShares(t,e,a,s){return we(t,e,a,s)}static calculateLiquidityOut(t,e,a,s,n,i,r,o){return Ie(t,e,a,s,n,i,r,o)}static calculateLiquidityLRNAOut(t,e,a,s,n,i,r,o){return xe(t,e,a,s,n,i,r,o)}static calculateCapDifference(t,e,a,s){let n=U(e),i=U(t),r=U(s),o=U(a),l=U(10).pow(18),c=o.div(l);if(n.div(r).lt(c)){let b=c.times(r).minus(n).times(i),d=n.times(U(1).minus(c));return b.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,a,s){return Ae(t,e,a,s)}static isSellAllowed(t){return Be(t)}static isBuyAllowed(t){return Ee(t)}static isAddLiquidityAllowed(t){return Fe(t)}static isRemoveLiquidityAllowed(t){return Re(t)}static recalculateAssetFee(t,e,a,s,n,i,r,o,l,c,p){return _e(t,e,a,s,n,i,r,o,l,c,p)}static recalculateProtocolFee(t,e,a,s,n,i,r,o,l,c,p){return Ce(t,e,a,s,n,i,r,o,l,c,p)}static verifyAssetCap(t,e,a,s){return Oe(t,e,a,s)}};import{big as ke}from"@galacticcouncil/common";var{FeeUtils:R}=y,ot=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let a=new Map(this.tokens.map(i=>[i.id,i])),s=a.get(t),n=a.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:s.hubReserves,hubReservesOut:n.hubReserves,sharesIn:s.shares,sharesOut:n.shares,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,tradeableIn:s.tradeable,tradeableOut:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,a){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,a),i=s===0n?0:I.calculateBuyFee(s,n),r=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let p=t.balanceIn/this.maxInRatio;return n>p&&r.push("MaxInRatioExceeded"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:i,errors:r}}validateAndSell(t,e,a){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,a),i=I.calculateSellFee(s,n),r=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let p=t.balanceOut/this.maxOutRatio;return n>p&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:i,errors:r}}calculateInGivenOut(t,e,a){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,a);let s=S.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.protocolFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateLrnaInGivenOut(t,e,a){let s=S.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,a){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,a);let s=S.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.protocolFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}calculateOutGivenLrnaIn(t,e,a){let s=S.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?R.toRaw(a.assetFee).toString():"0",a?R.toRaw(a.maxSlipFee).toString():"0"),n=BigInt(s);return n<0n?0n:n}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=S.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=S.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=S.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=S.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,a){let s=e-a;if(s===0)return t;let n=ke.pow10(Math.abs(s));return s>0?t*n:t/n}};import{AccountId as co,Binary as Ot,CompatibilityLevel as uo,Enum as He}from"polkadot-api";import{toHex as go}from"@polkadot-api/utils";import{Subscription as ho,distinctUntilChanged as yo,filter as Po,finalize as fo,map as So,merge as To,tap as vo}from"rxjs";import{HYDRATION_SS58_PREFIX as Io}from"@galacticcouncil/common";var{FeeUtils:eo}=y;var{FeeUtils:Co}=y,ko=Ot.toHex(Ot.fromText("omnipool")),Mo=He("Short");import{calculate_in_given_out as qe,calculate_out_given_in as Ge,calculate_amplification as Ue,calculate_add_one_asset as Ve,calculate_liquidity_out_one_asset as $e,calculate_shares as We,calculate_shares_for_amount as Ye,calculate_spot_price_with_fee as Xe,pool_account_name as Ke,recalculate_peg as ze}from"@galacticcouncil/math-stableswap";var A=class{static getPoolAddress(t){return Ke(t)}static defaultPegs(t){let e=[];for(let a=0;a<t;a++)e.push(["1","1"]);return e}static calculateAmplification(t,e,a,s,n){return Ue(t,e,a,s,n)}static calculateInGivenOut(t,e,a,s,n,i,r){return qe(t,e,a,s,n,i,r)}static calculateAddOneAsset(t,e,a,s,n,i,r){return Ve(t,e,a,s,n,i,r)}static calculateSharesForAmount(t,e,a,s,n,i,r){return Ye(t,e,a,s,n,i,r)}static calculateOutGivenIn(t,e,a,s,n,i,r){return Ge(t,e,a,s,n,i,r)}static calculateLiquidityOutOneAsset(t,e,a,s,n,i,r){return $e(t,e,a,s,n,i,r)}static calculateShares(t,e,a,s,n,i){return We(t,e,a,s,n,i)}static calculateSpotPriceWithFee(t,e,a,s,n,i,r,o){return Xe(t,e,a,s,n,i,r,o)}static recalculatePegs(t,e,a,s,n,i){let r=ze(t,e,a,s,n,i);return JSON.parse(r)}};import{RUNTIME_DECIMALS as je,big as At}from"@galacticcouncil/common";var{FeeUtils:V}=y,$=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 a=new Map(this.tokens.map(i=>[i.id,i])),s=a.get(t),n=a.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,tradeableIn:this.id===t?15:s.tradeable,tradeableOut:this.id===e?15:n.tradeable,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,a){let s=this.calculateInGivenOut(t,e),n=this.calculateInGivenOut(t,e,a),i=s===0n?0:I.calculateBuyFee(s,n),r=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:n,calculatedIn:s,amountOut:e,feePct:i,errors:r}}validateAndSell(t,e,a){let s=this.calculateOutGivenIn(t,e),n=this.calculateOutGivenIn(t,e,a),i=I.calculateSellFee(s,n),r=[],o=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||s<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:s,amountOut:n,feePct:i,errors:r}}calculateIn(t,e,a){let s=A.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),a?V.toRaw(a.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateAddOneAsset(t,e,a){let s=A.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),a?V.toRaw(a.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateSharesForAmount(t,e,a){let s=A.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),a?V.toRaw(a.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateInGivenOut(t,e,a){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,a):t.assetIn==this.id?this.calculateSharesForAmount(t,e,a):this.calculateIn(t,e,a)}spotPriceInGivenOut(t){let e=A.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,a){let s=A.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),a?V.toRaw(a.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateWithdrawOneAsset(t,e,a){let s=A.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),a?V.toRaw(a.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateShares(t,e,a){let s=A.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),a?V.toRaw(a.fee).toString():"0",this.getPegs()),n=BigInt(s);return n<0n?0n:n}calculateOutGivenIn(t,e,a){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,a):t.assetOut==this.id?this.calculateShares(t,e,a):this.calculateOut(t,e,a)}spotPriceOutGivenIn(t){let e=A.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:a,decimals:s})=>({asset_id:e,amount:a,decimals:s}));return JSON.stringify(t,j.jsonFormatter)}getAssets(t,e){let a={asset_id:Number(t),amount:e.toString()};return JSON.stringify([a],j.jsonFormatter)}normalizeSpot(t,e,a,s,n){return e?t*At.pow10(je-n):a?t/At.pow10(n-s):t}};import{AccountId as zl,CompatibilityLevel as jl}from"polkadot-api";import{toHex as Jl}from"@polkadot-api/utils";import{blake2b as tc}from"@noble/hashes/blake2b";import{Subscription as ac,distinctUntilChanged as sc,filter as nc,map as ic,merge as rc,tap as oc}from"rxjs";import{HYDRATION_SS58_PREFIX as cc,RUNTIME_DECIMALS as uc}from"@galacticcouncil/common";import{Binary as yl}from"polkadot-api";import{decodeEventLog as fl}from"viem";var{FeeUtils:ql}=y;var{FeeUtils:xc}=y;import{calculate_in_given_out as ta,calculate_out_given_in as ea,calculate_pool_trade_fee as aa,get_spot_price as sa,calculate_liquidity_in as na,calculate_shares as ia,calculate_spot_price as ra,calculate_spot_price_with_fee as oa,calculate_liquidity_out_asset_a as la,calculate_liquidity_out_asset_b as ca}from"@galacticcouncil/math-xyk";var L=class{static getSpotPrice(t,e,a){return sa(t,e,a)}static calculateInGivenOut(t,e,a){return ta(t,e,a)}static calculateOutGivenIn(t,e,a){return ea(t,e,a)}static calculatePoolTradeFee(t,e,a){return aa(t,e,a)}static calculateLiquidityIn(t,e,a){return na(t,e,a)}static calculateSpotPrice(t,e){return ra(t,e)}static calculateSpotPriceWithFee(t,e,a,s){return oa(t,e,a,s)}static calculateShares(t,e,a){return ia(t,e,a)}static calculateLiquidityOutAssetA(t,e,a,s){return la(t,e,a,s)}static calculateLiquidityOutAssetB(t,e,a,s){return ca(t,e,a,s)}};import{big as ua}from"@galacticcouncil/common";var{FeeUtils:Bt}=y,lt=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 a=new Map(this.tokens.map(i=>[i.id,i])),s=a.get(t),n=a.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:s.decimals,decimalsOut:n.decimals,balanceIn:s.balance,balanceOut:n.balance,assetInEd:s.existentialDeposit,assetOutEd:n.existentialDeposit}}validateAndBuy(t,e,a){let s=this.calculateInGivenOut(t,e),n=this.calculateTradeFee(s,a),i=Bt.toPct(a.exchangeFee),r=s+n,o=[];(e<this.minTradingLimit||s<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:s,amountOut:e,feePct:i,errors:o}}validateAndSell(t,e,a){let s=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(s,a),i=Bt.toPct(a.exchangeFee),r=s-n,o=[];(e<this.minTradingLimit||s<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:s,amountOut:r,feePct:i,errors:o}}calculateInGivenOut(t,e){let a=L.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(a);return s<0n?0n:s}calculateOutGivenIn(t,e){let a=L.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),s=BigInt(a);return s<0n?0n:s}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 a=L.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(a)}normalizeSpot(t,e,a){let s=e-a;if(s===0)return t;let n=ua.pow10(Math.abs(s));return s>0?t*n:t/n}};import{CompatibilityLevel as Qc}from"polkadot-api";import{Subscription as Zc}from"rxjs";import{big as Et,RUNTIME_DECIMALS as Ft}from"@galacticcouncil/common";var ct=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 a=new Map(this.tokens.map(i=>[i.id,i])),s=a.get(t),n=a.get(e);if(s==null)throw new Error("Pool does not contain tokenIn");if(n==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:s.balance,balanceOut:n.balance,decimalsIn:s.decimals,decimalsOut:n.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,a){let s=this.calculateInGivenOut(t,e),n=[];return e>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:n}}validateAndSell(t,e,a){let s=this.calculateOutGivenIn(t,e),n=[];return s>t.balanceOut&&n.push("TradeNotAllowed"),{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:n}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Et.toBigInt(1,Ft)}spotPriceOutGivenIn(t){return Et.toBigInt(1,Ft)}calculateTradeFee(t,e){return 0n}};import{AccountId as Tm}from"polkadot-api";import{toHex as wm}from"@polkadot-api/utils";import{Subscription as xm,filter as Om,map as Am,mergeMap as Bm}from"rxjs";import{erc20 as ba,HYDRATION_SS58_PREFIX as Fm}from"@galacticcouncil/common";var Mu=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{Binary as Xu}from"polkadot-api";import{decodeEventLog as zu}from"viem";import em from"big.js";import{big as sm,erc20 as da,h160 as ga}from"@galacticcouncil/common";var{ERC20:im}=da,{H160:rm}=ga;var om=10n**27n;var{ERC20:Hm}=ba;import{calculate_collateral_in_given_hollar_out as ya,calculate_collateral_out_given_hollar_in as Pa,calculate_hollar_in_given_collateral_out as fa,calculate_hollar_out_given_collateral_in as Sa,calculate_imbalance as Ta,calculate_max_price as va,calculate_buyback_limit as wa,calculate_buyback_price_with_fee as Ia}from"@galacticcouncil/math-hsm";var E=class{static calculateCollateralInGivenHollarOut(t,e,a){return ya(t,e,a)}static calculateCollateralOutGivenHollarIn(t,e,a){return Pa(t,e,a)}static calculateHollarOutGivenCollateralIn(t,e,a){return Sa(t,e,a)}static calculateHollarInGivenCollateralOut(t,e,a){return fa(t,e,a)}static calculateImbalance(t,e,a){return Ta(t,e,a)}static calculateBuybackLimit(t,e){return wa(t,e)}static calculateBuybackPriceWithFee(t,e,a){return Ia(t,e,a)}static calculateMaxPrice(t,e){return va(t,e)}};import{big as k,RUNTIME_DECIMALS as ut}from"@galacticcouncil/common";var{FeeUtils:W}=y,mt=class u extends ${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,a){let s=this.parsePair(t.assetOut,t.assetIn),n=super.calculateInGivenOut(s,e,{fee:this.fee}),i=this.calculateBuybackLimit(t);e>i&&a.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,n)>r&&a.push("MaxBuyPriceExceeded"),n>this.collateralBalance&&a.push("InsufficientCollateral"),a}validateTradeHollarOut(t,e,a){return this.collateralBalance+t>this.maxInHolding&&a.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&a.push("FacilitatorCapacityExceeded"),a}validateTradeConstraints(t,e,a){let s=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,s):this.validateTradeHollarOut(e,a,s)}validateAndBuy(t,e){let a=this.calculateInGivenOut(t,e),s=this.validateTradeConstraints(t,a,e);return{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e){let a=this.calculateOutGivenIn(t,e),s=this.validateTradeConstraints(t,e,a);return{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:s}}calculateHollarInGivenCollateralOut(t,e){let a=super.calculateInGivenOut(t,e,{fee:this.fee}),s=E.calculateHollarInGivenCollateralOut(e.toString(),a.toString(),W.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),a=E.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),W.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let a=super.calculateOutGivenIn(t,e,{fee:this.fee}),s=E.calculateCollateralOutGivenHollarIn(e.toString(),a.toString(),W.toRaw(this.buyBackFee).toString());return BigInt(s)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),a=E.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),W.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),a=E.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(a)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),a=E.calculateBuybackLimit(e.toString(),W.toRaw(this.buyBackRate).toString());return BigInt(a)}calculateBuyPrice(t,e,a){let s=E.calculateBuybackPriceWithFee(a.toString(),e.toString(),W.toRaw(this.buyBackFee).toString()),[n,i]=JSON.parse(s),r=k.pow10(t.decimalsIn+ut-t.decimalsOut);return BigInt(n)*r/BigInt(i)}calculateMaxPrice(t){let e=this.getCollateralPeg(),a=E.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[s,n]=JSON.parse(a),i=k.pow10(ut-t.decimalsOut);return BigInt(s)*i/BigInt(n)}spotPriceInGivenOut(t){let e=k.toBigInt(1,t.decimalsOut),s=this.calculateInGivenOut(t,e)*k.pow10(ut-t.decimalsOut);return this.normalizeSpotPrice(s,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=k.toBigInt(1,t.decimalsIn),s=this.calculateOutGivenIn(t,e)*k.pow10(ut-t.decimalsIn);return this.normalizeSpotPrice(s,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(s=>s.id!==this.hollarId),e=this.pegs[t],a=this.tokens[t].decimals;return this.isDefaultPeg(e)?[k.toBigInt(1,18).toString(),k.toBigInt(1,a).toString()]:e}isDefaultPeg(t){let[e,a]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&a==="1"}normalizeSpotPrice(t,e,a){let s=e-a;if(s===0)return t;let n=k.pow10(Math.abs(s));return s>0?t*n:t/n}};import{AccountId as Bp,CompatibilityLevel as Ep}from"polkadot-api";import{toHex as _p}from"@polkadot-api/utils";import{Subscription as Mp,combineLatest as Dp,filter as Lp,map as Hp,mergeMap as Np,pairwise as qp}from"rxjs";import{h160 as Oa,HYDRATION_SS58_PREFIX as Up}from"@galacticcouncil/common";import{Binary as cp}from"polkadot-api";import{decodeEventLog as mp}from"viem";var{FeeUtils:jp}=y,{H160:Qp}=Oa;var Z=class{static get(t){switch(t.type){case"Aave":return ct.fromPool(t);case"XYK":return lt.fromPool(t);case"Omnipool":return ot.fromPool(t);case"LBP":return it.fromPool(t);case"Stableswap":return $.fromPool(t);case"HSM":return mt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as Ea}from"@galacticcouncil/common";import{Subject as Ed,Subscription as Fd,takeUntil as Rd}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:Kd}=Ea;var tt=class{getProposals(t,e,a){let s=a.filter(m=>m.type==="XYK"),n=a.filter(m=>m.type!=="XYK"),i=new Set(n.map(m=>m.tokens).flat().map(m=>m.id)),r=i.has(t),o=i.has(e),l=new z,c=m=>{let h=dt(m),f=Object.keys(h),F=f.flatMap(O=>h[O]);return l.buildAndPopulateGraph(f,F)};if(!r&&!o){let m=s.filter(F=>F.tokens.find(O=>O.id===t)||F.tokens.find(O=>O.id===e)),h=c(m),f=l.findPaths(h,t,e);return this.parsePaths(f)}if(r&&o){let m=c(n),h=l.findPaths(m,t,e);return this.parsePaths(h)}let p=r?e:t,b=s.filter(m=>m.tokens.some(h=>h.id===p));if(b.length===0)return[];let d=[...n,...b],P=c(d),g=l.findPaths(P,t,e);return this.parsePaths(g)}parsePaths(t){let e=[];for(let a of t){let s=[];for(let n=0;n<a.length;n++){let i=a[n],r=a[n+1];if(r==null)break;s.push(this.toEdge(i,r))}e.push(s)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var et=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new tt,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,a){return`${t}->${e}::${a.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:a=[]}=this.filter,s=new Set(e),n=new Set(a);return t.filter(i=>n.has(i.type)?!1:s.size>0?s.has(i.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let a=await this.getPools();return this.validateInput(t,e,a),this.getPaths(t,e,a)}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(s=>s!==t).map(s=>this.getRoutes(s,t)))).filter(s=>s.length>0).map(([s])=>s[0].assetIn).sort()}validateInput(t,e,a){if(a.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let s=this.getAssets(a);if(!s.has(t))throw new Error(t+" is not supported asset");if(!s.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(a)}getAssets(t){let e=t.map(a=>a.tokens.map(s=>s.id)).flat().sort((a,s)=>a>s?1:-1);return new Set(e)}getPaths(t,e,a){let s=this.toPoolsMap(a);return this.getProposals(t,e,a).filter(i=>this.validPath(i,s)).map(i=>this.toHops(i,s))}getProposals(t,e,a){let s=this.buildRouteKey(t,e,a);if(this.routeProposals.has(s))return this.routeProposals.get(s);let n=this.routeSuggester.getProposals(t,e,a);return this.routeProposals.set(s,n),n}validPath(t,e){return t.length>0&&t.map(a=>this.validEdge(a,e)).reduce((a,s)=>a&&s)}validEdge([t,e,a],s){return s.get(t)?.validatePair(e,a)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Z.get(e)]))}toHops(t,e){return t.map(([a,s,n])=>{let i=e.get(a);return{poolAddress:a,poolId:i?.id,pool:i?.type,assetIn:s,assetOut:n}})}};import{big as w,RUNTIME_DECIMALS as Y}from"@galacticcouncil/common";var Rt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Rt||{}),_t=(a=>(a.Dca="Dca",a.TwapSell="TwapSell",a.TwapBuy="TwapBuy",a))(_t||{}),Ct=(a=>(a.OrderTooSmall="OrderTooSmall",a.OrderTooBig="OrderTooBig",a.OrderImpactTooBig="OrderImpactTooBig",a))(Ct||{});var{FeeUtils:kt}=y,at=class extends et{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,a){let s=super.validateInput(t,e,a),n=super.getPaths(t,e,a);if(!n.length)throw new pt(t,e);return{paths:n,pools:a,poolsMap:s}}async withCtx(t,e,a){let s=await super.getPools(),n=this.buildCtxSync(t,e,s);return a(n)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((a,s)=>{let n=a[a.length-1].amountOut,i=s[s.length-1].amountOut;return n>i?-1:1});return e.find(a=>a.every(s=>s.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(a=>a.tradeFeeRange).length>0){let a=t.map(n=>n.tradeFeeRange?.[0]??n.tradeFeePct).reduce((n,i)=>n+i),s=t.map(n=>n.tradeFeeRange?.[1]??n.tradeFeePct).reduce((n,i)=>n+i);return[a,s]}}getPoolFeeRange(t,e){let a=t.min?kt.toPct(t.min):void 0,s=t.max?kt.toPct(t.max):void 0;if(a&&s)return[a,Math.max(s,e)]}async getBestSell(t,e,a){return this.getSell(t,e,a)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,a,s){return this.withCtx(t,e,async({paths:n,poolsMap:i})=>{let r;if(s)r=await this.toSellSwaps(a,s,i);else{let o=n.map(c=>this.toSellSwaps(a,c,i)),l=await Promise.all(o);r=this.findBestSellRoute(l)}return this.buildSell(i,r)})}async getSells(t,e,a){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let i=s.map(o=>this.toSellSwaps(a,o,n));return(await Promise.all(i)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(n,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let a=e[0],s=e[e.length-1],n=this.isDirectTrade(e),i=this.getSellSpot(e),r=s.amountOut,o=n?s.calculatedOut:this.calculateDelta0Y(a.amountIn,e,t),l=o-r,c=this.getRouteFeeRange(e),p=n?s.tradeFeePct:I.calculateSellFee(o,r),b=B.mulSpot(a.amountIn,i,a.assetInDecimals,s.assetOutDecimals),d=I.calculateDiffToRef(o,b);return{type:"Sell",amountIn:a.amountIn,amountOut:s.amountOut,spotPrice:i,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:w.toDecimal(a.amountIn,a.assetInDecimals),amountOut:w.toDecimal(s.amountOut,s.assetOutDecimals),spotPrice:w.toDecimal(i,Y),tradeFee:w.toDecimal(l,s.assetOutDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(P=>P.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,a)=>e*a/10n**BigInt(Y))}calculateDelta0Y(t,e,a){let s=[];for(let n=0;n<e.length;n++){let i=e[n],r=a.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;n>0?l=s[n-1]:l=t;let c=r.calculateOutGivenIn(o,l);s.push(c)}return s[s.length-1]}async calculateMostLiquidRoute(t,e,a){let{paths:s,pools:n,poolsMap:i}=a,l=n.filter(g=>g.tokens.some(m=>m.id===t)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(m=>m.id===t)).map(g=>g.map(m=>m.balance).reduce((m,h)=>m+h)).sort((g,m)=>m<g?-1:1)[0],c=B.getFraction(l,.1),p=await Promise.all(s.map(g=>this.toSellSwaps(c,g,i))),d=this.findBestSellRoute(p).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut})),P=this.buildRouteKey(t,e,n);return this.mlr.set(P,d),d}async toSellSwaps(t,e,a){let s=[];for(let n=0;n<e.length;n++){let i=e[n],r=a.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;n>0?l=s[n-1].amountOut:l=typeof t=="string"?w.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r),{amountOut:p,calculatedOut:b,feePct:d,errors:P}=r.validateAndSell(o,l,c),g=this.getPoolFeeRange(c,d),m=r.spotPriceOutGivenIn(o),h=B.mulSpot(l,m,o.decimalsIn,o.decimalsOut),f=I.calculateDiffToRef(b,h);s.push({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:p,calculatedOut:b,spotPrice:m,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:P,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountIn:w.toDecimal(l,o.decimalsIn),amountOut:w.toDecimal(p,o.decimalsOut),calculatedOut:w.toDecimal(b,o.decimalsOut),spotPrice:w.toDecimal(m,Y),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:P}}})}return s}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async a=>{let s=this.buildRouteKey(t,e,a.pools),n=this.mlr.get(s);return n||this.calculateMostLiquidRoute(t,e,a)})}async getSpotPrice(t,e){return this.withCtx(t,e,async a=>{let{pools:s,poolsMap:n}=a,i=this.buildRouteKey(t,e,s),r=this.mlr.get(i);r||(r=await this.calculateMostLiquidRoute(t,e,a));let o=await this.toSellSwaps("1",r,n);return{amount:this.getSellSpot(o),decimals:Y}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((a,s)=>{let n=a[0].amountIn,i=s[0].amountIn;return n>i?1:-1});return e.find(a=>a.every(s=>s.errors.length==0))||e[0]}async getBestBuy(t,e,a){return this.getBuy(t,e,a)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,a,s){return this.withCtx(t,e,async({paths:n,poolsMap:i})=>{let r;if(s)r=await this.toBuySwaps(a,s,i);else{let o=n.map(c=>this.toBuySwaps(a,c,i)),l=await Promise.all(o);r=this.findBestBuyRoute(l)}return this.buildBuy(i,r)})}async getBuys(t,e,a){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let i=s.map(o=>this.toBuySwaps(a,o,n));return(await Promise.all(i)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(n,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let a=e[e.length-1],s=e[0],n=this.isDirectTrade(e),i=this.getBuySpot(e),r=s.amountIn,o=n?s.calculatedIn:this.calculateDelta0X(a.amountOut,e,t),l=r-o,c=this.getRouteFeeRange(e),p=n?s.tradeFeePct:I.calculateBuyFee(o,r),b=B.mulSpot(a.amountOut,i,a.assetOutDecimals,s.assetInDecimals),d;return o===0n?d=-100:d=I.calculateDiffToRef(b,o),{type:"Buy",amountOut:a.amountOut,amountIn:s.amountIn,spotPrice:i,tradeFee:l,tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:w.toDecimal(a.amountOut,a.assetOutDecimals),amountIn:w.toDecimal(s.amountIn,s.assetInDecimals),spotPrice:w.toDecimal(i,Y),tradeFee:w.toDecimal(l,s.assetInDecimals),tradeFeePct:p,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(P=>P.toHuman())}}}}calculateDelta0X(t,e,a){let s=[];for(let n=e.length-1;n>=0;n--){let i=e[n],r=a.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;n==e.length-1?l=t:l=s[0];let c=r.calculateInGivenOut(o,l);s.unshift(c)}return s[0]}async toBuySwaps(t,e,a){let s=[];for(let n=e.length-1;n>=0;n--){let i=e[n],r=a.get(i.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(i.assetIn,i.assetOut),l;n==e.length-1?l=typeof t=="string"?w.toBigInt(t,o.decimalsOut):t:l=s[0].amountIn;let c=await this.ctx.getPoolFees(o,r),{amountIn:p,calculatedIn:b,feePct:d,errors:P}=r.validateAndBuy(o,l,c),g=this.getPoolFeeRange(c,d),m=r.spotPriceInGivenOut(o),h=B.mulSpot(l,m,o.decimalsOut,o.decimalsIn),f;b===0n?f=-100:f=I.calculateDiffToRef(h,b),s.unshift({...i,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:p,calculatedIn:b,spotPrice:m,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:P,isSupply(){return r.type==="Aave"&&r.tokens[0].id===i.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===i.assetIn},toHuman(){return{...i,amountOut:w.toDecimal(l,o.decimalsOut),amountIn:w.toDecimal(p,o.decimalsIn),calculatedIn:w.toDecimal(b,o.decimalsIn),spotPrice:w.toDecimal(m,Y),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:P}}})}return s}};import{big as v}from"@galacticcouncil/common";var Mt=6e3,Dt=1000000000000000n,st=6,yt=-5,Pt=216e5,pb=3,Lt=.1,Ht=6;import{Enum as Nt}from"polkadot-api";var H=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:s,poolId:n})=>s==="Stableswap"?{pool:Nt("Stableswap",n),asset_in:e,asset_out:a}:{pool:Nt(s),asset_in:e,asset_out:a})}};var ft=class{schedulerOptions;router;constructor(t,e={}){this.router=new at(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Dt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,a,s,n){let i=await this.router.getBestSell(t,e,a),{amountIn:r,swaps:o,priceImpactPct:l}=i,c=o[0],p=o[o.length-1],{assetInDecimals:b}=c,{assetOutDecimals:d}=p,P=Math.abs(l),g=await this.getMinimumOrderBudget(t,b),m=this.getOptimalTradeCount(P),h=this.getMaximumTradeCount(r,g,s),f=n||Math.min(m,h),F=Math.round(s/f),O=r/BigInt(f),x=await this.router.getBestSell(t,e,O),N=r<g,M=[];N&&M.push("OrderTooSmall");let G=await this.getAssetOutEd(p),D=x.amountOut*BigInt(f),Gt=this.toBlockPeriod(F),Ut=x.tradeFee*BigInt(f),Vt=H.build(o),St={assetIn:t,assetOut:e,assetOutEd:G,errors:M,maxTradeCount:h,tradeCount:f,tradeFee:Ut,tradeImpactPct:x.priceImpactPct,tradePeriod:Gt,tradeRoute:Vt,type:"Dca"};return{...St,amountIn:r,amountOut:D,tradeAmountIn:x.amountIn,tradeAmountOut:x.amountOut,toHuman(){return{...St,amountIn:v.toDecimal(r,b),amountOut:v.toDecimal(D,d),assetOutEd:v.toDecimal(G,d),tradeAmountIn:v.toDecimal(x.amountIn,b),tradeAmountOut:v.toDecimal(x.amountOut,d)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let a=await this.router.getSpotPrice(0,t);if(a)return B.mulSpot(this.minOrderBudget,a.amount,12,e);let s=await this.router.getSpotPrice(t,0);if(s)return B.divSpot(this.minOrderBudget,s.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,a){let s=e*2n/10n;if(s===0n)return 0;let n=Number(t/s),i=Math.floor(a/this.blockTime),r=Math.max(0,Math.floor(i*(1-.1)));return Math.min(n,r)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,a,s){let n=await this.router.getBestSell(t,e,a),{swaps:i}=n,r=i[0],o=i[i.length-1],{assetInDecimals:l}=r,{assetOutDecimals:c}=o,p=await this.getMinimumOrderBudget(t,l),b=n.amountIn<p,d=[];b&&d.push("OrderTooSmall");let P=await this.getAssetOutEd(o),g=this.toBlockPeriod(s),m=H.build(i),h={assetIn:t,assetOut:e,assetOutEd:P,errors:d,maxTradeCount:0,tradeCount:0,tradeFee:n.tradeFee,tradeImpactPct:n.priceImpactPct,tradePeriod:g,tradeRoute:m,type:"Dca"};return{...h,amountIn:0n,amountOut:0n,tradeAmountIn:n.amountIn,tradeAmountOut:n.amountOut,toHuman(){return{...h,amountIn:"0",amountOut:"0",assetOutEd:v.toDecimal(P,c),tradeAmountIn:v.toDecimal(n.amountIn,l),tradeAmountOut:v.toDecimal(n.amountOut,c)}}}}async getTwapSellOrder(t,e,a){let s=await this.router.getBestSell(t,e,a),{amountIn:n,swaps:i,priceImpactPct:r}=s,o=i[0],l=i[i.length-1],{assetInDecimals:c}=o,{assetOutDecimals:p}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),P=n/BigInt(d),[g,m]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestSell(o.assetIn,l.assetOut,P)]),h=d===1,f=n<g,F=m.priceImpactPct<-5,O=[];f||h?O.push("OrderTooSmall"):F&&O.push("OrderImpactTooBig");let x=await this.getAssetOutEd(l),N=m.amountOut*BigInt(d),M=m.tradeFee*BigInt(d),G=H.build(i),D={assetIn:t,assetOut:e,assetOutEd:x,errors:O,tradeCount:d,tradeImpactPct:m.priceImpactPct,tradePeriod:6,tradeRoute:G,type:"TwapSell"};return{...D,amountIn:n,amountOut:N,tradeAmountIn:m.amountIn,tradeAmountOut:m.amountOut,tradeFee:M,toHuman(){return{...D,amountIn:v.toDecimal(n,c),amountOut:v.toDecimal(N,p),assetOutEd:v.toDecimal(x,p),tradeAmountIn:v.toDecimal(m.amountIn,c),tradeAmountOut:v.toDecimal(m.amountOut,p),tradeFee:v.toDecimal(M,p)}}}}async getTwapBuyOrder(t,e,a){let s=await this.router.getBestBuy(t,e,a),{amountOut:n,swaps:i,priceImpactPct:r}=s,o=i[0],l=i[i.length-1],{assetInDecimals:c}=o,{assetOutDecimals:p}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),P=n/BigInt(d),[g,m]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestBuy(o.assetIn,l.assetOut,P)]),h=m.amountIn*BigInt(d),f=d===1,F=h<g,O=m.priceImpactPct<-5,x=[];F||f?x.push("OrderTooSmall"):O&&x.push("OrderImpactTooBig");let N=await this.getAssetOutEd(l),M=m.tradeFee*BigInt(d),G=H.build(i),D={assetIn:t,assetOut:e,assetOutEd:N,errors:x,tradeCount:d,tradeImpactPct:m.priceImpactPct,tradePeriod:6,tradeRoute:G,type:"TwapBuy"};return{...D,amountIn:h,amountOut:n,tradeAmountIn:m.amountIn,tradeAmountOut:m.amountOut,tradeFee:M,toHuman(){return{...D,amountIn:v.toDecimal(h,c),amountOut:v.toDecimal(n,p),assetOutEd:v.toDecimal(N,p),tradeAmountIn:v.toDecimal(m.amountIn,c),tradeAmountOut:v.toDecimal(m.amountOut,p),tradeFee:v.toDecimal(M,c)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let s=216e5/(this.blockTime*6);return Math.round(s)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,a=Math.round(e);return Math.max(a,6)}async getAssetOutEd(t){let s=(await this.router.getPools()).find(n=>n.address===t.poolAddress)?.tokens.find(n=>n.id===t.assetOut);if(!s)throw new Error(`Asset ${t.assetOut} not found in pool ${t.poolAddress}`);return s.existentialDeposit}};export{Lt as DCA_TIME_RESERVE,Mt as DEFAULT_BLOCK_TIME,Dt as DEFAULT_MIN_BUDGET,Ht as ORDER_MIN_BLOCK_PERIOD,et as Router,st as TWAP_EXECUTION_INTERVAL,Pt as TWAP_MAX_DURATION,yt as TWAP_MAX_PRICE_IMPACT,pb as TWAP_TX_MULTIPLIER,Ct as TradeOrderError,_t as TradeOrderType,H as TradeRouteBuilder,at as TradeRouter,ft as TradeScheduler,Rt as TradeType};
|
|
1
|
+
var ee=Object.defineProperty;var J=(u,t)=>{for(var e in t)ee(u,e,{get:t[e],enumerable:!0})};import ae from"buffer";typeof window<"u"&&(window.Buffer=ae.Buffer);var Z=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 ie=10,tt=class{isNotVisited(t,e){let a=!0;return e.forEach(i=>{(i[0]===t[0]||i[1]===t[1])&&(a=!1)}),a}findPaths(t,e,a){let i=[],s=new Z,n=[];for(n.push([e,""]),s.enqueue(n);s.size()>0;){let r=s.dequeue();if(!r||r.length>ie)continue;let o=r[r.length-1];(a===null||o[0]===a)&&i.push(r),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let m=[...r];m.push(c),s.enqueue(m)}})}return i}findShortestPaths(t,e,a){let i=[],s=new Z,n=[];n.push([e,""]),s.enqueue(n);let r=1/0;for(;s.size()>0;){let o=s.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===a){o.length<r?(r=o.length,i.length=0,i.push(o)):o.length===r&&i.push(o);continue}let c=t.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&s.enqueue([...o,m])}return i}buildAndPopulateGraph(t,e){let a=new Map;for(let i of t)a.set(parseInt(i),[]);for(let[i,s,n]of e)a.get(s)?.push([n,i]);return a}};function yt(u){let t={};for(let e of u){let a=e.tokens.length;for(let i=0;i<a;i++){t[e.tokens[i].id]||(t[e.tokens[i].id]=[]);for(let s=0;s<a;s++){if(i==s)continue;let n=[e.address,e.tokens[i].id,e.tokens[s].id];t[e.tokens[i].id].push(n)}}}return t}import{calculate_in_given_out as se,calculate_out_given_in as ne,calculate_linear_weights as re,calculate_pool_trade_fee as oe,get_spot_price as le}from"@galacticcouncil/math-lbp";var M=class{static getSpotPrice(t,e,a,i,s){return le(t,e,a,i,s)}static calculateInGivenOut(t,e,a,i,s){return se(t,e,a,i,s)}static calculateOutGivenIn(t,e,a,i,s){return ne(t,e,a,i,s)}static calculateLinearWeights(t,e,a,i,s){return re(t,e,a,i,s)}static calculatePoolTradeFee(t,e,a){return oe(t,e,a)}};import{big as Rt,RUNTIME_DECIMALS as _t}from"@galacticcouncil/common";var lt={};J(lt,{withTimeout:()=>ce});function ce(u,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);u.then(n=>{clearTimeout(s),a(n)},n=>{clearTimeout(s),i(n)})})}var R={};J(R,{divSpot:()=>me,getFraction:()=>pe,mulScaled:()=>Ft,mulSpot:()=>ue});import{RUNTIME_DECIMALS as Et}from"@galacticcouncil/common";function Ft(u,t,e,a,i){let s=e+a-i,n=u*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function ue(u,t,e,a){return Ft(u,t,e,Et,a)}function me(u,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(Et+a-e);return u*i/t}function pe(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let a=BigInt(10)**BigInt(e),i=BigInt(Math.round(t*Number(a)));return u*i/(BigInt(100)*a)}var S={};J(S,{FeeUtils:()=>ft,shiftNeg:()=>be});import ge from"big.js";var ft=class u{static toPct(t){let[e,a]=t;return u.safeDivide(e*100,a)}static toRaw(t){let[e,a]=t;return u.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 i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function be(u,t){let e=ge(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var et={};J(et,{findNestedKey:()=>he,findNestedObj:()=>ye,jsonFormatter:()=>fe});var he=(u,t)=>{let e=[];return JSON.stringify(u,(a,i)=>(i&&i[t]&&e.push(i),i)),e[0]},ye=(u,t,e)=>{let a;return JSON.stringify(u,(i,s)=>(s&&s[t]===e&&(a=s),s)),a},fe=(u,t)=>typeof t=="bigint"?t.toString():t;var w={};J(w,{calculateBuyFee:()=>ve,calculateDiffToAvg:()=>Pe,calculateDiffToRef:()=>Se,calculateSellFee:()=>Te});import D from"big.js";function Pe(u,t){let e=D(u.toString()),a=D(t.toString());return e.minus(a).abs().div(e.plus(a).div(2)).mul(100).round(2).toNumber()}function Se(u,t){if(t===0n)return 0;let e=D(u.toString()),a=D(t.toString());return e.minus(a).div(a).mul(100).round(2).toNumber()}function Te(u,t){if(u===0n)return 0;let e=D(u.toString()),a=D(t.toString());return D(1).minus(a.div(e)).mul(100).round(2).toNumber()}function ve(u,t){if(u===0n)return 0;let e=D(u.toString());return D(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as Ii}from"@thi.ng/cache";var{FeeUtils:kt}=S,ct=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(t),s=a.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,weightIn:i.weight,weightOut:s.weight}}validateAndBuy(t,e,a){let i=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&s.push("MaxOutRatioExceeded"),i===t.assetOut){let r=this.calculateTradeFee(e,a),o=kt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&s.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:s}}else{let r=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return r>o&&s.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:s}}}validateAndSell(t,e,a){let i=this.tokens[0].id,s=[];e<this.minTradingLimit&&s.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&s.push("MaxInRatioExceeded"),i===t.assetIn){let r=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return r>o&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:s}}else{let r=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(r,a),l=kt.toPct(this.repayFeeApply?a.repayFee:a.exchangeFee),c=r-o,m=t.balanceOut/this.maxOutRatio;return c>m&&s.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:s}}}calculateInGivenOut(t,e){let a=M.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e){let a=M.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(t){let e=M.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),Rt.toBigInt(1,_t).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=M.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),Rt.toBigInt(1,_t).toString());return BigInt(e)}calculateTradeFee(t,e){let a=M.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(a)}};import{CompatibilityLevel as Cr}from"polkadot-api";import{Subscription as Dr,distinctUntilChanged as Lr,filter as qr,map as Nr}from"rxjs";import{memoize1 as Un}from"@thi.ng/memoize";import{TLRUCache as $n}from"@thi.ng/cache";import{ReplaySubject as zn,Subscription as jn,combineLatest as Qn,defer as Jn,from as Zn,interval as tr,merge as er,of as ar,EMPTY as ir}from"rxjs";import{bufferCount as nr,bufferTime as rr,catchError as or,filter as lr,finalize as cr,map as ur,pairwise as mr,repeat as pr,skip as dr,share as gr,startWith as br,switchMap as hr,tap as yr,throttleTime as fr}from"rxjs/operators";import{hydration as Ps,hydrationNext as Ss,hydrationIce as Ts}from"@galacticcouncil/descriptors";import{log as Ie}from"@galacticcouncil/common";import{map as us,shareReplay as ms,tap as ps}from"rxjs";import{defer as $i,from as Xi,of as Yi,timer as Ki}from"rxjs";import{catchError as ji,distinctUntilChanged as Qi,expand as Ji,map as Zi,shareReplay as ts,skip as es,switchMap as as,timeout as is}from"rxjs/operators";var{logger:gs}=Ie;import{getWsProvider as Os}from"polkadot-api/ws";import{withLogsRecorder as Bs}from"polkadot-api/logs-provider";import{Binary as Us}from"polkadot-api";import{log as we}from"@galacticcouncil/common";import{combineLatest as js,concat as Qs,defer as Js,from as Zs}from"rxjs";import{bufferCount as en,distinctUntilChanged as an,debounceTime as sn,map as nn,retry as rn,startWith as on,switchMap as ln,tap as cn,take as un,skip as mn,connect as pn}from"rxjs/operators";var{logger:hn}=we;import{BehaviorSubject as Fn}from"rxjs";import{log as Oe}from"@galacticcouncil/common";var Dn={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM",UniswapV3:"UNIV3"},{logger:Ln}=Oe;var{withTimeout:Fr}=lt;import{calculate_in_given_out as Be,calculate_lrna_in_given_out as Ee,calculate_out_given_in as Fe,calculate_out_given_lrna_in as Re,calculate_spot_price as _e,calculate_lrna_spot_price as ke,calculate_shares as Ce,calculate_liquidity_out as Me,calculate_liquidity_lrna_out as De,verify_asset_cap as Le,calculate_liquidity_hub_in as qe,is_sell_allowed as Ne,is_buy_allowed as He,is_add_liquidity_allowed as Ve,is_remove_liquidity_allowed as Ge,recalculate_asset_fee as Ue,recalculate_protocol_fee as We}from"@galacticcouncil/math-omnipool";import X from"big.js";var v=class{static calculateSpotPrice(t,e,a,i){return _e(t,e,a,i)}static calculateLrnaSpotPrice(t,e){return ke(t,e)}static calculateInGivenOut(t,e,a,i,s,n,r,o,l,c){return Be(t,e,a,i,s,n,r,o,l,c)}static calculateLrnaInGivenOut(t,e,a,i,s,n){return Ee(t,e,a,i,s,n)}static calculateOutGivenIn(t,e,a,i,s,n,r,o,l,c){return Fe(t,e,a,i,s,n,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,a,i,s,n){return Re(t,e,a,i,s,n)}static calculateShares(t,e,a,i){return Ce(t,e,a,i)}static calculateLiquidityOut(t,e,a,i,s,n,r,o){return Me(t,e,a,i,s,n,r,o)}static calculateLiquidityLRNAOut(t,e,a,i,s,n,r,o){return De(t,e,a,i,s,n,r,o)}static calculateCapDifference(t,e,a,i){let s=X(e),n=X(t),r=X(i),o=X(a),l=X(10).pow(18),c=o.div(l);if(s.div(r).lt(c)){let b=c.times(r).minus(s).times(n),d=s.times(X(1).minus(c));return b.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,a,i){return qe(t,e,a,i)}static isSellAllowed(t){return Ne(t)}static isBuyAllowed(t){return He(t)}static isAddLiquidityAllowed(t){return Ve(t)}static isRemoveLiquidityAllowed(t){return Ge(t)}static recalculateAssetFee(t,e,a,i,s,n,r,o,l,c,m){return Ue(t,e,a,i,s,n,r,o,l,c,m)}static recalculateProtocolFee(t,e,a,i,s,n,r,o,l,c,m){return We(t,e,a,i,s,n,r,o,l,c,m)}static verifyAssetCap(t,e,a,i){return Le(t,e,a,i)}};import{big as $e}from"@galacticcouncil/common";var{FeeUtils:C}=S,mt=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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(t),s=a.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:i.hubReserves,hubReservesOut:s.hubReserves,sharesIn:i.shares,sharesOut:s.shares,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,tradeableIn:i.tradeable,tradeableOut:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,a){let i=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,a),n=i===0n?0:w.calculateBuyFee(i,s),r=[],o=v.isSellAllowed(t.tradeableIn),l=v.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return s>m&&r.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,a){let i=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,a),n=w.calculateSellFee(i,s),r=[],o=v.isSellAllowed(t.tradeableIn),l=v.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return s>m&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:n,errors:r}}calculateInGivenOut(t,e,a){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,a);let i=v.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?C.toRaw(a.assetFee).toString():"0",a?C.toRaw(a.protocolFee).toString():"0",a?C.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateLrnaInGivenOut(t,e,a){let i=v.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?C.toRaw(a.assetFee).toString():"0",a?C.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e,a){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,a);let i=v.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?C.toRaw(a.assetFee).toString():"0",a?C.toRaw(a.protocolFee).toString():"0",a?C.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}calculateOutGivenLrnaIn(t,e,a){let i=v.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),a?C.toRaw(a.assetFee).toString():"0",a?C.toRaw(a.maxSlipFee).toString():"0"),s=BigInt(i);return s<0n?0n:s}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=v.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=v.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=v.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=v.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,a){let i=e-a;if(i===0)return t;let s=$e.pow10(Math.abs(i));return i>0?t*s:t/s}};import{AccountId as Ro,Binary as Ct,CompatibilityLevel as _o,Enum as ze}from"polkadot-api";import{toHex as Mo}from"@polkadot-api/utils";import{Subscription as Lo,distinctUntilChanged as qo,filter as No,finalize as Ho,map as Vo,merge as Go,tap as Uo}from"rxjs";import{HYDRATION_SS58_PREFIX as $o}from"@galacticcouncil/common";var{FeeUtils:Io}=S;var{FeeUtils:tl}=S,el=Ct.toHex(Ct.fromText("omnipool")),al=ze("Short");import{calculate_in_given_out as Qe,calculate_out_given_in as Je,calculate_amplification as Ze,calculate_add_one_asset as ta,calculate_liquidity_out_one_asset as ea,calculate_shares as aa,calculate_shares_for_amount as ia,calculate_spot_price_with_fee as sa,pool_account_name as na,recalculate_peg as ra}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return na(t)}static defaultPegs(t){let e=[];for(let a=0;a<t;a++)e.push(["1","1"]);return e}static calculateAmplification(t,e,a,i,s){return Ze(t,e,a,i,s)}static calculateInGivenOut(t,e,a,i,s,n,r){return Qe(t,e,a,i,s,n,r)}static calculateAddOneAsset(t,e,a,i,s,n,r){return ta(t,e,a,i,s,n,r)}static calculateSharesForAmount(t,e,a,i,s,n,r){return ia(t,e,a,i,s,n,r)}static calculateOutGivenIn(t,e,a,i,s,n,r){return Je(t,e,a,i,s,n,r)}static calculateLiquidityOutOneAsset(t,e,a,i,s,n,r){return ea(t,e,a,i,s,n,r)}static calculateShares(t,e,a,i,s,n){return aa(t,e,a,i,s,n)}static calculateSpotPriceWithFee(t,e,a,i,s,n,r,o){return sa(t,e,a,i,s,n,r,o)}static recalculatePegs(t,e,a,i,s,n){let r=ra(t,e,a,i,s,n);return JSON.parse(r)}};import{RUNTIME_DECIMALS as oa,big as Mt}from"@galacticcouncil/common";var{FeeUtils:Y}=S,K=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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(t),s=a.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,tradeableIn:this.id===t?15:i.tradeable,tradeableOut:this.id===e?15:s.tradeable,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,a){let i=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,a),n=i===0n?0:w.calculateBuyFee(i,s),r=[],o=v.isSellAllowed(t.tradeableIn),l=v.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,a){let i=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,a),n=w.calculateSellFee(i,s),r=[],o=v.isSellAllowed(t.tradeableIn),l=v.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||i<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:n,errors:r}}calculateIn(t,e,a){let i=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),a?Y.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateAddOneAsset(t,e,a){let i=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),a?Y.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateSharesForAmount(t,e,a){let i=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),a?Y.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateInGivenOut(t,e,a){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,a):t.assetIn==this.id?this.calculateSharesForAmount(t,e,a):this.calculateIn(t,e,a)}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,a){let i=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),a?Y.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateWithdrawOneAsset(t,e,a){let i=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),a?Y.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateShares(t,e,a){let i=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),a?Y.toRaw(a.fee).toString():"0",this.getPegs()),s=BigInt(i);return s<0n?0n:s}calculateOutGivenIn(t,e,a){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,a):t.assetOut==this.id?this.calculateShares(t,e,a):this.calculateOut(t,e,a)}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:a,decimals:i})=>({asset_id:e,amount:a,decimals:i}));return JSON.stringify(t,et.jsonFormatter)}getAssets(t,e){let a={asset_id:Number(t),amount:e.toString()};return JSON.stringify([a],et.jsonFormatter)}normalizeSpot(t,e,a,i,s){return e?t*Mt.pow10(oa-s):a?t/Mt.pow10(s-i):t}};import{AccountId as hc,CompatibilityLevel as yc}from"polkadot-api";import{toHex as Pc}from"@polkadot-api/utils";import{blake2b as Tc}from"@noble/hashes/blake2b";import{Subscription as Ic,distinctUntilChanged as wc,filter as xc,map as Oc,merge as Ac,tap as Bc}from"rxjs";import{HYDRATION_SS58_PREFIX as Fc,RUNTIME_DECIMALS as Rc}from"@galacticcouncil/common";import{Binary as ql}from"polkadot-api";import{decodeEventLog as Hl}from"viem";var{FeeUtils:oc}=S;var{FeeUtils:Xc}=S;import{calculate_in_given_out as ma,calculate_out_given_in as pa,calculate_pool_trade_fee as da,get_spot_price as ga,calculate_liquidity_in as ba,calculate_shares as ha,calculate_spot_price as ya,calculate_spot_price_with_fee as fa,calculate_liquidity_out_asset_a as Pa,calculate_liquidity_out_asset_b as Sa}from"@galacticcouncil/math-xyk";var N=class{static getSpotPrice(t,e,a){return ga(t,e,a)}static calculateInGivenOut(t,e,a){return ma(t,e,a)}static calculateOutGivenIn(t,e,a){return pa(t,e,a)}static calculatePoolTradeFee(t,e,a){return da(t,e,a)}static calculateLiquidityIn(t,e,a){return ba(t,e,a)}static calculateSpotPrice(t,e){return ya(t,e)}static calculateSpotPriceWithFee(t,e,a,i){return fa(t,e,a,i)}static calculateShares(t,e,a){return ha(t,e,a)}static calculateLiquidityOutAssetA(t,e,a,i){return Pa(t,e,a,i)}static calculateLiquidityOutAssetB(t,e,a,i){return Sa(t,e,a,i)}};import{big as Ta}from"@galacticcouncil/common";var{FeeUtils:Dt}=S,pt=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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(t),s=a.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}validateAndBuy(t,e,a){let i=this.calculateInGivenOut(t,e),s=this.calculateTradeFee(i,a),n=Dt.toPct(a.exchangeFee),r=i+s,o=[];(e<this.minTradingLimit||i<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:i,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,a){let i=this.calculateOutGivenIn(t,e),s=this.calculateTradeFee(i,a),n=Dt.toPct(a.exchangeFee),r=i-s,o=[];(e<this.minTradingLimit||i<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:i,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(t,e){let a=N.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e){let a=N.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(t){let e=N.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=N.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let a=N.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(a)}normalizeSpot(t,e,a){let i=e-a;if(i===0)return t;let s=Ta.pow10(Math.abs(i));return i>0?t*s:t/s}};import{CompatibilityLevel as fu}from"polkadot-api";import{Subscription as Su}from"rxjs";import{big as Lt,RUNTIME_DECIMALS as qt}from"@galacticcouncil/common";var dt=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 a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(t),s=a.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:i.balance,balanceOut:s.balance,decimalsIn:i.decimals,decimalsOut:s.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,a){let i=this.calculateInGivenOut(t,e),s=[];return e>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:i,calculatedIn:i,amountOut:e,feePct:0,errors:s}}validateAndSell(t,e,a){let i=this.calculateOutGivenIn(t,e),s=[];return i>t.balanceOut&&s.push("TradeNotAllowed"),{amountIn:e,calculatedOut:i,amountOut:i,feePct:0,errors:s}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Lt.toBigInt(1,qt)}spotPriceOutGivenIn(t){return Lt.toBigInt(1,qt)}calculateTradeFee(t,e){return 0n}};import{AccountId as Gm}from"polkadot-api";import{toHex as Wm}from"@polkadot-api/utils";import{Subscription as Xm,filter as Ym,map as Km,mergeMap as zm}from"rxjs";import{erc20 as Oa,HYDRATION_SS58_PREFIX as Qm}from"@galacticcouncil/common";var am=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");import{Binary as gm}from"polkadot-api";import{decodeEventLog as hm}from"viem";import vm from"big.js";import{big as wm,erc20 as wa,h160 as xa}from"@galacticcouncil/common";var{ERC20:Om}=wa,{H160:Am}=xa;var Bm=10n**27n;var{ERC20:np}=Oa;import{calculate_collateral_in_given_hollar_out as Ba,calculate_collateral_out_given_hollar_in as Ea,calculate_hollar_in_given_collateral_out as Fa,calculate_hollar_out_given_collateral_in as Ra,calculate_imbalance as _a,calculate_max_price as ka,calculate_buyback_limit as Ca,calculate_buyback_price_with_fee as Ma}from"@galacticcouncil/math-hsm";var _=class{static calculateCollateralInGivenHollarOut(t,e,a){return Ba(t,e,a)}static calculateCollateralOutGivenHollarIn(t,e,a){return Ea(t,e,a)}static calculateHollarOutGivenCollateralIn(t,e,a){return Ra(t,e,a)}static calculateHollarInGivenCollateralOut(t,e,a){return Fa(t,e,a)}static calculateImbalance(t,e,a){return _a(t,e,a)}static calculateBuybackLimit(t,e){return Ca(t,e)}static calculateBuybackPriceWithFee(t,e,a){return Ma(t,e,a)}static calculateMaxPrice(t,e){return ka(t,e)}};import{big as L,RUNTIME_DECIMALS as gt}from"@galacticcouncil/common";var{FeeUtils:z}=S,bt=class u extends K{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,a){let i=this.parsePair(t.assetOut,t.assetIn),s=super.calculateInGivenOut(i,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&a.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,s)>r&&a.push("MaxBuyPriceExceeded"),s>this.collateralBalance&&a.push("InsufficientCollateral"),a}validateTradeHollarOut(t,e,a){return this.collateralBalance+t>this.maxInHolding&&a.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&a.push("FacilitatorCapacityExceeded"),a}validateTradeConstraints(t,e,a){let i=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,i):this.validateTradeHollarOut(e,a,i)}validateAndBuy(t,e){let a=this.calculateInGivenOut(t,e),i=this.validateTradeConstraints(t,a,e);return{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e){let a=this.calculateOutGivenIn(t,e),i=this.validateTradeConstraints(t,e,a);return{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:i}}calculateHollarInGivenCollateralOut(t,e){let a=super.calculateInGivenOut(t,e,{fee:this.fee}),i=_.calculateHollarInGivenCollateralOut(e.toString(),a.toString(),z.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),a=_.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),z.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let a=super.calculateOutGivenIn(t,e,{fee:this.fee}),i=_.calculateCollateralOutGivenHollarIn(e.toString(),a.toString(),z.toRaw(this.buyBackFee).toString());return BigInt(i)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),a=_.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),z.toRaw(this.purchaseFee).toString());return BigInt(a)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),a=_.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(a)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),a=_.calculateBuybackLimit(e.toString(),z.toRaw(this.buyBackRate).toString());return BigInt(a)}calculateBuyPrice(t,e,a){let i=_.calculateBuybackPriceWithFee(a.toString(),e.toString(),z.toRaw(this.buyBackFee).toString()),[s,n]=JSON.parse(i),r=L.pow10(t.decimalsIn+gt-t.decimalsOut);return BigInt(s)*r/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),a=_.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[i,s]=JSON.parse(a),n=L.pow10(gt-t.decimalsOut);return BigInt(i)*n/BigInt(s)}spotPriceInGivenOut(t){let e=L.toBigInt(1,t.decimalsOut),i=this.calculateInGivenOut(t,e)*L.pow10(gt-t.decimalsOut);return this.normalizeSpotPrice(i,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=L.toBigInt(1,t.decimalsIn),i=this.calculateOutGivenIn(t,e)*L.pow10(gt-t.decimalsIn);return this.normalizeSpotPrice(i,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(i=>i.id!==this.hollarId),e=this.pegs[t],a=this.tokens[t].decimals;return this.isDefaultPeg(e)?[L.toBigInt(1,18).toString(),L.toBigInt(1,a).toString()]:e}isDefaultPeg(t){let[e,a]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&a==="1"}normalizeSpotPrice(t,e,a){let i=e-a;if(i===0)return t;let s=L.pow10(Math.abs(i));return i>0?t*s:t/s}};import{AccountId as zp,CompatibilityLevel as jp}from"polkadot-api";import{toHex as Zp}from"@polkadot-api/utils";import{Subscription as ad,combineLatest as id,filter as sd,map as nd,mergeMap as rd,pairwise as od}from"rxjs";import{h160 as La,HYDRATION_SS58_PREFIX as cd}from"@galacticcouncil/common";import{Binary as Fp}from"polkadot-api";import{decodeEventLog as _p}from"viem";var{FeeUtils:yd}=S,{H160:fd}=La;import y from"jsbi";import{LiquidityMath as Na,SwapMath as Ha,Tick as Va,TickList as Nt,TickMath as H}from"@uniswap/v3-sdk";var Tt=y.BigInt(0),Ht=y.BigInt(1),vt=y.BigInt(-1),at=class u{static calculateOutGivenIn(t,e,a){if(a<=0n||t.liquidity<=0n)return 0n;let i=u.computeSwap(t,e,y.BigInt(a.toString())),s=y.multiply(i.amountCalculated,vt);return BigInt(s.toString())}static calculateInGivenOut(t,e,a){if(a<=0n||t.liquidity<=0n)return 0n;let i=u.computeSwap(t,e,y.multiply(y.BigInt(a.toString()),vt));return BigInt(i.amountCalculated.toString())}static computeSwap(t,e,a){let i=u.buildTicks(t.ticks),s=t.tickSpacing,n=t.fee,r=e?y.add(H.MIN_SQRT_RATIO,Ht):y.subtract(H.MAX_SQRT_RATIO,Ht),o=y.greaterThanOrEqual(a,Tt),l=a,c=Tt,m=y.BigInt(t.sqrtPriceX96.toString()),b=t.tick,d=y.BigInt(t.liquidity.toString());for(;y.notEqual(l,Tt)&&y.notEqual(m,r);){let f=m,[g,p]=Nt.nextInitializedTickWithinOneWord(i,b,e,s);g<H.MIN_TICK?g=H.MIN_TICK:g>H.MAX_TICK&&(g=H.MAX_TICK);let h=H.getSqrtRatioAtTick(g),P=(e?y.lessThan(h,r):y.greaterThan(h,r))?r:h,[E,A,O,k]=Ha.computeSwapStep(m,P,d,l,n);if(m=E,o?(l=y.subtract(l,y.add(A,k)),c=y.subtract(c,O)):(l=y.add(l,O),c=y.add(c,y.add(A,k))),y.equal(m,h)){if(p){let F=Nt.getTick(i,g).liquidityNet;e&&(F=y.multiply(F,vt)),d=Na.addDelta(d,F)}b=e?g-1:g}else y.notEqual(m,f)&&(b=H.getTickAtSqrtRatio(m))}return{amountCalculated:c,sqrtPriceX96:m,liquidity:d,tick:b}}static buildTicks(t){return t.map(e=>new Va({index:e.index,liquidityGross:e.liquidityGross.toString(),liquidityNet:e.liquidityNet.toString()})).sort((e,a)=>e.index-a.index)}};import{RUNTIME_DECIMALS as Ga}from"@galacticcouncil/common";var Ua=1e6,Vt=10n**BigInt(Ga),Gt=192n,j=class u{type;address;id;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;token0;token1;sqrtPriceX96;tick;liquidity;tickSpacing;ticks;static fromPool(t){return new u(t)}constructor(t){this.type="UniswapV3",this.address=t.address,this.id=t.id,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.token0=t.token0,this.token1=t.token1,this.sqrtPriceX96=t.sqrtPriceX96,this.tick=t.tick,this.liquidity=t.liquidity,this.tickSpacing=t.tickSpacing,this.ticks=t.ticks}validatePair(t,e){let a=i=>i===this.token0||i===this.token1;return a(t)&&a(e)&&t!==e}parsePair(t,e){let a=new Map(this.tokens.map(n=>[n.id,n])),i=a.get(t),s=a.get(e);if(i==null)throw new Error("Pool does not contain tokenIn");if(s==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:i.decimals,decimalsOut:s.decimals,balanceIn:i.balance,balanceOut:s.balance,assetInEd:i.existentialDeposit,assetOutEd:s.existentialDeposit}}calculateInGivenOut(t,e,a){return at.calculateInGivenOut(this.toState(a!=null),this.isZeroForOne(t.assetIn),e)}calculateOutGivenIn(t,e,a){return at.calculateOutGivenIn(this.toState(a!=null),this.isZeroForOne(t.assetIn),e)}spotPriceOutGivenIn(t){let e=this.spotOutPerIn(this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsIn,t.decimalsOut)}spotPriceInGivenOut(t){let e=this.spotOutPerIn(!this.isZeroForOne(t.assetIn));return this.normalizeSpot(e,t.decimalsOut,t.decimalsIn)}validateAndSell(t,e,a){let i=this.calculateOutGivenIn(t,e),s=this.calculateOutGivenIn(t,e,this.fees()),n=w.calculateSellFee(i,s),r=[];(e<this.minTradingLimit||i<t.assetOutEd)&&r.push("InsufficientTradingAmount");let o=t.balanceIn/this.maxInRatio;e>o&&r.push("MaxInRatioExceeded");let l=t.balanceOut/this.maxOutRatio;return s>l&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:i,amountOut:s,feePct:n,errors:r}}validateAndBuy(t,e,a){let i=this.calculateInGivenOut(t,e),s=this.calculateInGivenOut(t,e,this.fees()),n=w.calculateBuyFee(i,s),r=[];(e<this.minTradingLimit||i<t.assetInEd)&&r.push("InsufficientTradingAmount");let o=t.balanceOut/this.maxOutRatio;e>o&&r.push("MaxOutRatioExceeded");let l=t.balanceIn/this.maxInRatio;return s>l&&r.push("MaxInRatioExceeded"),{amountIn:s,calculatedIn:i,amountOut:e,feePct:n,errors:r}}fees(){return{fee:[this.fee,Ua]}}isZeroForOne(t){return t===this.token0}toState(t){return{fee:t?this.fee:0,sqrtPriceX96:this.sqrtPriceX96,tick:this.tick,liquidity:this.liquidity,tickSpacing:this.tickSpacing,ticks:this.ticks}}spotOutPerIn(t){let e=this.sqrtPriceX96*this.sqrtPriceX96;if(e===0n)return 0n;let a=e*Vt>>Gt;return t?a:(Vt<<Gt)/e}normalizeSpot(t,e,a){let i=e-a;if(i===0)return t;let s=10n**BigInt(Math.abs(i));return i>0?t*s:t/s}};import{Subscription as Qd,filter as Jd,map as Zd,mergeMap as tg}from"rxjs";import{erc20 as Ya}from"@galacticcouncil/common";import{TICK_SPACINGS as sg,TickMath as ng,nearestUsableTick as rg}from"@uniswap/v3-sdk";import{parseAbi as It}from"viem";var Wa=It(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)"]),$a=It(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickBitmap(int16 wordPosition) view returns (uint256)","function ticks(int24 tick) view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized)"]),Xa=It(["function balanceOf(address account) view returns (uint256)"]);var{ERC20:gg}=Ya;var it=class{static get(t){switch(t.type){case"Aave":return dt.fromPool(t);case"XYK":return pt.fromPool(t);case"Omnipool":return mt.fromPool(t);case"LBP":return ct.fromPool(t);case"Stableswap":return K.fromPool(t);case"HSM":return bt.fromPool(t);case"UniswapV3":return j.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as ja}from"@galacticcouncil/common";import{Subject as Qg,Subscription as Jg,takeUntil as Zg}from"rxjs";var ht=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var{logger:yb}=ja;var st=class{getProposals(t,e,a){let i=a.filter(p=>p.type==="XYK"),s=a.filter(p=>p.type!=="XYK"),n=new Set(s.map(p=>p.tokens).flat().map(p=>p.id)),r=n.has(t),o=n.has(e),l=new tt,c=p=>{let h=yt(p),P=Object.keys(h),E=P.flatMap(A=>h[A]);return l.buildAndPopulateGraph(P,E)};if(!r&&!o){let p=i.filter(E=>E.tokens.find(A=>A.id===t)||E.tokens.find(A=>A.id===e)),h=c(p),P=l.findPaths(h,t,e);return this.parsePaths(P)}if(r&&o){let p=c(s),h=l.findPaths(p,t,e);return this.parsePaths(h)}let m=r?e:t,b=i.filter(p=>p.tokens.some(h=>h.id===m));if(b.length===0)return[];let d=[...s,...b],f=c(d),g=l.findPaths(f,t,e);return this.parsePaths(g)}parsePaths(t){let e=[];for(let a of t){let i=[];for(let s=0;s<a.length;s++){let n=a[s],r=a[s+1];if(r==null)break;i.push(this.toEdge(n,r))}e.push(i)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var nt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new st,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,a){return`${t}->${e}::${a.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:a=[]}=this.filter,i=new Set(e),s=new Set(a);return t.filter(n=>s.has(n.type)?!1:i.size>0?i.has(n.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let a=await this.getPools();return this.validateInput(t,e,a),this.getPaths(t,e,a)}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(i=>i!==t).map(i=>this.getRoutes(i,t)))).filter(i=>i.length>0).map(([i])=>i[0].assetIn).sort()}validateInput(t,e,a){if(a.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let i=this.getAssets(a);if(!i.has(t))throw new Error(t+" is not supported asset");if(!i.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(a)}getAssets(t){let e=t.map(a=>a.tokens.map(i=>i.id)).flat().sort((a,i)=>a>i?1:-1);return new Set(e)}getPaths(t,e,a){let i=this.toPoolsMap(a);return this.getProposals(t,e,a).filter(n=>this.validPath(n,i)).map(n=>this.toHops(n,i))}getProposals(t,e,a){let i=this.buildRouteKey(t,e,a);if(this.routeProposals.has(i))return this.routeProposals.get(i);let s=this.routeSuggester.getProposals(t,e,a);return this.routeProposals.set(i,s),s}validPath(t,e){return t.length>0&&t.map(a=>this.validEdge(a,e)).reduce((a,i)=>a&&i)}validEdge([t,e,a],i){return i.get(t)?.validatePair(e,a)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,it.get(e)]))}toHops(t,e){return t.map(([a,i,s])=>{let n=e.get(a),r={poolAddress:a,poolId:n?.id,pool:n?.type,assetIn:i,assetOut:s};return n instanceof j&&(r.fee=n.fee),r})}};import{big as x,RUNTIME_DECIMALS as Q}from"@galacticcouncil/common";var Ut=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Ut||{}),Wt=(a=>(a.Dca="Dca",a.TwapSell="TwapSell",a.TwapBuy="TwapBuy",a))(Wt||{}),$t=(a=>(a.OrderTooSmall="OrderTooSmall",a.OrderTooBig="OrderTooBig",a.OrderImpactTooBig="OrderImpactTooBig",a))($t||{});var{FeeUtils:Xt}=S,rt=class extends nt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,a){let i=super.validateInput(t,e,a),s=super.getPaths(t,e,a);if(!s.length)throw new ht(t,e);return{paths:s,pools:a,poolsMap:i}}async withCtx(t,e,a){let i=await super.getPools(),s=this.buildCtxSync(t,e,i);return a(s)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((a,i)=>{let s=a[a.length-1].amountOut,n=i[i.length-1].amountOut;return s>n?-1:1});return e.find(a=>a.every(i=>i.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(a=>a.tradeFeeRange).length>0){let a=t.map(s=>s.tradeFeeRange?.[0]??s.tradeFeePct).reduce((s,n)=>s+n),i=t.map(s=>s.tradeFeeRange?.[1]??s.tradeFeePct).reduce((s,n)=>s+n);return[a,i]}}getPoolFeeRange(t,e){let a=t.min?Xt.toPct(t.min):void 0,i=t.max?Xt.toPct(t.max):void 0;if(a&&i)return[a,Math.max(i,e)]}async getBestSell(t,e,a){return this.getSell(t,e,a)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,a,i){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let r;if(i)r=await this.toSellSwaps(a,i,n);else{let o=s.map(c=>this.toSellSwaps(a,c,n)),l=await Promise.all(o);r=this.findBestSellRoute(l)}return this.buildSell(n,r)})}async getSells(t,e,a){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let n=i.map(o=>this.toSellSwaps(a,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(s,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let a=e[0],i=e[e.length-1],s=this.isDirectTrade(e),n=this.getSellSpot(e),r=i.amountOut,o=s?i.calculatedOut:this.calculateDelta0Y(a.amountIn,e,t),l=o-r,c=this.getRouteFeeRange(e),m=s?i.tradeFeePct:w.calculateSellFee(o,r),b=R.mulSpot(a.amountIn,n,a.assetInDecimals,i.assetOutDecimals),d=w.calculateDiffToRef(o,b);return{type:"Sell",amountIn:a.amountIn,amountOut:i.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:x.toDecimal(a.amountIn,a.assetInDecimals),amountOut:x.toDecimal(i.amountOut,i.assetOutDecimals),spotPrice:x.toDecimal(n,Q),tradeFee:x.toDecimal(l,i.assetOutDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(f=>f.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,a)=>e*a/10n**BigInt(Q))}calculateDelta0Y(t,e,a){let i=[];for(let s=0;s<e.length;s++){let n=e[s],r=a.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;s>0?l=i[s-1]:l=t;let c=r.calculateOutGivenIn(o,l);i.push(c)}return i[i.length-1]}async calculateMostLiquidRoute(t,e,a){let{paths:i,pools:s,poolsMap:n}=a,l=s.filter(g=>g.tokens.some(p=>p.id===t)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(p=>p.id===t)).map(g=>g.map(p=>p.balance).reduce((p,h)=>p+h)).sort((g,p)=>p<g?-1:1)[0],c=R.getFraction(l,.1),m=await Promise.all(i.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})),f=this.buildRouteKey(t,e,s);return this.mlr.set(f,d),d}async toSellSwaps(t,e,a){let i=[];for(let s=0;s<e.length;s++){let n=e[s],r=a.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;s>0?l=i[s-1].amountOut:l=typeof t=="string"?x.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r),{amountOut:m,calculatedOut:b,feePct:d,errors:f}=r.validateAndSell(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceOutGivenIn(o),h=R.mulSpot(l,p,o.decimalsIn,o.decimalsOut),P=w.calculateDiffToRef(b,h);i.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:b,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:f,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:x.toDecimal(l,o.decimalsIn),amountOut:x.toDecimal(m,o.decimalsOut),calculatedOut:x.toDecimal(b,o.decimalsOut),spotPrice:x.toDecimal(p,Q),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:f}}})}return i}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async a=>{let i=this.buildRouteKey(t,e,a.pools),s=this.mlr.get(i);return s||this.calculateMostLiquidRoute(t,e,a)})}async getSpotPrice(t,e){return this.withCtx(t,e,async a=>{let{pools:i,poolsMap:s}=a,n=this.buildRouteKey(t,e,i),r=this.mlr.get(n);r||(r=await this.calculateMostLiquidRoute(t,e,a));let o=await this.toSellSwaps("1",r,s);return{amount:this.getSellSpot(o),decimals:Q}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((a,i)=>{let s=a[0].amountIn,n=i[0].amountIn;return s>n?1:-1});return e.find(a=>a.every(i=>i.errors.length==0))||e[0]}async getBestBuy(t,e,a){return this.getBuy(t,e,a)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,a,i){return this.withCtx(t,e,async({paths:s,poolsMap:n})=>{let r;if(i)r=await this.toBuySwaps(a,i,n);else{let o=s.map(c=>this.toBuySwaps(a,c,n)),l=await Promise.all(o);r=this.findBestBuyRoute(l)}return this.buildBuy(n,r)})}async getBuys(t,e,a){return this.withCtx(t,e,async({paths:i,poolsMap:s})=>{let n=i.map(o=>this.toBuySwaps(a,o,s));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(s,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let a=e[e.length-1],i=e[0],s=this.isDirectTrade(e),n=this.getBuySpot(e),r=i.amountIn,o=s?i.calculatedIn:this.calculateDelta0X(a.amountOut,e,t),l=r-o,c=this.getRouteFeeRange(e),m=s?i.tradeFeePct:w.calculateBuyFee(o,r),b=R.mulSpot(a.amountOut,n,a.assetOutDecimals,i.assetInDecimals),d;return o===0n?d=-100:d=w.calculateDiffToRef(b,o),{type:"Buy",amountOut:a.amountOut,amountIn:i.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:x.toDecimal(a.amountOut,a.assetOutDecimals),amountIn:x.toDecimal(i.amountIn,i.assetInDecimals),spotPrice:x.toDecimal(n,Q),tradeFee:x.toDecimal(l,i.assetInDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(f=>f.toHuman())}}}}calculateDelta0X(t,e,a){let i=[];for(let s=e.length-1;s>=0;s--){let n=e[s],r=a.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=t:l=i[0];let c=r.calculateInGivenOut(o,l);i.unshift(c)}return i[0]}async toBuySwaps(t,e,a){let i=[];for(let s=e.length-1;s>=0;s--){let n=e[s],r=a.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;s==e.length-1?l=typeof t=="string"?x.toBigInt(t,o.decimalsOut):t:l=i[0].amountIn;let c=await this.ctx.getPoolFees(o,r),{amountIn:m,calculatedIn:b,feePct:d,errors:f}=r.validateAndBuy(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceInGivenOut(o),h=R.mulSpot(l,p,o.decimalsOut,o.decimalsIn),P;b===0n?P=-100:P=w.calculateDiffToRef(h,b),i.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:m,calculatedIn:b,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:f,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:x.toDecimal(l,o.decimalsOut),amountIn:x.toDecimal(m,o.decimalsIn),calculatedIn:x.toDecimal(b,o.decimalsIn),spotPrice:x.toDecimal(p,Q),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:f}}})}return i}};import{big as I}from"@galacticcouncil/common";var Yt=6e3,Kt=1000000000000000n,ot=6,wt=-5,xt=216e5,Dh=3,zt=.1,jt=6;import{Enum as Ot}from"polkadot-api";var V=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s,fee:n})=>i==="Stableswap"?{pool:Ot("Stableswap",s),asset_in:e,asset_out:a}:i==="UniswapV3"?{pool:Ot("UniswapV3",n),asset_in:e,asset_out:a}:{pool:Ot(i),asset_in:e,asset_out:a})}};var At=class{schedulerOptions;router;constructor(t,e={}){this.router=new rt(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Kt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,a,i,s){let n=await this.router.getBestSell(t,e,a),{amountIn:r,swaps:o,priceImpactPct:l}=n,c=o[0],m=o[o.length-1],{assetInDecimals:b}=c,{assetOutDecimals:d}=m,f=Math.abs(l),g=await this.getMinimumOrderBudget(t,b),p=this.getOptimalTradeCount(f),h=this.getMaximumTradeCount(r,g,i),P=s||Math.min(p,h),E=Math.round(i/P),A=r/BigInt(P),O=await this.router.getBestSell(t,e,A),k=r<g,F=[];k&&F.push("OrderTooSmall");let U=await this.getAssetOutEd(m),q=O.amountOut*BigInt(P),Jt=this.toBlockPeriod(E),Zt=O.tradeFee*BigInt(P),te=V.build(o),Bt={assetIn:t,assetOut:e,assetOutEd:U,errors:F,maxTradeCount:h,tradeCount:P,tradeFee:Zt,tradeImpactPct:O.priceImpactPct,tradePeriod:Jt,tradeRoute:te,type:"Dca"};return{...Bt,amountIn:r,amountOut:q,tradeAmountIn:O.amountIn,tradeAmountOut:O.amountOut,toHuman(){return{...Bt,amountIn:I.toDecimal(r,b),amountOut:I.toDecimal(q,d),assetOutEd:I.toDecimal(U,d),tradeAmountIn:I.toDecimal(O.amountIn,b),tradeAmountOut:I.toDecimal(O.amountOut,d)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let a=await this.router.getSpotPrice(0,t);if(a)return R.mulSpot(this.minOrderBudget,a.amount,12,e);let i=await this.router.getSpotPrice(t,0);if(i)return R.divSpot(this.minOrderBudget,i.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,a){let i=e*2n/10n;if(i===0n)return 0;let s=Number(t/i),n=Math.floor(a/this.blockTime),r=Math.max(0,Math.floor(n*(1-.1)));return Math.min(s,r)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,a,i){let s=await this.router.getBestSell(t,e,a),{swaps:n}=s,r=n[0],o=n[n.length-1],{assetInDecimals:l}=r,{assetOutDecimals:c}=o,m=await this.getMinimumOrderBudget(t,l),b=s.amountIn<m,d=[];b&&d.push("OrderTooSmall");let f=await this.getAssetOutEd(o),g=this.toBlockPeriod(i),p=V.build(n),h={assetIn:t,assetOut:e,assetOutEd:f,errors:d,maxTradeCount:0,tradeCount:0,tradeFee:s.tradeFee,tradeImpactPct:s.priceImpactPct,tradePeriod:g,tradeRoute:p,type:"Dca"};return{...h,amountIn:0n,amountOut:0n,tradeAmountIn:s.amountIn,tradeAmountOut:s.amountOut,toHuman(){return{...h,amountIn:"0",amountOut:"0",assetOutEd:I.toDecimal(f,c),tradeAmountIn:I.toDecimal(s.amountIn,l),tradeAmountOut:I.toDecimal(s.amountOut,c)}}}}async getTwapSellOrder(t,e,a){let i=await this.router.getBestSell(t,e,a),{amountIn:s,swaps:n,priceImpactPct:r}=i,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),f=s/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestSell(o.assetIn,l.assetOut,f)]),h=d===1,P=s<g,E=p.priceImpactPct<-5,A=[];P||h?A.push("OrderTooSmall"):E&&A.push("OrderImpactTooBig");let O=await this.getAssetOutEd(l),k=p.amountOut*BigInt(d),F=p.tradeFee*BigInt(d),U=V.build(n),q={assetIn:t,assetOut:e,assetOutEd:O,errors:A,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:U,type:"TwapSell"};return{...q,amountIn:s,amountOut:k,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:F,toHuman(){return{...q,amountIn:I.toDecimal(s,c),amountOut:I.toDecimal(k,m),assetOutEd:I.toDecimal(O,m),tradeAmountIn:I.toDecimal(p.amountIn,c),tradeAmountOut:I.toDecimal(p.amountOut,m),tradeFee:I.toDecimal(F,m)}}}}async getTwapBuyOrder(t,e,a){let i=await this.router.getBestBuy(t,e,a),{amountOut:s,swaps:n,priceImpactPct:r}=i,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),f=s/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestBuy(o.assetIn,l.assetOut,f)]),h=p.amountIn*BigInt(d),P=d===1,E=h<g,A=p.priceImpactPct<-5,O=[];E||P?O.push("OrderTooSmall"):A&&O.push("OrderImpactTooBig");let k=await this.getAssetOutEd(l),F=p.tradeFee*BigInt(d),U=V.build(n),q={assetIn:t,assetOut:e,assetOutEd:k,errors:O,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:U,type:"TwapBuy"};return{...q,amountIn:h,amountOut:s,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:F,toHuman(){return{...q,amountIn:I.toDecimal(h,c),amountOut:I.toDecimal(s,m),assetOutEd:I.toDecimal(k,m),tradeAmountIn:I.toDecimal(p.amountIn,c),tradeAmountOut:I.toDecimal(p.amountOut,m),tradeFee:I.toDecimal(F,c)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let i=216e5/(this.blockTime*6);return Math.round(i)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,a=Math.round(e);return Math.max(a,6)}async getAssetOutEd(t){let i=(await this.router.getPools()).find(s=>s.address===t.poolAddress)?.tokens.find(s=>s.id===t.assetOut);if(!i)throw new Error(`Asset ${t.assetOut} not found in pool ${t.poolAddress}`);return i.existentialDeposit}};export{zt as DCA_TIME_RESERVE,Yt as DEFAULT_BLOCK_TIME,Kt as DEFAULT_MIN_BUDGET,jt as ORDER_MIN_BLOCK_PERIOD,nt as Router,ot as TWAP_EXECUTION_INTERVAL,xt as TWAP_MAX_DURATION,wt as TWAP_MAX_PRICE_IMPACT,Dh as TWAP_TX_MULTIPLIER,$t as TradeOrderError,Wt as TradeOrderType,V as TradeRouteBuilder,rt as TradeRouter,At as TradeScheduler,Ut as TradeType};
|
package/build/tx/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var be=Object.create;var Z=Object.defineProperty;var ye=Object.getOwnPropertyDescriptor;var fe=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var tt=(o,t)=>{for(var e in t)Z(o,e,{get:t[e],enumerable:!0})},Ct=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of fe(t))!Te.call(o,i)&&i!==e&&Z(o,i,{get:()=>t[i],enumerable:!(a=ye(t,i))||a.enumerable});return o};var et=(o,t,e)=>(e=o!=null?be(Pe(o)):{},Ct(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o)),Se=o=>Ct(Z({},"__esModule",{value:!0}),o);var Ia={};tt(Ia,{TxBuilderFactory:()=>yt});module.exports=Se(Ia);var j=require("@galacticcouncil/math-lbp");var Lt=require("@galacticcouncil/common");var at={};tt(at,{withTimeout:()=>we});function we(o,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);o.then(r=>{clearTimeout(s),a(r)},r=>{clearTimeout(s),i(r)})})}var P={};tt(P,{divSpot:()=>xe,getFraction:()=>Ie,mulScaled:()=>kt,mulSpot:()=>ve});var Pt=require("@galacticcouncil/common");function kt(o,t,e,a,i){let s=e+a-i,r=o*t;return s>0?r/BigInt(10)**BigInt(s):s<0?r*BigInt(10)**BigInt(-s):r}function ve(o,t,e,a){return kt(o,t,e,Pt.RUNTIME_DECIMALS,a)}function xe(o,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(Pt.RUNTIME_DECIMALS+a-e);return o*i/t}function Ie(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),i=BigInt(Math.round(t*Number(a)));return o*i/(BigInt(100)*a)}var m={};tt(m,{FeeUtils:()=>Tt,shiftNeg:()=>Ae});var Mt=et(require("big.js"));var Tt=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 i=10**a;return Math.round(t*i/e)/i}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ae(o,t){let e=(0,Mt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Be=et(require("big.js"));var{FeeUtils:Ja}=m;var Me=require("polkadot-api"),rt=require("rxjs");var C=require("rxjs"),T=require("rxjs/operators");var U=require("@galacticcouncil/descriptors");var Ht=require("@galacticcouncil/common"),G=require("rxjs");var F=require("rxjs"),b=require("rxjs/operators");function Nt(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,b.timeout)({first:e}),(0,b.map)(()=>"online"),(0,b.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,b.expand)(s=>(0,F.timer)(s.delayMs).pipe((0,b.switchMap)(a),(0,b.map)(r=>({state:r,delayMs:t})))),(0,b.skip)(1),(0,b.map)(s=>s.state),(0,b.distinctUntilChanged)(),(0,b.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Ee}=Ht.log,it=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,G.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Nt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,G.tap)({error:a=>Ee.error(t,a)}),(0,G.shareReplay)({bufferSize:1,refCount:!0}))}};var A=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(U.hydration),this.apiNext=this.client.getTypedApi(U.hydrationNext),this.apiIce=this.client.getTypedApi(U.hydrationIce),this.watcher=it.getInstance(this.client),this.at=e??"best"}};var Re=require("polkadot-api/ws"),Fe=require("polkadot-api/logs-provider");var Ce=require("polkadot-api");var qt=require("@galacticcouncil/common"),w=require("rxjs"),p=require("rxjs/operators");var{logger:V}=qt.log,$=class extends A{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:a}=await e.getValue(t,{at:this.at});return this.getBreakdown(a)}async getTokenBalance(t,e){let i=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(i)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,w.defer)(()=>{let e=this.watchSystemBalance(t),a=this.watchTokensBalance(t),i=this.watchErc20Balance(t);return(0,w.combineLatest)([e,a,i]).pipe((0,p.connect)(s=>(0,w.concat)(s.pipe((0,p.take)(1)),s.pipe((0,p.skip)(1),(0,p.debounceTime)(250)))))}).pipe((0,p.map)(e=>e.flat()),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([e,a],i)=>i===0?a:this.getDeltas(e,a))).pipe((0,p.tap)({subscribe:()=>V.debug("balance: subscribe",t),error:e=>V.error("balance",e)}),(0,p.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,w.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,p.map)(({value:a})=>({id:0,balance:this.getBreakdown(a.data)})),(0,p.tap)({error:a=>V.error("balance(system)",a)}))}watchTokenBalance(t,e){let a=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>a.watchValue(t,e,{at:"best"})).pipe((0,p.map)(({value:i})=>({id:e,balance:this.getBreakdown(i)})),(0,p.tap)({error:i=>V.error("balance(token)",i)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,p.distinctUntilChanged)((a,i)=>!i.deltas),(0,p.map)(({deltas:a})=>{let i=[];return a?.deleted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[r,n]=s.args;i.push({id:n,balance:this.getBreakdown(s.value)})}),i}),(0,p.tap)({error:a=>V.error("balance(tokens)",a)}))}watchErc20Balance(t,e){let a=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:r})=>r.asset_type.type==="Erc20").map(({keyArgs:r})=>{let[n]=r;return n}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async n=>[n,await this.getBalanceData(t,n)]))).map(([n,l])=>({id:n,balance:l}));return(0,w.defer)(()=>(0,w.from)(e?Promise.resolve(e):a()).pipe((0,p.switchMap)(s=>this.watcher.bestBlock$.pipe((0,p.switchMap)(()=>(0,w.from)(i(s))))),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([s,r],n)=>n===0?r.filter(l=>l.balance.total>0n):this.getDeltas(s,r)),(0,p.distinctUntilChanged)((s,r)=>r.length===0),(0,p.tap)({error:s=>V.error("balance(erc20)",s)})))}async getBalanceData(t,e){let a=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});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=(s,r)=>s!==void 0&&r!==void 0&&s.transferable===r.transferable&&s.total===r.total,i=t.reduce((s,r)=>(s.set(r.id,r.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};var ke=require("rxjs");var Gt=require("@galacticcouncil/common");var ks={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Ms}=Gt.log;var{withTimeout:Js}=at;var y=require("@galacticcouncil/math-omnipool"),Le=et(require("big.js"));var Ne=require("@galacticcouncil/common");var{FeeUtils:xi}=m;var H=require("polkadot-api"),Ue=require("@polkadot-api/utils"),q=require("rxjs"),Ve=require("@galacticcouncil/common");var{FeeUtils:_i}=m;var{FeeUtils:Vi}=m,Wi=H.Binary.toHex(H.Binary.fromText("omnipool")),$i=(0,H.Enum)("Short");var B=require("@galacticcouncil/math-stableswap");var Wt=require("@galacticcouncil/common");var{FeeUtils:gr}=m;var $t=require("polkadot-api"),je=require("@polkadot-api/utils"),Qe=require("@noble/hashes/blake2b"),Y=require("rxjs"),Yt=require("@galacticcouncil/common");var Ye=require("polkadot-api"),Xe=require("viem");var{FeeUtils:kr}=m;var{FeeUtils:en}=m;var _=require("@galacticcouncil/math-xyk");var Ze=require("@galacticcouncil/common");var{FeeUtils:Sn}=m;var ta=require("polkadot-api"),ea=require("rxjs");var Xt=require("@galacticcouncil/common");var oa=require("polkadot-api"),la=require("@polkadot-api/utils"),ut=require("rxjs"),At=require("@galacticcouncil/common");var wt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var vt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Kt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",xt="0x112b087b60C1a166130d59266363C45F8aa99db0",It="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",zt=1000000n;var jn=BigInt("0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");var nt=class{client;constructor(t){this.client=t.getWsProvider()}async getBlockTimestamp(){let t=await this.client.getBlock();return Number(t.timestamp)}async getReservesData(){return await this.client.readContract({abi:vt,address:xt,args:[It],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:vt,address:xt,args:[It,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:wt,address:Kt,args:[t],functionName:"getUserAccountData"})}};var sa=require("polkadot-api"),ia=require("viem");var h=et(require("big.js")),v=require("@galacticcouncil/common");var{ERC20:X}=v.erc20,{H160:Ot}=v.h160,ra=1.01,na=31536000n,jt=4,ot=-1,lt=10n**27n,ct=class{client;constructor(t){this.client=new nt(t)}async getSummary(t){let e=Ot.fromAny(t),[a,i,s,r]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[n]=a,[l,u]=i,[c,d,f,k,I,O]=s,E=v.big.toDecimal(O,18),M=[];for(let R of l){let N=R.underlyingAsset.toLowerCase(),S=n.find(({underlyingAsset:he})=>he.toLowerCase()===N);if(!S)throw new Error("Missing pool reserve for "+N);let ft=R.scaledATokenBalance,z=S.liquidityIndex,re=S.liquidityRate,ne=S.availableLiquidity,oe=S.priceInMarketReferenceCurrency,le=r+6,ce=this.calculateLinearInterest(re,S.lastUpdateTimestamp,le),ue=z*ce/lt,pe=ft*ue/lt,me=Number(u!==0&&u===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,de=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,ge=X.toAssetId(N);M.push({aTokenBalance:pe,availableLiquidity:ne,decimals:Number(S.decimals),isCollateral:de,priceInRef:oe,reserveId:ge,reserveAsset:N,reserveLiquidationThreshold:me})}return{healthFactor:Number(E),currentLiquidationThreshold:Number(v.big.toDecimal(k,jt)),totalCollateral:c,totalDebt:d,reserves:M}}async hasBorrowPositions(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=Ot.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,r,n,l,u]=a;return this.calculateHealthFactorFromBalances(s,i,n)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=X.fromAssetId(e),u=r.find(N=>N.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,isCollateral:d,priceInRef:f,reserveLiquidationThreshold:k}=u,I=v.big.toBigInt(a,c),O=d?I*f/10n**BigInt(c):0n,E=i-O;if(E<=0n)return 0;let M=(0,h.default)(i.toString()).mul(n).minus((0,h.default)(O.toString()).mul(k)).div(E.toString()),R=(0,h.default)(E.toString()).mul(M).div(s.toString()).toFixed(6,h.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:r,currentLiquidationThreshold:n}=await this.getSummary(t);if(s===0n)return ot;let l=X.fromAssetId(e),u=r.find(R=>R.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,priceInRef:d,reserveLiquidationThreshold:f}=u,I=v.big.toBigInt(a,c)*d/10n**BigInt(c),O=i+I;if(O<=0n)return 0;let E=(0,h.default)(i.toString()).mul(n).plus((0,h.default)(I.toString()).mul(f)).div(O.toString()),M=(0,h.default)(O.toString()).mul(E).div(s.toString()).toFixed(6,h.default.roundDown);return Number(M)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:r,reserves:n,healthFactor:l}=await this.getSummary(t);if(r===0n)return ot;let u=X.fromAssetId(a),c=X.fromAssetId(s),d=n.find(z=>z.reserveAsset===u),f=n.find(z=>z.reserveAsset===c);if(!d)throw new Error(`Missing reserve ctx for ${u}`);if(!f)throw new Error(`Missing reserve ctx for ${f}`);let k=v.big.toBigInt(e,d.decimals),I=v.big.toBigInt(i,f.decimals),O=k*d.priceInRef/10n**BigInt(d.decimals),E=I*f.priceInRef/10n**BigInt(f.decimals),M=d.isCollateral?(0,h.default)(O.toString()).mul(d.reserveLiquidationThreshold):(0,h.default)(0),S=(f.isCollateral?(0,h.default)(E.toString()).mul(f.reserveLiquidationThreshold):(0,h.default)(0)).minus(M).div(r.toString()),ft=(0,h.default)(l).plus(S).toFixed(6,h.default.roundDown);return Number(ft)}async getMaxWithdraw(t,e){let{totalDebt:a,reserves:i,healthFactor:s}=await this.getSummary(t),r=X.fromAssetId(e),n=i.find(l=>l.reserveAsset===r);if(!n)throw new Error("Missing reserve ctx for "+r);return this.calculateWithdrawMax(n,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let r of a){let n=this.calculateWithdrawMax(r,e,i);r.reserveId&&(s[r.reserveId]=n)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:r,priceInRef:n,reserveLiquidationThreshold:l,isCollateral:u}=t,c=i;if(u&&e>0n){let f=a-ra;if(f>0){let k=(0,h.default)(f).mul(e.toString()).div(l).toFixed(0,h.default.roundDown),I=(0,h.default)(k).div(n.toString()).mul(10**r).toFixed(0,h.default.roundDown);c=i<BigInt(I)?i:BigInt(I)}else c=0n}return{amount:c<s?c:s,decimals:r}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return lt;let s=t*BigInt(i)/na;return lt+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return ot;let i=e*a/t,s=v.big.toDecimal(i,jt);return Number(s)}};var{ERC20:So}=At.erc20;var D=require("@galacticcouncil/math-hsm");var Qt=require("@galacticcouncil/common");var{FeeUtils:Lo}=m;var Jt=require("polkadot-api"),ga=require("@polkadot-api/utils"),K=require("rxjs"),Bt=require("@galacticcouncil/common");var ma=require("polkadot-api"),da=require("viem");var{FeeUtils:nl}=m,{H160:ol}=Bt.h160;var Zt=require("@galacticcouncil/common"),_t=require("rxjs");var{logger:tc}=Zt.log;var te=require("@galacticcouncil/common");var{FeeUtils:cu}=m;var xa=require("@galacticcouncil/common");var Et=require("polkadot-api");var L=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,Et.Enum)("Stableswap",s),asset_in:e,asset_out:a}:{pool:(0,Et.Enum)(i),asset_in:e,asset_out:a})}};var Rt=require("polkadot-api");function ae(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var x=class extends A{evm;evmClient;balance;aaveUtils;constructor(t,e,a){super(t,a),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new $(t,a),this.aaveUtils=new ct(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:zt})}async dryRun(t,e){let a=(0,Rt.Enum)("Signed",t),i=(0,Rt.Enum)("system",a),r=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4,{at:this.at}),n=r.success&&!r.value.execution_result.success?r.value.execution_result.value.error:null;if(n){let l=n.type==="Module"?ae(n.value):n.type;throw new Error("Dry run execution error!",{cause:l})}return r}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var pt=class extends x{_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:i}=e[0],s=await this.balance.getBalance(this.beneficiary,i);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(t,this.slippagePct),n=i.assetIn,l=s.assetOut,u=t+r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.buy({asset_in:n,asset_out:l,amount:e,max_sell_amount:u}):c=this.api.tx.Router.buy({asset_in:n,asset_out:l,amount_out:e,max_amount_in:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=P.getFraction(e,this.slippagePct),n=i.assetIn,l=s.assetOut,u=e-r,c;return this.isDirectOmnipoolTrade(a)?c=this.api.tx.Omnipool.sell({asset_in:n,asset_out:l,amount:t,min_buy_amount:u}):c=this.api.tx.Router.sell({asset_in:n,asset_out:l,amount_in:t,min_amount_out:u,route:L.build(a)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,a=e[0],i=e[e.length-1],s=P.getFraction(t,this.slippagePct),r=a.assetIn,n=i.assetOut,l=t-s,u=this.api.tx.Router.sell_all({asset_in:r,asset_out:n,min_amount_out:l,route:L.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};var mt=require("polkadot-api");var dt=class extends x{_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:i,tradePeriod:s,tradeRoute:r}=this.order,n=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,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:i,min_amount_out:0n,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(n=await this.dispatchWithExtraGas(n)),this.wrapTx("DcaSchedule",n)}async buildTwapSellTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(s,this.slippagePct),u=s-l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,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:i,min_amount_out:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapSell",c)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r,tradeRoute:n}=this.order,l=P.getFraction(i,this.slippagePct),u=i+l,c=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:r,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:s,max_amount_in:u,route:n})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapBuy",c)}};var se=require("polkadot-api");var gt=class extends x{_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,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=P.getFraction(e,this.slippagePct),u=e-l,c=(0,se.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:u,partial:!1}),d=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(d=await this.dispatchWithExtraGas(d)),this.wrapTx("IntentSwap",d)}};var ie=require("polkadot-api");var ht=class extends x{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=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 partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:a}=this.trade,i=a[0],s=a[a.length-1],r=i.assetIn,n=s.assetOut,l=(0,ie.Enum)("Swap",{asset_in:r,asset_out:n,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentLimitOrder",u)}};var Ft=require("polkadot-api");var bt=class extends x{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=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 slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:r}=this.order,n=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,slippage:this.slippagePct*1e4,budget:t,period:r}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:n}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule",l)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:r}=this.order,n=P.getFraction(s,this.slippagePct),l=s-n,u=(0,Ft.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:i,amount_out:l,slippage:this.slippagePct*1e4,budget:t,period:r}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentDcaSchedule.twap",c)}};var yt=class{client;evmClient;at;constructor(t,e,a){this.client=t,this.evmClient=e,this.at=a}trade(t){return new pt(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new dt(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new gt(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new ht(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new bt(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
|
|
1
|
+
"use strict";var xe=Object.create;var it=Object.defineProperty;var ve=Object.getOwnPropertyDescriptor;var Ie=Object.getOwnPropertyNames;var Oe=Object.getPrototypeOf,Ae=Object.prototype.hasOwnProperty;var at=(o,t)=>{for(var e in t)it(o,e,{get:t[e],enumerable:!0})},qt=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ie(t))!Ae.call(o,a)&&a!==e&&it(o,a,{get:()=>t[a],enumerable:!(i=ve(t,a))||i.enumerable});return o};var J=(o,t,e)=>(e=o!=null?xe(Oe(o)):{},qt(t||!o||!o.__esModule?it(e,"default",{value:o,enumerable:!0}):e,o)),Be=o=>qt(it({},"__esModule",{value:!0}),o);var Li={};at(Li,{TxBuilderFactory:()=>wt});module.exports=Be(Li);var Z=require("@galacticcouncil/math-lbp");var Ut=require("@galacticcouncil/common");var st={};at(st,{withTimeout:()=>_e});function _e(o,t,e="timeout"){return new Promise((i,a)=>{let s=setTimeout(()=>a(new Error(e)),t);o.then(n=>{clearTimeout(s),i(n)},n=>{clearTimeout(s),a(n)})})}var P={};at(P,{divSpot:()=>Re,getFraction:()=>Fe,mulScaled:()=>Nt,mulSpot:()=>Ee});var vt=require("@galacticcouncil/common");function Nt(o,t,e,i,a){let s=e+i-a,n=o*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function Ee(o,t,e,i){return Nt(o,t,e,vt.RUNTIME_DECIMALS,i)}function Re(o,t,e,i){if(t===0n)return 0n;let a=BigInt(10)**BigInt(vt.RUNTIME_DECIMALS+i-e);return o*a/t}function Fe(o,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let i=BigInt(10)**BigInt(e),a=BigInt(Math.round(t*Number(i)));return o*a/(BigInt(100)*i)}var m={};at(m,{FeeUtils:()=>It,shiftNeg:()=>Ce});var Ht=J(require("big.js"));var It=class o{static toPct(t){let[e,i]=t;return o.safeDivide(e*100,i)}static toRaw(t){let[e,i]=t;return o.safeDivide(e,i)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,i=12){let a=10**i;return Math.round(t*a/e)/a}static safeRound(t){return parseFloat(t.toPrecision(15))}};function Ce(o,t){let e=(0,Ht.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var Me=J(require("big.js"));var{FeeUtils:ua}=m;var Ue=require("polkadot-api"),rt=require("rxjs");var k=require("rxjs"),T=require("rxjs/operators");var V=require("@galacticcouncil/descriptors");var Wt=require("@galacticcouncil/common"),U=require("rxjs");var F=require("rxjs"),b=require("rxjs/operators");function Vt(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let i=()=>(0,F.defer)(()=>(0,F.from)(o._request("system_health",[]))).pipe((0,b.timeout)({first:e}),(0,b.map)(()=>"online"),(0,b.catchError)(()=>(0,F.of)("offline")));return(0,F.of)({state:"offline",delayMs:0}).pipe((0,b.expand)(s=>(0,F.timer)(s.delayMs).pipe((0,b.switchMap)(i),(0,b.map)(n=>({state:n,delayMs:t})))),(0,b.skip)(1),(0,b.map)(s=>s.state),(0,b.distinctUntilChanged)(),(0,b.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:Le}=Wt.log,nt=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,U.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",Vt(t))}static getInstance(t){return this.instance||(this.instance=new o(t)),this.instance}watched(t,e){return e.pipe((0,U.tap)({error:i=>Le.error(t,i)}),(0,U.shareReplay)({bufferSize:1,refCount:!0}))}};var A=class{client;api;apiNext;apiIce;watcher;at;constructor(t,e){this.client=t,this.api=this.client.getTypedApi(V.hydration),this.apiNext=this.client.getTypedApi(V.hydrationNext),this.apiIce=this.client.getTypedApi(V.hydrationIce),this.watcher=nt.getInstance(this.client),this.at=e??"best"}};var qe=require("polkadot-api/ws"),Ne=require("polkadot-api/logs-provider");var He=require("polkadot-api");var $t=require("@galacticcouncil/common"),w=require("rxjs"),p=require("rxjs/operators");var{logger:W}=$t.log,X=class extends A{erc20Ids=null;constructor(t,e){super(t,e)}async getBalance(t,e){return e===0?this.getSystemBalance(t):this.getBalanceData(t,e)}async getSystemBalance(t){let e=this.api.query.System.Account,{data:i}=await e.getValue(t,{at:this.at});return this.getBreakdown(i)}async getTokenBalance(t,e){let a=await this.api.query.Tokens.Accounts.getValue(t,e,{at:this.at});return this.getBreakdown(a)}async getErc20Balance(t,e){return this.getBalanceData(t,e)}watchBalance(t){return(0,w.defer)(()=>{let e=this.watchSystemBalance(t),i=this.watchTokensBalance(t),a=this.watchErc20Balance(t);return(0,w.combineLatest)([e,i,a]).pipe((0,p.connect)(s=>(0,w.concat)(s.pipe((0,p.take)(1)),s.pipe((0,p.skip)(1),(0,p.debounceTime)(250)))))}).pipe((0,p.map)(e=>e.flat()),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([e,i],a)=>a===0?i:this.getDeltas(e,i))).pipe((0,p.tap)({subscribe:()=>W.debug("balance: subscribe",t),error:e=>W.error("balance",e)}),(0,p.retry)({delay:1e3}))}watchSystemBalance(t){let e=this.api.query.System.Account;return(0,w.defer)(()=>e.watchValue(t,{at:"best"})).pipe((0,p.map)(({value:i})=>({id:0,balance:this.getBreakdown(i.data)})),(0,p.tap)({error:i=>W.error("balance(system)",i)}))}watchTokenBalance(t,e){let i=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>i.watchValue(t,e,{at:"best"})).pipe((0,p.map)(({value:a})=>({id:e,balance:this.getBreakdown(a)})),(0,p.tap)({error:a=>W.error("balance(token)",a)}))}watchTokensBalance(t){let e=this.api.query.Tokens.Accounts;return(0,w.defer)(()=>e.watchEntries(t,{at:"best"})).pipe((0,p.distinctUntilChanged)((i,a)=>!a.deltas),(0,p.map)(({deltas:i})=>{let a=[];return i?.deleted.forEach(s=>{let[n,r]=s.args;a.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),i?.upserted.forEach(s=>{let[n,r]=s.args;a.push({id:r,balance:this.getBreakdown(s.value)})}),a}),(0,p.tap)({error:i=>W.error("balance(tokens)",i)}))}watchErc20Balance(t,e){let i=async()=>{if(this.erc20Ids)return this.erc20Ids;let s=await this.api.query.AssetRegistry.Assets.getEntries({at:"best"});return this.erc20Ids=s.filter(({value:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},a=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,l])=>({id:r,balance:l}));return(0,w.defer)(()=>(0,w.from)(e?Promise.resolve(e):i()).pipe((0,p.switchMap)(s=>this.watcher.bestBlock$.pipe((0,p.switchMap)(()=>(0,w.from)(a(s))))),(0,p.startWith)([]),(0,p.bufferCount)(2,1),(0,p.map)(([s,n],r)=>r===0?n.filter(l=>l.balance.total>0n):this.getDeltas(s,n)),(0,p.distinctUntilChanged)((s,n)=>n.length===0),(0,p.tap)({error:s=>W.error("balance(erc20)",s)})))}async getBalanceData(t,e){let i=await this.api.apis.CurrenciesApi.account(e,t,{at:this.at});return this.getBreakdown(i)}getBreakdown(t){let e=t.free>=t.frozen?t.free-t.frozen:0n,i=t.free+t.reserved;return{free:t.free,reserved:t.reserved,frozen:t.frozen,total:i,transferable:e}}getDeltas(t,e){let i=(s,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,a=t.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return e.filter(s=>!i(s.balance,a.get(s.id)))}};var Ge=require("rxjs");var Xt=require("@galacticcouncil/common");var Xa={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM",UniswapV3:"UNIV3"},{logger:Ya}=Xt.log;var{withTimeout:us}=st;var y=require("@galacticcouncil/math-omnipool"),We=J(require("big.js"));var $e=require("@galacticcouncil/common");var{FeeUtils:Ds}=m;var N=require("polkadot-api"),ze=require("@polkadot-api/utils"),H=require("rxjs"),je=require("@galacticcouncil/common");var{FeeUtils:Gs}=m;var{FeeUtils:en}=m,an=N.Binary.toHex(N.Binary.fromText("omnipool")),sn=(0,N.Enum)("Short");var B=require("@galacticcouncil/math-stableswap");var zt=require("@galacticcouncil/common");var{FeeUtils:An}=m;var jt=require("polkadot-api"),ai=require("@polkadot-api/utils"),si=require("@noble/hashes/blake2b"),K=require("rxjs"),Qt=require("@galacticcouncil/common");var Ze=require("polkadot-api"),ti=require("viem");var{FeeUtils:Yn}=m;var{FeeUtils:gr}=m;var _=require("@galacticcouncil/math-xyk");var ri=require("@galacticcouncil/common");var{FeeUtils:kr}=m;var oi=require("polkadot-api"),li=require("rxjs");var Jt=require("@galacticcouncil/common");var gi=require("polkadot-api"),hi=require("@polkadot-api/utils"),pt=require("rxjs"),Ft=require("@galacticcouncil/common");var At=[{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 Bt=[{inputs:[{internalType:"contract IEACAggregatorProxy",name:"_networkBaseTokenPriceInUsdProxyAggregator",type:"address"},{internalType:"contract IEACAggregatorProxy",name:"_marketReferenceCurrencyPriceInUsdProxyAggregator",type:"address"}],stateMutability:"nonpayable",type:"constructor"},{inputs:[],name:"ETH_CURRENCY_UNIT",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"view",type:"function"},{inputs:[],name:"MKR_ADDRESS",outputs:[{internalType:"address",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"bytes32",name:"_bytes32",type:"bytes32"}],name:"bytes32ToString",outputs:[{internalType:"string",name:"",type:"string"}],stateMutability:"pure",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"string",name:"name",type:"string"},{internalType:"string",name:"symbol",type:"string"},{internalType:"uint256",name:"decimals",type:"uint256"},{internalType:"uint256",name:"baseLTVasCollateral",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"reserveLiquidationBonus",type:"uint256"},{internalType:"uint256",name:"reserveFactor",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabled",type:"bool"},{internalType:"bool",name:"borrowingEnabled",type:"bool"},{internalType:"bool",name:"stableBorrowRateEnabled",type:"bool"},{internalType:"bool",name:"isActive",type:"bool"},{internalType:"bool",name:"isFrozen",type:"bool"},{internalType:"uint128",name:"liquidityIndex",type:"uint128"},{internalType:"uint128",name:"variableBorrowIndex",type:"uint128"},{internalType:"uint128",name:"liquidityRate",type:"uint128"},{internalType:"uint128",name:"variableBorrowRate",type:"uint128"},{internalType:"uint128",name:"stableBorrowRate",type:"uint128"},{internalType:"uint40",name:"lastUpdateTimestamp",type:"uint40"},{internalType:"address",name:"aTokenAddress",type:"address"},{internalType:"address",name:"stableDebtTokenAddress",type:"address"},{internalType:"address",name:"variableDebtTokenAddress",type:"address"},{internalType:"address",name:"interestRateStrategyAddress",type:"address"},{internalType:"uint256",name:"availableLiquidity",type:"uint256"},{internalType:"uint256",name:"totalPrincipalStableDebt",type:"uint256"},{internalType:"uint256",name:"averageStableRate",type:"uint256"},{internalType:"uint256",name:"stableDebtLastUpdateTimestamp",type:"uint256"},{internalType:"uint256",name:"totalScaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"priceInMarketReferenceCurrency",type:"uint256"},{internalType:"address",name:"priceOracle",type:"address"},{internalType:"uint256",name:"variableRateSlope1",type:"uint256"},{internalType:"uint256",name:"variableRateSlope2",type:"uint256"},{internalType:"uint256",name:"stableRateSlope1",type:"uint256"},{internalType:"uint256",name:"stableRateSlope2",type:"uint256"},{internalType:"uint256",name:"baseStableBorrowRate",type:"uint256"},{internalType:"uint256",name:"baseVariableBorrowRate",type:"uint256"},{internalType:"uint256",name:"optimalUsageRatio",type:"uint256"},{internalType:"bool",name:"isPaused",type:"bool"},{internalType:"bool",name:"isSiloedBorrowing",type:"bool"},{internalType:"uint128",name:"accruedToTreasury",type:"uint128"},{internalType:"uint128",name:"unbacked",type:"uint128"},{internalType:"uint128",name:"isolationModeTotalDebt",type:"uint128"},{internalType:"bool",name:"flashLoanEnabled",type:"bool"},{internalType:"uint256",name:"debtCeiling",type:"uint256"},{internalType:"uint256",name:"debtCeilingDecimals",type:"uint256"},{internalType:"uint8",name:"eModeCategoryId",type:"uint8"},{internalType:"uint256",name:"borrowCap",type:"uint256"},{internalType:"uint256",name:"supplyCap",type:"uint256"},{internalType:"uint16",name:"eModeLtv",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationThreshold",type:"uint16"},{internalType:"uint16",name:"eModeLiquidationBonus",type:"uint16"},{internalType:"address",name:"eModePriceSource",type:"address"},{internalType:"string",name:"eModeLabel",type:"string"},{internalType:"bool",name:"borrowableInIsolation",type:"bool"}],internalType:"struct IUiPoolDataProviderV3.AggregatedReserveData[]",name:"",type:"tuple[]"},{components:[{internalType:"uint256",name:"marketReferenceCurrencyUnit",type:"uint256"},{internalType:"int256",name:"marketReferenceCurrencyPriceInUsd",type:"int256"},{internalType:"int256",name:"networkBaseTokenPriceInUsd",type:"int256"},{internalType:"uint8",name:"networkBaseTokenPriceDecimals",type:"uint8"}],internalType:"struct IUiPoolDataProviderV3.BaseCurrencyInfo",name:"",type:"tuple"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"}],name:"getReservesList",outputs:[{internalType:"address[]",name:"",type:"address[]"}],stateMutability:"view",type:"function"},{inputs:[{internalType:"contract IPoolAddressesProvider",name:"provider",type:"address"},{internalType:"address",name:"user",type:"address"}],name:"getUserReservesData",outputs:[{components:[{internalType:"address",name:"underlyingAsset",type:"address"},{internalType:"uint256",name:"scaledATokenBalance",type:"uint256"},{internalType:"bool",name:"usageAsCollateralEnabledOnUser",type:"bool"},{internalType:"uint256",name:"stableBorrowRate",type:"uint256"},{internalType:"uint256",name:"scaledVariableDebt",type:"uint256"},{internalType:"uint256",name:"principalStableDebt",type:"uint256"},{internalType:"uint256",name:"stableBorrowLastUpdateTimestamp",type:"uint256"}],internalType:"struct IUiPoolDataProviderV3.UserReserveData[]",name:"",type:"tuple[]"},{internalType:"uint8",name:"",type:"uint8"}],stateMutability:"view",type:"function"},{inputs:[],name:"marketReferenceCurrencyPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"},{inputs:[],name:"networkBaseTokenPriceInUsdProxyAggregator",outputs:[{internalType:"contract IEACAggregatorProxy",name:"",type:"address"}],stateMutability:"view",type:"function"}];var Zt="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",_t="0x112b087b60C1a166130d59266363C45F8aa99db0",Et="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",te=1000000n;var lo=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:Bt,address:_t,args:[Et],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Bt,address:_t,args:[Et,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:At,address:Zt,args:[t],functionName:"getUserAccountData"})}};var ui=require("polkadot-api"),pi=require("viem");var h=J(require("big.js")),x=require("@galacticcouncil/common");var{ERC20:z}=x.erc20,{H160:Rt}=x.h160,mi=1.01,di=31536000n,ee=4,lt=-1,ct=10n**27n,ut=class{client;constructor(t){this.client=new ot(t)}async getSummary(t){let e=Rt.fromAny(t),[i,a,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=i,[l,u]=a,[c,g,f,C,I,O]=s,E=x.big.toDecimal(O,18),M=[];for(let R of l){let q=R.underlyingAsset.toLowerCase(),S=r.find(({underlyingAsset:we})=>we.toLowerCase()===q);if(!S)throw new Error("Missing pool reserve for "+q);let xt=R.scaledATokenBalance,Q=S.liquidityIndex,me=S.liquidityRate,de=S.availableLiquidity,ge=S.priceInMarketReferenceCurrency,he=n+6,be=this.calculateLinearInterest(me,S.lastUpdateTimestamp,he),ye=Q*be/ct,fe=xt*ye/ct,Pe=Number(u!==0&&u===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,Te=S.usageAsCollateralEnabled&&R.usageAsCollateralEnabledOnUser&&R.scaledATokenBalance>0n,Se=z.toAssetId(q);M.push({aTokenBalance:fe,availableLiquidity:de,decimals:Number(S.decimals),isCollateral:Te,priceInRef:ge,reserveId:Se,reserveAsset:q,reserveLiquidationThreshold:Pe})}return{healthFactor:Number(E),currentLiquidationThreshold:Number(x.big.toDecimal(C,ee)),totalCollateral:c,totalDebt:g,reserves:M}}async hasBorrowPositions(t){let e=Rt.fromAny(t),i=await this.client.getUserAccountData(e),[a,s]=i;return s>0n}async getHealthFactor(t){let e=Rt.fromAny(t),i=await this.client.getUserAccountData(e),[a,s,n,r,l,u]=i;return this.calculateHealthFactorFromBalances(s,a,r)}async getHealthFactorAfterWithdraw(t,e,i){let{totalCollateral:a,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return lt;let l=z.fromAssetId(e),u=n.find(q=>q.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,isCollateral:g,priceInRef:f,reserveLiquidationThreshold:C}=u,I=x.big.toBigInt(i,c),O=g?I*f/10n**BigInt(c):0n,E=a-O;if(E<=0n)return 0;let M=(0,h.default)(a.toString()).mul(r).minus((0,h.default)(O.toString()).mul(C)).div(E.toString()),R=(0,h.default)(E.toString()).mul(M).div(s.toString()).toFixed(6,h.default.roundDown);return Number(R)}async getHealthFactorAfterSupply(t,e,i){let{totalCollateral:a,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return lt;let l=z.fromAssetId(e),u=n.find(R=>R.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,priceInRef:g,reserveLiquidationThreshold:f}=u,I=x.big.toBigInt(i,c)*g/10n**BigInt(c),O=a+I;if(O<=0n)return 0;let E=(0,h.default)(a.toString()).mul(r).plus((0,h.default)(I.toString()).mul(f)).div(O.toString()),M=(0,h.default)(O.toString()).mul(E).div(s.toString()).toFixed(6,h.default.roundDown);return Number(M)}async getHealthFactorAfterSwap(t,e,i,a,s){let{totalDebt:n,reserves:r,healthFactor:l}=await this.getSummary(t);if(n===0n)return lt;let u=z.fromAssetId(i),c=z.fromAssetId(s),g=r.find(Q=>Q.reserveAsset===u),f=r.find(Q=>Q.reserveAsset===c);if(!g)throw new Error(`Missing reserve ctx for ${u}`);if(!f)throw new Error(`Missing reserve ctx for ${f}`);let C=x.big.toBigInt(e,g.decimals),I=x.big.toBigInt(a,f.decimals),O=C*g.priceInRef/10n**BigInt(g.decimals),E=I*f.priceInRef/10n**BigInt(f.decimals),M=g.isCollateral?(0,h.default)(O.toString()).mul(g.reserveLiquidationThreshold):(0,h.default)(0),S=(f.isCollateral?(0,h.default)(E.toString()).mul(f.reserveLiquidationThreshold):(0,h.default)(0)).minus(M).div(n.toString()),xt=(0,h.default)(l).plus(S).toFixed(6,h.default.roundDown);return Number(xt)}async getMaxWithdraw(t,e){let{totalDebt:i,reserves:a,healthFactor:s}=await this.getSummary(t),n=z.fromAssetId(e),r=a.find(l=>l.reserveAsset===n);if(!r)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(r,i,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:i,healthFactor:a}=await this.getSummary(t),s={};for(let n of i){let r=this.calculateWithdrawMax(n,e,a);n.reserveId&&(s[n.reserveId]=r)}return s}calculateWithdrawMax(t,e,i){let{aTokenBalance:a,availableLiquidity:s,decimals:n,priceInRef:r,reserveLiquidationThreshold:l,isCollateral:u}=t,c=a;if(u&&e>0n){let f=i-mi;if(f>0){let C=(0,h.default)(f).mul(e.toString()).div(l).toFixed(0,h.default.roundDown),I=(0,h.default)(C).div(r.toString()).mul(10**n).toFixed(0,h.default.roundDown);c=a<BigInt(I)?a:BigInt(I)}else c=0n}return{amount:c<s?c:s,decimals:n}}calculateLinearInterest(t,e,i){let a=i-e;if(a<=0)return ct;let s=t*BigInt(a)/di;return ct+s}calculateHealthFactorFromBalances(t,e,i){if(t===0n)return lt;let a=e*i/t,s=x.big.toDecimal(a,ee);return Number(s)}};var{ERC20:ko}=Ft.erc20;var D=require("@galacticcouncil/math-hsm");var ie=require("@galacticcouncil/common");var{FeeUtils:zo}=m;var ae=require("polkadot-api"),Si=require("@polkadot-api/utils"),j=require("rxjs"),kt=require("@galacticcouncil/common");var Pi=require("polkadot-api"),Ti=require("viem");var{FeeUtils:fl}=m,{H160:Pl}=kt.h160;var mt=J(require("jsbi")),et=require("@uniswap/v3-sdk"),Ol=mt.default.BigInt(0),Al=mt.default.BigInt(1),Bl=mt.default.BigInt(-1);var se=require("@galacticcouncil/common");var Hl=10n**BigInt(se.RUNTIME_DECIMALS);var gt=require("rxjs"),ne=require("@galacticcouncil/common"),Ct=require("@uniswap/v3-sdk");var dt=require("viem"),xi=(0,dt.parseAbi)(["function getPool(address tokenA, address tokenB, uint24 fee) view returns (address pool)"]),vi=(0,dt.parseAbi)(["function slot0() view returns (uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked)","function liquidity() view returns (uint128)","function tickBitmap(int16 wordPosition) view returns (uint256)","function ticks(int24 tick) view returns (uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized)"]),Ii=(0,dt.parseAbi)(["function balanceOf(address account) view returns (uint256)"]);var{ERC20:Zl}=ne.erc20;var re=require("@galacticcouncil/common"),Mt=require("rxjs");var{logger:Jc}=re.log;var oe=require("@galacticcouncil/common");var{FeeUtils:lp}=m;var Di=require("@galacticcouncil/common");var ht=require("polkadot-api");var L=class{static build(t){return t.map(({assetIn:e,assetOut:i,pool:a,poolId:s,fee:n})=>a==="Stableswap"?{pool:(0,ht.Enum)("Stableswap",s),asset_in:e,asset_out:i}:a==="UniswapV3"?{pool:(0,ht.Enum)("UniswapV3",n),asset_in:e,asset_out:i}:{pool:(0,ht.Enum)(a),asset_in:e,asset_out:i})}};var Dt=require("polkadot-api");function ce(o){let t=[],e=o;for(;e&&typeof e=="object"&&"type"in e;)t.push(e.type),e=e.value;return t.join(".")}var v=class extends A{evm;evmClient;balance;aaveUtils;constructor(t,e,i){super(t,i),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new X(t,i),this.aaveUtils=new ut(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:i=>this.dryRun(i,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:te})}async dryRun(t,e){let i=(0,Dt.Enum)("Signed",t),a=(0,Dt.Enum)("system",i),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(a,e.decodedCall,4,{at:this.at}),r=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(r){let l=r.type==="Module"?ce(r.value):r.type;throw new Error("Dry run execution error!",{cause:l})}return n}isDirectOmnipoolTrade(t){return t.length===1&&t[0].pool==="Omnipool"}};var bt=class extends v{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,swaps:e,type:i}=this.trade;if(i==="Buy")return this.buildBuyTx();let{assetIn:a}=e[0],s=await this.balance.getBalance(this.beneficiary,a);return t>=s.transferable-5n?this.buildSellAllTx():this.buildSellTx()}async buildBuyTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,a=i[0],s=i[i.length-1],n=P.getFraction(t,this.slippagePct),r=a.assetIn,l=s.assetOut,u=t+n,c;return this.isDirectOmnipoolTrade(i)?c=this.api.tx.Omnipool.buy({asset_in:r,asset_out:l,amount:e,max_sell_amount:u}):c=this.api.tx.Router.buy({asset_in:r,asset_out:l,amount_out:e,max_amount_in:u,route:L.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterBuy",c)}async buildSellTx(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,a=i[0],s=i[i.length-1],n=P.getFraction(e,this.slippagePct),r=a.assetIn,l=s.assetOut,u=e-n,c;return this.isDirectOmnipoolTrade(i)?c=this.api.tx.Omnipool.sell({asset_in:r,asset_out:l,amount:t,min_buy_amount:u}):c=this.api.tx.Router.sell({asset_in:r,asset_out:l,amount_in:t,min_amount_out:u,route:L.build(i)}),await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("RouterSell",c)}async buildSellAllTx(){let{amountOut:t,swaps:e}=this.trade,i=e[0],a=e[e.length-1],s=P.getFraction(t,this.slippagePct),n=i.assetIn,r=a.assetOut,l=t-s,u=this.api.tx.Router.sell_all({asset_in:n,asset_out:r,min_amount_out:l,route:L.build(e)});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("RouterSellAll",u)}};var yt=require("polkadot-api");var ft=class extends v{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:a,tradePeriod:s,tradeRoute:n}=this.order,r=this.api.tx.DCA.schedule({schedule:{owner:this.beneficiary,period:s,max_retries:this.maxRetries,total_amount:t,slippage:this.slippagePct*1e4,stability_threshold:void 0,order:(0,yt.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:a,min_amount_out:0n,route:n})},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:i,tradeAmountIn:a,tradeAmountOut:s,tradePeriod:n,tradeRoute:r}=this.order,l=P.getFraction(s,this.slippagePct),u=s-l,c=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,yt.Enum)("Sell",{asset_in:e,asset_out:i,amount_in:a,min_amount_out:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapSell",c)}async buildTwapBuyTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:a,tradeAmountOut:s,tradePeriod:n,tradeRoute:r}=this.order,l=P.getFraction(a,this.slippagePct),u=a+l,c=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,yt.Enum)("Buy",{asset_in:e,asset_out:i,amount_out:s,max_amount_in:u,route:r})},start_execution_block:void 0});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("DcaSchedule.twapBuy",c)}};var ue=require("polkadot-api");var Pt=class extends v{_trade;_beneficiary;_slippagePct=1;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withSlippage(t){return this._slippagePct=t,this}get trade(){if(!this._trade)throw new Error("Trade not set. Use setTrade().");return this._trade}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get slippagePct(){return this._slippagePct}async build(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,a=i[0],s=i[i.length-1],n=a.assetIn,r=s.assetOut,l=P.getFraction(e,this.slippagePct),u=e-l,c=(0,ue.Enum)("Swap",{asset_in:n,asset_out:r,amount_in:t,amount_out:u,partial:!1}),g=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(g=await this.dispatchWithExtraGas(g)),this.wrapTx("IntentSwap",g)}};var pe=require("polkadot-api");var Tt=class extends v{_trade;_beneficiary;_minAmountOut;_deadline;_partial=!0;setTrade(t){return this._trade=t,this}withBeneficiary(t){return this._beneficiary=t,this}withPartial(t){return this._partial=t,this}withMinAmountOut(t){return this._minAmountOut=t,this}withDeadline(t){return this._deadline=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 partial(){return this._partial}get minAmountOut(){return this._minAmountOut}get deadline(){return this._deadline}async build(){let{amountIn:t,amountOut:e,swaps:i}=this.trade,a=i[0],s=i[i.length-1],n=a.assetIn,r=s.assetOut,l=(0,pe.Enum)("Swap",{asset_in:n,asset_out:r,amount_in:t,amount_out:this.minAmountOut??e,partial:this.partial}),u=this.apiIce.tx.Intent.submit_intent({intent:{data:l,deadline:this.deadline}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(u=await this.dispatchWithExtraGas(u)),this.wrapTx("IntentLimitOrder",u)}};var Lt=require("polkadot-api");var St=class extends v{_order;_beneficiary;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=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 slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":case"TwapBuy":return this.buildTwapTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:i,assetOutEd:a,tradeAmountIn:s,tradePeriod:n}=this.order,r=(0,Lt.Enum)("Dca",{asset_in:e,asset_out:i,amount_in:s,amount_out:a,slippage:this.slippagePct*1e4,budget:t,period:n}),l=this.apiIce.tx.Intent.submit_intent({intent:{data:r}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(l=await this.dispatchWithExtraGas(l)),this.wrapTx("IntentDcaSchedule",l)}async buildTwapTx(){let{amountIn:t,assetIn:e,assetOut:i,tradeAmountIn:a,tradeAmountOut:s,tradePeriod:n}=this.order,r=P.getFraction(s,this.slippagePct),l=s-r,u=(0,Lt.Enum)("Dca",{asset_in:e,asset_out:i,amount_in:a,amount_out:l,slippage:this.slippagePct*1e4,budget:t,period:n}),c=this.apiIce.tx.Intent.submit_intent({intent:{data:u}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(c=await this.dispatchWithExtraGas(c)),this.wrapTx("IntentDcaSchedule.twap",c)}};var wt=class{client;evmClient;at;constructor(t,e,i){this.client=t,this.evmClient=e,this.at=i}trade(t){return new bt(this.client,this.evmClient,this.at).setTrade(t)}order(t){return new ft(this.client,this.evmClient,this.at).setOrder(t)}intentMarket(t){return new Pt(this.client,this.evmClient).setTrade(t)}intentLimit(t){return new Tt(this.client,this.evmClient).setTrade(t)}intentOrder(t){return new St(this.client,this.evmClient).setOrder(t)}};0&&(module.exports={TxBuilderFactory});
|