@galacticcouncil/sdk-next 1.2.0 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/aave/AaveLog.d.ts +4 -0
- package/build/aave/index.cjs +1 -1
- package/build/aave/index.d.ts +2 -0
- package/build/aave/index.mjs +1 -1
- package/build/aave/types.d.ts +7 -0
- package/build/evm/adapter.d.ts +3 -1
- package/build/evm/client.d.ts +3 -1
- package/build/evm/index.cjs +1 -1
- package/build/evm/index.mjs +1 -1
- package/build/gho/GhoTokenLog.d.ts +4 -0
- package/build/gho/index.d.ts +4 -2
- package/build/{pool/hsm → gho}/types.d.ts +1 -1
- package/build/index.cjs +1 -1
- package/build/index.d.ts +1 -0
- package/build/index.mjs +1 -1
- package/build/indexer/BlockFetcher.d.ts +10 -0
- package/build/indexer/Indexer.d.ts +19 -0
- package/build/indexer/IndexerStats.d.ts +33 -0
- package/build/indexer/RpcPool.d.ts +12 -0
- package/build/indexer/Semaphore.d.ts +9 -0
- package/build/indexer/index.cjs +1 -0
- package/build/indexer/index.d.ts +9 -0
- package/build/indexer/index.mjs +1 -0
- package/build/indexer/scale.d.ts +1 -0
- package/build/indexer/types.d.ts +17 -0
- package/build/oracle/MmOracleClient.d.ts +1 -1
- package/build/oracle/MmOracleLog.d.ts +4 -0
- package/build/oracle/abi.d.ts +11 -84
- package/build/oracle/index.d.ts +2 -0
- package/build/oracle/mappings.d.ts +25 -0
- package/build/oracle/types.d.ts +11 -0
- package/build/pool/PoolContextProvider.d.ts +4 -0
- package/build/pool/aave/AavePoolClient.d.ts +0 -1
- package/build/pool/aave/types.d.ts +0 -6
- package/build/pool/hsm/HsmPoolClient.d.ts +0 -1
- package/build/pool/index.cjs +1 -1
- package/build/pool/index.d.ts +1 -0
- package/build/pool/index.mjs +1 -1
- package/build/pool/stable/StableSwap.d.ts +1 -1
- package/build/pool/stable/StableSwapClient.d.ts +12 -3
- package/build/pool/stable/StableSwapPeg.d.ts +7 -0
- package/build/pool/stable/types.d.ts +12 -1
- package/build/pool/types.d.ts +3 -1
- package/build/pool/uniswapv3/UniswapV3Math.d.ts +7 -0
- package/build/pool/uniswapv3/UniswapV3Pool.d.ts +46 -0
- package/build/pool/uniswapv3/UniswapV3PoolClient.d.ts +45 -0
- package/build/pool/uniswapv3/abi.d.ts +111 -0
- package/build/pool/uniswapv3/const.d.ts +7 -0
- package/build/pool/uniswapv3/index.d.ts +5 -0
- package/build/pool/uniswapv3/types.d.ts +21 -0
- package/build/sor/index.cjs +1 -1
- package/build/sor/index.mjs +1 -1
- package/build/tx/TxBuilder.d.ts +2 -2
- package/build/tx/TxBuilderFactory.d.ts +3 -1
- package/build/tx/index.cjs +1 -1
- package/build/tx/index.mjs +1 -1
- package/package.json +9 -1
- package/build/pool/aave/AaveAbi.d.ts +0 -126
package/build/sor/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var $t=Object.defineProperty;var Y=(u,t)=>{for(var e in t)$t(u,e,{get:t[e],enumerable:!0})};import Xt from"buffer";typeof window<"u"&&(window.Buffer=Xt.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 Yt=10,K=class{isNotVisited(t,e){let s=!0;return e.forEach(a=>{(a[0]===t[0]||a[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let a=[],i=new z,o=[];for(o.push([e,""]),i.enqueue(o);i.size()>0;){let r=i.dequeue();if(!r||r.length>Yt)continue;let n=r[r.length-1];(s===null||n[0]===s)&&a.push(r),t.get(n[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let m=[...r];m.push(c),i.enqueue(m)}})}return a}findShortestPaths(t,e,s){let a=[],i=new z,o=[];o.push([e,""]),i.enqueue(o);let r=1/0;for(;i.size()>0;){let n=i.dequeue();if(!n)continue;let l=n[n.length-1];if(l[0]===s){n.length<r?(r=n.length,a.length=0,a.push(n)):n.length===r&&a.push(n);continue}let c=t.get(l[0]);for(let m of c??[])this.isNotVisited(m,n)&&i.enqueue([...n,m])}return a}buildAndPopulateGraph(t,e){let s=new Map;for(let a of t)s.set(parseInt(a),[]);for(let[a,i,o]of e)s.get(i)?.push([o,a]);return s}};function dt(u){let t={};for(let e of u){let s=e.tokens.length;for(let a=0;a<s;a++){t[e.tokens[a].id]||(t[e.tokens[a].id]=[]);for(let i=0;i<s;i++){if(a==i)continue;let o=[e.address,e.tokens[a].id,e.tokens[i].id];t[e.tokens[a].id].push(o)}}}return t}import{calculate_in_given_out as zt,calculate_out_given_in as Kt,calculate_linear_weights as jt,calculate_pool_trade_fee as Qt,get_spot_price as Jt}from"@galacticcouncil/math-lbp";var R=class{static getSpotPrice(t,e,s,a,i){return Jt(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i){return zt(t,e,s,a,i)}static calculateOutGivenIn(t,e,s,a,i){return Kt(t,e,s,a,i)}static calculateLinearWeights(t,e,s,a,i){return jt(t,e,s,a,i)}static calculatePoolTradeFee(t,e,s){return Qt(t,e,s)}};import{big as xt,RUNTIME_DECIMALS as wt}from"@galacticcouncil/common";var it={};Y(it,{withTimeout:()=>Zt});function Zt(u,t,e="timeout"){return new Promise((s,a)=>{let i=setTimeout(()=>a(new Error(e)),t);u.then(o=>{clearTimeout(i),s(o)},o=>{clearTimeout(i),a(o)})})}var A={};Y(A,{divSpot:()=>ee,getFraction:()=>se,mulScaled:()=>It,mulSpot:()=>te});import{RUNTIME_DECIMALS as St}from"@galacticcouncil/common";function It(u,t,e,s,a){let i=e+s-a,o=u*t;return i>0?o/BigInt(10)**BigInt(i):i<0?o*BigInt(10)**BigInt(-i):o}function te(u,t,e,s){return It(u,t,e,St,s)}function ee(u,t,e,s){if(t===0n)return 0n;let a=BigInt(10)**BigInt(St+s-e);return u*a/t}function se(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let s=BigInt(10)**BigInt(e),a=BigInt(Math.round(t*Number(s)));return u*a/(BigInt(100)*s)}var f={};Y(f,{FeeUtils:()=>gt,shiftNeg:()=>oe});import ie from"big.js";var gt=class u{static toPct(t){let[e,s]=t;return u.safeDivide(e*100,s)}static toRaw(t){let[e,s]=t;return u.safeDivide(e,s)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,s=12){let a=10**s;return Math.round(t*a/e)/a}static safeRound(t){return parseFloat(t.toPrecision(15))}};function oe(u,t){let e=ie(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var j={};Y(j,{findNestedKey:()=>re,findNestedObj:()=>ne,jsonFormatter:()=>le});var re=(u,t)=>{let e=[];return JSON.stringify(u,(s,a)=>(a&&a[t]&&e.push(a),a)),e[0]},ne=(u,t,e)=>{let s;return JSON.stringify(u,(a,i)=>(i&&i[t]===e&&(s=i),i)),s},le=(u,t)=>typeof t=="bigint"?t.toString():t;var w={};Y(w,{calculateBuyFee:()=>me,calculateDiffToAvg:()=>ce,calculateDiffToRef:()=>ue,calculateSellFee:()=>pe});import k from"big.js";function ce(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function ue(u,t){if(t===0n)return 0;let e=k(u.toString()),s=k(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function pe(u,t){if(u===0n)return 0;let e=k(u.toString()),s=k(t.toString());return k(1).minus(s.div(e)).mul(100).round(2).toNumber()}function me(u,t){if(u===0n)return 0;let e=k(u.toString());return k(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as Qs}from"@thi.ng/cache";var{FeeUtils:Tt}=f,ot=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(o=>[o.id,o])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,weightIn:a.weight,weightOut:i.weight}}validateAndBuy(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let o=t.balanceOut/this.maxOutRatio;if(e>o&&i.push("MaxOutRatioExceeded"),a===t.assetOut){let r=this.calculateTradeFee(e,s),n=Tt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:n,errors:i}}else{let r=this.calculateInGivenOut(t,e),n=t.balanceIn/this.maxInRatio;return r>n&&i.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let o=t.balanceIn/this.maxInRatio;if(e>o&&i.push("MaxInRatioExceeded"),a===t.assetIn){let r=this.calculateOutGivenIn(t,e),n=t.balanceOut/this.maxOutRatio;return r>n&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:i}}else{let r=this.calculateOutGivenIn(t,e),n=this.calculateTradeFee(r,s),l=Tt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=r-n,m=t.balanceOut/this.maxOutRatio;return c>m&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let s=R.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=R.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=R.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),xt.toBigInt(1,wt).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=R.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),xt.toBigInt(1,wt).toString());return BigInt(e)}calculateTradeFee(t,e){let s=R.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as lr}from"polkadot-api";import{Subscription as ur,distinctUntilChanged as pr,filter as mr,map as dr}from"rxjs";import{memoize1 as Po}from"@thi.ng/memoize";import{TLRUCache as fo}from"@thi.ng/cache";import{ReplaySubject as xo,Subscription as wo,combineLatest as To,defer as vo,from as Bo,interval as Ao,merge as Fo,of as Eo,EMPTY as _o}from"rxjs";import{bufferCount as ko,bufferTime as Co,catchError as Mo,filter as Lo,finalize as Do,map as Ho,pairwise as No,repeat as qo,skip as Go,share as Vo,startWith as Uo,switchMap as Wo,tap as $o,throttleTime as Xo}from"rxjs/operators";import{hydration as Ya,hydrationNext as za,hydrationIce as Ka}from"@galacticcouncil/descriptors";import{log as de}from"@galacticcouncil/common";import{map as Ha,shareReplay as Na,tap as qa}from"rxjs";import{defer as fa,from as Sa,of as Ia,timer as Oa}from"rxjs";import{catchError as wa,distinctUntilChanged as Ta,expand as va,map as Ba,shareReplay as Aa,skip as Fa,switchMap as Ea,timeout as _a}from"rxjs/operators";var{logger:Va}=de;import{getWsProvider as ti}from"polkadot-api/ws";import{withLogsRecorder as si}from"polkadot-api/logs-provider";import{Binary as Pi}from"polkadot-api";import{log as ge}from"@galacticcouncil/common";import{combineLatest as wi,concat as Ti,defer as vi,from as Bi}from"rxjs";import{bufferCount as Fi,distinctUntilChanged as Ei,debounceTime as _i,map as Ri,retry as ki,startWith as Ci,switchMap as Mi,tap as Li,take as Di,skip as Hi,connect as Ni}from"rxjs/operators";var{logger:Ui}=ge;import{BehaviorSubject as ao}from"rxjs";import{log as be}from"@galacticcouncil/common";var co={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:uo}=be;var{withTimeout:ir}=it;import{calculate_in_given_out as ye,calculate_lrna_in_given_out as fe,calculate_out_given_in as Se,calculate_out_given_lrna_in as Ie,calculate_spot_price as Oe,calculate_lrna_spot_price as xe,calculate_shares as we,calculate_liquidity_out as Te,calculate_liquidity_lrna_out as ve,verify_asset_cap as Be,calculate_liquidity_hub_in as Ae,is_sell_allowed as Fe,is_buy_allowed as Ee,is_add_liquidity_allowed as _e,is_remove_liquidity_allowed as Re,recalculate_asset_fee as ke,recalculate_protocol_fee as Ce}from"@galacticcouncil/math-omnipool";import V from"big.js";var S=class{static calculateSpotPrice(t,e,s,a){return Oe(t,e,s,a)}static calculateLrnaSpotPrice(t,e){return xe(t,e)}static calculateInGivenOut(t,e,s,a,i,o,r,n,l,c){return ye(t,e,s,a,i,o,r,n,l,c)}static calculateLrnaInGivenOut(t,e,s,a,i,o){return fe(t,e,s,a,i,o)}static calculateOutGivenIn(t,e,s,a,i,o,r,n,l,c){return Se(t,e,s,a,i,o,r,n,l,c)}static calculateOutGivenLrnaIn(t,e,s,a,i,o){return Ie(t,e,s,a,i,o)}static calculateShares(t,e,s,a){return we(t,e,s,a)}static calculateLiquidityOut(t,e,s,a,i,o,r,n){return Te(t,e,s,a,i,o,r,n)}static calculateLiquidityLRNAOut(t,e,s,a,i,o,r,n){return ve(t,e,s,a,i,o,r,n)}static calculateCapDifference(t,e,s,a){let i=V(e),o=V(t),r=V(a),n=V(s),l=V(10).pow(18),c=n.div(l);if(i.div(r).lt(c)){let h=c.times(r).minus(i).times(o),d=i.times(V(1).minus(c));return h.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,s,a){return Ae(t,e,s,a)}static isSellAllowed(t){return Fe(t)}static isBuyAllowed(t){return Ee(t)}static isAddLiquidityAllowed(t){return _e(t)}static isRemoveLiquidityAllowed(t){return Re(t)}static recalculateAssetFee(t,e,s,a,i,o,r,n,l,c,m){return ke(t,e,s,a,i,o,r,n,l,c,m)}static recalculateProtocolFee(t,e,s,a,i,o,r,n,l,c,m){return Ce(t,e,s,a,i,o,r,n,l,c,m)}static verifyAssetCap(t,e,s,a){return Be(t,e,s,a)}};import{big as Me}from"@galacticcouncil/common";var{FeeUtils:_}=f,nt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let s=new Map(this.tokens.map(o=>[o.id,o])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:a.hubReserves,hubReservesOut:i.hubReserves,sharesIn:a.shares,sharesOut:i.shares,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,tradeableIn:a.tradeable,tradeableOut:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),o=a===0n?0:w.calculateBuyFee(a,i),r=[],n=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!n||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return i>m&&r.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:o,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),o=w.calculateSellFee(a,i),r=[],n=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);(!n||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return i>m&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:o,errors:r}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let a=S.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?_.toRaw(s.assetFee).toString():"0",s?_.toRaw(s.protocolFee).toString():"0",s?_.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,s){let a=S.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?_.toRaw(s.assetFee).toString():"0",s?_.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let a=S.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?_.toRaw(s.assetFee).toString():"0",s?_.toRaw(s.protocolFee).toString():"0",s?_.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,s){let a=S.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?_.toRaw(s.assetFee).toString():"0",s?_.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=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,s){let a=e-s;if(a===0)return t;let i=Me.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as rn,Binary as vt,CompatibilityLevel as nn,Enum as He}from"polkadot-api";import{toHex as un}from"@polkadot-api/utils";import{Subscription as mn,distinctUntilChanged as dn,filter as gn,finalize as hn,map as bn,merge as Pn,tap as yn}from"rxjs";import{HYDRATION_SS58_PREFIX as Sn}from"@galacticcouncil/common";var{FeeUtils:jr}=f;var{FeeUtils:Fn}=f,En=vt.toHex(vt.fromText("omnipool")),_n=He("Short");import{calculate_in_given_out as qe,calculate_out_given_in as Ge,calculate_amplification as Ve,calculate_add_one_asset as Ue,calculate_liquidity_out_one_asset as We,calculate_shares as $e,calculate_shares_for_amount as Xe,calculate_spot_price_with_fee as Ye,pool_account_name as ze,recalculate_peg as Ke}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return ze(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,a,i){return Ve(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i,o,r){return qe(t,e,s,a,i,o,r)}static calculateAddOneAsset(t,e,s,a,i,o,r){return Ue(t,e,s,a,i,o,r)}static calculateSharesForAmount(t,e,s,a,i,o,r){return Xe(t,e,s,a,i,o,r)}static calculateOutGivenIn(t,e,s,a,i,o,r){return Ge(t,e,s,a,i,o,r)}static calculateLiquidityOutOneAsset(t,e,s,a,i,o,r){return We(t,e,s,a,i,o,r)}static calculateShares(t,e,s,a,i,o){return $e(t,e,s,a,i,o)}static calculateSpotPriceWithFee(t,e,s,a,i,o,r,n){return Ye(t,e,s,a,i,o,r,n)}static recalculatePegs(t,e,s,a,i,o){let r=Ke(t,e,s,a,i,o);return JSON.parse(r)}};import{RUNTIME_DECIMALS as je,big as Bt}from"@galacticcouncil/common";var{FeeUtils:U}=f,W=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new u(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(o=>[o.id,o])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:a.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),o=a===0n?0:w.calculateBuyFee(a,i),r=[],n=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!n||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:o,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),o=w.calculateSellFee(a,i),r=[],n=S.isSellAllowed(t.tradeableIn),l=S.isBuyAllowed(t.tradeableOut);return(!n||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:o,errors:r}}calculateIn(t,e,s){let a=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?U.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateAddOneAsset(t,e,s){let a=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?U.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateSharesForAmount(t,e,s){let a=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?U.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateInGivenOut(t,e,s){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,s):t.assetIn==this.id?this.calculateSharesForAmount(t,e,s):this.calculateIn(t,e,s)}spotPriceInGivenOut(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,s){let a=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?U.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,s){let a=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?U.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateShares(t,e,s){let a=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?U.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,s):t.assetOut==this.id?this.calculateShares(t,e,s):this.calculateOut(t,e,s)}spotPriceOutGivenIn(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:s,decimals:a})=>({asset_id:e,amount:s,decimals:a}));return JSON.stringify(t,j.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],j.jsonFormatter)}normalizeSpot(t,e,s,a,i){return e?t*Bt.pow10(je-i):s?t/Bt.pow10(i-a):t}};import{AccountId as cl,CompatibilityLevel as ul}from"polkadot-api";import{toHex as ml}from"@polkadot-api/utils";import{blake2b as gl}from"@noble/hashes/blake2b";import{Subscription as bl,distinctUntilChanged as Pl,map as yl,merge as fl,tap as Sl}from"rxjs";import{HYDRATION_SS58_PREFIX as Ol,RUNTIME_DECIMALS as xl}from"@galacticcouncil/common";var{FeeUtils:Cl}=f;import{calculate_in_given_out as Je,calculate_out_given_in as Ze,calculate_pool_trade_fee as ts,get_spot_price as es,calculate_liquidity_in as ss,calculate_shares as as,calculate_spot_price as is,calculate_spot_price_with_fee as os,calculate_liquidity_out_asset_a as rs,calculate_liquidity_out_asset_b as ns}from"@galacticcouncil/math-xyk";var D=class{static getSpotPrice(t,e,s){return es(t,e,s)}static calculateInGivenOut(t,e,s){return Je(t,e,s)}static calculateOutGivenIn(t,e,s){return Ze(t,e,s)}static calculatePoolTradeFee(t,e,s){return ts(t,e,s)}static calculateLiquidityIn(t,e,s){return ss(t,e,s)}static calculateSpotPrice(t,e){return is(t,e)}static calculateSpotPriceWithFee(t,e,s,a){return os(t,e,s,a)}static calculateShares(t,e,s){return as(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,a){return rs(t,e,s,a)}static calculateLiquidityOutAssetB(t,e,s,a){return ns(t,e,s,a)}};import{big as ls}from"@galacticcouncil/common";var{FeeUtils:At}=f,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 s=new Map(this.tokens.map(o=>[o.id,o])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(a,s),o=At.toPct(s.exchangeFee),r=a+i,n=[];(e<this.minTradingLimit||a<t.assetInEd)&&n.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&n.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return r>c&&n.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:a,amountOut:e,feePct:o,errors:n}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(a,s),o=At.toPct(s.exchangeFee),r=a-i,n=[];(e<this.minTradingLimit||a<t.assetOutEd)&&n.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&n.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return r>c&&n.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:r,feePct:o,errors:n}}calculateInGivenOut(t,e){let s=D.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=D.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=D.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=D.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let s=D.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}normalizeSpot(t,e,s){let a=e-s;if(a===0)return t;let i=ls.pow10(Math.abs(a));return a>0?t*i:t/i}};import{CompatibilityLevel as rc}from"polkadot-api";import{Subscription as lc}from"rxjs";import{big as Ft,RUNTIME_DECIMALS as Et}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 s=new Map(this.tokens.map(o=>[o.id,o])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=[];return a>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return Ft.toBigInt(1,Et)}spotPriceOutGivenIn(t){return Ft.toBigInt(1,Et)}calculateTradeFee(t,e){return 0n}};import{AccountId as qc,Binary as Gc}from"polkadot-api";import{toHex as Uc}from"@polkadot-api/utils";import{Subscription as $c,filter as Xc,map as Yc,mergeMap as zc}from"rxjs";import{decodeEventLog as jc}from"viem";import{erc20 as us,HYDRATION_SS58_PREFIX as Jc}from"@galacticcouncil/common";var{ERC20:ou}=us;import{calculate_collateral_in_given_hollar_out as ms,calculate_collateral_out_given_hollar_in as ds,calculate_hollar_in_given_collateral_out as gs,calculate_hollar_out_given_collateral_in as hs,calculate_imbalance as bs,calculate_max_price as Ps,calculate_buyback_limit as ys,calculate_buyback_price_with_fee as fs}from"@galacticcouncil/math-hsm";var F=class{static calculateCollateralInGivenHollarOut(t,e,s){return ms(t,e,s)}static calculateCollateralOutGivenHollarIn(t,e,s){return ds(t,e,s)}static calculateHollarOutGivenCollateralIn(t,e,s){return hs(t,e,s)}static calculateHollarInGivenCollateralOut(t,e,s){return gs(t,e,s)}static calculateImbalance(t,e,s){return bs(t,e,s)}static calculateBuybackLimit(t,e){return ys(t,e)}static calculateBuybackPriceWithFee(t,e,s){return fs(t,e,s)}static calculateMaxPrice(t,e){return Ps(t,e)}};import{big as C,RUNTIME_DECIMALS as ut}from"@galacticcouncil/common";var{FeeUtils:$}=f,pt=class u extends W{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new u(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,s){let a=this.parsePair(t.assetOut,t.assetIn),i=super.calculateInGivenOut(a,e,{fee:this.fee}),o=this.calculateBuybackLimit(t);e>o&&s.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,i)>r&&s.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(t,e,s){return this.collateralBalance+t>this.maxInHolding&&s.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&s.push("FacilitatorCapacityExceeded"),s}validateTradeConstraints(t,e,s){let a=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,a):this.validateTradeHollarOut(e,s,a)}validateAndBuy(t,e){let s=this.calculateInGivenOut(t,e),a=this.validateTradeConstraints(t,s,e);return{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e){let s=this.calculateOutGivenIn(t,e),a=this.validateTradeConstraints(t,e,s);return{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateHollarInGivenCollateralOut(t,e){let s=super.calculateInGivenOut(t,e,{fee:this.fee}),a=F.calculateHollarInGivenCollateralOut(e.toString(),s.toString(),$.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),s=F.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),$.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let s=super.calculateOutGivenIn(t,e,{fee:this.fee}),a=F.calculateCollateralOutGivenHollarIn(e.toString(),s.toString(),$.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),s=F.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),$.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),s=F.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(s)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),s=F.calculateBuybackLimit(e.toString(),$.toRaw(this.buyBackRate).toString());return BigInt(s)}calculateBuyPrice(t,e,s){let a=F.calculateBuybackPriceWithFee(s.toString(),e.toString(),$.toRaw(this.buyBackFee).toString()),[i,o]=JSON.parse(a),r=C.pow10(t.decimalsIn+ut-t.decimalsOut);return BigInt(i)*r/BigInt(o)}calculateMaxPrice(t){let e=this.getCollateralPeg(),s=F.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[a,i]=JSON.parse(s),o=C.pow10(ut-t.decimalsOut);return BigInt(a)*o/BigInt(i)}spotPriceInGivenOut(t){let e=C.toBigInt(1,t.decimalsOut),a=this.calculateInGivenOut(t,e)*C.pow10(ut-t.decimalsOut);return this.normalizeSpotPrice(a,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=C.toBigInt(1,t.decimalsIn),a=this.calculateOutGivenIn(t,e)*C.pow10(ut-t.decimalsIn);return this.normalizeSpotPrice(a,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(a=>a.id!==this.hollarId),e=this.pegs[t],s=this.tokens[t].decimals;return this.isDefaultPeg(e)?[C.toBigInt(1,18).toString(),C.toBigInt(1,s).toString()]:e}isDefaultPeg(t){let[e,s]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&s==="1"}normalizeSpotPrice(t,e,s){let a=e-s;if(a===0)return t;let i=C.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as Du,Binary as Hu,CompatibilityLevel as Nu}from"polkadot-api";import{toHex as Vu}from"@polkadot-api/utils";import{Subscription as $u,combineLatest as Xu,filter as Yu,map as zu,mergeMap as Ku,pairwise as ju}from"rxjs";import{decodeEventLog as Ju}from"viem";import{h160 as Is,HYDRATION_SS58_PREFIX as tp}from"@galacticcouncil/common";var{FeeUtils:np}=f,{H160:lp}=Is;var Z=class{static get(t){switch(t.type){case"Aave":return ct.fromPool(t);case"XYK":return lt.fromPool(t);case"Omnipool":return nt.fromPool(t);case"LBP":return ot.fromPool(t);case"Stableswap":return W.fromPool(t);case"HSM":return pt.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as ws}from"@galacticcouncil/common";import{Subject as qp,Subscription as Gp,takeUntil as Vp}from"rxjs";var mt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var{logger:om}=ws;var tt=class{getProposals(t,e,s){let a=s.filter(p=>p.type==="XYK"),i=s.filter(p=>p.type!=="XYK"),o=new Set(i.map(p=>p.tokens).flat().map(p=>p.id)),r=o.has(t),n=o.has(e),l=new K,c=p=>{let b=dt(p),y=Object.keys(b),E=y.flatMap(v=>b[v]);return l.buildAndPopulateGraph(y,E)};if(!r&&!n){let p=a.filter(E=>E.tokens.find(v=>v.id===t)||E.tokens.find(v=>v.id===e)),b=c(p),y=l.findPaths(b,t,e);return this.parsePaths(y)}if(r&&n){let p=c(i),b=l.findPaths(p,t,e);return this.parsePaths(b)}let m=r?e:t,h=a.filter(p=>p.tokens.some(b=>b.id===m));if(h.length===0)return[];let d=[...i,...h],P=c(d),g=l.findPaths(P,t,e);return this.parsePaths(g)}parsePaths(t){let e=[];for(let s of t){let a=[];for(let i=0;i<s.length;i++){let o=s[i],r=s[i+1];if(r==null)break;a.push(this.toEdge(o,r))}e.push(a)}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,s){return`${t}->${e}::${s.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:s=[]}=this.filter,a=new Set(e),i=new Set(s);return t.filter(o=>i.has(o.type)?!1:a.size>0?a.has(o.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let s=await this.getPools();return this.validateInput(t,e,s),this.getPaths(t,e,s)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(a=>a!==t).map(a=>this.getRoutes(a,t)))).filter(a=>a.length>0).map(([a])=>a[0].assetIn).sort()}validateInput(t,e,s){if(s.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let a=this.getAssets(s);if(!a.has(t))throw new Error(t+" is not supported asset");if(!a.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(a=>a.id)).flat().sort((s,a)=>s>a?1:-1);return new Set(e)}getPaths(t,e,s){let a=this.toPoolsMap(s);return this.getProposals(t,e,s).filter(o=>this.validPath(o,a)).map(o=>this.toHops(o,a))}getProposals(t,e,s){let a=this.buildRouteKey(t,e,s);if(this.routeProposals.has(a))return this.routeProposals.get(a);let i=this.routeSuggester.getProposals(t,e,s);return this.routeProposals.set(a,i),i}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,a)=>s&&a)}validEdge([t,e,s],a){return a.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,Z.get(e)]))}toHops(t,e){return t.map(([s,a,i])=>{let o=e.get(s);return{poolAddress:s,poolId:o?.id,pool:o?.type,assetIn:a,assetOut:i}})}};import{big as x,RUNTIME_DECIMALS as X}from"@galacticcouncil/common";var Rt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Rt||{}),kt=(s=>(s.Dca="Dca",s.TwapSell="TwapSell",s.TwapBuy="TwapBuy",s))(kt||{}),Ct=(s=>(s.OrderTooSmall="OrderTooSmall",s.OrderTooBig="OrderTooBig",s.OrderImpactTooBig="OrderImpactTooBig",s))(Ct||{});var{FeeUtils:Mt}=f,st=class extends et{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,s){let a=super.validateInput(t,e,s),i=super.getPaths(t,e,s);if(!i.length)throw new mt(t,e);return{paths:i,pools:s,poolsMap:a}}async withCtx(t,e,s){let a=await super.getPools(),i=this.buildCtxSync(t,e,a);return s(i)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,a)=>{let i=s[s.length-1].amountOut,o=a[a.length-1].amountOut;return i>o?-1:1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,o)=>i+o),a=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,o)=>i+o);return[s,a]}}getPoolFeeRange(t,e){let s=t.min?Mt.toPct(t.min):void 0,a=t.max?Mt.toPct(t.max):void 0;if(s&&a)return[s,Math.max(a,e)]}async getBestSell(t,e,s){return this.getSell(t,e,s)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:o})=>{let r;if(a)r=await this.toSellSwaps(s,a,o);else{let n=i.map(c=>this.toSellSwaps(s,c,o)),l=await Promise.all(n);r=this.findBestSellRoute(l)}return this.buildSell(o,r)})}async getSells(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let o=a.map(n=>this.toSellSwaps(s,n,i));return(await Promise.all(o)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildSell(i,n)).sort((n,l)=>n.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let s=e[0],a=e[e.length-1],i=this.isDirectTrade(e),o=this.getSellSpot(e),r=a.amountOut,n=i?a.calculatedOut:this.calculateDelta0Y(s.amountIn,e,t),l=n-r,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:w.calculateSellFee(n,r),h=A.mulSpot(s.amountIn,o,s.assetInDecimals,a.assetOutDecimals),d=w.calculateDiffToRef(n,h);return{type:"Sell",amountIn:s.amountIn,amountOut:a.amountOut,spotPrice:o,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:x.toDecimal(s.amountIn,s.assetInDecimals),amountOut:x.toDecimal(a.amountOut,a.assetOutDecimals),spotPrice:x.toDecimal(o,X),tradeFee:x.toDecimal(l,a.assetOutDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(P=>P.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,s)=>e*s/10n**BigInt(X))}calculateDelta0Y(t,e,s){let a=[];for(let i=0;i<e.length;i++){let o=e[i],r=s.get(o.poolAddress);if(r==null)throw new Error("Pool does not exit");let n=r.parsePair(o.assetIn,o.assetOut),l;i>0?l=a[i-1]:l=t;let c=r.calculateOutGivenIn(n,l);a.push(c)}return a[a.length-1]}async calculateMostLiquidRoute(t,e,s){let{paths:a,pools:i,poolsMap:o}=s,l=i.filter(g=>g.tokens.some(p=>p.id===t)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(p=>p.id===t)).map(g=>g.map(p=>p.balance).reduce((p,b)=>p+b)).sort((g,p)=>p<g?-1:1)[0],c=A.getFraction(l,.1),m=await Promise.all(a.map(g=>this.toSellSwaps(c,g,o))),d=this.findBestSellRoute(m).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut})),P=this.buildRouteKey(t,e,i);return this.mlr.set(P,d),d}async toSellSwaps(t,e,s){let a=[];for(let i=0;i<e.length;i++){let o=e[i],r=s.get(o.poolAddress);if(r==null)throw new Error("Pool does not exit");let n=r.parsePair(o.assetIn,o.assetOut),l;i>0?l=a[i-1].amountOut:l=typeof t=="string"?x.toBigInt(t,n.decimalsIn):t;let c=await this.ctx.getPoolFees(n,r),{amountOut:m,calculatedOut:h,feePct:d,errors:P}=r.validateAndSell(n,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceOutGivenIn(n),b=A.mulSpot(l,p,n.decimalsIn,n.decimalsOut),y=w.calculateDiffToRef(h,b);a.push({...o,assetInDecimals:n.decimalsIn,assetOutDecimals:n.decimalsOut,amountIn:l,amountOut:m,calculatedOut:h,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:y,errors:P,isSupply(){return r.type==="Aave"&&r.tokens[0].id===o.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===o.assetIn},toHuman(){return{...o,amountIn:x.toDecimal(l,n.decimalsIn),amountOut:x.toDecimal(m,n.decimalsOut),calculatedOut:x.toDecimal(h,n.decimalsOut),spotPrice:x.toDecimal(p,X),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:y,errors:P}}})}return a}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async s=>{let a=this.buildRouteKey(t,e,s.pools),i=this.mlr.get(a);return i||this.calculateMostLiquidRoute(t,e,s)})}async getSpotPrice(t,e){return this.withCtx(t,e,async s=>{let{pools:a,poolsMap:i}=s,o=this.buildRouteKey(t,e,a),r=this.mlr.get(o);r||(r=await this.calculateMostLiquidRoute(t,e,s));let n=await this.toSellSwaps("1",r,i);return{amount:this.getSellSpot(n),decimals:X}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((s,a)=>{let i=s[0].amountIn,o=a[0].amountIn;return i>o?1:-1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}async getBestBuy(t,e,s){return this.getBuy(t,e,s)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:o})=>{let r;if(a)r=await this.toBuySwaps(s,a,o);else{let n=i.map(c=>this.toBuySwaps(s,c,o)),l=await Promise.all(n);r=this.findBestBuyRoute(l)}return this.buildBuy(o,r)})}async getBuys(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let o=a.map(n=>this.toBuySwaps(s,n,i));return(await Promise.all(o)).filter(n=>n.every(l=>l.errors.length==0)).map(n=>this.buildBuy(i,n)).sort((n,l)=>n.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let s=e[e.length-1],a=e[0],i=this.isDirectTrade(e),o=this.getBuySpot(e),r=a.amountIn,n=i?a.calculatedIn:this.calculateDelta0X(s.amountOut,e,t),l=r-n,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:w.calculateBuyFee(n,r),h=A.mulSpot(s.amountOut,o,s.assetOutDecimals,a.assetInDecimals),d;return n===0n?d=-100:d=w.calculateDiffToRef(h,n),{type:"Buy",amountOut:s.amountOut,amountIn:a.amountIn,spotPrice:o,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:x.toDecimal(s.amountOut,s.assetOutDecimals),amountIn:x.toDecimal(a.amountIn,a.assetInDecimals),spotPrice:x.toDecimal(o,X),tradeFee:x.toDecimal(l,a.assetInDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(P=>P.toHuman())}}}}calculateDelta0X(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let o=e[i],r=s.get(o.poolAddress);if(r==null)throw new Error("Pool does not exit");let n=r.parsePair(o.assetIn,o.assetOut),l;i==e.length-1?l=t:l=a[0];let c=r.calculateInGivenOut(n,l);a.unshift(c)}return a[0]}async toBuySwaps(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let o=e[i],r=s.get(o.poolAddress);if(r==null)throw new Error("Pool does not exit");let n=r.parsePair(o.assetIn,o.assetOut),l;i==e.length-1?l=typeof t=="string"?x.toBigInt(t,n.decimalsOut):t:l=a[0].amountIn;let c=await this.ctx.getPoolFees(n,r),{amountIn:m,calculatedIn:h,feePct:d,errors:P}=r.validateAndBuy(n,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceInGivenOut(n),b=A.mulSpot(l,p,n.decimalsOut,n.decimalsIn),y;h===0n?y=-100:y=w.calculateDiffToRef(b,h),a.unshift({...o,assetInDecimals:n.decimalsIn,assetOutDecimals:n.decimalsOut,amountOut:l,amountIn:m,calculatedIn:h,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:y,errors:P,isSupply(){return r.type==="Aave"&&r.tokens[0].id===o.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===o.assetIn},toHuman(){return{...o,amountOut:x.toDecimal(l,n.decimalsOut),amountIn:x.toDecimal(m,n.decimalsIn),calculatedIn:x.toDecimal(h,n.decimalsIn),spotPrice:x.toDecimal(p,X),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:y,errors:P}}})}return a}};import{big as O}from"@galacticcouncil/common";var Lt=6e3,Dt=1000000000000000n,at=6,bt=-5,Pt=216e5,xd=3,Ht=.1,Nt=6;import{Enum as qt}from"polkadot-api";var H=class{static build(t){return t.map(({assetIn:e,assetOut:s,pool:a,poolId:i})=>a==="Stableswap"?{pool:qt("Stableswap",i),asset_in:e,asset_out:s}:{pool:qt(a),asset_in:e,asset_out:s})}};var yt=class{schedulerOptions;router;constructor(t,e={}){this.router=new st(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,s,a,i){let o=await this.router.getBestSell(t,e,s),{amountIn:r,swaps:n,priceImpactPct:l}=o,c=n[0],m=n[n.length-1],{assetInDecimals:h}=c,{assetOutDecimals:d}=m,P=Math.abs(l),g=await this.getMinimumOrderBudget(t,h),p=this.getOptimalTradeCount(P),b=this.getMaximumTradeCount(r,g,a),y=i||Math.min(p,b),E=Math.round(a/y),v=r/BigInt(y),T=await this.router.getBestSell(t,e,v),N=r<g,M=[];N&&M.push("OrderTooSmall");let G=await this.getAssetOutEd(m),L=T.amountOut*BigInt(y),Vt=this.toBlockPeriod(E),Ut=T.tradeFee*BigInt(y),Wt=H.build(n),ft={assetIn:t,assetOut:e,assetOutEd:G,errors:M,maxTradeCount:b,tradeCount:y,tradeFee:Ut,tradeImpactPct:T.priceImpactPct,tradePeriod:Vt,tradeRoute:Wt,type:"Dca"};return{...ft,amountIn:r,amountOut:L,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...ft,amountIn:O.toDecimal(r,h),amountOut:O.toDecimal(L,d),assetOutEd:O.toDecimal(G,d),tradeAmountIn:O.toDecimal(T.amountIn,h),tradeAmountOut:O.toDecimal(T.amountOut,d)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let s=await this.router.getSpotPrice(0,t);if(s)return A.mulSpot(this.minOrderBudget,s.amount,12,e);let a=await this.router.getSpotPrice(t,0);if(a)return A.divSpot(this.minOrderBudget,a.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,s){let a=e*2n/10n;if(a===0n)return 0;let i=Number(t/a),o=Math.floor(s/this.blockTime),r=Math.max(0,Math.floor(o*(1-.1)));return Math.min(i,r)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,s,a){let i=await this.router.getBestSell(t,e,s),{swaps:o}=i,r=o[0],n=o[o.length-1],{assetInDecimals:l}=r,{assetOutDecimals:c}=n,m=await this.getMinimumOrderBudget(t,l),h=i.amountIn<m,d=[];h&&d.push("OrderTooSmall");let P=await this.getAssetOutEd(n),g=this.toBlockPeriod(a),p=H.build(o),b={assetIn:t,assetOut:e,assetOutEd:P,errors:d,maxTradeCount:0,tradeCount:0,tradeFee:i.tradeFee,tradeImpactPct:i.priceImpactPct,tradePeriod:g,tradeRoute:p,type:"Dca"};return{...b,amountIn:0n,amountOut:0n,tradeAmountIn:i.amountIn,tradeAmountOut:i.amountOut,toHuman(){return{...b,amountIn:"0",amountOut:"0",assetOutEd:O.toDecimal(P,c),tradeAmountIn:O.toDecimal(i.amountIn,l),tradeAmountOut:O.toDecimal(i.amountOut,c)}}}}async getTwapSellOrder(t,e,s){let a=await this.router.getBestSell(t,e,s),{amountIn:i,swaps:o,priceImpactPct:r}=a,n=o[0],l=o[o.length-1],{assetInDecimals:c}=n,{assetOutDecimals:m}=l,h=Math.abs(r),d=this.getTwapTradeCount(h),P=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestSell(n.assetIn,l.assetOut,P)]),b=d===1,y=i<g,E=p.priceImpactPct<-5,v=[];y||b?v.push("OrderTooSmall"):E&&v.push("OrderImpactTooBig");let T=await this.getAssetOutEd(l),N=p.amountOut*BigInt(d),M=p.tradeFee*BigInt(d),G=H.build(o),L={assetIn:t,assetOut:e,assetOutEd:T,errors:v,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:G,type:"TwapSell"};return{...L,amountIn:i,amountOut:N,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:M,toHuman(){return{...L,amountIn:O.toDecimal(i,c),amountOut:O.toDecimal(N,m),assetOutEd:O.toDecimal(T,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(M,m)}}}}async getTwapBuyOrder(t,e,s){let a=await this.router.getBestBuy(t,e,s),{amountOut:i,swaps:o,priceImpactPct:r}=a,n=o[0],l=o[o.length-1],{assetInDecimals:c}=n,{assetOutDecimals:m}=l,h=Math.abs(r),d=this.getTwapTradeCount(h),P=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestBuy(n.assetIn,l.assetOut,P)]),b=p.amountIn*BigInt(d),y=d===1,E=b<g,v=p.priceImpactPct<-5,T=[];E||y?T.push("OrderTooSmall"):v&&T.push("OrderImpactTooBig");let N=await this.getAssetOutEd(l),M=p.tradeFee*BigInt(d),G=H.build(o),L={assetIn:t,assetOut:e,assetOutEd:N,errors:T,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:G,type:"TwapBuy"};return{...L,amountIn:b,amountOut:i,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:M,toHuman(){return{...L,amountIn:O.toDecimal(b,c),amountOut:O.toDecimal(i,m),assetOutEd:O.toDecimal(N,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(M,c)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let a=216e5/(this.blockTime*6);return Math.round(a)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,s=Math.round(e);return Math.max(s,6)}async getAssetOutEd(t){let a=(await this.router.getPools()).find(i=>i.address===t.poolAddress)?.tokens.find(i=>i.id===t.assetOut);if(!a)throw new Error(`Asset ${t.assetOut} not found in pool ${t.poolAddress}`);return a.existentialDeposit}};export{Ht as DCA_TIME_RESERVE,Lt as DEFAULT_BLOCK_TIME,Dt as DEFAULT_MIN_BUDGET,Nt as ORDER_MIN_BLOCK_PERIOD,et as Router,at as TWAP_EXECUTION_INTERVAL,Pt as TWAP_MAX_DURATION,bt as TWAP_MAX_PRICE_IMPACT,xd as TWAP_TX_MULTIPLIER,Ct as TradeOrderError,kt as TradeOrderType,H as TradeRouteBuilder,st as TradeRouter,yt 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/TxBuilder.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { PolkadotClient } from 'polkadot-api';
|
|
2
2
|
import { PublicClient } from 'viem';
|
|
3
3
|
import { AaveUtils } from '../aave';
|
|
4
|
-
import { Papi } from '../api';
|
|
4
|
+
import { BlockAt, Papi } from '../api';
|
|
5
5
|
import { BalanceClient } from '../client';
|
|
6
6
|
import { EvmClient } from '../evm';
|
|
7
7
|
import { Swap } from '../sor';
|
|
@@ -11,7 +11,7 @@ export declare abstract class TxBuilder extends Papi {
|
|
|
11
11
|
protected readonly evmClient: PublicClient;
|
|
12
12
|
protected readonly balance: BalanceClient;
|
|
13
13
|
protected readonly aaveUtils: AaveUtils;
|
|
14
|
-
constructor(client: PolkadotClient, evm: EvmClient);
|
|
14
|
+
constructor(client: PolkadotClient, evm: EvmClient, at?: BlockAt);
|
|
15
15
|
protected wrapTx(name: string, tx: Transaction): Tx;
|
|
16
16
|
protected dispatchWithExtraGas(tx: Transaction): Promise<Transaction>;
|
|
17
17
|
protected dryRun(account: string, tx: Transaction): Promise<DryRunResult>;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { PolkadotClient } from 'polkadot-api';
|
|
2
|
+
import { BlockAt } from '../api';
|
|
2
3
|
import { EvmClient } from '../evm';
|
|
3
4
|
import { Trade, TradeOrder } from '../sor';
|
|
4
5
|
import { TradeTxBuilder } from './TradeTxBuilder';
|
|
@@ -9,7 +10,8 @@ import { IntentOrderTxBuilder } from './IntentOrderTxBuilder';
|
|
|
9
10
|
export declare class TxBuilderFactory {
|
|
10
11
|
private client;
|
|
11
12
|
private evmClient;
|
|
12
|
-
|
|
13
|
+
private at?;
|
|
14
|
+
constructor(client: PolkadotClient, evmClient: EvmClient, at?: BlockAt);
|
|
13
15
|
trade(trade: Trade): TradeTxBuilder;
|
|
14
16
|
order(order: TradeOrder): OrderTxBuilder;
|
|
15
17
|
intentMarket(trade: Trade): IntentMarketTxBuilder;
|
package/build/tx/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var ye=Object.create;var Z=Object.defineProperty;var fe=Object.getOwnPropertyDescriptor;var Pe=Object.getOwnPropertyNames;var Te=Object.getPrototypeOf,Se=Object.prototype.hasOwnProperty;var tt=(o,t)=>{for(var e in t)Z(o,e,{get:t[e],enumerable:!0})},Rt=(o,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Pe(t))!Se.call(o,i)&&i!==e&&Z(o,i,{get:()=>t[i],enumerable:!(a=fe(t,i))||a.enumerable});return o};var et=(o,t,e)=>(e=o!=null?ye(Te(o)):{},Rt(t||!o||!o.__esModule?Z(e,"default",{value:o,enumerable:!0}):e,o)),we=o=>Rt(Z({},"__esModule",{value:!0}),o);var Pa={};tt(Pa,{TxBuilderFactory:()=>yt});module.exports=we(Pa);var K=require("@galacticcouncil/math-lbp");var Lt=require("@galacticcouncil/common");var at={};tt(at,{withTimeout:()=>xe});function xe(o,t,e="timeout"){return new Promise((a,i)=>{let s=setTimeout(()=>i(new Error(e)),t);o.then(n=>{clearTimeout(s),a(n)},n=>{clearTimeout(s),i(n)})})}var P={};tt(P,{divSpot:()=>Ie,getFraction:()=>Oe,mulScaled:()=>Ct,mulSpot:()=>ve});var Pt=require("@galacticcouncil/common");function Ct(o,t,e,a,i){let s=e+a-i,n=o*t;return s>0?n/BigInt(10)**BigInt(s):s<0?n*BigInt(10)**BigInt(-s):n}function ve(o,t,e,a){return Ct(o,t,e,Pt.RUNTIME_DECIMALS,a)}function Ie(o,t,e,a){if(t===0n)return 0n;let i=BigInt(10)**BigInt(Pt.RUNTIME_DECIMALS+a-e);return o*i/t}function Oe(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 d={};tt(d,{FeeUtils:()=>Tt,shiftNeg:()=>Be});var Dt=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 Be(o,t){let e=(0,Dt.default)(typeof o=="bigint"?o.toString():o);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var _e=et(require("big.js"));var{FeeUtils:Xa}=d;var Me=require("polkadot-api"),nt=require("rxjs");var C=require("rxjs"),T=require("rxjs/operators");var U=require("@galacticcouncil/descriptors");var Nt=require("@galacticcouncil/common"),G=require("rxjs");var R=require("rxjs"),b=require("rxjs/operators");function Ht(o,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let a=()=>(0,R.defer)(()=>(0,R.from)(o._request("system_health",[]))).pipe((0,b.timeout)({first:e}),(0,b.map)(()=>"online"),(0,b.catchError)(()=>(0,R.of)("offline")));return(0,R.of)({state:"offline",delayMs:0}).pipe((0,b.expand)(s=>(0,R.timer)(s.delayMs).pipe((0,b.switchMap)(a),(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:Ee}=Nt.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)",Ht(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"),Ce=require("polkadot-api/logs-provider");var ke=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[n,r]=s.args;i.push({id:r,balance:this.getBreakdown({free:0n,reserved:0n,frozen:0n})})}),a?.upserted.forEach(s=>{let[n,r]=s.args;i.push({id:r,balance:this.getBreakdown(s.value)})}),i}),(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:n})=>n.asset_type.type==="Erc20").map(({keyArgs:n})=>{let[r]=n;return r}),this.erc20Ids},i=async s=>(await Promise.all(s.map(async r=>[r,await this.getBalanceData(t,r)]))).map(([r,l])=>({id:r,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,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=>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,n)=>s!==void 0&&n!==void 0&&s.transferable===n.transferable&&s.total===n.total,i=t.reduce((s,n)=>(s.set(n.id,n.balance),s),new Map);return e.filter(s=>!a(s.balance,i.get(s.id)))}};var De=require("rxjs");var Gt=require("@galacticcouncil/common");var Bs={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:_s}=Gt.log;var{withTimeout:Xs}=at;var y=require("@galacticcouncil/math-omnipool"),He=et(require("big.js"));var Ne=require("@galacticcouncil/common");var{FeeUtils:fi}=d;var N=require("polkadot-api"),Ue=require("@polkadot-api/utils"),q=require("rxjs"),Ve=require("@galacticcouncil/common");var{FeeUtils:xi}=d;var{FeeUtils:Hi}=d,Ni=N.Binary.toHex(N.Binary.fromText("omnipool")),qi=(0,N.Enum)("Short");var B=require("@galacticcouncil/math-stableswap");var Vt=require("@galacticcouncil/common");var{FeeUtils:un}=d;var Wt=require("polkadot-api"),Ye=require("@polkadot-api/utils"),ze=require("@noble/hashes/blake2b"),J=require("rxjs"),$t=require("@galacticcouncil/common");var{FeeUtils:wn}=d;var _=require("@galacticcouncil/math-xyk");var je=require("@galacticcouncil/common");var{FeeUtils:Gn}=d;var Qe=require("polkadot-api"),Je=require("rxjs");var Xt=require("@galacticcouncil/common");var Yt=require("polkadot-api"),ta=require("@polkadot-api/utils"),rt=require("rxjs"),ea=require("viem"),St=require("@galacticcouncil/common");var{ERC20:Pr}=St.erc20;var M=require("@galacticcouncil/math-hsm");var zt=require("@galacticcouncil/common");var{FeeUtils:Dr}=d;var wt=require("polkadot-api"),na=require("@polkadot-api/utils"),X=require("rxjs"),ra=require("viem"),xt=require("@galacticcouncil/common");var{FeeUtils:Qr}=d,{H160:Jr}=xt.h160;var jt=require("@galacticcouncil/common"),vt=require("rxjs");var{logger:Xo}=jt.log;var Qt=require("@galacticcouncil/common");var{FeeUtils:ec}=d;var ba=require("@galacticcouncil/common");var It=require("polkadot-api");var L=class{static build(t){return t.map(({assetIn:e,assetOut:a,pool:i,poolId:s})=>i==="Stableswap"?{pool:(0,It.Enum)("Stableswap",s),asset_in:e,asset_out:a}:{pool:(0,It.Enum)(i),asset_in:e,asset_out:a})}};var Ft=require("polkadot-api");var Zt=[{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Supply",type:"event"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"to",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"}],name:"Withdraw",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"address",name:"to",type:"address"}],name:"withdraw",outputs:[{internalType:"uint256",name:"",type:"uint256"}],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!1,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"onBehalfOf",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"enum DataTypes.InterestRateMode",name:"interestRateMode",type:"uint8"},{indexed:!1,internalType:"uint256",name:"borrowRate",type:"uint256"},{indexed:!0,internalType:"uint16",name:"referralCode",type:"uint16"}],name:"Borrow",type:"event"},{inputs:[{internalType:"address",name:"asset",type:"address"},{internalType:"uint256",name:"amount",type:"uint256"},{internalType:"uint256",name:"interestRateMode",type:"uint256"},{internalType:"uint16",name:"referralCode",type:"uint16"},{internalType:"address",name:"onBehalfOf",type:"address"}],name:"borrow",outputs:[],stateMutability:"nonpayable",type:"function"},{anonymous:!1,inputs:[{indexed:!0,internalType:"address",name:"reserve",type:"address"},{indexed:!0,internalType:"address",name:"user",type:"address"},{indexed:!0,internalType:"address",name:"repayer",type:"address"},{indexed:!1,internalType:"uint256",name:"amount",type:"uint256"},{indexed:!1,internalType:"bool",name:"useATokens",type:"bool"}],name:"Repay",type:"event"},{inputs:[{internalType:"address",name:"user",type:"address"}],name:"getUserAccountData",outputs:[{internalType:"uint256",name:"totalCollateralBase",type:"uint256"},{internalType:"uint256",name:"totalDebtBase",type:"uint256"},{internalType:"uint256",name:"availableBorrowsBase",type:"uint256"},{internalType:"uint256",name:"currentLiquidationThreshold",type:"uint256"},{internalType:"uint256",name:"ltv",type:"uint256"},{internalType:"uint256",name:"healthFactor",type:"uint256"}],stateMutability:"view",type:"function"}];var Ot=[{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 te="0x1b02E051683b5cfaC5929C25E84adb26ECf87B38",At="0x112b087b60C1a166130d59266363C45F8aa99db0",Bt="0xf3Ba4D1b50f78301BDD7EAEa9B67822A15FCA691",ee=1000000n;var Gc=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:Ot,address:At,args:[Bt],functionName:"getReservesData"})}async getUserReservesData(t){return await this.client.readContract({abi:Ot,address:At,args:[Bt,t],functionName:"getUserReservesData"})}async getUserAccountData(t){return await this.client.readContract({abi:Zt,address:te,args:[t],functionName:"getUserAccountData"})}};var h=et(require("big.js")),x=require("@galacticcouncil/common");var{ERC20:Y}=x.erc20,{H160:_t}=x.h160,ya=1.01,fa=31536000n,ae=4,lt=-1,ct=10n**27n,ut=class{client;constructor(t){this.client=new ot(t)}async getSummary(t){let e=_t.fromAny(t),[a,i,s,n]=await Promise.all([this.client.getReservesData(),this.client.getUserReservesData(e),this.client.getUserAccountData(e),this.client.getBlockTimestamp()]),[r]=a,[l,u]=i,[c,m,f,k,I,O]=s,F=x.big.toDecimal(O,18),D=[];for(let E of l){let H=E.underlyingAsset.toLowerCase(),S=r.find(({underlyingAsset:be})=>be.toLowerCase()===H);if(!S)throw new Error("Missing pool reserve for "+H);let ft=E.scaledATokenBalance,z=S.liquidityIndex,re=S.liquidityRate,oe=S.availableLiquidity,le=S.priceInMarketReferenceCurrency,ce=n+6,ue=this.calculateLinearInterest(re,S.lastUpdateTimestamp,ce),pe=z*ue/ct,me=ft*pe/ct,de=Number(u!==0&&u===S.eModeCategoryId?S.eModeLiquidationThreshold:S.reserveLiquidationThreshold)/1e4,ge=S.usageAsCollateralEnabled&&E.usageAsCollateralEnabledOnUser&&E.scaledATokenBalance>0n,he=Y.toAssetId(H);D.push({aTokenBalance:me,availableLiquidity:oe,decimals:Number(S.decimals),isCollateral:ge,priceInRef:le,reserveId:he,reserveAsset:H,reserveLiquidationThreshold:de})}return{healthFactor:Number(F),currentLiquidationThreshold:Number(x.big.toDecimal(k,ae)),totalCollateral:c,totalDebt:m,reserves:D}}async hasBorrowPositions(t){let e=_t.fromAny(t),a=await this.client.getUserAccountData(e),[i,s]=a;return s>0n}async getHealthFactor(t){let e=_t.fromAny(t),a=await this.client.getUserAccountData(e),[i,s,n,r,l,u]=a;return this.calculateHealthFactorFromBalances(s,i,r)}async getHealthFactorAfterWithdraw(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return lt;let l=Y.fromAssetId(e),u=n.find(H=>H.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,isCollateral:m,priceInRef:f,reserveLiquidationThreshold:k}=u,I=x.big.toBigInt(a,c),O=m?I*f/10n**BigInt(c):0n,F=i-O;if(F<=0n)return 0;let D=(0,h.default)(i.toString()).mul(r).minus((0,h.default)(O.toString()).mul(k)).div(F.toString()),E=(0,h.default)(F.toString()).mul(D).div(s.toString()).toFixed(6,h.default.roundDown);return Number(E)}async getHealthFactorAfterSupply(t,e,a){let{totalCollateral:i,totalDebt:s,reserves:n,currentLiquidationThreshold:r}=await this.getSummary(t);if(s===0n)return lt;let l=Y.fromAssetId(e),u=n.find(E=>E.reserveAsset===l);if(!u)throw new Error("Missing reserve ctx for "+l);let{decimals:c,priceInRef:m,reserveLiquidationThreshold:f}=u,I=x.big.toBigInt(a,c)*m/10n**BigInt(c),O=i+I;if(O<=0n)return 0;let F=(0,h.default)(i.toString()).mul(r).plus((0,h.default)(I.toString()).mul(f)).div(O.toString()),D=(0,h.default)(O.toString()).mul(F).div(s.toString()).toFixed(6,h.default.roundDown);return Number(D)}async getHealthFactorAfterSwap(t,e,a,i,s){let{totalDebt:n,reserves:r,healthFactor:l}=await this.getSummary(t);if(n===0n)return lt;let u=Y.fromAssetId(a),c=Y.fromAssetId(s),m=r.find(z=>z.reserveAsset===u),f=r.find(z=>z.reserveAsset===c);if(!m)throw new Error(`Missing reserve ctx for ${u}`);if(!f)throw new Error(`Missing reserve ctx for ${f}`);let k=x.big.toBigInt(e,m.decimals),I=x.big.toBigInt(i,f.decimals),O=k*m.priceInRef/10n**BigInt(m.decimals),F=I*f.priceInRef/10n**BigInt(f.decimals),D=m.isCollateral?(0,h.default)(O.toString()).mul(m.reserveLiquidationThreshold):(0,h.default)(0),S=(f.isCollateral?(0,h.default)(F.toString()).mul(f.reserveLiquidationThreshold):(0,h.default)(0)).minus(D).div(n.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),n=Y.fromAssetId(e),r=i.find(l=>l.reserveAsset===n);if(!r)throw new Error("Missing reserve ctx for "+n);return this.calculateWithdrawMax(r,a,s)}async getMaxWithdrawAll(t){let{totalDebt:e,reserves:a,healthFactor:i}=await this.getSummary(t),s={};for(let n of a){let r=this.calculateWithdrawMax(n,e,i);n.reserveId&&(s[n.reserveId]=r)}return s}calculateWithdrawMax(t,e,a){let{aTokenBalance:i,availableLiquidity:s,decimals:n,priceInRef:r,reserveLiquidationThreshold:l,isCollateral:u}=t,c=i;if(u&&e>0n){let f=a-ya;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(r.toString()).mul(10**n).toFixed(0,h.default.roundDown);c=i<BigInt(I)?i:BigInt(I)}else c=0n}return{amount:c<s?c:s,decimals:n}}calculateLinearInterest(t,e,a){let i=a-e;if(i<=0)return ct;let s=t*BigInt(i)/fa;return ct+s}calculateHealthFactorFromBalances(t,e,a){if(t===0n)return lt;let i=e*a/t,s=x.big.toDecimal(i,ae);return Number(s)}};function se(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){super(t),this.evm=e,this.evmClient=e.getWsProvider(),this.balance=new $(t),this.aaveUtils=new ut(e)}wrapTx(t,e){return{name:t,get:()=>e,dryRun:a=>this.dryRun(a,e)}}async dispatchWithExtraGas(t){return this.api.tx.Dispatcher.dispatch_with_extra_gas({call:t.decodedCall,extra_gas:ee})}async dryRun(t,e){let a=(0,Ft.Enum)("Signed",t),i=(0,Ft.Enum)("system",a),n=await this.client.getUnsafeApi().apis.DryRunApi.dry_run_call(i,e.decodedCall,4),r=n.success&&!n.value.execution_result.success?n.value.execution_result.value.error:null;if(r){let l=r.type==="Module"?se(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 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,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],n=P.getFraction(t,this.slippagePct),r=i.assetIn,l=s.assetOut,u=t+n,c;return this.isDirectOmnipoolTrade(a)?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(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],n=P.getFraction(e,this.slippagePct),r=i.assetIn,l=s.assetOut,u=e-n,c;return this.isDirectOmnipoolTrade(a)?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(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),n=a.assetIn,r=i.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 mt=require("polkadot-api");var dt=class extends v{_order;_beneficiary;_maxRetries=3;_slippagePct=1;setOrder(t){return this._order=t,this}withBeneficiary(t){return this._beneficiary=t,this}withMaxRetries(t){return this._maxRetries=t,this}withSlippage(t){return this._slippagePct=t,this}get order(){if(!this._order)throw new Error("Order not set. Use setOrder().");return this._order}get beneficiary(){if(!this._beneficiary)throw new Error("Beneficiary not set. Use withBeneficiary().");return this._beneficiary}get maxRetries(){return this._maxRetries}get slippagePct(){return this._slippagePct}async build(){let{type:t}=this.order;switch(t){case"Dca":return this.buildDcaTx();case"TwapSell":return this.buildTwapSellTx();case"TwapBuy":return this.buildTwapBuyTx();default:throw new Error(`Unsupported TradeOrderType: ${t}`)}}async buildDcaTx(){let{amountIn:t,assetIn:e,assetOut:a,tradeAmountIn:i,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,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,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:a,tradeAmountIn:i,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,mt.Enum)("Sell",{asset_in:e,asset_out:a,amount_in:i,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:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n,tradeRoute:r}=this.order,l=P.getFraction(i,this.slippagePct),u=i+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,mt.Enum)("Buy",{asset_in:e,asset_out:a,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 ie=require("polkadot-api");var gt=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:a}=this.trade,i=a[0],s=a[a.length-1],n=i.assetIn,r=s.assetOut,l=P.getFraction(e,this.slippagePct),u=e-l,c=(0,ie.Enum)("Swap",{asset_in:n,asset_out:r,amount_in:t,amount_out:u,partial:!1}),m=this.apiIce.tx.Intent.submit_intent({intent:{data:c}});return await this.aaveUtils.hasBorrowPositions(this.beneficiary)&&(m=await this.dispatchWithExtraGas(m)),this.wrapTx("IntentSwap",m)}};var ne=require("polkadot-api");var ht=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:a}=this.trade,i=a[0],s=a[a.length-1],n=i.assetIn,r=s.assetOut,l=(0,ne.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 Et=require("polkadot-api");var bt=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:a,assetOutEd:i,tradeAmountIn:s,tradePeriod:n}=this.order,r=(0,Et.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:s,amount_out:i,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:a,tradeAmountIn:i,tradeAmountOut:s,tradePeriod:n}=this.order,r=P.getFraction(s,this.slippagePct),l=s-r,u=(0,Et.Enum)("Dca",{asset_in:e,asset_out:a,amount_in:i,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 yt=class{client;evmClient;constructor(t,e){this.client=t,this.evmClient=e}trade(t){return new pt(this.client,this.evmClient).setTrade(t)}order(t){return new dt(this.client,this.evmClient).setOrder(t)}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});
|