@reyaxyz/api-sdk 0.18.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/dist/clients/api-client.js +1 -1
  2. package/dist/clients/api-client.js.map +1 -1
  3. package/dist/clients/helpers/exposure.calculator.js +436 -0
  4. package/dist/clients/helpers/exposure.calculator.js.map +1 -0
  5. package/dist/clients/helpers/number.js +13 -0
  6. package/dist/clients/helpers/number.js.map +1 -0
  7. package/dist/clients/helpers/trade.simulation.types.js +3 -0
  8. package/dist/clients/helpers/trade.simulation.types.js.map +1 -0
  9. package/dist/clients/modules/account.js +11 -0
  10. package/dist/clients/modules/account.js.map +1 -1
  11. package/dist/clients/modules/trade.simulation.js +40 -38
  12. package/dist/clients/modules/trade.simulation.js.map +1 -1
  13. package/dist/clients/types.js.map +1 -1
  14. package/dist/index.js +2 -0
  15. package/dist/index.js.map +1 -1
  16. package/dist/types/clients/helpers/exposure.calculator.d.ts +58 -0
  17. package/dist/types/clients/helpers/exposure.calculator.d.ts.map +1 -0
  18. package/dist/types/clients/helpers/number.d.ts +3 -0
  19. package/dist/types/clients/helpers/number.d.ts.map +1 -0
  20. package/dist/types/clients/helpers/trade.simulation.types.d.ts +104 -0
  21. package/dist/types/clients/helpers/trade.simulation.types.d.ts.map +1 -0
  22. package/dist/types/clients/modules/account.d.ts +3 -1
  23. package/dist/types/clients/modules/account.d.ts.map +1 -1
  24. package/dist/types/clients/modules/trade.simulation.d.ts +3 -0
  25. package/dist/types/clients/modules/trade.simulation.d.ts.map +1 -1
  26. package/dist/types/clients/types.d.ts +5 -1
  27. package/dist/types/clients/types.d.ts.map +1 -1
  28. package/dist/types/index.d.ts +2 -0
  29. package/dist/types/index.d.ts.map +1 -1
  30. package/package.json +4 -3
  31. package/src/clients/api-client.ts +1 -1
  32. package/src/clients/helpers/exposure.calculator.ts +792 -0
  33. package/src/clients/helpers/number.ts +8 -0
  34. package/src/clients/helpers/trade.simulation.types.ts +115 -0
  35. package/src/clients/modules/account.ts +11 -0
  36. package/src/clients/modules/trade.simulation.ts +103 -44
  37. package/src/clients/types.ts +8 -1
  38. package/src/index.ts +2 -0
