@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,23 @@
|
|
|
1
|
+
import { Subscription } from 'rxjs';
|
|
2
|
+
import { PoolType, PoolFees, PoolPair } from '../types';
|
|
3
|
+
import { PoolClient } from '../PoolClient';
|
|
4
|
+
import { StableSwapBase } from './StableSwap';
|
|
5
|
+
import { TStableswap } from './types';
|
|
6
|
+
export declare class StableSwapClient extends PoolClient<StableSwapBase> {
|
|
7
|
+
protected poolsData: Map<number, TStableswap>;
|
|
8
|
+
getPoolType(): PoolType;
|
|
9
|
+
private getPoolAddress;
|
|
10
|
+
private getPoolLimits;
|
|
11
|
+
private getPoolAmplification;
|
|
12
|
+
private getPoolTokens;
|
|
13
|
+
isSupported(): Promise<boolean>;
|
|
14
|
+
protected loadPools(): Promise<StableSwapBase[]>;
|
|
15
|
+
getPoolFees(_pair: PoolPair, address: string): Promise<PoolFees>;
|
|
16
|
+
private getDefaultPegs;
|
|
17
|
+
private getRecentPegs;
|
|
18
|
+
private subscribeIssuance;
|
|
19
|
+
private subscribePoolPegs;
|
|
20
|
+
private subscribeBlock;
|
|
21
|
+
protected subscribeUpdates(): Subscription;
|
|
22
|
+
private hasOnRamps;
|
|
23
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { Enum, FixedSizeArray, SizedHex } from 'polkadot-api';
|
|
2
|
+
import { HydrationQueries } from '@galacticcouncil/descriptors';
|
|
3
|
+
export type TStableswap = HydrationQueries['Stableswap']['Pools']['Value'];
|
|
4
|
+
export type TStableswapPeg = HydrationQueries['Stableswap']['PoolPegs']['Value'];
|
|
5
|
+
export type TEmaOracle = HydrationQueries['EmaOracle']['Oracles']['Value'];
|
|
6
|
+
export type TEmaName = SizedHex<8>;
|
|
7
|
+
export type TEmaPair = FixedSizeArray<2, number>;
|
|
8
|
+
export type TEmaPeriod = Enum<{
|
|
9
|
+
LastBlock: undefined;
|
|
10
|
+
Short: undefined;
|
|
11
|
+
TenMinutes: undefined;
|
|
12
|
+
Hour: undefined;
|
|
13
|
+
Day: undefined;
|
|
14
|
+
Week: undefined;
|
|
15
|
+
}>;
|
|
@@ -1,17 +1,27 @@
|
|
|
1
1
|
import type { AssetType } from '../types';
|
|
2
|
+
export type PoolFilter = {
|
|
3
|
+
useOnly?: PoolType[];
|
|
4
|
+
exclude?: PoolType[];
|
|
5
|
+
};
|
|
2
6
|
export declare enum PoolType {
|
|
3
7
|
Aave = "Aave",
|
|
4
8
|
LBP = "LBP",
|
|
5
9
|
Omni = "Omnipool",
|
|
6
10
|
Stable = "Stableswap",
|
|
7
|
-
XYK = "XYK"
|
|
11
|
+
XYK = "XYK",
|
|
12
|
+
HSM = "HSM"
|
|
8
13
|
}
|
|
9
14
|
export declare enum PoolError {
|
|
15
|
+
UnknownError = "UnknownError",
|
|
16
|
+
FacilitatorCapacityExceeded = "FacilitatorCapacityExceeded",
|
|
10
17
|
InsufficientTradingAmount = "InsufficientTradingAmount",
|
|
18
|
+
InsufficientCollateral = "InsufficientCollateral",
|
|
19
|
+
MaxHoldingExceeded = "MaxHoldingExceeded",
|
|
11
20
|
MaxInRatioExceeded = "MaxInRatioExceeded",
|
|
12
21
|
MaxOutRatioExceeded = "MaxOutRatioExceeded",
|
|
13
22
|
TradeNotAllowed = "TradeNotAllowed",
|
|
14
|
-
|
|
23
|
+
MaxBuyBackExceeded = "MaxBuyBackExceeded",
|
|
24
|
+
MaxBuyPriceExceeded = "MaxBuyPriceExceeded"
|
|
15
25
|
}
|
|
16
26
|
export interface PoolPair {
|
|
17
27
|
assetIn: number;
|
|
@@ -32,6 +42,7 @@ export type PoolBase = {
|
|
|
32
42
|
maxOutRatio: bigint;
|
|
33
43
|
minTradingLimit: bigint;
|
|
34
44
|
};
|
|
45
|
+
export type PoolPegs = string[][];
|
|
35
46
|
export interface PoolToken {
|
|
36
47
|
id: number;
|
|
37
48
|
balance: bigint;
|
|
@@ -73,7 +84,7 @@ export interface Pool extends PoolBase {
|
|
|
73
84
|
}
|
|
74
85
|
export interface IPoolCtxProvider {
|
|
75
86
|
getPools(): Promise<PoolBase[]>;
|
|
76
|
-
getPoolFees(
|
|
87
|
+
getPoolFees(poolPair: PoolPair, pool: Pool): Promise<PoolFees>;
|
|
77
88
|
}
|
|
78
89
|
export type Hop = {
|
|
79
90
|
pool: PoolType;
|
|
@@ -10,7 +10,7 @@ export declare class XykPool implements Pool {
|
|
|
10
10
|
maxOutRatio: bigint;
|
|
11
11
|
minTradingLimit: bigint;
|
|
12
12
|
static fromPool(pool: PoolBase): XykPool;
|
|
13
|
-
constructor(
|
|
13
|
+
constructor(pool: PoolBase);
|
|
14
14
|
validatePair(_tokenIn: number, _tokenOut: number): boolean;
|
|
15
15
|
parsePair(tokenIn: number, tokenOut: number): PoolPair;
|
|
16
16
|
validateAndBuy(poolPair: PoolPair, amountOut: bigint, fees: XykPoolFees): BuyCtx;
|
|
@@ -20,4 +20,16 @@ export declare class XykPool implements Pool {
|
|
|
20
20
|
spotPriceInGivenOut(poolPair: PoolPair): bigint;
|
|
21
21
|
spotPriceOutGivenIn(poolPair: PoolPair): bigint;
|
|
22
22
|
calculateTradeFee(amount: bigint, fees: XykPoolFees): bigint;
|
|
23
|
+
/**
|
|
24
|
+
* Normalize spot to runtime decimals.
|
|
25
|
+
*
|
|
26
|
+
* - if `decimalsIn === decimalsOut`: spot already 18dp
|
|
27
|
+
* - if `decimalsIn > decimalsOut`: spot in 18 - (decimalsIn - decimalsOut)
|
|
28
|
+
* - if `decimalsIn < decimalsOut`: spot in 18 + (decimalsOut - decimalsIn)
|
|
29
|
+
*
|
|
30
|
+
* @param spotRaw - raw spot
|
|
31
|
+
* @param decimalsIn - asset in decimals
|
|
32
|
+
* @param decimalsOut - asset out decimals
|
|
33
|
+
*/
|
|
34
|
+
private normalizeSpot;
|
|
23
35
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { Subscription } from 'rxjs';
|
|
2
|
+
import { PoolBase, PoolType, PoolFees, PoolTokenOverride } from '../types';
|
|
3
|
+
import { PoolClient } from '../PoolClient';
|
|
4
|
+
export declare class XykPoolClient extends PoolClient<PoolBase> {
|
|
5
|
+
private decimals;
|
|
6
|
+
getPoolType(): PoolType;
|
|
7
|
+
withOverride(override?: PoolTokenOverride[]): Promise<void>;
|
|
8
|
+
private getPoolLimits;
|
|
9
|
+
isSupported(): Promise<boolean>;
|
|
10
|
+
loadPools(): Promise<PoolBase[]>;
|
|
11
|
+
getPoolFees(): Promise<PoolFees>;
|
|
12
|
+
private getExchangeFee;
|
|
13
|
+
protected subscribeUpdates(): Subscription;
|
|
14
|
+
}
|
|
@@ -1,13 +1,24 @@
|
|
|
1
|
-
import { Hop, IPoolCtxProvider, Pool, PoolBase,
|
|
2
|
-
export type RouterOptions = {
|
|
3
|
-
useOnly: PoolType[];
|
|
4
|
-
};
|
|
1
|
+
import { Hop, IPoolCtxProvider, Pool, PoolBase, PoolFilter } from '../pool';
|
|
5
2
|
export declare class Router {
|
|
6
3
|
private readonly routeSuggester;
|
|
7
|
-
private readonly
|
|
4
|
+
private readonly routeProposals;
|
|
8
5
|
protected readonly ctx: IPoolCtxProvider;
|
|
9
|
-
private
|
|
10
|
-
constructor(ctx: IPoolCtxProvider
|
|
6
|
+
private filter;
|
|
7
|
+
constructor(ctx: IPoolCtxProvider);
|
|
8
|
+
withFilter(filter?: PoolFilter): Promise<void>;
|
|
9
|
+
protected onFilterChanged(): void;
|
|
10
|
+
protected buildRouteKey(assetIn: number, assetOut: number, pools: PoolBase[]): string;
|
|
11
|
+
/**
|
|
12
|
+
* Filter pools given the following contraints:
|
|
13
|
+
*
|
|
14
|
+
* 1) Exclusions always win
|
|
15
|
+
* 2) If useOnly is specified, allow only those types
|
|
16
|
+
* 3) Otherwise everything not excluded passes
|
|
17
|
+
*
|
|
18
|
+
* @param pools - supported & active amms
|
|
19
|
+
* @returns filtered pools
|
|
20
|
+
*/
|
|
21
|
+
protected applyPoolFilter(pools: PoolBase[]): PoolBase[];
|
|
11
22
|
/**
|
|
12
23
|
* List trading pools
|
|
13
24
|
*/
|
|
@@ -23,6 +34,12 @@ export declare class Router {
|
|
|
23
34
|
* List tradeable assets
|
|
24
35
|
*/
|
|
25
36
|
getTradeableAssets(): Promise<number[]>;
|
|
37
|
+
/**
|
|
38
|
+
* Return list of all routeble assets from substrate based pools
|
|
39
|
+
*
|
|
40
|
+
* @returns {number[]} List of all routeable asset ids
|
|
41
|
+
*/
|
|
42
|
+
getRouteableAssets(toAsset: number): Promise<number[]>;
|
|
26
43
|
/**
|
|
27
44
|
* Ckeck if asset pair is valid
|
|
28
45
|
*
|
|
@@ -44,7 +61,8 @@ export declare class Router {
|
|
|
44
61
|
* @param {number} assetOut - assetOut id
|
|
45
62
|
* @param {PoolBase[]} pools - trading pools
|
|
46
63
|
*/
|
|
47
|
-
protected getPaths(assetIn: number, assetOut: number
|
|
64
|
+
protected getPaths(assetIn: number, assetOut: number, pools: PoolBase[]): Hop[][];
|
|
65
|
+
private getProposals;
|
|
48
66
|
/**
|
|
49
67
|
* Check if path is valid -> all edges are valid asset pairs
|
|
50
68
|
*
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { Router } from './Router';
|
|
2
|
+
import { Trade } from './types';
|
|
3
|
+
import { Hop, IPoolCtxProvider } from '../pool';
|
|
4
|
+
import { Amount } from '../types';
|
|
5
|
+
export declare class TradeRouter extends Router {
|
|
6
|
+
private readonly mlr;
|
|
7
|
+
constructor(ctx: IPoolCtxProvider);
|
|
8
|
+
protected onFilterChanged(): void;
|
|
9
|
+
private buildCtxSync;
|
|
10
|
+
private withCtx;
|
|
11
|
+
/**
|
|
12
|
+
* Check whether trade is direct or not
|
|
13
|
+
*
|
|
14
|
+
* @param {Swap[]} swaps - trade route swaps
|
|
15
|
+
* @returns true if direct trade, otherwise false
|
|
16
|
+
*/
|
|
17
|
+
private isDirectTrade;
|
|
18
|
+
/**
|
|
19
|
+
* Find the best sell route
|
|
20
|
+
*
|
|
21
|
+
* @param {SellSwap[]} swaps - sell routes
|
|
22
|
+
* @returns the most beneficial route without errors, if exist
|
|
23
|
+
*/
|
|
24
|
+
private findBestSellRoute;
|
|
25
|
+
/**
|
|
26
|
+
* Route fee range [min,max] in case pool is using dynamic fees
|
|
27
|
+
*
|
|
28
|
+
* @param {Swap[]} swaps - trade routes
|
|
29
|
+
* @returns min & max fee range if swapping through the pool with
|
|
30
|
+
* dynamic fees support
|
|
31
|
+
*/
|
|
32
|
+
private getRouteFeeRange;
|
|
33
|
+
/**
|
|
34
|
+
* Pool fee range [min,max] in case pool is using dynamic fees
|
|
35
|
+
*
|
|
36
|
+
* @param {PoolFees} fees - pool fees
|
|
37
|
+
* @returns min & max fee range if swapping through the pool with
|
|
38
|
+
* dynamic fees support
|
|
39
|
+
*/
|
|
40
|
+
private getPoolFeeRange;
|
|
41
|
+
/**
|
|
42
|
+
* Calculate and return best possible sell trade for assetIn > assetOut
|
|
43
|
+
*
|
|
44
|
+
* @param {number} assetIn - assetIn id
|
|
45
|
+
* @param {number} assetOut - assetOut id
|
|
46
|
+
* @param {bigint} amountIn - amount of assetIn to sell for assetOut
|
|
47
|
+
* @returns best possible sell trade of given token pair
|
|
48
|
+
*/
|
|
49
|
+
getBestSell(assetIn: number, assetOut: number, amountIn: bigint | string): Promise<Trade>;
|
|
50
|
+
/**
|
|
51
|
+
* Calculate and return sell spot price for assetIn > assetOut
|
|
52
|
+
*
|
|
53
|
+
* @param route - sell route
|
|
54
|
+
* @returns sell spot price
|
|
55
|
+
*/
|
|
56
|
+
private getSellSpot;
|
|
57
|
+
/**
|
|
58
|
+
* Calculate and return sell trade for assetIn > assetOut pair
|
|
59
|
+
*
|
|
60
|
+
* @param {number} assetIn - asset in
|
|
61
|
+
* @param {number} assetOut - asset out
|
|
62
|
+
* @param {bigint | string} amountIn - amount of assetIn to sell for assetOut
|
|
63
|
+
* @param {Hop[]} route - explicit route to use for trade
|
|
64
|
+
* @returns sell trade breakdown of given asset pair
|
|
65
|
+
*/
|
|
66
|
+
getSell(assetIn: number, assetOut: number, amountIn: bigint | string, route?: Hop[]): Promise<Trade>;
|
|
67
|
+
/**
|
|
68
|
+
* Calculate and return all possible sells for assetIn > assetOut
|
|
69
|
+
*
|
|
70
|
+
* @param {number} assetIn - asset in
|
|
71
|
+
* @param {number} assetOut - asset out
|
|
72
|
+
* @param {bigint | string} amountIn - amount of assetIn to sell for assetOut
|
|
73
|
+
* @returns possible sell trades of given asset pair
|
|
74
|
+
*/
|
|
75
|
+
getSells(assetIn: number, assetOut: number, amountIn: bigint | string): Promise<Trade[]>;
|
|
76
|
+
/**
|
|
77
|
+
* Build sell trade
|
|
78
|
+
*
|
|
79
|
+
* @param poolsMap - pools map
|
|
80
|
+
* @param route - sell route
|
|
81
|
+
* @returns sell trade
|
|
82
|
+
*/
|
|
83
|
+
private buildSell;
|
|
84
|
+
/**
|
|
85
|
+
* Calculate route spot price
|
|
86
|
+
*
|
|
87
|
+
* @param route - trade route
|
|
88
|
+
* @returns spot price
|
|
89
|
+
*/
|
|
90
|
+
private calculateSpot;
|
|
91
|
+
/**
|
|
92
|
+
* Calculate the output amount of a trade assuming fees are zero
|
|
93
|
+
*
|
|
94
|
+
* @param amountIn - amount of assetIn to sell for assetOut
|
|
95
|
+
* @param route - trade route
|
|
96
|
+
* @param poolsMap - pools map
|
|
97
|
+
* @returns the amount out if fees are zero
|
|
98
|
+
*/
|
|
99
|
+
private calculateDelta0Y;
|
|
100
|
+
/**
|
|
101
|
+
* Calculate and cache the most liquid route
|
|
102
|
+
*
|
|
103
|
+
* To avoid routing through the pools with low liquidity, 0.1% from the
|
|
104
|
+
* most liquid pool asset is used as reference value to determine the
|
|
105
|
+
* sweet spot.
|
|
106
|
+
*
|
|
107
|
+
* @param {number} assetIn - asset in
|
|
108
|
+
* @param {number} assetOut - asset out
|
|
109
|
+
* @param {Ctx} ctx - route ctx
|
|
110
|
+
* @return most liquid route of given asset pair
|
|
111
|
+
*/
|
|
112
|
+
private calculateMostLiquidRoute;
|
|
113
|
+
/**
|
|
114
|
+
* Calculate and return sell route for given path
|
|
115
|
+
*
|
|
116
|
+
* @param amountIn - amount of assetIn to sell for assetOut
|
|
117
|
+
* @param path - current path
|
|
118
|
+
* @param poolsMap - pools map
|
|
119
|
+
* @returns sell route for given path with corresponding pool pairs
|
|
120
|
+
*/
|
|
121
|
+
private toSellSwaps;
|
|
122
|
+
/**
|
|
123
|
+
* Returns the most liquid route
|
|
124
|
+
*
|
|
125
|
+
* @param {number} assetIn - asset in
|
|
126
|
+
* @param {number} assetOut - asset out
|
|
127
|
+
* @return most liquid route of given asset pair
|
|
128
|
+
*/
|
|
129
|
+
getMostLiquidRoute(assetIn: number, assetOut: number): Promise<Hop[]>;
|
|
130
|
+
/**
|
|
131
|
+
* Calculate and return best possible spot price for assetIn > assetOut pair
|
|
132
|
+
*
|
|
133
|
+
* @param {number} assetIn - asset in
|
|
134
|
+
* @param {number} assetOut - asset out
|
|
135
|
+
* @return spot price of given asset pair, or undefined if trade not supported
|
|
136
|
+
*/
|
|
137
|
+
getSpotPrice(assetIn: number, assetOut: number): Promise<Amount | undefined>;
|
|
138
|
+
/**
|
|
139
|
+
* Find best buy route without errors
|
|
140
|
+
*
|
|
141
|
+
* @param swaps - buy routes
|
|
142
|
+
* @returns best buy route if exist, otherwise first one found
|
|
143
|
+
*/
|
|
144
|
+
private findBestBuyRoute;
|
|
145
|
+
/**
|
|
146
|
+
* Calculate and return best possible buy trade for assetIn > assetOut pair
|
|
147
|
+
*
|
|
148
|
+
* @param {number} assetIn - asset in
|
|
149
|
+
* @param {number} assetOut - asset out
|
|
150
|
+
* @param {bigint | string} amountOut - amount of assetOut to buy for assetIn
|
|
151
|
+
* @returns best possible buy trade of given asset pair
|
|
152
|
+
*/
|
|
153
|
+
getBestBuy(assetIn: number, assetOut: number, amountOut: bigint | string): Promise<Trade>;
|
|
154
|
+
/**
|
|
155
|
+
* Calculate and return buy spot price for assetIn > assetOut
|
|
156
|
+
*
|
|
157
|
+
* @param route - buy route
|
|
158
|
+
* @returns buy spot price
|
|
159
|
+
*/
|
|
160
|
+
private getBuySpot;
|
|
161
|
+
/**
|
|
162
|
+
* Calculate and return buy trade for assetIn > assetOut pair
|
|
163
|
+
*
|
|
164
|
+
* @param {number} assetIn - asset in
|
|
165
|
+
* @param {number} assetOut - asset out
|
|
166
|
+
* @param {bigint | string} amountOut - amount of assetOut to buy for assetIn
|
|
167
|
+
* @param {Hop[]} route - explicit route to use for trade
|
|
168
|
+
* @returns buy trade breakdown of given asset pair
|
|
169
|
+
*/
|
|
170
|
+
getBuy(assetIn: number, assetOut: number, amountOut: bigint | string, route?: Hop[]): Promise<Trade>;
|
|
171
|
+
/**
|
|
172
|
+
* Calculate and return all possible buy trades for assetIn > assetOut
|
|
173
|
+
*
|
|
174
|
+
* @param {number} assetIn - asset in
|
|
175
|
+
* @param {number} assetOut - asset out
|
|
176
|
+
* @param {bigint | string} amountOut - amount of assetOut to buy for assetIn
|
|
177
|
+
* @returns possible buy trades of given asset pair
|
|
178
|
+
*/
|
|
179
|
+
getBuys(assetIn: number, assetOut: number, amountOut: bigint | string): Promise<Trade[]>;
|
|
180
|
+
/**
|
|
181
|
+
* Build buy trade
|
|
182
|
+
*
|
|
183
|
+
* @param poolsMap - pools map
|
|
184
|
+
* @param route - buy route
|
|
185
|
+
* @returns buy trade
|
|
186
|
+
*/
|
|
187
|
+
private buildBuy;
|
|
188
|
+
/**
|
|
189
|
+
* Calculates the required input amount for a trade to receive a desired output amount,
|
|
190
|
+
* assuming fees are zero.
|
|
191
|
+
*
|
|
192
|
+
* @param amountOut - amount of assetOut to buy for assetIn
|
|
193
|
+
* @param route - trade route
|
|
194
|
+
* @param poolsMap - pools map
|
|
195
|
+
* @returns the required input amount for a trade if fees are zero
|
|
196
|
+
*/
|
|
197
|
+
private calculateDelta0X;
|
|
198
|
+
/**
|
|
199
|
+
* Calculate and return buy route for given path
|
|
200
|
+
*
|
|
201
|
+
* @param amountOut - amount of assetOut to buy for assetIn
|
|
202
|
+
* @param path - current path
|
|
203
|
+
* @param poolsMap - pools map
|
|
204
|
+
* @returns buy route for given path
|
|
205
|
+
*/
|
|
206
|
+
private toBuySwaps;
|
|
207
|
+
}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { TradeDcaOrder, TradeOrder } from './types';
|
|
2
|
+
import { TradeRouter } from './TradeRouter';
|
|
3
|
+
import { IPoolCtxProvider } from '../pool';
|
|
4
|
+
export type TradeSchedulerOptions = {
|
|
5
|
+
blockTime?: number;
|
|
6
|
+
minBudgetInNative?: bigint;
|
|
7
|
+
};
|
|
8
|
+
export declare class TradeScheduler {
|
|
9
|
+
private readonly schedulerOptions;
|
|
10
|
+
protected readonly router: TradeRouter;
|
|
11
|
+
constructor(ctx: IPoolCtxProvider, options?: TradeSchedulerOptions);
|
|
12
|
+
get blockTime(): number;
|
|
13
|
+
get minOrderBudget(): bigint;
|
|
14
|
+
/**
|
|
15
|
+
* Build a DCA (Dollar Cost Averaging) order
|
|
16
|
+
*
|
|
17
|
+
* @param assetIn - storage key of assetIn
|
|
18
|
+
* @param assetOut - storage key of assetOut
|
|
19
|
+
* @param amountInTotal - order budget
|
|
20
|
+
* @param duration - order duration in ms
|
|
21
|
+
* @param noOfTrades - number of trades within the order
|
|
22
|
+
* @returns - dca trade order
|
|
23
|
+
*/
|
|
24
|
+
getDcaOrder(assetIn: number, assetOut: number, amountInTotal: string, duration: number, noOfTrades?: number): Promise<TradeDcaOrder>;
|
|
25
|
+
/**
|
|
26
|
+
* Calculate minimum order budget (amountIn) required for order
|
|
27
|
+
* execution.
|
|
28
|
+
*
|
|
29
|
+
* @param asset - assetIn id
|
|
30
|
+
* @param decimals - assetIn decimals
|
|
31
|
+
* @returns minimum order budget
|
|
32
|
+
*/
|
|
33
|
+
getMinimumOrderBudget(asset: number, decimals: number): Promise<bigint>;
|
|
34
|
+
/**
|
|
35
|
+
* Calculate maximum number of trades for dca order execution.
|
|
36
|
+
*
|
|
37
|
+
* Single trade execution amount must be at least 20% of
|
|
38
|
+
* minimum order budget.
|
|
39
|
+
*
|
|
40
|
+
* Block period can't exceed total duration.
|
|
41
|
+
*
|
|
42
|
+
* @param amountIn - entering / given budget
|
|
43
|
+
* @param amountInMin - minimal budget to schedule an order
|
|
44
|
+
* @param duration - order duration in ms
|
|
45
|
+
*
|
|
46
|
+
* @returns maximum number of trades to execute the order
|
|
47
|
+
*/
|
|
48
|
+
protected getMaximumTradeCount(amountIn: bigint, amountInMin: bigint, duration: number): number;
|
|
49
|
+
/**
|
|
50
|
+
* Calculate optimal number of trades for order execution.
|
|
51
|
+
*
|
|
52
|
+
* We aim to achieve price impact 0.1% per single execution
|
|
53
|
+
* with at least 3 trades.
|
|
54
|
+
*
|
|
55
|
+
* @param priceImpact - price impact of swap execution (single trade)
|
|
56
|
+
* @returns optimal number of trades to execute the order
|
|
57
|
+
*/
|
|
58
|
+
protected getOptimalTradeCount(priceImpact: number): number;
|
|
59
|
+
/**
|
|
60
|
+
* Build an open budget DCA (Dollar Cost Averaging) order.
|
|
61
|
+
*
|
|
62
|
+
* @param assetIn - storage key of assetIn
|
|
63
|
+
* @param assetOut - storage key of assetOut
|
|
64
|
+
* @param amountIn - per-trade amount
|
|
65
|
+
* @param periodMs - interval between trades in ms
|
|
66
|
+
* @returns - dca trade order with amountIn = 0 (open budget)
|
|
67
|
+
*/
|
|
68
|
+
getOpenBudgetDcaOrder(assetIn: number, assetOut: number, amountIn: string, periodMs: number): Promise<TradeDcaOrder>;
|
|
69
|
+
/**
|
|
70
|
+
* Build a TWAP (Time-Weighted Average Price) sell order
|
|
71
|
+
*
|
|
72
|
+
* @param assetIn - assetIn id
|
|
73
|
+
* @param assetOut - assetOut id
|
|
74
|
+
* @param amountInTotal - order budget
|
|
75
|
+
* @returns twap trade order
|
|
76
|
+
*/
|
|
77
|
+
getTwapSellOrder(assetIn: number, assetOut: number, amountInTotal: string): Promise<TradeOrder>;
|
|
78
|
+
/**
|
|
79
|
+
* Build a TWAP (Time-Weighted Average Price) buy order
|
|
80
|
+
*
|
|
81
|
+
* @param assetIn - assetIn id
|
|
82
|
+
* @param assetOut - assetOut id
|
|
83
|
+
* @param amountInTotal - order budget
|
|
84
|
+
* @returns twap trade order
|
|
85
|
+
*/
|
|
86
|
+
getTwapBuyOrder(assetIn: number, assetOut: number, amountInTotal: string): Promise<TradeOrder>;
|
|
87
|
+
/**
|
|
88
|
+
* Calculate number of trades for twap order execution.
|
|
89
|
+
*
|
|
90
|
+
* We aim to achieve price impact 0.1% per single execution
|
|
91
|
+
* with max execution time 6 hours.
|
|
92
|
+
*
|
|
93
|
+
* @param priceImpact - price impact of swap execution (via single trade)
|
|
94
|
+
* @returns optimal number of trades to execute the order
|
|
95
|
+
*/
|
|
96
|
+
getTwapTradeCount(priceImpact: number): number;
|
|
97
|
+
/**
|
|
98
|
+
* Calculate approx. execution time for twap order.
|
|
99
|
+
*
|
|
100
|
+
* @param tradeCount - number of trades per order
|
|
101
|
+
* @returns unix representation of execution time
|
|
102
|
+
*/
|
|
103
|
+
getTwapExecutionTime(tradeCount: number): number;
|
|
104
|
+
/**
|
|
105
|
+
* Convert unix execution period to block period
|
|
106
|
+
*
|
|
107
|
+
* @param periodMsec - period in miliseconds
|
|
108
|
+
* @returns block execution period
|
|
109
|
+
*/
|
|
110
|
+
private toBlockPeriod;
|
|
111
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export declare const DEFAULT_BLOCK_TIME = 6000;
|
|
2
|
+
export declare const DEFAULT_MIN_BUDGET = 1000000000000000n;
|
|
3
|
+
export declare const TWAP_EXECUTION_INTERVAL = 6;
|
|
4
|
+
export declare const TWAP_MAX_PRICE_IMPACT = -5;
|
|
5
|
+
export declare const TWAP_MAX_DURATION: number;
|
|
6
|
+
export declare const TWAP_TX_MULTIPLIER = 3;
|
|
7
|
+
export declare const DCA_TIME_RESERVE = 0.1;
|
|
8
|
+
export declare const ORDER_MIN_BLOCK_PERIOD = 6;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var Ie=Object.create;var yt=Object.defineProperty;var we=Object.getOwnPropertyDescriptor;var Oe=Object.getOwnPropertyNames;var ve=Object.getPrototypeOf,Te=Object.prototype.hasOwnProperty;var J=(c,t)=>{for(var e in t)yt(c,e,{get:t[e],enumerable:!0})},jt=(c,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Oe(t))!Te.call(c,a)&&a!==e&&yt(c,a,{get:()=>t[a],enumerable:!(s=we(t,a))||s.enumerable});return c};var Et=(c,t,e)=>(e=c!=null?Ie(ve(c)):{},jt(t||!c||!c.__esModule?yt(e,"default",{value:c,enumerable:!0}):e,c)),xe=c=>jt(yt({},"__esModule",{value:!0}),c);var ps={};J(ps,{DCA_TIME_RESERVE:()=>he,DEFAULT_BLOCK_TIME:()=>ge,DEFAULT_MIN_BUDGET:()=>$t,ORDER_MIN_BLOCK_PERIOD:()=>be,Router:()=>rt,TWAP_EXECUTION_INTERVAL:()=>Pt,TWAP_MAX_DURATION:()=>Yt,TWAP_MAX_PRICE_IMPACT:()=>Xt,TWAP_TX_MULTIPLIER:()=>ol,TradeOrderError:()=>Ut,TradeOrderType:()=>Wt,TradeRouteBuilder:()=>W,TradeRouter:()=>ot,TradeScheduler:()=>Rt,TradeType:()=>Vt});module.exports=xe(ps);var lt=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 Be=10,ct=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 lt,n=[];for(n.push([e,""]),i.enqueue(n);i.size()>0;){let r=i.dequeue();if(!r||r.length>Be)continue;let o=r[r.length-1];(s===null||o[0]===s)&&a.push(r),t.get(o[0])?.forEach(u=>{if(this.isNotVisited(u,r)){let m=[...r];m.push(u),i.enqueue(m)}})}return a}findShortestPaths(t,e,s){let a=[],i=new lt,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 u=t.get(l[0]);for(let m of u??[])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 kt(c){let t={};for(let e of c){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}var H=require("@galacticcouncil/math-lbp"),G=class{static getSpotPrice(t,e,s,a,i){return(0,H.get_spot_price)(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i){return(0,H.calculate_in_given_out)(t,e,s,a,i)}static calculateOutGivenIn(t,e,s,a,i){return(0,H.calculate_out_given_in)(t,e,s,a,i)}static calculateLinearWeights(t,e,s,a,i){return(0,H.calculate_linear_weights)(t,e,s,a,i)}static calculatePoolTradeFee(t,e,s){return(0,H.calculate_pool_trade_fee)(t,e,s)}};var Z=require("@galacticcouncil/common");var ft={};J(ft,{withTimeout:()=>Ae});function Ae(c,t,e="timeout"){return new Promise((s,a)=>{let i=setTimeout(()=>a(new Error(e)),t);c.then(n=>{clearTimeout(i),s(n)},n=>{clearTimeout(i),a(n)})})}var C={};J(C,{divSpot:()=>_e,getFraction:()=>Re,mulScaled:()=>Qt,mulSpot:()=>Fe});var Ct=require("@galacticcouncil/common");function Qt(c,t,e,s,a){let i=e+s-a,n=c*t;return i>0?n/BigInt(10)**BigInt(i):i<0?n*BigInt(10)**BigInt(-i):n}function Fe(c,t,e,s){return Qt(c,t,e,Ct.RUNTIME_DECIMALS,s)}function _e(c,t,e,s){if(t===0n)return 0n;let a=BigInt(10)**BigInt(Ct.RUNTIME_DECIMALS+s-e);return c*a/t}function Re(c,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 c*a/(BigInt(100)*s)}var w={};J(w,{FeeUtils:()=>Mt,shiftNeg:()=>ke});var Zt=Et(require("big.js"));var Mt=class c{static toPct(t){let[e,s]=t;return c.safeDivide(e*100,s)}static toRaw(t){let[e,s]=t;return c.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 ke(c,t){let e=(0,Zt.default)(typeof c=="bigint"?c.toString():c);return t===0?e.toString():e.div(Math.pow(10,t)).toString()}var ut={};J(ut,{findNestedKey:()=>Ce,findNestedObj:()=>Me,jsonFormatter:()=>Le});var Ce=(c,t)=>{let e=[];return JSON.stringify(c,(s,a)=>(a&&a[t]&&e.push(a),a)),e[0]},Me=(c,t,e)=>{let s;return JSON.stringify(c,(a,i)=>(i&&i[t]===e&&(s=i),i)),s},Le=(c,t)=>typeof t=="bigint"?t.toString():t;var A={};J(A,{calculateBuyFee:()=>qe,calculateDiffToAvg:()=>De,calculateDiffToRef:()=>He,calculateSellFee:()=>Ne});var N=Et(require("big.js"));function De(c,t){let e=(0,N.default)(c.toString()),s=(0,N.default)(t.toString());return e.minus(s).abs().div(e.plus(s).div(2)).mul(100).round(2).toNumber()}function He(c,t){if(t===0n)return 0;let e=(0,N.default)(c.toString()),s=(0,N.default)(t.toString());return e.minus(s).div(s).mul(100).round(2).toNumber()}function Ne(c,t){if(c===0n)return 0;let e=(0,N.default)(c.toString()),s=(0,N.default)(t.toString());return(0,N.default)(1).minus(s.div(e)).mul(100).round(2).toNumber()}function qe(c,t){if(c===0n)return 0;let e=(0,N.default)(c.toString());return(0,N.default)(t.toString()).div(e).minus(1).mul(100).round(2).toNumber()}var{FeeUtils:te}=w,St=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;fee;repayFeeApply;static fromPool(t){return new c(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=te.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),l=e+r,u=this.calculateInGivenOut(t,l),m=t.balanceIn/this.maxInRatio;return u>m&&i.push("MaxInRatioExceeded"),{amountIn:u,calculatedIn:u,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=te.toPct(this.repayFeeApply?s.repayFee:s.exchangeFee),u=r-o,m=t.balanceOut/this.maxOutRatio;return u>m&&i.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:r,amountOut:u,feePct:l,errors:i}}}calculateInGivenOut(t,e){let s=G.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=G.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=G.getSpotPrice(t.balanceOut.toString(),t.balanceIn.toString(),t.weightOut.toString(),t.weightIn.toString(),Z.big.toBigInt(1,Z.RUNTIME_DECIMALS).toString());return BigInt(e)}spotPriceOutGivenIn(t){let e=G.getSpotPrice(t.balanceIn.toString(),t.balanceOut.toString(),t.weightIn.toString(),t.weightOut.toString(),Z.big.toBigInt(1,Z.RUNTIME_DECIMALS).toString());return BigInt(e)}calculateTradeFee(t,e){let s=G.calculatePoolTradeFee(t.toString(),this.repayFeeApply?e.repayFee[0]:e.exchangeFee[0],this.repayFeeApply?e.repayFee[1]:e.exchangeFee[1]);return BigInt(s)}};var Ye=require("polkadot-api"),vt=require("rxjs");var V=require("rxjs"),R=require("rxjs/operators");var se=require("@galacticcouncil/descriptors");var ee=require("@galacticcouncil/common"),Lt=require("rxjs");var It=require("rxjs"),$=require("rxjs/operators");var{logger:Gs}=ee.log;var Ge=require("polkadot-api/ws"),Ve=require("polkadot-api/logs-provider");var We=require("polkadot-api/sm-provider");var Ue=require("polkadot-api");var ae=require("@galacticcouncil/common"),Ot=require("rxjs"),M=require("rxjs/operators");var{logger:ra}=ae.log;var Xe=require("rxjs");var ie=require("@galacticcouncil/common");var fa={Aave:"AAVE",LBP:"LBP",Omnipool:"OMNI",Stableswap:"STBL",XYK:"XYK",HSM:"HSM"},{logger:Sa}=ie.log;var{withTimeout:La}=ft;var h=require("@galacticcouncil/math-omnipool"),z=Et(require("big.js")),I=class{static calculateSpotPrice(t,e,s,a){return(0,h.calculate_spot_price)(t,e,s,a)}static calculateLrnaSpotPrice(t,e){return(0,h.calculate_lrna_spot_price)(t,e)}static calculateInGivenOut(t,e,s,a,i,n,r,o,l,u){return(0,h.calculate_in_given_out)(t,e,s,a,i,n,r,o,l,u)}static calculateLrnaInGivenOut(t,e,s,a,i,n){return(0,h.calculate_lrna_in_given_out)(t,e,s,a,i,n)}static calculateOutGivenIn(t,e,s,a,i,n,r,o,l,u){return(0,h.calculate_out_given_in)(t,e,s,a,i,n,r,o,l,u)}static calculateOutGivenLrnaIn(t,e,s,a,i,n){return(0,h.calculate_out_given_lrna_in)(t,e,s,a,i,n)}static calculateShares(t,e,s,a){return(0,h.calculate_shares)(t,e,s,a)}static calculateLiquidityOut(t,e,s,a,i,n,r,o){return(0,h.calculate_liquidity_out)(t,e,s,a,i,n,r,o)}static calculateLiquidityLRNAOut(t,e,s,a,i,n,r,o){return(0,h.calculate_liquidity_lrna_out)(t,e,s,a,i,n,r,o)}static calculateCapDifference(t,e,s,a){let i=(0,z.default)(e),n=(0,z.default)(t),r=(0,z.default)(a),o=(0,z.default)(s),l=(0,z.default)(10).pow(18),u=o.div(l);if(i.div(r).lt(u)){let b=u.times(r).minus(i).times(n),d=i.times((0,z.default)(1).minus(u));return b.div(d).toFixed(0)}else return"0"}static calculateLimitHubIn(t,e,s,a){return(0,h.calculate_liquidity_hub_in)(t,e,s,a)}static isSellAllowed(t){return(0,h.is_sell_allowed)(t)}static isBuyAllowed(t){return(0,h.is_buy_allowed)(t)}static isAddLiquidityAllowed(t){return(0,h.is_add_liquidity_allowed)(t)}static isRemoveLiquidityAllowed(t){return(0,h.is_remove_liquidity_allowed)(t)}static recalculateAssetFee(t,e,s,a,i,n,r,o,l,u,m){return(0,h.recalculate_asset_fee)(t,e,s,a,i,n,r,o,l,u,m)}static recalculateProtocolFee(t,e,s,a,i,n,r,o,l,u,m){return(0,h.recalculate_protocol_fee)(t,e,s,a,i,n,r,o,l,u,m)}static verifyAssetCap(t,e,s,a){return(0,h.verify_asset_cap)(t,e,s,a)}};var ne=require("@galacticcouncil/common");var{FeeUtils:q}=w,Tt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;hubAssetId;static fromPool(t){return new c(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:A.calculateBuyFee(a,i),r=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetInEd)&&r.push("InsufficientTradingAmount");let u=t.balanceOut/this.maxOutRatio;e>u&&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=A.calculateSellFee(a,i),r=[],o=I.isSellAllowed(t.tradeableIn),l=I.isBuyAllowed(t.tradeableOut);(!o||!l)&&r.push("TradeNotAllowed"),(e<this.minTradingLimit||a<t.assetOutEd)&&r.push("InsufficientTradingAmount");let u=t.balanceIn/this.maxInRatio;e>u&&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=I.calculateInGivenOut(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?q.toRaw(s.assetFee).toString():"0",s?q.toRaw(s.protocolFee).toString():"0",s?q.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateLrnaInGivenOut(t,e,s){let a=I.calculateLrnaInGivenOut(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?q.toRaw(s.assetFee).toString():"0",s?q.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=I.calculateOutGivenIn(t.balanceIn.toString(),t.hubReservesIn.toString(),t.sharesIn.toString(),t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?q.toRaw(s.assetFee).toString():"0",s?q.toRaw(s.protocolFee).toString():"0",s?q.toRaw(s.maxSlipFee).toString():"0"),i=BigInt(a);return i<0n?0n:i}calculateOutGivenLrnaIn(t,e,s){let a=I.calculateOutGivenLrnaIn(t.balanceOut.toString(),t.hubReservesOut.toString(),t.sharesOut.toString(),e.toString(),s?q.toRaw(s.assetFee).toString():"0",s?q.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=I.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=I.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=I.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=I.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=ne.big.pow10(Math.abs(a));return a>0?t*i:t/i}};var K=require("polkadot-api"),Ke=require("@polkadot-api/utils"),j=require("rxjs"),je=require("@galacticcouncil/common");var{FeeUtils:fi}=w,Si=K.Binary.toHex(K.Binary.fromText("omnipool")),Ii=(0,K.Enum)("Short");var O=require("@galacticcouncil/math-stableswap"),k=class{static getPoolAddress(t){return(0,O.pool_account_name)(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(0,O.calculate_amplification)(t,e,s,a,i)}static calculateInGivenOut(t,e,s,a,i,n,r){return(0,O.calculate_in_given_out)(t,e,s,a,i,n,r)}static calculateAddOneAsset(t,e,s,a,i,n,r){return(0,O.calculate_add_one_asset)(t,e,s,a,i,n,r)}static calculateSharesForAmount(t,e,s,a,i,n,r){return(0,O.calculate_shares_for_amount)(t,e,s,a,i,n,r)}static calculateOutGivenIn(t,e,s,a,i,n,r){return(0,O.calculate_out_given_in)(t,e,s,a,i,n,r)}static calculateLiquidityOutOneAsset(t,e,s,a,i,n,r){return(0,O.calculate_liquidity_out_one_asset)(t,e,s,a,i,n,r)}static calculateShares(t,e,s,a,i,n){return(0,O.calculate_shares)(t,e,s,a,i,n)}static calculateSpotPriceWithFee(t,e,s,a,i,n,r,o){return(0,O.calculate_spot_price_with_fee)(t,e,s,a,i,n,r,o)}static recalculatePegs(t,e,s,a,i,n){let r=(0,O.recalculate_peg)(t,e,s,a,i,n);return JSON.parse(r)}};var dt=require("@galacticcouncil/common");var{FeeUtils:et}=w,st=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;amplification;isRampPeriod;id;fee;totalIssuance;pegs;static fromPool(t){return new c(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:A.calculateBuyFee(a,i),r=[],o=I.isSellAllowed(t.tradeableIn),l=I.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=A.calculateSellFee(a,i),r=[],o=I.isSellAllowed(t.tradeableIn),l=I.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=k.calculateInGivenOut(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?et.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateAddOneAsset(t,e,s){let a=k.calculateAddOneAsset(this.getReserves(),e.toString(),Number(t.assetIn),this.amplification.toString(),this.totalIssuance.toString(),s?et.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateSharesForAmount(t,e,s){let a=k.calculateSharesForAmount(this.getReserves(),Number(t.assetOut),e.toString(),this.amplification.toString(),this.totalIssuance.toString(),s?et.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=k.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=k.calculateOutGivenIn(this.getReserves(),Number(t.assetIn),Number(t.assetOut),e.toString(),this.amplification.toString(),s?et.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateWithdrawOneAsset(t,e,s){let a=k.calculateLiquidityOutOneAsset(this.getReserves(),e.toString(),Number(t.assetOut),this.amplification.toString(),this.totalIssuance.toString(),s?et.toRaw(s.fee).toString():"0",this.getPegs()),i=BigInt(a);return i<0n?0n:i}calculateShares(t,e,s){let a=k.calculateShares(this.getReserves(),this.getAssets(t.assetIn,e),this.amplification.toString(),this.totalIssuance.toString(),s?et.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=k.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,ut.jsonFormatter)}getAssets(t,e){let s={asset_id:Number(t),amount:e.toString()};return JSON.stringify([s],ut.jsonFormatter)}normalizeSpot(t,e,s,a,i){return e?t*dt.big.pow10(dt.RUNTIME_DECIMALS-i):s?t/dt.big.pow10(i-a):t}};var re=require("polkadot-api"),Je=require("@polkadot-api/utils"),Ze=require("@noble/hashes/blake2b"),gt=require("rxjs"),oe=require("@galacticcouncil/common");var{FeeUtils:Ji}=w;var v=require("@galacticcouncil/math-xyk"),X=class{static getSpotPrice(t,e,s){return(0,v.get_spot_price)(t,e,s)}static calculateInGivenOut(t,e,s){return(0,v.calculate_in_given_out)(t,e,s)}static calculateOutGivenIn(t,e,s){return(0,v.calculate_out_given_in)(t,e,s)}static calculatePoolTradeFee(t,e,s){return(0,v.calculate_pool_trade_fee)(t,e,s)}static calculateLiquidityIn(t,e,s){return(0,v.calculate_liquidity_in)(t,e,s)}static calculateSpotPrice(t,e){return(0,v.calculate_spot_price)(t,e)}static calculateSpotPriceWithFee(t,e,s,a){return(0,v.calculate_spot_price_with_fee)(t,e,s,a)}static calculateShares(t,e,s){return(0,v.calculate_shares)(t,e,s)}static calculateLiquidityOutAssetA(t,e,s,a){return(0,v.calculate_liquidity_out_asset_a)(t,e,s,a)}static calculateLiquidityOutAssetB(t,e,s,a){return(0,v.calculate_liquidity_out_asset_b)(t,e,s,a)}};var ce=require("@galacticcouncil/common");var{FeeUtils:le}=w,xt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(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=le.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 u=t.balanceIn/this.maxInRatio;return r>u&&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=le.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 u=t.balanceOut/this.maxOutRatio;return r>u&&o.push("MaxOutRatioExceeded"),{amountIn:e,calculatedOut:a,amountOut:r,feePct:n,errors:o}}calculateInGivenOut(t,e){let s=X.calculateInGivenOut(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}calculateOutGivenIn(t,e){let s=X.calculateOutGivenIn(t.balanceIn.toString(),t.balanceOut.toString(),e.toString()),a=BigInt(s);return a<0n?0n:a}spotPriceInGivenOut(t){let e=X.calculateSpotPrice(t.balanceOut.toString(),t.balanceIn.toString());return this.normalizeSpot(BigInt(e),t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=X.calculateSpotPrice(t.balanceIn.toString(),t.balanceOut.toString());return this.normalizeSpot(BigInt(e),t.decimalsIn,t.decimalsOut)}calculateTradeFee(t,e){let s=X.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=ce.big.pow10(Math.abs(a));return a>0?t*i:t/i}};var es=require("polkadot-api"),ss=require("rxjs");var at=require("@galacticcouncil/common");var Bt=class c{type;address;tokens;maxInRatio;maxOutRatio;minTradingLimit;static fromPool(t){return new c(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.big.toBigInt(1,at.RUNTIME_DECIMALS)}spotPriceOutGivenIn(t){return at.big.toBigInt(1,at.RUNTIME_DECIMALS)}calculateTradeFee(t,e){return 0n}};var ue=require("polkadot-api"),is=require("@polkadot-api/utils"),At=require("rxjs"),ns=require("viem"),Ht=require("@galacticcouncil/common");var{ERC20:Yn}=Ht.erc20;var B=require("@galacticcouncil/math-hsm"),L=class{static calculateCollateralInGivenHollarOut(t,e,s){return(0,B.calculate_collateral_in_given_hollar_out)(t,e,s)}static calculateCollateralOutGivenHollarIn(t,e,s){return(0,B.calculate_collateral_out_given_hollar_in)(t,e,s)}static calculateHollarOutGivenCollateralIn(t,e,s){return(0,B.calculate_hollar_out_given_collateral_in)(t,e,s)}static calculateHollarInGivenCollateralOut(t,e,s){return(0,B.calculate_hollar_in_given_collateral_out)(t,e,s)}static calculateImbalance(t,e,s){return(0,B.calculate_imbalance)(t,e,s)}static calculateBuybackLimit(t,e){return(0,B.calculate_buyback_limit)(t,e)}static calculateBuybackPriceWithFee(t,e,s){return(0,B.calculate_buyback_price_with_fee)(t,e,s)}static calculateMaxPrice(t,e){return(0,B.calculate_max_price)(t,e)}};var F=require("@galacticcouncil/common");var{FeeUtils:it}=w,Ft=class c extends st{hsmAddress;hsmMintCapacity;hollarId;hollarH160;collateralId;collateralBalance;maxBuyPriceCoefficient;maxInHolding;purchaseFee;buyBackFee;buyBackRate;static fromPool(t){return new c(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=L.calculateHollarInGivenCollateralOut(e.toString(),s.toString(),it.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateCollateralInGivenHollarOut(t){let e=this.getCollateralPeg(),s=L.calculateCollateralInGivenHollarOut(t.toString(),JSON.stringify(e),it.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=L.calculateCollateralOutGivenHollarIn(e.toString(),s.toString(),it.toRaw(this.buyBackFee).toString());return BigInt(a)}calculateHollarOutGivenCollateralIn(t){let e=this.getCollateralPeg(),s=L.calculateHollarOutGivenCollateralIn(t.toString(),JSON.stringify(e),it.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=L.calculateImbalance(t.balanceIn.toString(),JSON.stringify(e),t.balanceOut.toString());return BigInt(s)}calculateBuybackLimit(t){let e=this.calculateImbalance(t),s=L.calculateBuybackLimit(e.toString(),it.toRaw(this.buyBackRate).toString());return BigInt(s)}calculateBuyPrice(t,e,s){let a=L.calculateBuybackPriceWithFee(s.toString(),e.toString(),it.toRaw(this.buyBackFee).toString()),[i,n]=JSON.parse(a),r=F.big.pow10(t.decimalsIn+F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(i)*r/BigInt(n)}calculateMaxPrice(t){let e=this.getCollateralPeg(),s=L.calculateMaxPrice(JSON.stringify(e),this.maxBuyPriceCoefficient.toString()),[a,i]=JSON.parse(s),n=F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return BigInt(a)*n/BigInt(i)}spotPriceInGivenOut(t){let e=F.big.toBigInt(1,t.decimalsOut),a=this.calculateInGivenOut(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-t.decimalsOut);return this.normalizeSpotPrice(a,t.decimalsOut,t.decimalsIn)}spotPriceOutGivenIn(t){let e=F.big.toBigInt(1,t.decimalsIn),a=this.calculateOutGivenIn(t,e)*F.big.pow10(F.RUNTIME_DECIMALS-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)?[F.big.toBigInt(1,18).toString(),F.big.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=F.big.pow10(Math.abs(a));return a>0?t*i:t/i}};var Nt=require("polkadot-api"),ls=require("@polkadot-api/utils"),nt=require("rxjs"),cs=require("viem"),qt=require("@galacticcouncil/common");var{FeeUtils:Or}=w,{H160:vr}=qt.h160;var ht=class{static get(t){switch(t.type){case"Aave":return Bt.fromPool(t);case"XYK":return xt.fromPool(t);case"Omnipool":return Tt.fromPool(t);case"LBP":return St.fromPool(t);case"Stableswap":return st.fromPool(t);case"HSM":return Ft.fromPool(t);default:throw new Error("Pool type "+t.type+" is not supported yet")}}};var me=require("@galacticcouncil/common"),Gt=require("rxjs");var _t=class extends Error{constructor(t,e){super(),this.message=`Route from ${t} to ${e} not found in current configuration`,this.name="RouteNotFound"}};var{logger:mo}=me.log;var bt=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 ct,u=p=>{let y=kt(p),f=Object.keys(y),D=f.flatMap(E=>y[E]);return l.buildAndPopulateGraph(f,D)};if(!r&&!o){let p=a.filter(D=>D.tokens.find(E=>E.id===t)||D.tokens.find(E=>E.id===e)),y=u(p),f=l.findPaths(y,t,e);return this.parsePaths(f)}if(r&&o){let p=u(i),y=l.findPaths(p,t,e);return this.parsePaths(y)}let m=r?e:t,b=a.filter(p=>p.tokens.some(y=>y.id===m));if(b.length===0)return[];let d=[...i,...b],S=u(d),g=l.findPaths(S,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 rt=class{routeSuggester;routeProposals;ctx;filter={};constructor(t){this.ctx=t,this.routeSuggester=new bt,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,ht.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}})}};var P=require("@galacticcouncil/common");var Vt=(e=>(e.Buy="Buy",e.Sell="Sell",e))(Vt||{}),Wt=(s=>(s.Dca="Dca",s.TwapSell="TwapSell",s.TwapBuy="TwapBuy",s))(Wt||{}),Ut=(s=>(s.OrderTooSmall="OrderTooSmall",s.OrderTooBig="OrderTooBig",s.OrderImpactTooBig="OrderImpactTooBig",s))(Ut||{});var{FeeUtils:de}=w,ot=class extends rt{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 _t(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?de.toPct(t.min):void 0,a=t.max?de.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(u=>this.toSellSwaps(s,u,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,u=this.getRouteFeeRange(e),m=i?a.tradeFeePct:A.calculateSellFee(o,r),b=C.mulSpot(s.amountIn,n,s.assetInDecimals,a.assetOutDecimals),d=A.calculateDiffToRef(o,b);return{type:"Sell",amountIn:s.amountIn,amountOut:a.amountOut,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:u,priceImpactPct:d,swaps:e,toHuman(){return{type:"Sell",amountIn:P.big.toDecimal(s.amountIn,s.assetInDecimals),amountOut:P.big.toDecimal(a.amountOut,a.assetOutDecimals),spotPrice:P.big.toDecimal(n,P.RUNTIME_DECIMALS),tradeFee:P.big.toDecimal(l,a.assetOutDecimals),tradeFeePct:m,tradeFeeRange:u,priceImpactPct:d,swaps:e.map(S=>S.toHuman())}}}}calculateSpot(t){return t.map(e=>e.spotPrice).reduce((e,s)=>e*s/10n**BigInt(P.RUNTIME_DECIMALS))}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 u=r.calculateOutGivenIn(o,l);a.push(u)}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,y)=>p+y)).sort((g,p)=>p<g?-1:1)[0],u=C.getFraction(l,.1),m=await Promise.all(a.map(g=>this.toSellSwaps(u,g,n))),d=this.findBestSellRoute(m).map(g=>({poolAddress:g.poolAddress,poolId:g?.poolId,pool:g.pool,assetIn:g.assetIn,assetOut:g.assetOut})),S=this.buildRouteKey(t,e,i);return this.mlr.set(S,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"?P.big.toBigInt(t,o.decimalsIn):t;let u=await this.ctx.getPoolFees(o,r),{amountOut:m,calculatedOut:b,feePct:d,errors:S}=r.validateAndSell(o,l,u),g=this.getPoolFeeRange(u,d),p=r.spotPriceOutGivenIn(o),y=C.mulSpot(l,p,o.decimalsIn,o.decimalsOut),f=A.calculateDiffToRef(b,y);a.push({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountIn:l,amountOut:m,calculatedOut:b,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:S,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:P.big.toDecimal(l,o.decimalsIn),amountOut:P.big.toDecimal(m,o.decimalsOut),calculatedOut:P.big.toDecimal(b,o.decimalsOut),spotPrice:P.big.toDecimal(p,P.RUNTIME_DECIMALS),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:S}}})}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:P.RUNTIME_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(u=>this.toBuySwaps(s,u,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,u=this.getRouteFeeRange(e),m=i?a.tradeFeePct:A.calculateBuyFee(o,r),b=C.mulSpot(s.amountOut,n,s.assetOutDecimals,a.assetInDecimals),d;return o===0n?d=-100:d=A.calculateDiffToRef(b,o),{type:"Buy",amountOut:s.amountOut,amountIn:a.amountIn,spotPrice:n,tradeFee:l,tradeFeePct:m,tradeFeeRange:u,priceImpactPct:d,swaps:e,toHuman(){return{type:"Buy",amountOut:P.big.toDecimal(s.amountOut,s.assetOutDecimals),amountIn:P.big.toDecimal(a.amountIn,a.assetInDecimals),spotPrice:P.big.toDecimal(n,P.RUNTIME_DECIMALS),tradeFee:P.big.toDecimal(l,a.assetInDecimals),tradeFeePct:m,tradeFeeRange:u,priceImpactPct:d,swaps:e.map(S=>S.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 u=r.calculateInGivenOut(o,l);a.unshift(u)}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"?P.big.toBigInt(t,o.decimalsOut):t:l=a[0].amountIn;let u=await this.ctx.getPoolFees(o,r),{amountIn:m,calculatedIn:b,feePct:d,errors:S}=r.validateAndBuy(o,l,u),g=this.getPoolFeeRange(u,d),p=r.spotPriceInGivenOut(o),y=C.mulSpot(l,p,o.decimalsOut,o.decimalsIn),f;b===0n?f=-100:f=A.calculateDiffToRef(y,b),a.unshift({...n,assetInDecimals:o.decimalsIn,assetOutDecimals:o.decimalsOut,amountOut:l,amountIn:m,calculatedIn:b,spotPrice:p,tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:S,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:P.big.toDecimal(l,o.decimalsOut),amountIn:P.big.toDecimal(m,o.decimalsIn),calculatedIn:P.big.toDecimal(b,o.decimalsIn),spotPrice:P.big.toDecimal(p,P.RUNTIME_DECIMALS),tradeFeePct:d,tradeFeeRange:g,priceImpactPct:f,errors:S}}})}return a}};var x=require("@galacticcouncil/common");var ge=6e3,$t=1000000000000000n,Pt=6,Xt=-5,Yt=216e5,ol=3,he=.1,be=6;var zt=require("polkadot-api");var W=class{static build(t){return t.map(({assetIn:e,assetOut:s,pool:a,poolId:i})=>a==="Stableswap"?{pool:(0,zt.Enum)("Stableswap",i),asset_in:e,asset_out:s}:{pool:(0,zt.Enum)(a),asset_in:e,asset_out:s})}};var Rt=class{schedulerOptions;router;constructor(t,e={}){this.router=new ot(t),this.router.withFilter({exclude:["HSM"]}),this.schedulerOptions=Object.freeze({blockTime:e.blockTime??6e3,minBudgetInNative:e.minBudgetInNative??$t})}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,u=o[0],m=o[o.length-1],{assetInDecimals:b}=u,{assetOutDecimals:d}=m,S=Math.abs(l),g=await this.getMinimumOrderBudget(t,b),p=this.getOptimalTradeCount(S),y=this.getMaximumTradeCount(r,g,a),f=i||Math.min(p,y),D=Math.round(a/f),E=r/BigInt(f),_=await this.router.getBestSell(t,e,E),Y=r<g,Q=[];Y&&Q.push("OrderTooSmall");let U=_.amountOut*BigInt(f),ye=this.toBlockPeriod(D),fe=_.tradeFee*BigInt(f),Se=W.build(o),Kt={assetIn:t,assetOut:e,errors:Q,maxTradeCount:y,tradeCount:f,tradeFee:fe,tradeImpactPct:_.priceImpactPct,tradePeriod:ye,tradeRoute:Se,type:"Dca"};return{...Kt,amountIn:r,amountOut:U,tradeAmountIn:_.amountIn,tradeAmountOut:_.amountOut,toHuman(){return{...Kt,amountIn:x.big.toDecimal(r,b),amountOut:x.big.toDecimal(U,d),tradeAmountIn:x.big.toDecimal(_.amountIn,b),tradeAmountOut:x.big.toDecimal(_.amountOut,d)}}}}async getMinimumOrderBudget(t,e){if(0===t)return this.minOrderBudget;let s=await this.router.getSpotPrice(0,t);if(s)return C.mulSpot(this.minOrderBudget,s.amount,12,e);let a=await this.router.getSpotPrice(t,0);if(a)return C.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:u}=o,m=await this.getMinimumOrderBudget(t,l),b=i.amountIn<m,d=[];b&&d.push("OrderTooSmall");let S=this.toBlockPeriod(a),g=W.build(n),p={assetIn:t,assetOut:e,errors:d,maxTradeCount:0,tradeCount:0,tradeFee:i.tradeFee,tradeImpactPct:i.priceImpactPct,tradePeriod:S,tradeRoute:g,type:"Dca"};return{...p,amountIn:0n,amountOut:0n,tradeAmountIn:i.amountIn,tradeAmountOut:i.amountOut,toHuman(){return{...p,amountIn:"0",amountOut:"0",tradeAmountIn:x.big.toDecimal(i.amountIn,l),tradeAmountOut:x.big.toDecimal(i.amountOut,u)}}}}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:u}=o,{assetOutDecimals:m}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),S=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestSell(o.assetIn,l.assetOut,S)]),y=d===1,f=i<g,D=p.priceImpactPct<-5,E=[];f||y?E.push("OrderTooSmall"):D&&E.push("OrderImpactTooBig");let _=p.amountOut*BigInt(d),Y=p.tradeFee*BigInt(d),Q=W.build(n),U={assetIn:t,assetOut:e,errors:E,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:Q,type:"TwapSell"};return{...U,amountIn:i,amountOut:_,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:Y,toHuman(){return{...U,amountIn:x.big.toDecimal(i,u),amountOut:x.big.toDecimal(_,m),tradeAmountIn:x.big.toDecimal(p.amountIn,u),tradeAmountOut:x.big.toDecimal(p.amountOut,m),tradeFee:x.big.toDecimal(Y,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:u}=o,{assetOutDecimals:m}=l,b=Math.abs(r),d=this.getTwapTradeCount(b),S=i/BigInt(d),[g,p]=await Promise.all([this.getMinimumOrderBudget(t,u),this.router.getBestBuy(o.assetIn,l.assetOut,S)]),y=p.amountIn*BigInt(d),f=d===1,D=y<g,E=p.priceImpactPct<-5,_=[];D||f?_.push("OrderTooSmall"):E&&_.push("OrderImpactTooBig");let Y=p.tradeFee*BigInt(d),Q=W.build(n),U={assetIn:t,assetOut:e,errors:_,tradeCount:d,tradeImpactPct:p.priceImpactPct,tradePeriod:6,tradeRoute:Q,type:"TwapBuy"};return{...U,amountIn:y,amountOut:i,tradeAmountIn:p.amountIn,tradeAmountOut:p.amountOut,tradeFee:Y,toHuman(){return{...U,amountIn:x.big.toDecimal(y,u),amountOut:x.big.toDecimal(i,m),tradeAmountIn:x.big.toDecimal(p.amountIn,u),tradeAmountOut:x.big.toDecimal(p.amountOut,m),tradeFee:x.big.toDecimal(Y,u)}}}}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)}};0&&(module.exports={DCA_TIME_RESERVE,DEFAULT_BLOCK_TIME,DEFAULT_MIN_BUDGET,ORDER_MIN_BLOCK_PERIOD,Router,TWAP_EXECUTION_INTERVAL,TWAP_MAX_DURATION,TWAP_MAX_PRICE_IMPACT,TWAP_TX_MULTIPLIER,TradeOrderError,TradeOrderType,TradeRouteBuilder,TradeRouter,TradeScheduler,TradeType});
|