@galacticcouncil/sdk-next 1.0.0-beta.0 → 1.0.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/README.md +131 -78
- package/build/aave/AaveClient.d.ts +77 -0
- package/build/aave/AaveUtils.d.ts +78 -0
- package/build/aave/abi/AavePool.d.ts +208 -0
- package/build/aave/abi/AavePoolDataProvider.d.ts +384 -0
- package/build/aave/abi/index.d.ts +2 -0
- package/build/aave/const.d.ts +6 -0
- package/build/aave/index.cjs +1 -0
- package/build/aave/index.d.ts +4 -0
- package/build/aave/index.mjs +1 -0
- package/build/aave/types.d.ts +17 -0
- package/build/api/Papi.d.ts +10 -0
- package/build/api/Watcher.d.ts +11 -0
- package/build/api/index.d.ts +3 -0
- package/build/api/probe.d.ts +26 -0
- package/build/api/provider/index.d.ts +2 -0
- package/build/api/provider/smoldot.d.ts +1 -0
- package/build/api/provider/websocket.d.ts +4 -0
- package/build/{types/client → client}/AssetClient.d.ts +1 -1
- package/build/client/BalanceClient.d.ts +20 -0
- package/build/client/ChainParams.d.ts +9 -0
- package/build/client/index.cjs +1 -0
- package/build/{types/client → client}/index.d.ts +1 -0
- package/build/client/index.mjs +1 -0
- package/build/{types/consts.d.ts → consts.d.ts} +2 -2
- package/build/evm/adapter.d.ts +11 -0
- package/build/evm/chain.d.ts +2 -0
- package/build/evm/client.d.ts +15 -0
- package/build/evm/index.cjs +1 -0
- package/build/evm/index.d.ts +4 -0
- package/build/evm/index.mjs +1 -0
- package/build/evm/types.d.ts +7 -0
- package/build/factory.d.ts +29 -0
- package/build/farm/LiquidityMiningApi.d.ts +29 -0
- package/build/farm/LiquidityMiningClient.d.ts +146 -0
- package/build/farm/MultiCurrencyContainer.d.ts +8 -0
- package/build/farm/RewardClaimSimulator.d.ts +16 -0
- package/build/farm/const.d.ts +4 -0
- package/build/farm/index.cjs +1 -0
- package/build/farm/index.d.ts +3 -0
- package/build/farm/index.mjs +1 -0
- package/build/farm/types.d.ts +46 -0
- package/build/gho/GhoTokenClient.d.ts +6 -0
- package/build/gho/abi.d.ts +124 -0
- package/build/gho/index.d.ts +2 -0
- package/build/index.cjs +1 -1
- package/build/{types/index.d.ts → index.d.ts} +6 -0
- package/build/index.mjs +1 -1
- package/build/oracle/MmOracleClient.d.ts +7 -0
- package/build/oracle/abi.d.ts +196 -0
- package/build/oracle/index.d.ts +3 -0
- package/build/oracle/types.d.ts +5 -0
- package/build/pool/PoolClient.d.ts +75 -0
- package/build/pool/PoolContextProvider.d.ts +41 -0
- package/build/pool/PoolLog.d.ts +11 -0
- package/build/pool/PoolStore.d.ts +20 -0
- package/build/pool/aave/AaveAbi.d.ts +126 -0
- package/build/pool/aave/AavePool.d.ts +24 -0
- package/build/pool/aave/AavePoolClient.d.ts +19 -0
- package/build/pool/aave/index.d.ts +2 -0
- package/build/pool/aave/types.d.ts +13 -0
- package/build/pool/hsm/HsmMath.d.ts +21 -0
- package/build/pool/hsm/HsmPool.d.ts +63 -0
- package/build/pool/hsm/HsmPoolClient.d.ts +26 -0
- package/build/pool/hsm/index.d.ts +3 -0
- package/build/pool/hsm/types.d.ts +7 -0
- package/build/pool/index.cjs +1 -0
- package/build/{types/pool → pool}/index.d.ts +4 -2
- package/build/pool/index.mjs +1 -0
- package/build/{types/pool → pool}/lbp/LbpPool.d.ts +1 -1
- package/build/{types/pool → pool}/lbp/LbpPoolClient.d.ts +9 -7
- package/build/{types/pool → pool}/omni/OmniMath.d.ts +7 -6
- package/build/{types/pool → pool}/omni/OmniPool.d.ts +14 -1
- package/build/pool/omni/OmniPoolClient.d.ts +29 -0
- package/build/pool/omni/types.d.ts +11 -0
- package/build/{types/pool → pool}/stable/StableMath.d.ts +1 -2
- package/build/{types/pool → pool}/stable/StableSwap.d.ts +21 -4
- package/build/pool/stable/StableSwapClient.d.ts +23 -0
- package/build/pool/stable/types.d.ts +15 -0
- package/build/{types/pool → pool}/types.d.ts +14 -3
- package/build/{types/pool → pool}/xyk/XykPool.d.ts +13 -1
- package/build/pool/xyk/XykPoolClient.d.ts +14 -0
- package/build/{types/sor → sor}/Router.d.ts +26 -8
- package/build/sor/TradeRouteBuilder.d.ts +4 -0
- package/build/sor/TradeRouter.d.ts +207 -0
- package/build/sor/TradeScheduler.d.ts +111 -0
- package/build/sor/const.d.ts +8 -0
- package/build/sor/index.cjs +1 -0
- package/build/sor/index.d.ts +6 -0
- package/build/sor/index.mjs +1 -0
- package/build/{types/sor → sor}/route/bfs.d.ts +11 -2
- package/build/{types/sor → sor}/route/index.d.ts +1 -1
- package/build/sor/route/suggester.d.ts +33 -0
- package/build/sor/types.d.ts +68 -0
- package/build/staking/StakingApi.d.ts +66 -0
- package/build/staking/StakingClient.d.ts +132 -0
- package/build/staking/index.cjs +1 -0
- package/build/staking/index.d.ts +2 -0
- package/build/staking/index.mjs +1 -0
- package/build/staking/types.d.ts +16 -0
- package/build/staking/utils.d.ts +1 -0
- package/build/tx/OrderTxBuilder.d.ts +21 -0
- package/build/tx/TradeTxBuilder.d.ts +18 -0
- package/build/tx/TxBuilder.d.ts +19 -0
- package/build/tx/TxBuilderFactory.d.ts +12 -0
- package/build/tx/index.cjs +1 -0
- package/build/tx/index.d.ts +2 -0
- package/build/tx/index.mjs +1 -0
- package/build/tx/types.d.ts +10 -0
- package/build/tx/utils.d.ts +5 -0
- package/build/{types/types.d.ts → types.d.ts} +9 -2
- package/build/utils/QueryBus.d.ts +10 -0
- package/build/utils/async.d.ts +1 -0
- package/build/utils/calc.d.ts +52 -0
- package/build/utils/format.d.ts +11 -0
- package/build/utils/index.cjs +1 -0
- package/build/{types/utils → utils}/index.d.ts +3 -3
- package/build/utils/index.mjs +1 -0
- package/build/{types/utils → utils}/math.d.ts +0 -9
- package/package.json +70 -15
- package/build/types/api/Papi.d.ts +0 -375
- package/build/types/api/client.d.ts +0 -2
- package/build/types/api/index.d.ts +0 -2
- package/build/types/client/BalanceClient.d.ts +0 -17
- package/build/types/pool/PoolClient.d.ts +0 -25
- package/build/types/pool/PoolContextProvider.d.ts +0 -26
- package/build/types/pool/omni/OmniPoolClient.d.ts +0 -13
- package/build/types/pool/stable/StableSwapClient.d.ts +0 -16
- package/build/types/pool/xyk/XykPoolClient.d.ts +0 -12
- package/build/types/sor/TradeRouter.d.ts +0 -155
- package/build/types/sor/TradeUtils.d.ts +0 -12
- package/build/types/sor/index.d.ts +0 -4
- package/build/types/sor/route/suggester.d.ts +0 -24
- package/build/types/sor/types.d.ts +0 -31
- package/build/types/utils/big.d.ts +0 -3
- package/build/types/utils/evm.d.ts +0 -3
- package/build/types/utils/format.d.ts +0 -4
- package/build/types/utils/xc.d.ts +0 -1
- /package/build/{types/errors.d.ts → errors.d.ts} +0 -0
- /package/build/{types/pool → pool}/PoolFactory.d.ts +0 -0
- /package/build/{types/pool → pool}/lbp/LbpMath.d.ts +0 -0
- /package/build/{types/pool → pool}/lbp/index.d.ts +0 -0
- /package/build/{types/pool → pool}/omni/index.d.ts +0 -0
- /package/build/{types/pool → pool}/stable/index.d.ts +0 -0
- /package/build/{types/pool → pool}/xyk/XykMath.d.ts +0 -0
- /package/build/{types/pool → pool}/xyk/index.d.ts +0 -0
- /package/build/{types/sor → sor}/route/graph.d.ts +0 -0
- /package/build/{types/utils → utils}/Queue.d.ts +0 -0
- /package/build/{types/utils → utils}/Stack.d.ts +0 -0
- /package/build/{types/utils → utils}/json.d.ts +0 -0
- /package/build/{types/utils → utils}/traversal/bfs.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var Ut=Object.defineProperty;var X=(u,t)=>{for(var e in t)Ut(u,e,{get:t[e],enumerable:!0})};import $t from"buffer";typeof window<"u"&&(window.Buffer=$t.Buffer);var Y=class{constructor(t=1/0){this.capacity=t}storage=[];enqueue(t){if(this.size()===this.capacity)throw Error("Queue has reached max capacity, you cannot add more items");this.storage.push(t)}dequeue(){return this.storage.shift()}size(){return this.storage.length}};var Xt=10,z=class{isNotVisited(t,e){let s=!0;return e.forEach(a=>{(a[0]===t[0]||a[1]===t[1])&&(s=!1)}),s}findPaths(t,e,s){let a=[],i=new Y,n=[];for(n.push([e,""]),i.enqueue(n);i.size()>0;){let r=i.dequeue();if(!r||r.length>Xt)continue;let o=r[r.length-1];(s===null||o[0]===s)&&a.push(r),t.get(o[0])?.forEach(c=>{if(this.isNotVisited(c,r)){let m=[...r];m.push(c),i.enqueue(m)}})}return a}findShortestPaths(t,e,s){let a=[],i=new Y,n=[];n.push([e,""]),i.enqueue(n);let r=1/0;for(;i.size()>0;){let o=i.dequeue();if(!o)continue;let l=o[o.length-1];if(l[0]===s){o.length<r?(r=o.length,a.length=0,a.push(o)):o.length===r&&a.push(o);continue}let c=t.get(l[0]);for(let m of c??[])this.isNotVisited(m,o)&&i.enqueue([...o,m])}return a}buildAndPopulateGraph(t,e){let s=new Map;for(let a of t)s.set(parseInt(a),[]);for(let[a,i,n]of e)s.get(i)?.push([n,a]);return s}};function mt(u){let t={};for(let e of u){let s=e.tokens.length;for(let a=0;a<s;a++){t[e.tokens[a].id]||(t[e.tokens[a].id]=[]);for(let i=0;i<s;i++){if(a==i)continue;let n=[e.address,e.tokens[a].id,e.tokens[i].id];t[e.tokens[a].id].push(n)}}}return t}import{calculate_in_given_out as Yt,calculate_out_given_in as zt,calculate_linear_weights as Kt,calculate_pool_trade_fee as jt,get_spot_price as Qt}from"@galacticcouncil/math-lbp";var E=class{static getSpotPrice(t,e,s,a,i){return Qt(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i){return Yt(t,e,s,a,i)}static calculateOutGivenIn(t,e,s,a,i){return zt(t,e,s,a,i)}static calculateLinearWeights(t,e,s,a,i){return Kt(t,e,s,a,i)}static calculatePoolTradeFee(t,e,s){return jt(t,e,s)}};import{big as wt,RUNTIME_DECIMALS as Ot}from"@galacticcouncil/common";var at={};X(at,{withTimeout:()=>Jt});function Jt(u,t,e="timeout"){return new Promise((s,a)=>{let i=setTimeout(()=>a(new Error(e)),t);u.then(n=>{clearTimeout(i),s(n)},n=>{clearTimeout(i),a(n)})})}var A={};X(A,{divSpot:()=>te,getFraction:()=>ee,mulScaled:()=>St,mulSpot:()=>Zt});import{RUNTIME_DECIMALS as ft}from"@galacticcouncil/common";function St(u,t,e,s,a){let i=e+s-a,n=u*t;return i>0?n/BigInt(10)**BigInt(i):i<0?n*BigInt(10)**BigInt(-i):n}function Zt(u,t,e,s){return St(u,t,e,ft,s)}function te(u,t,e,s){if(t===0n)return 0n;let a=BigInt(10)**BigInt(ft+s-e);return u*a/t}function ee(u,t,e=2){if(t<.01||t>100)throw new Error("Supported range is from 0.01% - 100%");let s=BigInt(10)**BigInt(e),a=BigInt(Math.round(t*Number(s)));return u*a/(BigInt(100)*s)}var S={};X(S,{FeeUtils:()=>dt,shiftNeg:()=>ie});import ae from"big.js";var dt=class u{static toPct(t){let[e,s]=t;return u.safeDivide(e*100,s)}static toRaw(t){let[e,s]=t;return u.safeDivide(e,s)}static fromPermill(t){return[t,1e6]}static fromPerbill(t){return[t,1e9]}static fromRate(t,e){return[t,e]}static safeDivide(t,e,s=12){let a=10**s;return Math.round(t*a/e)/a}static safeRound(t){return parseFloat(t.toPrecision(15))}};function ie(u,t){let e=ae(typeof u=="bigint"?u.toString():u);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var K={};X(K,{findNestedKey:()=>ne,findNestedObj:()=>re,jsonFormatter:()=>oe});var ne=(u,t)=>{let e=[];return JSON.stringify(u,(s,a)=>(a&&a[t]&&e.push(a),a)),e[0]},re=(u,t,e)=>{let s;return JSON.stringify(u,(a,i)=>(i&&i[t]===e&&(s=i),i)),s},oe=(u,t)=>typeof t=="bigint"?t.toString():t;var v={};X(v,{calculateBuyFee:()=>pe,calculateDiffToAvg:()=>le,calculateDiffToRef:()=>ce,calculateSellFee:()=>ue});import k from"big.js";function le(u,t){let e=k(u.toString()),s=k(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function ce(u,t){if(t===0n)return 0;let e=k(u.toString()),s=k(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function ue(u,t){if(u===0n)return 0;let e=k(u.toString()),s=k(t.toString());return k(1).minus(s.div(e)).mul(100).round(2).toNumber()}function pe(u,t){if(u===0n)return 0;let e=k(u.toString());return k(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}import{TLRUCache as Ys}from"@thi.ng/cache";var{FeeUtils:vt}=S,it=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new u(t)}constructor(t){this.type="LBP",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.fee=t.fee,this.repayFeeApply=t.repayFeeApply}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,weightIn:a.weight,weightOut:i.weight}}validateAndBuy(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let n=t.balanceOut/this.maxOutRatio;if(e>n&&i.push("MaxOutRatioExceeded"),a===t.assetOut){let r=this.calculateTradeFee(e,s),o=vt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+r,c=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return c>m&&i.push("MaxInRatioExceeded"),{amountIn:c,calculatedIn:c,amountOut:e,feePct:o,errors:i}}else{let r=this.calculateInGivenOut(t,e),o=t.balanceIn/this.maxInRatio;return r>o&&i.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:r,amountOut:e,feePct:0,errors:i}}}validateAndSell(t,e,s){let a=this.tokens[0].id,i=[];e<this.minTradingLimit&&i.push("InsufficientTradingAmount");let n=t.balanceIn/this.maxInRatio;if(e>n&&i.push("MaxInRatioExceeded"),a===t.assetIn){let r=this.calculateOutGivenIn(t,e),o=t.balanceOut/this.maxOutRatio;return r>o&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:r,feePct:0,errors:i}}else{let r=this.calculateOutGivenIn(t,e),o=this.calculateTradeFee(r,s),l=vt.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),c=r-o,m=t.balanceOut/this.maxOutRatio;return c>m&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:c,feePct:l,errors:i}}}calculateInGivenOut(t,e){let s=E.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=E.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=E.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),wt.toBigInt(1,Ot).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=E.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),wt.toBigInt(1,Ot).toString());return BigInt(e)}calculateTradeFee(t,e){let s=E.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};import{CompatibilityLevel as ar}from"polkadot-api";import{Subscription as nr,distinctUntilChanged as rr,filter as or,map as lr}from"rxjs";import{memoize1 as dn}from"@thi.ng/memoize";import{TLRUCache as hn}from"@thi.ng/cache";import{ReplaySubject as fn,Subscription as Sn,combineLatest as In,defer as wn,from as On,interval as vn,merge as Tn,of as xn,EMPTY as Bn}from"rxjs";import{bufferCount as Fn,bufferTime as _n,catchError as Rn,filter as En,finalize as kn,map as Cn,pairwise as Mn,repeat as Ln,skip as Dn,share as Hn,startWith as Nn,switchMap as qn,tap as Gn,throttleTime as Vn}from"rxjs/operators";import{hydration as Wa,hydrationNext as Ua}from"@galacticcouncil/descriptors";import{log as me}from"@galacticcouncil/common";import{map as Ca,shareReplay as Ma,tap as La}from"rxjs";import{defer as ha,from as ba,of as Pa,timer as ya}from"rxjs";import{catchError as Sa,distinctUntilChanged as Ia,expand as wa,map as Oa,shareReplay as va,skip as Ta,switchMap as xa,timeout as Ba}from"rxjs/operators";var{logger:Ha}=me;import{getWsProvider as Ka}from"polkadot-api/ws";import{withLogsRecorder as Qa}from"polkadot-api/logs-provider";import{getSmProvider as ei}from"polkadot-api/sm-provider";import{Binary as gi}from"polkadot-api";import{log as de}from"@galacticcouncil/common";import{combineLatest as Ii,concat as wi,defer as Oi,from as vi}from"rxjs";import{bufferCount as xi,distinctUntilChanged as Bi,debounceTime as Ai,map as Fi,retry as _i,startWith as Ri,switchMap as Ei,tap as ki,take as Ci,skip as Mi,connect as Li}from"rxjs/operators";var{logger:Ni}=de;import{BehaviorSubject as Zi}from"rxjs";import{log as he}from"@galacticcouncil/common";var rn={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:on}=he;var{withTimeout:Zn}=at;import{calculate_in_given_out as Pe,calculate_lrna_in_given_out as ye,calculate_out_given_in as fe,calculate_out_given_lrna_in as Se,calculate_spot_price as Ie,calculate_lrna_spot_price as we,calculate_shares as Oe,calculate_liquidity_out as ve,calculate_liquidity_lrna_out as Te,verify_asset_cap as xe,calculate_liquidity_hub_in as Be,is_sell_allowed as Ae,is_buy_allowed as Fe,is_add_liquidity_allowed as _e,is_remove_liquidity_allowed as Re,recalculate_asset_fee as Ee,recalculate_protocol_fee as ke}from"@galacticcouncil/math-omnipool";import G from"big.js";var f=class{static calculateSpotPrice(t,e,s,a){return Ie(t,e,s,a)}static calculateLrnaSpotPrice(t,e){return we(t,e)}static calculateInGivenOut(t,e,s,a,i,n,r,o,l,c){return Pe(t,e,s,a,i,n,r,o,l,c)}static calculateLrnaInGivenOut(t,e,s,a,i,n){return ye(t,e,s,a,i,n)}static calculateOutGivenIn(t,e,s,a,i,n,r,o,l,c){return fe(t,e,s,a,i,n,r,o,l,c)}static calculateOutGivenLrnaIn(t,e,s,a,i,n){return Se(t,e,s,a,i,n)}static calculateShares(t,e,s,a){return Oe(t,e,s,a)}static calculateLiquidityOut(t,e,s,a,i,n,r,o){return ve(t,e,s,a,i,n,r,o)}static calculateLiquidityLRNAOut(t,e,s,a,i,n,r,o){return Te(t,e,s,a,i,n,r,o)}static calculateCapDifference(t,e,s,a){let i=G(e),n=G(t),r=G(a),o=G(s),l=G(10).pow(18),c=o.div(l);if(i.div(r).lt(c)){let h=c.times(r).minus(i).times(n),d=i.times(G(1).minus(c));return h.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,s,a){return Be(t,e,s,a)}static isSellAllowed(t){return Ae(t)}static isBuyAllowed(t){return Fe(t)}static isAddLiquidityAllowed(t){return _e(t)}static isRemoveLiquidityAllowed(t){return Re(t)}static recalculateAssetFee(t,e,s,a,i,n,r,o,l,c,m){return Ee(t,e,s,a,i,n,r,o,l,c,m)}static recalculateProtocolFee(t,e,s,a,i,n,r,o,l,c,m){return ke(t,e,s,a,i,n,r,o,l,c,m)}static verifyAssetCap(t,e,s,a){return xe(t,e,s,a)}};import{big as Ce}from"@galacticcouncil/common";var{FeeUtils:R}=S,rt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new u(t)}constructor(t){this.type="Omnipool",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.hubAssetId=t.hubAssetId}validatePair(t,e){return this.hubAssetId!=e}parsePair(t,e){let s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,hubReservesIn:a.hubReserves,hubReservesOut:i.hubReserves,sharesIn:a.shares,sharesOut:i.shares,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,tradeableIn:a.tradeable,tradeableOut:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),n=a===0n?0:v.calculateBuyFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount");let c=t.balanceOut/this.maxOutRatio;e>c&&r.push("MaxOutRatioExceeded");let m=t.balanceIn/this.maxInRatio;return i>m&&r.push("MaxInRatioExceeded"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),n=v.calculateSellFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount");let c=t.balanceIn/this.maxInRatio;e>c&&r.push("MaxInRatioExceeded");let m=t.balanceOut/this.maxOutRatio;return i>m&&r.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:n,errors:r}}calculateInGivenOut(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateLrnaInGivenOut(t,e,s);let a=f.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.protocolFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,s){let a=f.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){if(t.assetIn==this.hubAssetId)return this.calculateOutGivenLrnaIn(t,e,s);let a=f.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.protocolFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,s){let a=f.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?R.toRaw(s.assetFee).toString():"0",s?R.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}spotPriceInGivenOut(t){if(t.assetIn==this.hubAssetId)return this.spotPriceLrnaInGivenOut(t);let e=f.calculateSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString(),t.balanceIn.toString(),t.hubReservesIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceLrnaInGivenOut(t){let e=f.calculateLrnaSpotPrice(t.hubReservesOut.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){if(t.assetIn==this.hubAssetId)return this.spotPriceOutGivenLrnaIn(t);let e=f.calculateSpotPrice(t.balanceIn.toString(),t.hubReservesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}spotPriceOutGivenLrnaIn(t){let e=f.calculateLrnaSpotPrice(t.balanceOut.toString(),t.hubReservesOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}normalizeSpot(t,e,s){let a=e-s;if(a===0)return t;let i=Ce.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as Wr,Binary as Tt,CompatibilityLevel as Ur,Enum as Me}from"polkadot-api";import{toHex as Yr}from"@polkadot-api/utils";import{Subscription as Kr,distinctUntilChanged as jr,filter as Qr,finalize as Jr,map as Zr,merge as to,tap as eo}from"rxjs";import{HYDRATION_SS58_PREFIX as ao}from"@galacticcouncil/common";var{FeeUtils:mo}=S,go=Tt.toHex(Tt.fromText("omnipool")),ho=Me("Short");import{calculate_in_given_out as De,calculate_out_given_in as He,calculate_amplification as Ne,calculate_add_one_asset as qe,calculate_liquidity_out_one_asset as Ge,calculate_shares as Ve,calculate_shares_for_amount as We,calculate_spot_price_with_fee as Ue,pool_account_name as $e,recalculate_peg as Xe}from"@galacticcouncil/math-stableswap";var B=class{static getPoolAddress(t){return $e(t)}static defaultPegs(t){let e=[];for(let s=0;s<t;s++)e.push(["1","1"]);return e}static calculateAmplification(t,e,s,a,i){return Ne(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i,n,r){return De(t,e,s,a,i,n,r)}static calculateAddOneAsset(t,e,s,a,i,n,r){return qe(t,e,s,a,i,n,r)}static calculateSharesForAmount(t,e,s,a,i,n,r){return We(t,e,s,a,i,n,r)}static calculateOutGivenIn(t,e,s,a,i,n,r){return He(t,e,s,a,i,n,r)}static calculateLiquidityOutOneAsset(t,e,s,a,i,n,r){return Ge(t,e,s,a,i,n,r)}static calculateShares(t,e,s,a,i,n){return Ve(t,e,s,a,i,n)}static calculateSpotPriceWithFee(t,e,s,a,i,n,r,o){return Ue(t,e,s,a,i,n,r,o)}static recalculatePegs(t,e,s,a,i,n){let r=Xe(t,e,s,a,i,n);return JSON.parse(r)}};import{RUNTIME_DECIMALS as Ye,big as xt}from"@galacticcouncil/common";var{FeeUtils:V}=S,W=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new u(t)}constructor(t){this.type="Stableswap",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit,this.amplification=t.amplification,this.isRampPeriod=t.isRampPeriod,this.id=t.id,this.fee=t.fee,this.totalIssuance=t.totalIssuance,this.pegs=t.pegs}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,tradeableIn:this.id===t?15:a.tradeable,tradeableOut:this.id===e?15:i.tradeable,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateInGivenOut(t,e,s),n=a===0n?0:v.calculateBuyFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount"),{amountIn:i,calculatedIn:a,amountOut:e,feePct:n,errors:r}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateOutGivenIn(t,e,s),n=v.calculateSellFee(a,i),r=[],o=f.isSellAllowed(t.tradeableIn),l=f.isBuyAllowed(t.tradeableOut);return(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount"),{amountIn:e,calculatedOut:a,amountOut:i,feePct:n,errors:r}}calculateIn(t,e,s){let a=B.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateAddOneAsset(t,e,s){let a=B.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateSharesForAmount(t,e,s){let a=B.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateInGivenOut(t,e,s){return t.assetOut==this.id?this.calculateAddOneAsset(t,e,s):t.assetIn==this.id?this.calculateSharesForAmount(t,e,s):this.calculateIn(t,e,s)}spotPriceInGivenOut(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetOut.toString(),t.assetIn.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetOut===this.id,t.assetIn===this.id,t.decimalsOut,t.decimalsIn)}calculateOut(t,e,s){let a=B.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,s){let a=B.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateShares(t,e,s){let a=B.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?V.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateOutGivenIn(t,e,s){return t.assetIn==this.id?this.calculateWithdrawOneAsset(t,e,s):t.assetOut==this.id?this.calculateShares(t,e,s):this.calculateOut(t,e,s)}spotPriceOutGivenIn(t){let e=B.calculateSpotPriceWithFee(this.id.toString(),this.getReserves(),this.amplification.toString(),t.assetIn.toString(),t.assetOut.toString(),this.totalIssuance.toString(),"0",this.getPegs());return this.normalizeSpot(BigInt(e),t.assetIn===this.id,t.assetOut===this.id,t.decimalsIn,t.decimalsOut)}getPegs(){return JSON.stringify(this.pegs)}getReserves(){let t=this.tokens.filter(e=>e.id!=this.id).map(({id:e,balance:s,decimals:a})=>({asset_id:e,amount:s,decimals:a}));return JSON.stringify(t,K.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],K.jsonFormatter)}normalizeSpot(t,e,s,a,i){return e?t*xt.pow10(Ye-i):s?t/xt.pow10(i-a):t}};import{AccountId as Wo,CompatibilityLevel as Uo}from"polkadot-api";import{toHex as Xo}from"@polkadot-api/utils";import{blake2b as zo}from"@noble/hashes/blake2b";import{Subscription as jo,distinctUntilChanged as Qo,map as Jo,merge as Zo,tap as tl}from"rxjs";import{HYDRATION_SS58_PREFIX as sl,RUNTIME_DECIMALS as al}from"@galacticcouncil/common";var{FeeUtils:gl}=S;import{calculate_in_given_out as Ke,calculate_out_given_in as je,calculate_pool_trade_fee as Qe,get_spot_price as Je,calculate_liquidity_in as Ze,calculate_shares as ts,calculate_spot_price as es,calculate_spot_price_with_fee as ss,calculate_liquidity_out_asset_a as as,calculate_liquidity_out_asset_b as is}from"@galacticcouncil/math-xyk";var L=class{static getSpotPrice(t,e,s){return Je(t,e,s)}static calculateInGivenOut(t,e,s){return Ke(t,e,s)}static calculateOutGivenIn(t,e,s){return je(t,e,s)}static calculatePoolTradeFee(t,e,s){return Qe(t,e,s)}static calculateLiquidityIn(t,e,s){return Ze(t,e,s)}static calculateSpotPrice(t,e){return es(t,e)}static calculateSpotPriceWithFee(t,e,s,a){return ss(t,e,s,a)}static calculateShares(t,e,s){return ts(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,a){return as(t,e,s,a)}static calculateLiquidityOutAssetB(t,e,s,a){return is(t,e,s,a)}};import{big as ns}from"@galacticcouncil/common";var{FeeUtils:Bt}=S,ot=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t)}constructor(t){this.type="XYK",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,decimalsIn:a.decimals,decimalsOut:i.decimals,balanceIn:a.balance,balanceOut:i.balance,assetInEd:a.existentialDeposit,assetOutEd:i.existentialDeposit}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=this.calculateTradeFee(a,s),n=Bt.toPct(s.exchangeFee),r=a+i,o=[];(e<this.minTradingLimit||a<t.assetInEd)&&o.push("InsufficientTradingAmount");let l=t.balanceOut/this.maxOutRatio;e>l&&o.push("MaxOutRatioExceeded");let c=t.balanceIn/this.maxInRatio;return r>c&&o.push("MaxInRatioExceeded"),{amountIn:r,calculatedIn:a,amountOut:e,feePct:n,errors:o}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=this.calculateTradeFee(a,s),n=Bt.toPct(s.exchangeFee),r=a-i,o=[];(e<this.minTradingLimit||a<t.assetOutEd)&&o.push("InsufficientTradingAmount");let l=t.balanceIn/this.maxInRatio;e>l&&o.push("MaxInRatioExceeded");let c=t.balanceOut/this.maxOutRatio;return r>c&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(t,e){let s=L.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=L.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=L.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=L.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let s=L.calculatePoolTradeFee(t.toString(),e.exchangeFee[0],e.exchangeFee[1]);return BigInt(s)}normalizeSpot(t,e,s){let a=e-s;if(a===0)return t;let i=ns.pow10(Math.abs(a));return a>0?t*i:t/i}};import{CompatibilityLevel as ql}from"polkadot-api";import{Subscription as Vl}from"rxjs";import{big as At,RUNTIME_DECIMALS as Ft}from"@galacticcouncil/common";var lt=class u{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new u(t)}constructor(t){this.type="Aave",this.address=t.address,this.tokens=t.tokens,this.maxInRatio=t.maxInRatio,this.maxOutRatio=t.maxOutRatio,this.minTradingLimit=t.minTradingLimit}validatePair(t,e){return!0}parsePair(t,e){let s=new Map(this.tokens.map(n=>[n.id,n])),a=s.get(t),i=s.get(e);if(a==null)throw new Error("Pool does not contain tokenIn");if(i==null)throw new Error("Pool does not contain tokenOut");return{assetIn:t,assetOut:e,balanceIn:a.balance,balanceOut:i.balance,decimalsIn:a.decimals,decimalsOut:i.decimals,assetInEd:0n,assetOutEd:0n}}validateAndBuy(t,e,s){let a=this.calculateInGivenOut(t,e),i=[];return e>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:a,calculatedIn:a,amountOut:e,feePct:0,errors:i}}validateAndSell(t,e,s){let a=this.calculateOutGivenIn(t,e),i=[];return a>t.balanceOut&&i.push("TradeNotAllowed"),{amountIn:e,calculatedOut:a,amountOut:a,feePct:0,errors:i}}calculateInGivenOut(t,e){return e}calculateOutGivenIn(t,e){return e}spotPriceInGivenOut(t){return At.toBigInt(1,Ft)}spotPriceOutGivenIn(t){return At.toBigInt(1,Ft)}calculateTradeFee(t,e){return 0n}};import{AccountId as yc,Binary as fc}from"polkadot-api";import{toHex as Ic}from"@polkadot-api/utils";import{Subscription as Oc,filter as vc,map as Tc,mergeMap as xc}from"rxjs";import{decodeEventLog as Ac}from"viem";import{erc20 as os,HYDRATION_SS58_PREFIX as _c}from"@galacticcouncil/common";var{ERC20:Dc}=os;import{calculate_collateral_in_given_hollar_out as cs,calculate_collateral_out_given_hollar_in as us,calculate_hollar_in_given_collateral_out as ps,calculate_hollar_out_given_collateral_in as ms,calculate_imbalance as ds,calculate_max_price as gs,calculate_buyback_limit as hs,calculate_buyback_price_with_fee as bs}from"@galacticcouncil/math-hsm";var F=class{static calculateCollateralInGivenHollarOut(t,e,s){return cs(t,e,s)}static calculateCollateralOutGivenHollarIn(t,e,s){return us(t,e,s)}static calculateHollarOutGivenCollateralIn(t,e,s){return ms(t,e,s)}static calculateHollarInGivenCollateralOut(t,e,s){return ps(t,e,s)}static calculateImbalance(t,e,s){return ds(t,e,s)}static calculateBuybackLimit(t,e){return hs(t,e)}static calculateBuybackPriceWithFee(t,e,s){return bs(t,e,s)}static calculateMaxPrice(t,e){return gs(t,e)}};import{big as C,RUNTIME_DECIMALS as ct}from"@galacticcouncil/common";var{FeeUtils:U}=S,ut=class u extends W{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new u(t)}constructor(t){super(t),this.type="HSM",this.hsmAddress=t.hsmAddress,this.hsmMintCapacity=t.hsmMintCapacity,this.hollarId=t.hollarId,this.hollarH160=t.hollarH160,this.collateralId=t.collateralId,this.collateralBalance=t.collateralBalance,this.maxBuyPriceCoefficient=t.maxBuyPriceCoefficient,this.maxInHolding=t.maxInHolding,this.purchaseFee=t.purchaseFee,this.buyBackFee=t.buyBackFee,this.buyBackRate=t.buyBackRate}validatePair(t,e){return!0}parsePair(t,e){return super.parsePair(t,e)}validateTradeHollarIn(t,e,s){let a=this.parsePair(t.assetOut,t.assetIn),i=super.calculateInGivenOut(a,e,{fee:this.fee}),n=this.calculateBuybackLimit(t);e>n&&s.push("MaxBuyBackExceeded");let r=this.calculateMaxPrice(t);return this.calculateBuyPrice(t,e,i)>r&&s.push("MaxBuyPriceExceeded"),i>this.collateralBalance&&s.push("InsufficientCollateral"),s}validateTradeHollarOut(t,e,s){return this.collateralBalance+t>this.maxInHolding&&s.push("MaxHoldingExceeded"),e>this.hsmMintCapacity&&s.push("FacilitatorCapacityExceeded"),s}validateTradeConstraints(t,e,s){let a=[];return t.assetIn===this.hollarId?this.validateTradeHollarIn(t,e,a):this.validateTradeHollarOut(e,s,a)}validateAndBuy(t,e){let s=this.calculateInGivenOut(t,e),a=this.validateTradeConstraints(t,s,e);return{amountIn:s,calculatedIn:s,amountOut:e,feePct:0,errors:a}}validateAndSell(t,e){let s=this.calculateOutGivenIn(t,e),a=this.validateTradeConstraints(t,e,s);return{amountIn:e,calculatedOut:s,amountOut:s,feePct:0,errors:a}}calculateHollarInGivenCollateralOut(t,e){let s=super.calculateInGivenOut(t,e,{fee:this.fee}),a=F.calculateHollarInGivenCollateralOut(e.toString(),s.toString(),U.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),s=F.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),U.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateInGivenOut(t,e){return t.assetOut==this.hollarId?this.calculateCollateralInGivenHollarOut(e):this.calculateHollarInGivenCollateralOut(t,e)}calculateCollateralOutGivenHollarIn(t,e){let s=super.calculateOutGivenIn(t,e,{fee:this.fee}),a=F.calculateCollateralOutGivenHollarIn(e.toString(),s.toString(),U.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),s=F.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),U.toRaw(this.purchaseFee).toString());return BigInt(s)}calculateOutGivenIn(t,e){return t.assetIn==this.hollarId?this.calculateCollateralOutGivenHollarIn(t,e):this.calculateHollarOutGivenCollateralIn(e)}calculateImbalance(t){let e=this.getCollateralPeg(),s=F.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(s)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),s=F.calculateBuybackLimit(e.toString(),U.toRaw(this.buyBackRate).toString());return BigInt(s)}calculateBuyPrice(t,e,s){let a=F.calculateBuybackPriceWithFee(s.toString(),e.toString(),U.toRaw(this.buyBackFee).toString()),[i,n]=JSON.parse(a),r=C.pow10(t.decimalsIn+ct-t.decimalsOut);return BigInt(i)*r/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),s=F.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[a,i]=JSON.parse(s),n=C.pow10(ct-t.decimalsOut);return BigInt(a)*n/BigInt(i)}spotPriceInGivenOut(t){let e=C.toBigInt(1,t.decimalsOut),a=this.calculateInGivenOut(t,e)*C.pow10(ct-t.decimalsOut);return this.normalizeSpotPrice(a,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=C.toBigInt(1,t.decimalsIn),a=this.calculateOutGivenIn(t,e)*C.pow10(ct-t.decimalsIn);return this.normalizeSpotPrice(a,t.decimalsIn,t.decimalsOut)}getCollateralPeg(){let t=this.tokens.findIndex(a=>a.id!==this.hollarId),e=this.pegs[t],s=this.tokens[t].decimals;return this.isDefaultPeg(e)?[C.toBigInt(1,18).toString(),C.toBigInt(1,s).toString()]:e}isDefaultPeg(t){let[e,s]=t;return Array.isArray(t)&&t.length===2&&e==="1"&&s==="1"}normalizeSpotPrice(t,e,s){let a=e-s;if(a===0)return t;let i=C.pow10(Math.abs(a));return a>0?t*i:t/i}};import{AccountId as hu,Binary as bu,CompatibilityLevel as Pu}from"polkadot-api";import{toHex as Su}from"@polkadot-api/utils";import{Subscription as Ou,combineLatest as vu,filter as Tu,map as xu,mergeMap as Bu,pairwise as Au}from"rxjs";import{decodeEventLog as _u}from"viem";import{h160 as ys,HYDRATION_SS58_PREFIX as Eu}from"@galacticcouncil/common";var{FeeUtils:Nu}=S,{H160:qu}=ys;var J=class{static get(t){switch(t.type){case"Aave":return lt.fromPool(t);case"XYK":return ot.fromPool(t);case"Omnipool":return rt.fromPool(t);case"LBP":return it.fromPool(t);case"Stableswap":return W.fromPool(t);case"HSM":return ut.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};import{log as Ss}from"@galacticcouncil/common";import{Subject as fp,Subscription as Sp,takeUntil as Ip}from"rxjs";var pt=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var{logger:Dp}=Ss;var Z=class{getProposals(t,e,s){let a=s.filter(p=>p.type==="XYK"),i=s.filter(p=>p.type!=="XYK"),n=new Set(i.map(p=>p.tokens).flat().map(p=>p.id)),r=n.has(t),o=n.has(e),l=new z,c=p=>{let b=mt(p),P=Object.keys(b),_=P.flatMap(x=>b[x]);return l.buildAndPopulateGraph(P,_)};if(!r&&!o){let p=a.filter(_=>_.tokens.find(x=>x.id===t)||_.tokens.find(x=>x.id===e)),b=c(p),P=l.findPaths(b,t,e);return this.parsePaths(P)}if(r&&o){let p=c(i),b=l.findPaths(p,t,e);return this.parsePaths(b)}let m=r?e:t,h=a.filter(p=>p.tokens.some(b=>b.id===m));if(h.length===0)return[];let d=[...i,...h],y=c(d),g=l.findPaths(y,t,e);return this.parsePaths(g)}parsePaths(t){let e=[];for(let s of t){let a=[];for(let i=0;i<s.length;i++){let n=s[i],r=s[i+1];if(r==null)break;a.push(this.toEdge(n,r))}e.push(a)}return e}toEdge(t,e){return[e[1],t[0],e[0]]}};var tt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new Z,this.routeProposals=new Map}async withFilter(t){this.filter=t||{},this.routeProposals.clear(),this.onFilterChanged()}onFilterChanged(){}buildRouteKey(t,e,s){return`${t}->${e}::${s.length}`}applyPoolFilter(t){let{useOnly:e=[],exclude:s=[]}=this.filter,a=new Set(e),i=new Set(s);return t.filter(n=>i.has(n.type)?!1:a.size>0?a.has(n.type):!0)}async getPools(){let t=await this.ctx.getPools();return this.applyPoolFilter(t)}async getRoutes(t,e){let s=await this.getPools();return this.validateInput(t,e,s),this.getPaths(t,e,s)}async getTradeableAssets(){let t=await this.getPools(),e=this.getAssets(t);return Array.from(e)}async getRouteableAssets(t){let e=await this.getTradeableAssets();return(await Promise.all(e.filter(a=>a!==t).map(a=>this.getRoutes(a,t)))).filter(a=>a.length>0).map(([a])=>a[0].assetIn).sort()}validateInput(t,e,s){if(s.length===0)throw new Error("No pools configured");if(t===e)throw new Error("Trading pair can't be identical");let a=this.getAssets(s);if(!a.has(t))throw new Error(t+" is not supported asset");if(!a.has(e))throw new Error(e+" is not supported asset");return this.toPoolsMap(s)}getAssets(t){let e=t.map(s=>s.tokens.map(a=>a.id)).flat().sort((s,a)=>s>a?1:-1);return new Set(e)}getPaths(t,e,s){let a=this.toPoolsMap(s);return this.getProposals(t,e,s).filter(n=>this.validPath(n,a)).map(n=>this.toHops(n,a))}getProposals(t,e,s){let a=this.buildRouteKey(t,e,s);if(this.routeProposals.has(a))return this.routeProposals.get(a);let i=this.routeSuggester.getProposals(t,e,s);return this.routeProposals.set(a,i),i}validPath(t,e){return t.length>0&&t.map(s=>this.validEdge(s,e)).reduce((s,a)=>s&&a)}validEdge([t,e,s],a){return a.get(t)?.validatePair(e,s)||!1}toPoolsMap(t){return new Map(t.map(e=>[e.address,J.get(e)]))}toHops(t,e){return t.map(([s,a,i])=>{let n=e.get(s);return{poolAddress:s,poolId:n?.id,pool:n?.type,assetIn:a,assetOut:i}})}};import{big as w,RUNTIME_DECIMALS as $}from"@galacticcouncil/common";var Rt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Rt||{}),Et=(s=>(s.Dca="Dca",s.TwapSell="TwapSell",s.TwapBuy="TwapBuy",s))(Et||{}),kt=(s=>(s.OrderTooSmall="OrderTooSmall",s.OrderTooBig="OrderTooBig",s.OrderImpactTooBig="OrderImpactTooBig",s))(kt||{});var{FeeUtils:Ct}=S,et=class extends tt{mlr;constructor(t){super(t),this.mlr=new Map}onFilterChanged(){this.mlr.clear()}buildCtxSync(t,e,s){let a=super.validateInput(t,e,s),i=super.getPaths(t,e,s);if(!i.length)throw new pt(t,e);return{paths:i,pools:s,poolsMap:a}}async withCtx(t,e,s){let a=await super.getPools(),i=this.buildCtxSync(t,e,a);return s(i)}isDirectTrade(t){return t.length==1}findBestSellRoute(t){let e=t.sort((s,a)=>{let i=s[s.length-1].amountOut,n=a[a.length-1].amountOut;return i>n?-1:1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}getRouteFeeRange(t){if(t.filter(s=>s.tradeFeeRange).length>0){let s=t.map(i=>i.tradeFeeRange?.[0]??i.tradeFeePct).reduce((i,n)=>i+n),a=t.map(i=>i.tradeFeeRange?.[1]??i.tradeFeePct).reduce((i,n)=>i+n);return[s,a]}}getPoolFeeRange(t,e){let s=t.min?Ct.toPct(t.min):void 0,a=t.max?Ct.toPct(t.max):void 0;if(s&&a)return[s,Math.max(a,e)]}async getBestSell(t,e,s){return this.getSell(t,e,s)}getSellSpot(t){let e=t[t.length-1];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getSell(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:n})=>{let r;if(a)r=await this.toSellSwaps(s,a,n);else{let o=i.map(c=>this.toSellSwaps(s,c,n)),l=await Promise.all(o);r=this.findBestSellRoute(l)}return this.buildSell(n,r)})}async getSells(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let n=a.map(o=>this.toSellSwaps(s,o,i));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildSell(i,o)).sort((o,l)=>o.amountOut>l.amountOut?-1:1)})}buildSell(t,e){let s=e[0],a=e[e.length-1],i=this.isDirectTrade(e),n=this.getSellSpot(e),r=a.amountOut,o=i?a.calculatedOut:this.calculateDelta0Y(s.amountIn,e,t),l=o-r,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:v.calculateSellFee(o,r),h=A.mulSpot(s.amountIn,n,s.assetInDecimals,a.assetOutDecimals),d=v.calculateDiffToRef(o,h);return{type:"Sell",amountIn:s.amountIn,amountOut:a.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:w.toDecimal(s.amountIn,s.assetInDecimals),amountOut:w.toDecimal(a.amountOut,a.assetOutDecimals),spotPrice:w.toDecimal(n,$),tradeFee:w.toDecimal(l,a.assetOutDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(y=>y.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,s)=>e*s/10n**BigInt($))}calculateDelta0Y(t,e,s){let a=[];for(let i=0;i<e.length;i++){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i>0?l=a[i-1]:l=t;let c=r.calculateOutGivenIn(o,l);a.push(c)}return a[a.length-1]}async calculateMostLiquidRoute(t,e,s){let{paths:a,pools:i,poolsMap:n}=s,l=i.filter(g=>g.tokens.some(p=>p.id===t)).map(g=>g.type==="Aave"?g.tokens:g.tokens.filter(p=>p.id===t)).map(g=>g.map(p=>p.balance).reduce((p,b)=>p+b)).sort((g,p)=>p<g?-1:1)[0],c=A.getFraction(l,.1),m=await Promise.all(a.map(g=>this.toSellSwaps(c,g,n))),d=this.findBestSellRoute(m).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut})),y=this.buildRouteKey(t,e,i);return this.mlr.set(y,d),d}async toSellSwaps(t,e,s){let a=[];for(let i=0;i<e.length;i++){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i>0?l=a[i-1].amountOut:l=typeof t=="string"?w.toBigInt(t,o.decimalsIn):t;let c=await this.ctx.getPoolFees(o,r),{amountOut:m,calculatedOut:h,feePct:d,errors:y}=r.validateAndSell(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceOutGivenIn(o),b=A.mulSpot(l,p,o.decimalsIn,o.decimalsOut),P=v.calculateDiffToRef(h,b);a.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:h,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y,isSupply(){return r.type==="Aave"&&r.tokens[0].id===n.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===n.assetIn},toHuman(){return{...n,amountIn:w.toDecimal(l,o.decimalsIn),amountOut:w.toDecimal(m,o.decimalsOut),calculatedOut:w.toDecimal(h,o.decimalsOut),spotPrice:w.toDecimal(p,$),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y}}})}return a}async getMostLiquidRoute(t,e){return this.withCtx(t,e,async s=>{let a=this.buildRouteKey(t,e,s.pools),i=this.mlr.get(a);return i||this.calculateMostLiquidRoute(t,e,s)})}async getSpotPrice(t,e){return this.withCtx(t,e,async s=>{let{pools:a,poolsMap:i}=s,n=this.buildRouteKey(t,e,a),r=this.mlr.get(n);r||(r=await this.calculateMostLiquidRoute(t,e,s));let o=await this.toSellSwaps("1",r,i);return{amount:this.getSellSpot(o),decimals:$}}).catch(()=>{})}findBestBuyRoute(t){let e=t.sort((s,a)=>{let i=s[0].amountIn,n=a[0].amountIn;return i>n?1:-1});return e.find(s=>s.every(a=>a.errors.length==0))||e[0]}async getBestBuy(t,e,s){return this.getBuy(t,e,s)}getBuySpot(t){let e=t[0];return t.length===1?e.spotPrice:this.calculateSpot(t)}async getBuy(t,e,s,a){return this.withCtx(t,e,async({paths:i,poolsMap:n})=>{let r;if(a)r=await this.toBuySwaps(s,a,n);else{let o=i.map(c=>this.toBuySwaps(s,c,n)),l=await Promise.all(o);r=this.findBestBuyRoute(l)}return this.buildBuy(n,r)})}async getBuys(t,e,s){return this.withCtx(t,e,async({paths:a,poolsMap:i})=>{let n=a.map(o=>this.toBuySwaps(s,o,i));return(await Promise.all(n)).filter(o=>o.every(l=>l.errors.length==0)).map(o=>this.buildBuy(i,o)).sort((o,l)=>o.amountIn>l.amountIn?1:-1)})}buildBuy(t,e){let s=e[e.length-1],a=e[0],i=this.isDirectTrade(e),n=this.getBuySpot(e),r=a.amountIn,o=i?a.calculatedIn:this.calculateDelta0X(s.amountOut,e,t),l=r-o,c=this.getRouteFeeRange(e),m=i?a.tradeFeePct:v.calculateBuyFee(o,r),h=A.mulSpot(s.amountOut,n,s.assetOutDecimals,a.assetInDecimals),d;return o===0n?d=-100:d=v.calculateDiffToRef(h,o),{type:"Buy",amountOut:s.amountOut,amountIn:a.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:w.toDecimal(s.amountOut,s.assetOutDecimals),amountIn:w.toDecimal(a.amountIn,a.assetInDecimals),spotPrice:w.toDecimal(n,$),tradeFee:w.toDecimal(l,a.assetInDecimals),tradeFeePct:m,tradeFeeRange:c,priceImpactPct:d,swaps:e.map(y=>y.toHuman())}}}}calculateDelta0X(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i==e.length-1?l=t:l=a[0];let c=r.calculateInGivenOut(o,l);a.unshift(c)}return a[0]}async toBuySwaps(t,e,s){let a=[];for(let i=e.length-1;i>=0;i--){let n=e[i],r=s.get(n.poolAddress);if(r==null)throw new Error("Pool does not exit");let o=r.parsePair(n.assetIn,n.assetOut),l;i==e.length-1?l=typeof t=="string"?w.toBigInt(t,o.decimalsOut):t:l=a[0].amountIn;let c=await this.ctx.getPoolFees(o,r),{amountIn:m,calculatedIn:h,feePct:d,errors:y}=r.validateAndBuy(o,l,c),g=this.getPoolFeeRange(c,d),p=r.spotPriceInGivenOut(o),b=A.mulSpot(l,p,o.decimalsOut,o.decimalsIn),P;h===0n?P=-100:P=v.calculateDiffToRef(b,h),a.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:m,calculatedIn:h,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y,isSupply(){return r.type==="Aave"&&r.tokens[0].id===n.assetIn},isWithdraw(){return r.type==="Aave"&&r.tokens[1].id===n.assetIn},toHuman(){return{...n,amountOut:w.toDecimal(l,o.decimalsOut),amountIn:w.toDecimal(m,o.decimalsIn),calculatedIn:w.toDecimal(h,o.decimalsIn),spotPrice:w.toDecimal(p,$),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:P,errors:y}}})}return a}};import{big as O}from"@galacticcouncil/common";var Mt=6e3,Lt=1000000000000000n,st=6,ht=-5,bt=216e5,Nm=3,Dt=.1,Ht=6;import{Enum as Nt}from"polkadot-api";var D=class{static build(t){return t.map(({assetIn:e,assetOut:s,pool:a,poolId:i})=>a==="Stableswap"?{pool:Nt("Stableswap",i),asset_in:e,asset_out:s}:{pool:Nt(a),asset_in:e,asset_out:s})}};var Pt=class{schedulerOptions;router;constructor(t,e={}){this.router=new et(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??Lt})}get blockTime(){return this.schedulerOptions.blockTime}get minOrderBudget(){return this.schedulerOptions.minBudgetInNative}async getDcaOrder(t,e,s,a,i){let n=await this.router.getBestSell(t,e,s),{amountIn:r,swaps:o,priceImpactPct:l}=n,c=o[0],m=o[o.length-1],{assetInDecimals:h}=c,{assetOutDecimals:d}=m,y=Math.abs(l),g=await this.getMinimumOrderBudget(t,h),p=this.getOptimalTradeCount(y),b=this.getMaximumTradeCount(r,g,a),P=i||Math.min(p,b),_=Math.round(a/P),x=r/BigInt(P),T=await this.router.getBestSell(t,e,x),H=r<g,N=[];H&&N.push("OrderTooSmall");let M=T.amountOut*BigInt(P),Gt=this.toBlockPeriod(_),Vt=T.tradeFee*BigInt(P),Wt=D.build(o),yt={assetIn:t,assetOut:e,errors:N,maxTradeCount:b,tradeCount:P,tradeFee:Vt,tradeImpactPct:T.priceImpactPct,tradePeriod:Gt,tradeRoute:Wt,type:"Dca"};return{...yt,amountIn:r,amountOut:M,tradeAmountIn:T.amountIn,tradeAmountOut:T.amountOut,toHuman(){return{...yt,amountIn:O.toDecimal(r,h),amountOut:O.toDecimal(M,d),tradeAmountIn:O.toDecimal(T.amountIn,h),tradeAmountOut:O.toDecimal(T.amountOut,d)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let s=await this.router.getSpotPrice(0,t);if(s)return A.mulSpot(this.minOrderBudget,s.amount,12,e);let a=await this.router.getSpotPrice(t,0);if(a)return A.divSpot(this.minOrderBudget,a.amount,12,e);throw new Error("Unable to calculate order budget")}getMaximumTradeCount(t,e,s){let a=e*2n/10n;if(a===0n)return 0;let i=Number(t/a),n=Math.floor(s/this.blockTime),r=Math.max(0,Math.floor(n*(1-.1)));return Math.min(i,r)}getOptimalTradeCount(t){let e=Math.round(t*10)||1;return Math.max(e,3)}async getOpenBudgetDcaOrder(t,e,s,a){let i=await this.router.getBestSell(t,e,s),{swaps:n}=i,r=n[0],o=n[n.length-1],{assetInDecimals:l}=r,{assetOutDecimals:c}=o,m=await this.getMinimumOrderBudget(t,l),h=i.amountIn<m,d=[];h&&d.push("OrderTooSmall");let y=this.toBlockPeriod(a),g=D.build(n),p={assetIn:t,assetOut:e,errors:d,maxTradeCount:0,tradeCount:0,tradeFee:i.tradeFee,tradeImpactPct:i.priceImpactPct,tradePeriod:y,tradeRoute:g,type:"Dca"};return{...p,amountIn:0n,amountOut:0n,tradeAmountIn:i.amountIn,tradeAmountOut:i.amountOut,toHuman(){return{...p,amountIn:"0",amountOut:"0",tradeAmountIn:O.toDecimal(i.amountIn,l),tradeAmountOut:O.toDecimal(i.amountOut,c)}}}}async getTwapSellOrder(t,e,s){let a=await this.router.getBestSell(t,e,s),{amountIn:i,swaps:n,priceImpactPct:r}=a,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,h=Math.abs(r),d=this.getTwapTradeCount(h),y=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestSell(o.assetIn,l.assetOut,y)]),b=d===1,P=i<g,_=p.priceImpactPct<-5,x=[];P||b?x.push("OrderTooSmall"):_&&x.push("OrderImpactTooBig");let T=p.amountOut*BigInt(d),H=p.tradeFee*BigInt(d),N=D.build(n),M={assetIn:t,assetOut:e,errors:x,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapSell"};return{...M,amountIn:i,amountOut:T,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(i,c),amountOut:O.toDecimal(T,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(H,m)}}}}async getTwapBuyOrder(t,e,s){let a=await this.router.getBestBuy(t,e,s),{amountOut:i,swaps:n,priceImpactPct:r}=a,o=n[0],l=n[n.length-1],{assetInDecimals:c}=o,{assetOutDecimals:m}=l,h=Math.abs(r),d=this.getTwapTradeCount(h),y=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,c),this.router.getBestBuy(o.assetIn,l.assetOut,y)]),b=p.amountIn*BigInt(d),P=d===1,_=b<g,x=p.priceImpactPct<-5,T=[];_||P?T.push("OrderTooSmall"):x&&T.push("OrderImpactTooBig");let H=p.tradeFee*BigInt(d),N=D.build(n),M={assetIn:t,assetOut:e,errors:T,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:N,type:"TwapBuy"};return{...M,amountIn:b,amountOut:i,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:H,toHuman(){return{...M,amountIn:O.toDecimal(b,c),amountOut:O.toDecimal(i,m),tradeAmountIn:O.toDecimal(p.amountIn,c),tradeAmountOut:O.toDecimal(p.amountOut,m),tradeFee:O.toDecimal(H,c)}}}}getTwapTradeCount(t){let e=this.getOptimalTradeCount(t);if(this.getTwapExecutionTime(e)>216e5){let a=216e5/(this.blockTime*6);return Math.round(a)}return e}getTwapExecutionTime(t){return t*6*this.blockTime}toBlockPeriod(t){let e=t/this.blockTime,s=Math.round(e);return Math.max(s,6)}};export{Dt as DCA_TIME_RESERVE,Mt as DEFAULT_BLOCK_TIME,Lt as DEFAULT_MIN_BUDGET,Ht as ORDER_MIN_BLOCK_PERIOD,tt as Router,st as TWAP_EXECUTION_INTERVAL,bt as TWAP_MAX_DURATION,ht as TWAP_MAX_PRICE_IMPACT,Nm as TWAP_TX_MULTIPLIER,kt as TradeOrderError,Et as TradeOrderType,D as TradeRouteBuilder,et as TradeRouter,Pt as TradeScheduler,Rt as TradeType};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
export type Path = Node[];
|
|
2
1
|
export type Node = [id: number, from: string];
|
|
2
|
+
export type Path = Node[];
|
|
3
3
|
/**
|
|
4
4
|
* Breadth First Search.
|
|
5
5
|
*
|
|
@@ -25,7 +25,16 @@ export declare class Bfs {
|
|
|
25
25
|
* @param dst - destination node or null if requesting all posible paths from src
|
|
26
26
|
* @returns paths
|
|
27
27
|
*/
|
|
28
|
-
findPaths(g: Map<number, Path>, src: number, dst: number
|
|
28
|
+
findPaths(g: Map<number, Path>, src: number, dst: number): Path[];
|
|
29
|
+
/**
|
|
30
|
+
* Finding shortest paths in graph from given source to destination
|
|
31
|
+
*
|
|
32
|
+
* @param g - routes graph containing nodes & corresponding edges
|
|
33
|
+
* @param src - source node
|
|
34
|
+
* @param dst - destination node or null if requesting all posible paths from src
|
|
35
|
+
* @returns shortest paths
|
|
36
|
+
*/
|
|
37
|
+
findShortestPaths(g: Map<number, Path>, src: number, dst: number | null): Path[];
|
|
29
38
|
/**
|
|
30
39
|
* Build and populate graph
|
|
31
40
|
*
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { Edge } from './graph';
|
|
2
|
+
import { PoolBase } from '../../pool';
|
|
3
|
+
export type RouteProposal = Edge[];
|
|
4
|
+
export declare class RouteSuggester {
|
|
5
|
+
/**
|
|
6
|
+
* Returns ideal path proposals from `tokenIn` to `tokenOut`
|
|
7
|
+
* based on BFS over trusted, isolated or both pools.
|
|
8
|
+
*
|
|
9
|
+
* - Trusted pools = all pools except XYK (isolated)
|
|
10
|
+
*
|
|
11
|
+
* The routing strategy is:
|
|
12
|
+
* - If neither `tokenIn` and `tokenOut` is in a trusted pool:
|
|
13
|
+
* → Run BFS over isolated pools only, searching for all paths.
|
|
14
|
+
* - If both `tokenIn` and `tokenOut` are in trusted pools:
|
|
15
|
+
* → Run BFS over trusted pools only, searching for shortest paths.
|
|
16
|
+
* - Otherwise:
|
|
17
|
+
* → Run BFS over all relevant pools (trusted + isolated).
|
|
18
|
+
*
|
|
19
|
+
* This strategy minimizes search scope while ensuring all viable
|
|
20
|
+
* paths are discovered.
|
|
21
|
+
*
|
|
22
|
+
* NOTE: Filtering of valid swaps and pair execution is handled by the router,
|
|
23
|
+
* not in this step.
|
|
24
|
+
*
|
|
25
|
+
* @param tokenIn - The starting token (asset ID as string)
|
|
26
|
+
* @param tokenOut - The destination token (asset ID as string)
|
|
27
|
+
* @param pools - The list of available pools
|
|
28
|
+
* @returns Array of path proposals (each path is a list of edges)
|
|
29
|
+
*/
|
|
30
|
+
getProposals(tokenIn: number, tokenOut: number, pools: PoolBase[]): RouteProposal[];
|
|
31
|
+
private parsePaths;
|
|
32
|
+
private toEdge;
|
|
33
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { Enum } from 'polkadot-api';
|
|
2
|
+
import type { Hop, PoolBuy, PoolError, PoolSell } from '../pool';
|
|
3
|
+
export interface Humanizer {
|
|
4
|
+
toHuman(): any;
|
|
5
|
+
}
|
|
6
|
+
export type Swap = Hop & Humanizer & {
|
|
7
|
+
assetInDecimals: number;
|
|
8
|
+
assetOutDecimals: number;
|
|
9
|
+
amountIn: bigint;
|
|
10
|
+
amountOut: bigint;
|
|
11
|
+
spotPrice: bigint;
|
|
12
|
+
tradeFeePct: number;
|
|
13
|
+
tradeFeeRange?: [number, number];
|
|
14
|
+
priceImpactPct: number;
|
|
15
|
+
errors: PoolError[];
|
|
16
|
+
isSupply(): boolean;
|
|
17
|
+
isWithdraw(): boolean;
|
|
18
|
+
};
|
|
19
|
+
export type SellSwap = Swap & PoolSell;
|
|
20
|
+
export type BuySwap = Swap & PoolBuy;
|
|
21
|
+
export interface Trade extends Humanizer {
|
|
22
|
+
type: TradeType;
|
|
23
|
+
amountIn: bigint;
|
|
24
|
+
amountOut: bigint;
|
|
25
|
+
spotPrice: bigint;
|
|
26
|
+
tradeFee: bigint;
|
|
27
|
+
tradeFeePct: number;
|
|
28
|
+
tradeFeeRange?: [number, number];
|
|
29
|
+
priceImpactPct: number;
|
|
30
|
+
swaps: Swap[];
|
|
31
|
+
}
|
|
32
|
+
export declare enum TradeType {
|
|
33
|
+
Buy = "Buy",
|
|
34
|
+
Sell = "Sell"
|
|
35
|
+
}
|
|
36
|
+
export type TradeRoute = {
|
|
37
|
+
pool: ReturnType<typeof Enum>;
|
|
38
|
+
asset_in: number;
|
|
39
|
+
asset_out: number;
|
|
40
|
+
};
|
|
41
|
+
export interface TradeOrder extends Humanizer {
|
|
42
|
+
amountIn: bigint;
|
|
43
|
+
amountOut: bigint;
|
|
44
|
+
assetIn: number;
|
|
45
|
+
assetOut: number;
|
|
46
|
+
errors: TradeOrderError[];
|
|
47
|
+
tradeAmountIn: bigint;
|
|
48
|
+
tradeAmountOut: bigint;
|
|
49
|
+
tradeCount: number;
|
|
50
|
+
tradeFee: bigint;
|
|
51
|
+
tradeImpactPct: number;
|
|
52
|
+
tradePeriod: number;
|
|
53
|
+
tradeRoute: TradeRoute[];
|
|
54
|
+
type: TradeOrderType;
|
|
55
|
+
}
|
|
56
|
+
export declare enum TradeOrderType {
|
|
57
|
+
Dca = "Dca",
|
|
58
|
+
TwapSell = "TwapSell",
|
|
59
|
+
TwapBuy = "TwapBuy"
|
|
60
|
+
}
|
|
61
|
+
export declare enum TradeOrderError {
|
|
62
|
+
OrderTooSmall = "OrderTooSmall",
|
|
63
|
+
OrderTooBig = "OrderTooBig",
|
|
64
|
+
OrderImpactTooBig = "OrderImpactTooBig"
|
|
65
|
+
}
|
|
66
|
+
export interface TradeDcaOrder extends TradeOrder {
|
|
67
|
+
maxTradeCount: number;
|
|
68
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import Big from 'big.js';
|
|
2
|
+
import { BalanceClient } from '../client';
|
|
3
|
+
import { Balance } from '../types';
|
|
4
|
+
import { TVote } from './types';
|
|
5
|
+
import { StakingClient } from './StakingClient';
|
|
6
|
+
export declare const BIG_10: Big.Big;
|
|
7
|
+
export declare const BIG_BILL: Big.Big;
|
|
8
|
+
export declare class StakingApi {
|
|
9
|
+
private readonly client;
|
|
10
|
+
private readonly balance;
|
|
11
|
+
constructor(client: StakingClient, balanceClient: BalanceClient);
|
|
12
|
+
getPotBalance(): Promise<Balance>;
|
|
13
|
+
getStakingPosition(id: bigint): Promise<{
|
|
14
|
+
stake: bigint;
|
|
15
|
+
rewardPerStake: bigint;
|
|
16
|
+
createdAt: number;
|
|
17
|
+
actionPoints: bigint;
|
|
18
|
+
accumulatedUnpaidRewards: bigint;
|
|
19
|
+
accumulatedSlashPoints: bigint;
|
|
20
|
+
accumulatedLockedRewards: bigint;
|
|
21
|
+
votes: TVote[];
|
|
22
|
+
} | undefined>;
|
|
23
|
+
getStake(address: string): Promise<{
|
|
24
|
+
totalStake: bigint;
|
|
25
|
+
accumulatedRewardPerStake: bigint;
|
|
26
|
+
potReservedBalance: bigint;
|
|
27
|
+
positionId: bigint | undefined;
|
|
28
|
+
stakePosition: {
|
|
29
|
+
stake: bigint;
|
|
30
|
+
rewardPerStake: bigint;
|
|
31
|
+
createdAt: number;
|
|
32
|
+
actionPoints: bigint;
|
|
33
|
+
accumulatedUnpaidRewards: bigint;
|
|
34
|
+
accumulatedSlashPoints: bigint;
|
|
35
|
+
accumulatedLockedRewards: bigint;
|
|
36
|
+
votes: TVote[];
|
|
37
|
+
} | undefined;
|
|
38
|
+
}>;
|
|
39
|
+
getCurrentActionPoints(votes: TVote[], initialActionPoints: bigint, stakePosition: bigint, activeReferendaIds: string[]): {
|
|
40
|
+
currentActionPoints: string;
|
|
41
|
+
maxActionPoints: string;
|
|
42
|
+
};
|
|
43
|
+
getRewards(account: string, openGovReferendaIds: Array<string>, blockNumber: string): Promise<{
|
|
44
|
+
rewards: string;
|
|
45
|
+
payablePercentage: string;
|
|
46
|
+
extraPayablePercentage: string | undefined;
|
|
47
|
+
constants: {
|
|
48
|
+
a: string;
|
|
49
|
+
b: string;
|
|
50
|
+
};
|
|
51
|
+
maxRewards?: undefined;
|
|
52
|
+
allocatedRewardsPercentage?: undefined;
|
|
53
|
+
points?: undefined;
|
|
54
|
+
} | {
|
|
55
|
+
rewards: string;
|
|
56
|
+
maxRewards: string;
|
|
57
|
+
allocatedRewardsPercentage: number;
|
|
58
|
+
points: string;
|
|
59
|
+
payablePercentage: string;
|
|
60
|
+
extraPayablePercentage: string | undefined;
|
|
61
|
+
constants: {
|
|
62
|
+
a: string;
|
|
63
|
+
b: string;
|
|
64
|
+
};
|
|
65
|
+
} | undefined>;
|
|
66
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { Papi } from '../api';
|
|
2
|
+
export declare class StakingClient extends Papi {
|
|
3
|
+
getPalletId(): Promise<string>;
|
|
4
|
+
getPeriodLength(): Promise<number>;
|
|
5
|
+
getUnclaimablePeriods(): Promise<bigint>;
|
|
6
|
+
getNFTCollectionId(): Promise<bigint>;
|
|
7
|
+
getStaking(): Promise<{
|
|
8
|
+
total_stake: bigint;
|
|
9
|
+
accumulated_reward_per_stake: bigint;
|
|
10
|
+
pot_reserved_balance: bigint;
|
|
11
|
+
}>;
|
|
12
|
+
getUniques(address: string, collectionId: bigint): Promise<{
|
|
13
|
+
address: import("polkadot-api").SS58String;
|
|
14
|
+
collectionId: bigint;
|
|
15
|
+
itemId: bigint;
|
|
16
|
+
}[]>;
|
|
17
|
+
getStakingPositionsValue(id: bigint): Promise<{
|
|
18
|
+
stake: bigint;
|
|
19
|
+
action_points: bigint;
|
|
20
|
+
reward_per_stake: bigint;
|
|
21
|
+
created_at: number;
|
|
22
|
+
accumulated_slash_points: bigint;
|
|
23
|
+
accumulated_unpaid_rewards: bigint;
|
|
24
|
+
accumulated_locked_rewards: bigint;
|
|
25
|
+
} | undefined>;
|
|
26
|
+
getStakingVotes(id: bigint): Promise<[number, {
|
|
27
|
+
amount: bigint;
|
|
28
|
+
conviction: import("@galacticcouncil/descriptors").VotingConviction;
|
|
29
|
+
}][]>;
|
|
30
|
+
getReferendumInfo(key: number): Promise<import("polkadot-api").Enum<{
|
|
31
|
+
Ongoing: {
|
|
32
|
+
"track": number;
|
|
33
|
+
"origin": import("polkadot-api").Enum<{
|
|
34
|
+
system: import("polkadot-api").Enum<{
|
|
35
|
+
Root: undefined;
|
|
36
|
+
Signed: import("polkadot-api").SS58String;
|
|
37
|
+
None: undefined;
|
|
38
|
+
Authorized: undefined;
|
|
39
|
+
}>;
|
|
40
|
+
TechnicalCommittee: import("polkadot-api").Enum<{
|
|
41
|
+
Members: import("polkadot-api").FixedSizeArray<2, number>;
|
|
42
|
+
Member: import("polkadot-api").SS58String;
|
|
43
|
+
_Phantom: undefined;
|
|
44
|
+
}>;
|
|
45
|
+
Origins: import("polkadot-api").Enum<{
|
|
46
|
+
WhitelistedCaller: undefined;
|
|
47
|
+
ReferendumCanceller: undefined;
|
|
48
|
+
ReferendumKiller: undefined;
|
|
49
|
+
GeneralAdmin: undefined;
|
|
50
|
+
OmnipoolAdmin: undefined;
|
|
51
|
+
Treasurer: undefined;
|
|
52
|
+
Spender: undefined;
|
|
53
|
+
Tipper: undefined;
|
|
54
|
+
EconomicParameters: undefined;
|
|
55
|
+
}>;
|
|
56
|
+
Ethereum: {
|
|
57
|
+
type: "EthereumTransaction";
|
|
58
|
+
value: import("polkadot-api").SizedHex<20>;
|
|
59
|
+
};
|
|
60
|
+
PolkadotXcm: import("polkadot-api").Enum<{
|
|
61
|
+
Xcm: {
|
|
62
|
+
parents: number;
|
|
63
|
+
interior: import("@galacticcouncil/descriptors").XcmV5Junctions;
|
|
64
|
+
};
|
|
65
|
+
Response: {
|
|
66
|
+
parents: number;
|
|
67
|
+
interior: import("@galacticcouncil/descriptors").XcmV5Junctions;
|
|
68
|
+
};
|
|
69
|
+
}>;
|
|
70
|
+
CumulusXcm: import("polkadot-api").Enum<{
|
|
71
|
+
Relay: undefined;
|
|
72
|
+
SiblingParachain: number;
|
|
73
|
+
}>;
|
|
74
|
+
}>;
|
|
75
|
+
"proposal": import("@galacticcouncil/descriptors").PreimagesBounded;
|
|
76
|
+
"enactment": import("@galacticcouncil/descriptors").TraitsScheduleDispatchTime;
|
|
77
|
+
"submitted": number;
|
|
78
|
+
"submission_deposit": {
|
|
79
|
+
amount: bigint;
|
|
80
|
+
who: import("polkadot-api").SS58String;
|
|
81
|
+
};
|
|
82
|
+
"decision_deposit"?: {
|
|
83
|
+
amount: bigint;
|
|
84
|
+
who: import("polkadot-api").SS58String;
|
|
85
|
+
} | undefined;
|
|
86
|
+
"deciding"?: {
|
|
87
|
+
since: number;
|
|
88
|
+
confirming: number | undefined;
|
|
89
|
+
} | undefined;
|
|
90
|
+
"tally": {
|
|
91
|
+
ayes: bigint;
|
|
92
|
+
nays: bigint;
|
|
93
|
+
support: bigint;
|
|
94
|
+
};
|
|
95
|
+
"in_queue": boolean;
|
|
96
|
+
"alarm"?: [number, import("polkadot-api").FixedSizeArray<2, number>] | undefined;
|
|
97
|
+
};
|
|
98
|
+
Approved: [number, {
|
|
99
|
+
amount: bigint;
|
|
100
|
+
who: import("polkadot-api").SS58String;
|
|
101
|
+
} | undefined, {
|
|
102
|
+
amount: bigint;
|
|
103
|
+
who: import("polkadot-api").SS58String;
|
|
104
|
+
} | undefined];
|
|
105
|
+
Rejected: [number, {
|
|
106
|
+
amount: bigint;
|
|
107
|
+
who: import("polkadot-api").SS58String;
|
|
108
|
+
} | undefined, {
|
|
109
|
+
amount: bigint;
|
|
110
|
+
who: import("polkadot-api").SS58String;
|
|
111
|
+
} | undefined];
|
|
112
|
+
Cancelled: [number, {
|
|
113
|
+
amount: bigint;
|
|
114
|
+
who: import("polkadot-api").SS58String;
|
|
115
|
+
} | undefined, {
|
|
116
|
+
amount: bigint;
|
|
117
|
+
who: import("polkadot-api").SS58String;
|
|
118
|
+
} | undefined];
|
|
119
|
+
TimedOut: [number, {
|
|
120
|
+
amount: bigint;
|
|
121
|
+
who: import("polkadot-api").SS58String;
|
|
122
|
+
} | undefined, {
|
|
123
|
+
amount: bigint;
|
|
124
|
+
who: import("polkadot-api").SS58String;
|
|
125
|
+
} | undefined];
|
|
126
|
+
Killed: number;
|
|
127
|
+
}> | undefined>;
|
|
128
|
+
getTimePointsPerPeriod(): Promise<number>;
|
|
129
|
+
getTimePointsWeight(): Promise<number>;
|
|
130
|
+
getActionPointsWeight(): Promise<number>;
|
|
131
|
+
getSixBlockSince(): Promise<string>;
|
|
132
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var et=Object.create;var v=Object.defineProperty;var nt=Object.getOwnPropertyDescriptor;var ot=Object.getOwnPropertyNames;var it=Object.getPrototypeOf,at=Object.prototype.hasOwnProperty;var rt=(n,t)=>{for(var e in t)v(n,e,{get:t[e],enumerable:!0})},$=(n,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let c of ot(t))!at.call(n,c)&&c!==e&&v(n,c,{get:()=>t[c],enumerable:!(o=nt(t,c))||o.enumerable});return n};var st=(n,t,e)=>(e=n!=null?et(it(n)):{},$(t||!n||!n.__esModule?v(e,"default",{value:n,enumerable:!0}):e,n)),ct=n=>$(v({},"__esModule",{value:!0}),n);var mt={};rt(mt,{BIG_10:()=>G,BIG_BILL:()=>N,StakingApi:()=>O,StakingClient:()=>E});module.exports=ct(mt);var l=require("@galacticcouncil/math-staking"),d=st(require("big.js"));var b={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},z=n=>Object.keys(b).includes(n);var F=require("polkadot-api"),Y=require("@polkadot-api/utils"),j=require("@galacticcouncil/common");function X(n){let t=("modl"+n).padEnd(32,"\0"),e=new TextEncoder().encode(t),o=(0,Y.toHex)(e);return(0,F.AccountId)(j.HYDRATION_SS58_PREFIX).dec(o)}var x="20000000000000000",A="2000",G=(0,d.default)(10),N=(0,d.default)(G.pow(12)),O=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=X(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,o]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let c=e.created_at,i=await o.reduce(async(a,[p,r])=>{let g=await a,S=p,P=r.amount,h=r.conviction.type.toLowerCase(),u=await this.client.getReferendumInfo(S);return u&&(u.type==="Approved"||u.type==="Rejected")&&z(h)&&g.push({id:S,amount:P,conviction:h}),g},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:c,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:i}}async getStake(t){let e=await this.client.getNFTCollectionId(),[o,c]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),i=c.find(a=>a)?.itemId;return{totalStake:o?.total_stake,accumulatedRewardPerStake:o?.accumulated_reward_per_stake,potReservedBalance:o?.pot_reserved_balance,positionId:i,stakePosition:i?await this.getStakingPosition(i):void 0}}getCurrentActionPoints(t,e,o,c){let i=(0,d.default)(0),a=(0,d.default)(0),p=b.locked6x,r=(0,d.default)(o.toString()).mul(p),g=100,S=[];t.forEach(u=>{let f=b[u.conviction],k=c.includes(u.id.toString());k&&S.push(u.id.toString());let w=(0,d.default)(u.amount.toString()).mul(g).div(r);i=i.plus(Math.floor(w.mul(f).toNumber())),a=a.plus(Math.floor(w.mul(k?p:f).toNumber()))});let P=Math.floor((0,d.default)(o.toString()).mul(p).mul(g).div(r).toNumber());c.forEach(u=>{S.includes(u)||(a=a.plus(P))});let h={democracyVote:1};return i=i.mul(h.democracyVote),i=i.plus(e.toString()||"0"),a=a.mul(h.democracyVote),a=a.plus(e.toString()||"0"),{currentActionPoints:i.toString(),maxActionPoints:a.toString()}}async getRewards(t,e,o){let c=await this.getStake(t),{potReservedBalance:i,accumulatedRewardPerStake:a,totalStake:p,stakePosition:r}=c;if(!r)return;let[g,S,P,h,u,f,k]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),w=(0,d.default)(g.transferable.toString()).minus(i.toString()),Q=w.gt(0)&&p>0?(0,l.calculate_accumulated_rps)(a.toString(),w.toString(),p.toString()):a.toString(),I=(0,l.calculate_period_number)(S.toString(),o,k),R=(0,l.calculate_period_number)(S.toString(),r.createdAt.toString(),k),Z=(0,l.calculate_rewards)(Q,r.rewardPerStake.toString(),r.stake.toString()),L=this.getCurrentActionPoints(r.votes,r.actionPoints,r.stake,e),M=(0,l.calculate_points)(R,I,h.toString(),u.toString(),L.currentActionPoints,f.toString(),r.accumulatedSlashPoints.toString()),B=(0,l.sigmoid)(M,x,A),W=(()=>{if(!e.length)return;let tt=(0,l.calculate_points)(R,I,h.toString(),u.toString(),L.maxActionPoints.toString(),f.toString(),r.accumulatedSlashPoints.toString());return(0,l.sigmoid)(tt,x,A)})(),q=(0,d.default)(Z).plus(r.accumulatedUnpaidRewards.toString()).plus(r.accumulatedLockedRewards.toString());if((0,d.default)(I).minus(R).lte(P.toString()))return{rewards:"0",payablePercentage:B,extraPayablePercentage:W,constants:{a:x,b:A}};let D=(0,l.calculate_percentage_amount)(q.toString(),B),U=(0,d.default)(r.accumulatedLockedRewards.toString()),H=U.gt(D)?U:(0,d.default)(D);return{rewards:H.div(N).toString(),maxRewards:q.div(N).toString(),allocatedRewardsPercentage:H.div(q).mul(100).toNumber(),points:M,payablePercentage:B,extraPayablePercentage:W,constants:{a:x,b:A}}}};var V=require("polkadot-api");var T=require("@galacticcouncil/descriptors");var K=require("@galacticcouncil/common"),y=require("rxjs");var m=require("rxjs"),s=require("rxjs/operators");function J(n,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let o=()=>(0,m.defer)(()=>(0,m.from)(n._request("system_health",[]))).pipe((0,s.timeout)({first:e}),(0,s.map)(()=>"online"),(0,s.catchError)(()=>(0,m.of)("offline")));return(0,m.of)({state:"offline",delayMs:0}).pipe((0,s.expand)(i=>(0,m.timer)(i.delayMs).pipe((0,s.switchMap)(o),(0,s.map)(a=>({state:a,delayMs:t})))),(0,s.skip)(1),(0,s.map)(i=>i.state),(0,s.distinctUntilChanged)(),(0,s.shareReplay)({bufferSize:1,refCount:!0}))}var{logger:ut}=K.log,_=class n{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe((0,y.map)(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",J(t))}static getInstance(t){return this.instance||(this.instance=new n(t)),this.instance}watched(t,e){return e.pipe((0,y.tap)({error:o=>ut.error(t,o)}),(0,y.shareReplay)({bufferSize:1,refCount:!0}))}};var C=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(T.hydration),this.apiNext=this.client.getTypedApi(T.hydrationNext),this.watcher=_.getInstance(this.client)}};var dt=require("polkadot-api/ws"),pt=require("polkadot-api/logs-provider");var gt=require("polkadot-api/sm-provider");var E=class extends C{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return V.Binary.toText(V.Binary.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:a})=>{let[p,r,g]=a;return{address:p,collectionId:r,itemId:g}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};0&&(module.exports={BIG_10,BIG_BILL,StakingApi,StakingClient});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import X from"buffer";typeof window<"u"&&(window.Buffer=X.Buffer);import{calculate_accumulated_rps as Z,calculate_percentage_amount as tt,calculate_period_number as E,calculate_points as L,calculate_rewards as et,sigmoid as M}from"@galacticcouncil/math-staking";import s from"big.js";var y={none:.1,locked1x:1,locked2x:2,locked3x:3,locked4x:4,locked5x:5,locked6x:6},O=c=>Object.keys(y).includes(c);import{AccountId as G}from"polkadot-api";import{toHex as J}from"@polkadot-api/utils";import{HYDRATION_SS58_PREFIX as K}from"@galacticcouncil/common";function V(c){let t=("modl"+c).padEnd(32,"\0"),e=new TextEncoder().encode(t),n=J(e);return G(K).dec(n)}var P="20000000000000000",k="2000",nt=s(10),W=s(nt.pow(12)),D=class{client;balance;constructor(t,e){this.client=t,this.balance=e}async getPotBalance(){let t=await this.client.getPalletId(),e=V(t);return await this.balance.getBalance(e,0)}async getStakingPosition(t){let[e,n]=await Promise.all([this.client.getStakingPositionsValue(t),this.client.getStakingVotes(t)]);if(!e)return;let l=e.created_at,o=await n.reduce(async(i,[u,a])=>{let d=await i,p=u,m=a.amount,g=a.conviction.type.toLowerCase(),r=await this.client.getReferendumInfo(p);return r&&(r.type==="Approved"||r.type==="Rejected")&&O(g)&&d.push({id:p,amount:m,conviction:g}),d},Promise.resolve([]));return{stake:e.stake,rewardPerStake:e.reward_per_stake,createdAt:l,actionPoints:e.action_points,accumulatedUnpaidRewards:e.accumulated_unpaid_rewards,accumulatedSlashPoints:e.accumulated_slash_points,accumulatedLockedRewards:e.accumulated_locked_rewards,votes:o}}async getStake(t){let e=await this.client.getNFTCollectionId(),[n,l]=await Promise.all([this.client.getStaking(),this.client.getUniques(t,e)]),o=l.find(i=>i)?.itemId;return{totalStake:n?.total_stake,accumulatedRewardPerStake:n?.accumulated_reward_per_stake,potReservedBalance:n?.pot_reserved_balance,positionId:o,stakePosition:o?await this.getStakingPosition(o):void 0}}getCurrentActionPoints(t,e,n,l){let o=s(0),i=s(0),u=y.locked6x,a=s(n.toString()).mul(u),d=100,p=[];t.forEach(r=>{let S=y[r.conviction],f=l.includes(r.id.toString());f&&p.push(r.id.toString());let h=s(r.amount.toString()).mul(d).div(a);o=o.plus(Math.floor(h.mul(S).toNumber())),i=i.plus(Math.floor(h.mul(f?u:S).toNumber()))});let m=Math.floor(s(n.toString()).mul(u).mul(d).div(a).toNumber());l.forEach(r=>{p.includes(r)||(i=i.plus(m))});let g={democracyVote:1};return o=o.mul(g.democracyVote),o=o.plus(e.toString()||"0"),i=i.mul(g.democracyVote),i=i.plus(e.toString()||"0"),{currentActionPoints:o.toString(),maxActionPoints:i.toString()}}async getRewards(t,e,n){let l=await this.getStake(t),{potReservedBalance:o,accumulatedRewardPerStake:i,totalStake:u,stakePosition:a}=l;if(!a)return;let[d,p,m,g,r,S,f]=await Promise.all([this.getPotBalance(),this.client.getPeriodLength(),this.client.getUnclaimablePeriods(),this.client.getTimePointsPerPeriod(),this.client.getTimePointsWeight(),this.client.getActionPointsWeight(),this.client.getSixBlockSince()]),h=s(d.transferable.toString()).minus(o.toString()),F=h.gt(0)&&u>0?Z(i.toString(),h.toString(),u.toString()):i.toString(),b=E(p.toString(),n,f),x=E(p.toString(),a.createdAt.toString(),f),Y=et(F,a.rewardPerStake.toString(),a.stake.toString()),T=this.getCurrentActionPoints(a.votes,a.actionPoints,a.stake,e),I=L(x,b,g.toString(),r.toString(),T.currentActionPoints,S.toString(),a.accumulatedSlashPoints.toString()),A=M(I,P,k),R=(()=>{if(!e.length)return;let j=L(x,b,g.toString(),r.toString(),T.maxActionPoints.toString(),S.toString(),a.accumulatedSlashPoints.toString());return M(j,P,k)})(),_=s(Y).plus(a.accumulatedUnpaidRewards.toString()).plus(a.accumulatedLockedRewards.toString());if(s(b).minus(x).lte(m.toString()))return{rewards:"0",payablePercentage:A,extraPayablePercentage:R,constants:{a:P,b:k}};let B=tt(_.toString(),A),q=s(a.accumulatedLockedRewards.toString()),N=q.gt(B)?q:s(B);return{rewards:N.div(W).toString(),maxRewards:_.div(W).toString(),allocatedRewardsPercentage:N.div(_).mul(100).toNumber(),points:I,payablePercentage:A,extraPayablePercentage:R,constants:{a:P,b:k}}}};import{Binary as $}from"polkadot-api";import{hydration as yt,hydrationNext as Pt}from"@galacticcouncil/descriptors";import{log as gt}from"@galacticcouncil/common";import{map as mt,shareReplay as St,tap as ft}from"rxjs";import{defer as ot,from as it,of as U,timer as at}from"rxjs";import{catchError as rt,distinctUntilChanged as st,expand as ct,map as C,shareReplay as lt,skip as ut,switchMap as dt,timeout as pt}from"rxjs/operators";function H(c,{intervalMs:t=5e3,rpcTimeoutMs:e=1e4}={}){let n=()=>ot(()=>it(c._request("system_health",[]))).pipe(pt({first:e}),C(()=>"online"),rt(()=>U("offline")));return U({state:"offline",delayMs:0}).pipe(ct(o=>at(o.delayMs).pipe(dt(n),C(i=>({state:i,delayMs:t})))),ut(1),C(o=>o.state),st(),lt({bufferSize:1,refCount:!0}))}var{logger:ht}=gt,w=class c{static instance=null;bestBlock$;finalizedBlock$;connection$;constructor(t){this.bestBlock$=this.watched("watcher(bestBlock)",t.getUnsafeApi().query.System.Number.watchValue({at:"best"}).pipe(mt(({value:e})=>e))),this.finalizedBlock$=this.watched("watcher(finalizedBlock)",t.finalizedBlock$),this.connection$=this.watched("watcher(connection)",H(t))}static getInstance(t){return this.instance||(this.instance=new c(t)),this.instance}watched(t,e){return e.pipe(ft({error:n=>ht.error(t,n)}),St({bufferSize:1,refCount:!0}))}};var v=class{client;api;apiNext;watcher;constructor(t){this.client=t,this.api=this.client.getTypedApi(yt),this.apiNext=this.client.getTypedApi(Pt),this.watcher=w.getInstance(this.client)}};import{getWsProvider as te}from"polkadot-api/ws";import{withLogsRecorder as ne}from"polkadot-api/logs-provider";import{getSmProvider as re}from"polkadot-api/sm-provider";var z=class extends v{async getPalletId(){let t=this.api.constants.Staking.PalletId,e=await t();return $.toText($.fromHex(e))}async getPeriodLength(){let t=this.api.constants.Staking.PeriodLength;return await t()}async getUnclaimablePeriods(){let t=this.api.constants.Staking.UnclaimablePeriods;return await t()}async getNFTCollectionId(){let t=this.api.constants.Staking.NFTCollectionId;return await t()}async getStaking(){return await this.api.query.Staking.Staking.getValue()}async getUniques(t,e){return(await this.api.query.Uniques.Account.getEntries(t,e)).map(({keyArgs:i})=>{let[u,a,d]=i;return{address:u,collectionId:a,itemId:d}})}async getStakingPositionsValue(t){return await this.api.query.Staking.Positions.getValue(t)}async getStakingVotes(t){return await this.api.query.Staking.Votes.getValue(t)}async getReferendumInfo(t){return await this.api.query.Referenda.ReferendumInfoFor.getValue(t)}async getTimePointsPerPeriod(){let t=this.api.constants.Staking.TimePointsPerPeriod;return await t()}async getTimePointsWeight(){let t=this.api.constants.Staking.TimePointsWeight;return await t()/1e6}async getActionPointsWeight(){let t=this.api.constants.Staking.ActionPointsWeight;return await t()/1e9}async getSixBlockSince(){return(await this.api.query.Staking.SixSecBlocksSince.getValue()).toString()}};export{nt as BIG_10,W as BIG_BILL,D as StakingApi,z as StakingClient};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const CONVICTIONS: {
|
|
2
|
+
readonly none: 0.1;
|
|
3
|
+
readonly locked1x: 1;
|
|
4
|
+
readonly locked2x: 2;
|
|
5
|
+
readonly locked3x: 3;
|
|
6
|
+
readonly locked4x: 4;
|
|
7
|
+
readonly locked5x: 5;
|
|
8
|
+
readonly locked6x: 6;
|
|
9
|
+
};
|
|
10
|
+
export type TConviction = keyof typeof CONVICTIONS;
|
|
11
|
+
export type TVote = {
|
|
12
|
+
id: number;
|
|
13
|
+
amount: bigint;
|
|
14
|
+
conviction: TConviction;
|
|
15
|
+
};
|
|
16
|
+
export declare const isConviction: (conviction: string) => conviction is TConviction;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function getAccountAddress(seed: string): import("polkadot-api").SS58String;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { TradeOrder } from '../sor';
|
|
2
|
+
import { TxBuilder } from './TxBuilder';
|
|
3
|
+
import { Tx } from './types';
|
|
4
|
+
export declare class OrderTxBuilder extends TxBuilder {
|
|
5
|
+
private _order?;
|
|
6
|
+
private _beneficiary?;
|
|
7
|
+
private _maxRetries;
|
|
8
|
+
private _slippagePct;
|
|
9
|
+
setOrder(order: TradeOrder): this;
|
|
10
|
+
withBeneficiary(beneficiary: string): this;
|
|
11
|
+
withMaxRetries(maxRetries: number): this;
|
|
12
|
+
withSlippage(slippage: number): this;
|
|
13
|
+
private get order();
|
|
14
|
+
private get beneficiary();
|
|
15
|
+
private get maxRetries();
|
|
16
|
+
private get slippagePct();
|
|
17
|
+
build(): Promise<Tx>;
|
|
18
|
+
private buildDcaTx;
|
|
19
|
+
private buildTwapSellTx;
|
|
20
|
+
private buildTwapBuyTx;
|
|
21
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import { Trade } from '../sor';
|
|
2
|
+
import { TxBuilder } from './TxBuilder';
|
|
3
|
+
import { Tx } from './types';
|
|
4
|
+
export declare class TradeTxBuilder extends TxBuilder {
|
|
5
|
+
private _trade?;
|
|
6
|
+
private _beneficiary?;
|
|
7
|
+
private _slippagePct;
|
|
8
|
+
setTrade(trade: Trade): this;
|
|
9
|
+
withBeneficiary(beneficiary: string): this;
|
|
10
|
+
withSlippage(slippage: number): this;
|
|
11
|
+
private get trade();
|
|
12
|
+
private get beneficiary();
|
|
13
|
+
private get slippagePct();
|
|
14
|
+
build(): Promise<Tx>;
|
|
15
|
+
private buildBuyTx;
|
|
16
|
+
private buildSellTx;
|
|
17
|
+
private buildSellAllTx;
|
|
18
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { PolkadotClient } from 'polkadot-api';
|
|
2
|
+
import { PublicClient } from 'viem';
|
|
3
|
+
import { AaveUtils } from '../aave';
|
|
4
|
+
import { Papi } from '../api';
|
|
5
|
+
import { BalanceClient } from '../client';
|
|
6
|
+
import { EvmClient } from '../evm';
|
|
7
|
+
import { Swap } from '../sor';
|
|
8
|
+
import { DryRunResult, Transaction, Tx } from './types';
|
|
9
|
+
export declare abstract class TxBuilder extends Papi {
|
|
10
|
+
protected readonly evm: EvmClient;
|
|
11
|
+
protected readonly evmClient: PublicClient;
|
|
12
|
+
protected readonly balance: BalanceClient;
|
|
13
|
+
protected readonly aaveUtils: AaveUtils;
|
|
14
|
+
constructor(client: PolkadotClient, evm: EvmClient);
|
|
15
|
+
protected wrapTx(name: string, tx: Transaction): Tx;
|
|
16
|
+
protected dispatchWithExtraGas(tx: Transaction): Promise<Transaction>;
|
|
17
|
+
protected dryRun(account: string, tx: Transaction): Promise<DryRunResult>;
|
|
18
|
+
protected isDirectOmnipoolTrade(swaps: Swap[]): boolean;
|
|
19
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { PolkadotClient } from 'polkadot-api';
|
|
2
|
+
import { EvmClient } from '../evm';
|
|
3
|
+
import { Trade, TradeOrder } from '../sor';
|
|
4
|
+
import { TradeTxBuilder } from './TradeTxBuilder';
|
|
5
|
+
import { OrderTxBuilder } from './OrderTxBuilder';
|
|
6
|
+
export declare class TxBuilderFactory {
|
|
7
|
+
private client;
|
|
8
|
+
private evmClient;
|
|
9
|
+
constructor(client: PolkadotClient, evmClient: EvmClient);
|
|
10
|
+
trade(trade: Trade): TradeTxBuilder;
|
|
11
|
+
order(order: TradeOrder): OrderTxBuilder;
|
|
12
|
+
}
|