@@ -0,0 +1,8 @@
1
+ import BigNumber from 'bignumber.js';
2
+
3
+ export function amountNormalizer(
4
+ value: BigNumber | number | string,
5
+ decimals: number = 18,
6
+ ): BigNumber {
7
+ return BigNumber(value).div(BigNumber(10).pow(decimals));
8
+ }
@@ -0,0 +1,115 @@
1
+ import BigNumber from 'bignumber.js';
2
+
3
+ export interface MarketStorage {
4
+ market_id: number;
5
+ quote_collateral: string;
6
+ instrument_address: string;
7
+ name: string;
8
+ risk_block_id: number;
9
+ collateral_pool_id: number;
10
+ block_timestamp: number;
11
+ block_number: number;
12
+ }
13
+
14
+ export interface MarketConfiguration {
15
+ market_id: number;
16
+ risk_matrix_index: number;
17
+ max_open_interest: number;
18
+ oracle_node_id: string;
19
+ mtm_window: number;
20
+ dutch_config_lambda: number;
21
+ dutch_config_min_base: number;
22
+ slippage_params_phi: number;
23
+ slippage_params_beta: number;
24
+ block_timestamp: number;
25
+ block_number: number;
26
+ }
27
+
28
+ export type AccountAssetBalance = {
29
+ accountId: number;
30
+ collateral: string;
31
+ amount: number;
32
+ };
33
+
34
+ export interface RiskMultipliersConfiguration {
35
+ collateral_pool_id: number;
36
+ im_multiplier: number;
37
+ mmr_multiplier: number;
38
+ dutch_multiplier: number;
39
+ adl_multiplier: number;
40
+ im_buffer_multiplier: number;
41
+ block_timestamp: number;
42
+ block_number: number;
43
+ }
44
+
45
+ export interface RiskMatrix {
46
+ collateral_pool_id: number;
47
+ risk_block_id: number;
48
+ matrix: BigNumber[][];
49
+ }
50
+
51
+ export interface ExchangeInfo {
52
+ price: number;
53
+ priceHaircut: number;
54
+ autoExchangeDiscount: number;
55
+ tokenAddress: string;
56
+ }
57
+
58
+ export interface PositionInfo {
59
+ base: BigNumber;
60
+ realized_pnl: BigNumber;
61
+ last_price: BigNumber;
62
+ last_timestamp: BigNumber;
63
+ funding_value: BigNumber;
64
+ base_multiplier: BigNumber;
65
+ adl_unwind_price: BigNumber;
66
+ market_id: number;
67
+ }
68
+
69
+ export type PositionInfoMarketConfiguration = PositionInfo & {
70
+ market_configuration: MarketConfiguration;
71
+ };
72
+
73
+ export interface MarginInfo {
74
+ assetAddress: string;
75
+ marginBalance: number;
76
+ realBalance: number;
77
+ initialDelta: number;
78
+ maintenanceDelta: number;
79
+ liquidationDelta: number;
80
+ dutchDelta: number;
81
+ adlDelta: number;
82
+ initialBufferDelta: number;
83
+ liquidationMarginRequirement: number;
84
+ }
85
+
86
+ export interface CollateralInfo {
87
+ netDeposits: number;
88
+ marginBalance: number;
89
+ realBalance: number;
90
+ }
91
+
92
+ export type ExposureCommandState = {
93
+ rootCollateralPoolId: number;
94
+ oraclePrice: number;
95
+ rate: number;
96
+ accountBalancePerAsset: AccountAssetBalance[];
97
+ groupedByCollateral: Record<string, AccountAssetBalance>;
98
+ riskMultipliers: RiskMultipliersConfiguration;
99
+ riskMatrices: RiskMatrix[];
100
+ exchangeInfoPerAsset: ExchangeInfo[];
101
+ positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];
102
+ uniqueTokenAddresses: string[];
103
+ uniqueQuoteCollaterals: string[];
104
+ tokenMarginInfoPerAsset: MarginInfo[];
105
+ realizedPnLSum: BigNumber;
106
+ unrealizedPnLSum: BigNumber;
107
+ };
108
+
109
+ export type TradeSimulationState = {
110
+ feeParameter: BigNumber;
111
+ marketStorage: MarketStorage;
112
+ marketConfiguration: MarketConfiguration;
113
+ exposureDataAccount: ExposureCommandState;
114
+ exposureDataPassivePool: ExposureCommandState;
115
+ };
@@ -9,8 +9,10 @@ import {
9
9
  GetPositionsForMarginAccountResult,
10
10
  GetPositionsHistoryForMarginAccountParams,
11
11
  GetPositionsHistoryForMarginAccountResult,
12
+ GetTransactionSimulationInitialDataParams,
12
13
  } from '../types';
13
14
  import RestClient from './rest';
15
+ import { TradeSimulationState } from '../helpers/trade.simulation.types';
14
16
 
15
17
  export default class AccountClient extends RestClient {
16
18
  /**
@@ -75,4 +77,13 @@ export default class AccountClient extends RestClient {
75
77
  direction: params.direction,
76
78
  });
77
79
  }
80
+
81
+ async getTransactionSimulationInitialData(
82
+ params: GetTransactionSimulationInitialDataParams,
83
+ ): Promise<TradeSimulationState> {
84
+ const uri = `/api/accounts/${params.marginAccountId}/trade-simulation-data`;
85
+ return this.get(uri, {
86
+ marketId: params.marketId,
87
+ });
88
+ }
78
89
  }
@@ -3,56 +3,37 @@ import {
3
3
  TradeSimulationLoadDataParams,
4
4
  TradeSimulationSimulateParams,
5
5
  } from '../types';
6
-
7
- type LoadedData = {
8
- marketData: number;
9
- };
10
-
11
- // The maximum is inclusive and the minimum is inclusive
12
- function getRandomIntInclusive(min: number, max: number) {
13
- min = Math.ceil(min);
14
- max = Math.floor(max);
15
- return Math.floor(Math.random() * (max - min + 1) + min);
16
- }
17
-
18
- const randomHealth = () => {
19
- return Math.random() * 100 > 50
20
- ? 'healthy'
21
- : Math.random() * 100 > 50
22
- ? 'danger'
23
- : 'warning';
24
- };
25
-
26
- function getRandomFloat(min: number, max: number): number {
27
- return Math.random() * (max - min) + min;
28
- }
6
+ import AccountClient from './account';
7
+ import { TradeSimulationState } from '../helpers/trade.simulation.types';
8
+ import { ExposureCommand } from '../helpers/exposure.calculator';
9
+ import BigNumber from 'bignumber.js';
29
10
 
30
11
  export default class TradeSimulationClient {
31
12
  private marketId: number | null = null;
32
13
  private accountId: number | null = null;
33
- private loadedData: LoadedData | null = null;
14
+ private loadedData: TradeSimulationState | null = null;
15
+ private accountClient: AccountClient;
16
+ constructor(accountClient: AccountClient) {
17
+ // Constructor added
18
+ this.accountClient = accountClient;
19
+ }
34
20
 
35
21
  // Method to asynchronously load data based on marketId and accountId
36
22
  async arm(params: TradeSimulationLoadDataParams): Promise<void> {
37
23
  this.marketId = params.marketId;
38
24
  this.accountId = params.marginAccountId;
39
25
 
40
- // Simulate fetching data (@todo replace this with actual data fetching logic)
41
- const marketData = await this.fetchMarketData(
42
- this.marketId,
43
- this.accountId,
44
- );
45
-
46
- // Store the loaded data
47
- this.loadedData = { marketData };
26
+ this.loadedData = await this.fetchMarketData(this.marketId, this.accountId);
48
27
  }
49
28
 
50
29
  private async fetchMarketData(
51
30
  marketId: number,
52
31
  accountId: number,
53
- ): Promise<number> {
54
- await new Promise((resolve) => setTimeout(resolve, 500)); // wait for 500ms
55
- return 1 + marketId + accountId;
32
+ ): Promise<TradeSimulationState> {
33
+ return this.accountClient.getTransactionSimulationInitialData({
34
+ marginAccountId: accountId,
35
+ marketId: marketId,
36
+ });
56
37
  }
57
38
 
58
39
  // Synchronous method to simulate operations based on an amount
@@ -61,17 +42,95 @@ export default class TradeSimulationClient {
61
42
  throw new Error('Data not loaded. Call arm() first.');
62
43
  }
63
44
 
64
- // @todo perform simulation
45
+ const amount = BigNumber(params.amount)
46
+ .div(this.loadedData.exposureDataAccount.oraclePrice)
47
+ .toNumber();
48
+
49
+ const userAccountExposure = new ExposureCommand(
50
+ this.loadedData.exposureDataAccount.rootCollateralPoolId,
51
+ this.loadedData.exposureDataAccount.oraclePrice,
52
+ this.loadedData.exposureDataAccount.rate,
53
+ this.loadedData.exposureDataAccount.accountBalancePerAsset,
54
+ this.loadedData.exposureDataAccount.groupedByCollateral,
55
+ this.loadedData.exposureDataAccount.riskMultipliers,
56
+ this.loadedData.exposureDataAccount.riskMatrices,
57
+ this.loadedData.exposureDataAccount.exchangeInfoPerAsset,
58
+ this.loadedData.exposureDataAccount.positionInfoMarketConfiguration,
59
+ this.loadedData.exposureDataAccount.uniqueTokenAddresses,
60
+ this.loadedData.exposureDataAccount.uniqueQuoteCollaterals,
61
+ this.loadedData.exposureDataAccount.tokenMarginInfoPerAsset,
62
+ this.loadedData.exposureDataAccount.realizedPnLSum,
63
+ this.loadedData.exposureDataAccount.unrealizedPnLSum,
64
+ );
65
+
66
+ const passivePoolExposure = new ExposureCommand(
67
+ this.loadedData.exposureDataPassivePool.rootCollateralPoolId,
68
+ this.loadedData.exposureDataPassivePool.oraclePrice,
69
+ this.loadedData.exposureDataPassivePool.rate,
70
+ this.loadedData.exposureDataPassivePool.accountBalancePerAsset,
71
+ this.loadedData.exposureDataPassivePool.groupedByCollateral,
72
+ this.loadedData.exposureDataPassivePool.riskMultipliers,
73
+ this.loadedData.exposureDataPassivePool.riskMatrices,
74
+ this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,
75
+ this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,
76
+ this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,
77
+ this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,
78
+ this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,
79
+ this.loadedData.exposureDataPassivePool.realizedPnLSum,
80
+ this.loadedData.exposureDataPassivePool.unrealizedPnLSum,
81
+ );
82
+
83
+ const slippage = passivePoolExposure.getSlippage(
84
+ amount,
85
+ this.loadedData.marketConfiguration,
86
+ this.loadedData.marketStorage,
87
+ );
88
+ const estimatedPrice = ExposureCommand.calculateEstimatedPrice(
89
+ this.loadedData.exposureDataPassivePool.oraclePrice,
90
+ slippage,
91
+ );
92
+ const fees = ExposureCommand.calculateFee(
93
+ this.loadedData.exposureDataAccount.oraclePrice,
94
+ amount,
95
+ this.loadedData.feeParameter,
96
+ );
97
+
98
+ const oldMarginInfo = userAccountExposure.getUsdNodeMarginInfo;
99
+
100
+ const newMarginInfo = userAccountExposure.getUsdNodeMarginInfoPostTrade(
101
+ amount,
102
+ this.loadedData.marketStorage.quote_collateral,
103
+ this.loadedData.marketConfiguration,
104
+ );
105
+
106
+ const impliedLeverage = ExposureCommand.calculateImpliedLeverage(
107
+ amount * this.loadedData.exposureDataAccount.oraclePrice,
108
+ oldMarginInfo.marginBalance - oldMarginInfo.initialDelta,
109
+ newMarginInfo.marginBalance - newMarginInfo.initialDelta,
110
+ );
111
+
112
+ const postTradeImr =
113
+ newMarginInfo.marginBalance - newMarginInfo.initialDelta;
114
+
115
+ const liquidationPrice = ExposureCommand.calculateLiquidation(
116
+ newMarginInfo,
117
+ this.loadedData.exposureDataAccount.oraclePrice,
118
+ amount,
119
+ );
120
+
121
+ const marginRatio = ExposureCommand.getMarginRatio(newMarginInfo);
122
+
123
+ const marginRatioHealth = ExposureCommand.evaluateHealthStatus(marginRatio);
65
124
 
66
125
  return {
67
- estimatedPrice: getRandomIntInclusive(1000, 100000) + params.amount,
68
- estimatedSlippage: getRandomFloat(0.00001, 0.05),
69
- fees: getRandomIntInclusive(1000, 100000),
70
- impliedLeverage: getRandomIntInclusive(20, 50),
71
- imr: getRandomIntInclusive(1000, 100000),
72
- liquidationPrice: getRandomIntInclusive(1000, 100000),
73
- marginRatio: getRandomIntInclusive(0, 100),
74
- marginRatioHealth: randomHealth(),
126
+ estimatedPrice: estimatedPrice,
127
+ estimatedSlippage: slippage,
128
+ fees: fees,
129
+ impliedLeverage: impliedLeverage,
130
+ imr: postTradeImr,
131
+ liquidationPrice: liquidationPrice.toNumber(),
132
+ marginRatio: marginRatio,
133
+ marginRatioHealth: marginRatioHealth,
75
134
  } as SimulateTradeEntity;
76
135
  }
77
136
  }
@@ -10,6 +10,7 @@ export enum CandlesResolution {
10
10
 
11
11
  // -- Candles --
12
12
  export interface Candle {
13
+ id: string;
13
14
  startedAt: string;
14
15
  ticker: string;
15
16
  resolution: CandlesResolution;
@@ -21,7 +22,6 @@ export interface Candle {
21
22
  usdVolume: string;
22
23
  trades: number;
23
24
  startingOpenInterest: string;
24
- id: string;
25
25
  }
26
26
 
27
27
  export interface MarketCandlesResponse {
@@ -275,3 +275,10 @@ export type GetLpPoolWithdrawBalanceParams = {
275
275
  };
276
276
 
277
277
  export type GetLpPoolWithdrawBalanceResult = number;
278
+
279
+ // ---- Transaction Simulation ----
280
+
281
+ export type GetTransactionSimulationInitialDataParams = {
282
+ marketId: MarketEntity['id'];
283
+ marginAccountId: MarginAccountEntity['id'];
284
+ };
package/src/index.ts CHANGED
@@ -1,2 +1,4 @@
1
1
  export { ApiClient } from './clients/api-client';
2
2
  export * from './clients/types';
3
+ export * from './clients/helpers/exposure.calculator';
4
+ export * from './clients/helpers/trade.simulation.types';