@reyaxyz/api-sdk 0.143.2 → 0.144.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.
Files changed (23) hide show
  1. package/README.md +1 -1
  2. package/dist/clients/modules/isolated-order.simulation/index.js +14 -9
  3. package/dist/clients/modules/isolated-order.simulation/index.js.map +1 -1
  4. package/dist/clients/modules/isolated-order.simulation/types.js.map +1 -1
  5. package/dist/clients/modules/trade.simulation/index.js +21 -10
  6. package/dist/clients/modules/trade.simulation/index.js.map +1 -1
  7. package/dist/clients/modules/trade.simulation/types.js.map +1 -1
  8. package/dist/clients/modules/trade.simulation/utils.js +35 -0
  9. package/dist/clients/modules/trade.simulation/utils.js.map +1 -0
  10. package/dist/types/clients/modules/isolated-order.simulation/index.d.ts.map +1 -1
  11. package/dist/types/clients/modules/isolated-order.simulation/types.d.ts +2 -0
  12. package/dist/types/clients/modules/isolated-order.simulation/types.d.ts.map +1 -1
  13. package/dist/types/clients/modules/trade.simulation/index.d.ts.map +1 -1
  14. package/dist/types/clients/modules/trade.simulation/types.d.ts +9 -0
  15. package/dist/types/clients/modules/trade.simulation/types.d.ts.map +1 -1
  16. package/dist/types/clients/modules/trade.simulation/utils.d.ts +8 -0
  17. package/dist/types/clients/modules/trade.simulation/utils.d.ts.map +1 -0
  18. package/package.json +3 -3
  19. package/src/clients/modules/isolated-order.simulation/index.ts +19 -25
  20. package/src/clients/modules/isolated-order.simulation/types.ts +2 -0
  21. package/src/clients/modules/trade.simulation/index.ts +26 -30
  22. package/src/clients/modules/trade.simulation/types.ts +12 -2
  23. package/src/clients/modules/trade.simulation/utils.ts +52 -0
package/README.md CHANGED
@@ -6,5 +6,5 @@
6
6
 
7
7
  | Statements | Branches | Functions | Lines |
8
8
  | --------------------------- | ----------------------- | ------------------------- | ----------------- |
9
- | ![Statements](https://img.shields.io/badge/statements-1.26%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-6.76%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-0.48%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-1.26%25-red.svg?style=flat) |
9
+ | ![Statements](https://img.shields.io/badge/statements-1.23%25-red.svg?style=flat) | ![Branches](https://img.shields.io/badge/branches-6.47%25-red.svg?style=flat) | ![Functions](https://img.shields.io/badge/functions-0.47%25-red.svg?style=flat) | ![Lines](https://img.shields.io/badge/lines-1.24%25-red.svg?style=flat) |
10
10
 
@@ -42,6 +42,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
42
42
  var common_1 = require("@reyaxyz/common");
43
43
  var bignumber_js_1 = __importDefault(require("bignumber.js"));
44
44
  var common_2 = require("@reyaxyz/common");
45
+ var utils_1 = require("../trade.simulation/utils");
45
46
  var IsolatedOrderSimulationClient = /** @class */ (function () {
46
47
  function IsolatedOrderSimulationClient(accountClient) {
47
48
  this.loadedData = null;
@@ -81,24 +82,27 @@ var IsolatedOrderSimulationClient = /** @class */ (function () {
81
82
  };
82
83
  // Synchronous method to simulate operations
83
84
  IsolatedOrderSimulationClient.prototype.simulate = function (params) {
84
- if (!this.loadedData) {
85
+ if (!this.loadedData || !this.marketId) {
85
86
  throw new Error('Data not loaded. Call arm() first.');
86
87
  }
88
+ var oraclePrice = this.loadedData.exposureDataPassivePool.oraclePricePerMarket[this.loadedData.marketConfiguration.market_id];
87
89
  var amount;
88
90
  if (params.fromBase) {
89
91
  amount = params.amount;
90
92
  }
91
93
  else {
92
- amount = (0, bignumber_js_1.default)(params.amount)
93
- .div(this.loadedData.exposureDataPassivePool.oraclePricePerMarket[this.loadedData.marketConfiguration.market_id])
94
- .toNumber();
94
+ amount = (0, bignumber_js_1.default)(params.amount).div(oraclePrice).toNumber();
95
95
  }
96
96
  var userAccountExposure = IsolatedOrderSimulationClient.genExposureCommandObject(this.loadedData.exposureDataAccount);
97
97
  var passivePoolExposure = IsolatedOrderSimulationClient.genExposureCommandObject(this.loadedData.exposureDataPassivePool);
98
98
  var slippage = passivePoolExposure.getSlippage((0, bignumber_js_1.default)(amount).negated().toNumber(), this.loadedData.marketConfiguration, this.loadedData.marketStorage);
99
- var estimatedPrice = common_1.ExposureCommand.calculateEstimatedPrice(this.loadedData.exposureDataPassivePool.oraclePricePerMarket[this.loadedData.marketConfiguration.market_id], slippage);
99
+ var estimatedPrice = common_1.ExposureCommand.calculateEstimatedPrice(oraclePrice, slippage);
100
100
  var amountSize = estimatedPrice * amount;
101
- var fees = common_1.ExposureCommand.calculateFee(this.loadedData.exposureDataPassivePool.oraclePricePerMarket[this.loadedData.marketConfiguration.market_id], amount, this.loadedData.feeParameter);
101
+ var feesV2 = (0, utils_1.computeFee)({
102
+ tradeSimulationState: this.loadedData,
103
+ marketId: this.marketId,
104
+ orderBase: amount,
105
+ });
102
106
  /*
103
107
  amount of margin in rUSD terms that needs to be transferred from the source account to the destination account,
104
108
  this value is equal to absolute size in rUSD terms / leverage
@@ -120,7 +124,7 @@ var IsolatedOrderSimulationClient = /** @class */ (function () {
120
124
  * the market where the trade is being made by the isolated account that is going to be created as part of isolated
121
125
  * trade operation
122
126
  * */
123
- var liquidationPrice = common_1.ExposureCommand.calculateLiquidation(requiredMargin, isolatedLMR, this.loadedData.exposureDataPassivePool.oraclePricePerMarket[this.loadedData.marketConfiguration.market_id], amount);
127
+ var liquidationPrice = common_1.ExposureCommand.calculateLiquidation(requiredMargin, isolatedLMR, oraclePrice, amount);
124
128
  // todo: p1: margin ratio seems to be wrong on ui
125
129
  var marginRatio = common_1.ExposureCommand.getMarginRatio(newMarginInfoSource);
126
130
  var marginRatioHealth = common_1.ExposureCommand.evaluateHealthStatus(marginRatio * 100);
@@ -132,8 +136,9 @@ var IsolatedOrderSimulationClient = /** @class */ (function () {
132
136
  return {
133
137
  estimatedPrice: estimatedPrice,
134
138
  estimatedSlippage: slippage * 100,
135
- fees: fees,
136
- takerFeesPercentage: (0, bignumber_js_1.default)(this.loadedData.feeParameter).toNumber() * 100,
139
+ fees: feesV2.fee,
140
+ takerFeesPercentage: feesV2.feePercentage,
141
+ feesV2: feesV2,
137
142
  liquidationPrice: liquidationPrice.toNumber(),
138
143
  marginRatio: marginRatio * 100,
139
144
  marginRatioHealth: marginRatioHealth,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"/","sources":["clients/modules/isolated-order.simulation/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,0CAMyB;AACzB,8DAAqC;AAQrC,0CAA0D;AAE1D;IAKE,uCAAY,aAA4B;QAJhC,eAAU,GAAgC,IAAI,CAAC;QAE/C,aAAQ,GAAkB,IAAI,CAAC;QAGrC,oBAAoB;QACpB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IAED,qEAAqE;IAC/D,2CAAG,GAAT,UAAU,MAA6C;;;;;;wBACrD,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;wBAChC,KAAA,IAAI,CAAA;wBAAc,qBAAM,IAAI,CAAC,eAAe,CAC1C,MAAM,CAAC,QAAQ,EACf,MAAM,CAAC,eAAe,CACvB,EAAA;;wBAHD,GAAK,UAAU,GAAG,SAGjB,CAAC;;;;;KACH;IAEM,sDAAwB,GAA/B,UACE,oBAA0C;QAE1C,OAAO,IAAI,wBAAe,CACxB,oBAAoB,CAAC,SAAS,EAC9B,oBAAoB,CAAC,oBAAoB,EACzC,oBAAoB,CAAC,oBAAoB,EACzC,oBAAoB,CAAC,sBAAsB,EAC3C,oBAAoB,CAAC,mBAAmB,EACxC,oBAAoB,CAAC,eAAe,EACpC,oBAAoB,CAAC,YAAY,EACjC,oBAAoB,CAAC,oBAAoB,EACzC,oBAAoB,CAAC,+BAA+B,EACpD,oBAAoB,CAAC,oBAAoB,EACzC,oBAAoB,CAAC,sBAAsB,EAC3C,oBAAoB,CAAC,uBAAuB,EAC5C,oBAAoB,CAAC,cAAc,EACnC,oBAAoB,CAAC,gBAAgB,EACrC,oBAAoB,CA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AClB,QAAQ,EAAE,QAAQ;YAClB,eAAe,EAAE,eAAe;SACjC,CAAC;IACJ,CAAC;IAED,mDAAW,GAAX,UAAY,KAAa;QACvB,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACxD,CAAC;QACD,eAAe;QACf,IAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,UAAU,CAAC,uBAAuB,CAAC,oBAAoB,CAAC,QAAQ,CAAC;YACpE,KAAK,CAAC;QACR,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,oBAAoB,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;IAC7E,CAAC;IACH,oCAAC;AAAD,CAAC,AApdD,IAodC","sourcesContent":["import {\n SimulateIsolatedOrderEntity,\n IsolatedOrderSimulationConvertValueParams,\n IsolatedOrderSimulationConvertValueResult,\n IsolatedOrderSimulationLoadDataParams,\n IsolatedOrderSimulationSimulateParams,\n LeverageBoundsAndAvailableMarginResult,\n LeverageBoundsAndAvailableMarginParams,\n} from './types';\nimport AccountClient from '../account';\nimport {\n amountNormalizer,\n ExposureCommand,\n ExposureCommandState,\n RiskMatrix,\n TradeSimulationState,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { EditCollateralAction } from '@reyaxyz/common';\nimport {\n EstimatedPriceParams,\n EstimatedPriceResult,\n TradeSimulationConvertValueEstimatedPriceParams,\n TradeSimulationConvertValueResult,\n} from '../trade.simulation/types';\nimport { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';\n\nexport default class IsolatedOrderSimulationClient {\n private loadedData: TradeSimulationState | null = null;\n private accountClient: AccountClient;\n private marketId: number | null = null;\n\n constructor(accountClient: AccountClient) {\n // Constructor added\n this.accountClient = accountClient;\n }\n\n // Method to asynchronously load data based on marketId and accountId\n async arm(params: IsolatedOrderSimulationLoadDataParams): Promise<void> {\n this.marketId = params.marketId;\n this.loadedData = await this.fetchMarketData(\n params.marketId,\n params.marginAccountId,\n );\n }\n\n static genExposureCommandObject(\n exposureCommandState: ExposureCommandState,\n ): ExposureCommand {\n return new ExposureCommand(\n exposureCommandState.accountId,\n exposureCommandState.rootCollateralPoolId,\n exposureCommandState.oraclePricePerMarket,\n exposureCommandState.accountBalancePerAsset,\n exposureCommandState.groupedByCollateral,\n exposureCommandState.riskMultipliers,\n exposureCommandState.riskMatrices,\n exposureCommandState.exchangeInfoPerAsset,\n exposureCommandState.positionInfoMarketConfiguration,\n exposureCommandState.uniqueTokenAddresses,\n exposureCommandState.uniqueQuoteCollaterals,\n exposureCommandState.tokenMarginInfoPerAsset,\n exposureCommandState.realizedPnLSum,\n exposureCommandState.unrealizedPnLSum,\n exposureCommandState.mtmRpnlSum,\n exposureCommandState.collateralAddressToExchangePrice,\n );\n }\n\n private async fetchMarketData(\n marketId: number,\n accountId: number,\n ): Promise<TradeSimulationState> {\n return this.accountClient.getTransactionSimulationInitialData({\n marginAccountId: accountId,\n marketId: marketId,\n });\n }\n\n // Synchronous method to simulate operations\n simulate(\n params: IsolatedOrderSimulationSimulateParams,\n ): SimulateIsolatedOrderEntity {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n const userAccountExposure =\n IsolatedOrderSimulationClient.genExposureCommandObject(\n this.loadedData.exposureDataAccount,\n );\n\n const passivePoolExposure =\n IsolatedOrderSimulationClient.genExposureCommandObject(\n this.loadedData.exposureDataPassivePool,\n );\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n const amountSize = estimatedPrice * amount;\n\n const fees = ExposureCommand.calculateFee(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n amount,\n this.loadedData.feeParameter,\n );\n\n /*\n amount of margin in rUSD terms that needs to be transferred from the source account to the destination account,\n this value is equal to absolute size in rUSD terms / leverage\n */\n\n const requiredMargin = BigNumber(amountSize)\n .abs()\n .div(BigNumber(params.isolatedPositionLeverage))\n .toNumber();\n\n const editCollateralActions: EditCollateralAction[] =\n userAccountExposure.getEditCollateralActionsToCoverMargin(requiredMargin);\n\n const newMarginInfoSource =\n userAccountExposure.getUsdNodeMarginInfoPostEditCollaterals(\n editCollateralActions,\n );\n\n /*\n * Compute Isolated Account Liquidation Margin Requirement Post Transfer + Trade\n * */\n\n const isolatedLMR = this.calculateIsolatedLMR(amountSize);\n\n /*\n * margin balance of the destination account is the requiredMargin which is expected to be transferred\n * to the destination account that performs the isolated trade\n * the liquidation price in this case is trying to estimate what the liquidation price would be all else equal for\n * the market where the trade is being made by the isolated account that is going to be created as part of isolated\n * trade operation\n * */\n const liquidationPrice = ExposureCommand.calculateLiquidation(\n requiredMargin,\n isolatedLMR,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n amount,\n );\n\n // todo: p1: margin ratio seems to be wrong on ui\n const marginRatio = ExposureCommand.getMarginRatio(newMarginInfoSource);\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const baseSpacing = amountNormalizer(\n this.loadedData.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * estimatedPrice;\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n estimatedPrice: estimatedPrice,\n estimatedSlippage: slippage * 100,\n fees: fees,\n takerFeesPercentage:\n BigNumber(this.loadedData.feeParameter).toNumber() * 100,\n liquidationPrice: liquidationPrice.toNumber(),\n marginRatio: marginRatio * 100,\n marginRatioHealth: marginRatioHealth,\n snappedAmount,\n snappedAmountInBase,\n requiredMargin: requiredMargin,\n editCollateralActions: editCollateralActions,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n maxSlippage: 1,\n } as SimulateIsolatedOrderEntity;\n }\n\n convertValue(\n params: IsolatedOrderSimulationConvertValueParams,\n ): IsolatedOrderSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n if (!params.fromBase)\n return BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n else\n return BigNumber(params.amount)\n .times(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n convertValueEstimatedPrice(\n params: TradeSimulationConvertValueEstimatedPriceParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n const amountForSlippage = params.fromBase\n ? params.amount\n : BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amountForSlippage).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n if (!params.fromBase)\n return BigNumber(params.amount).div(estimatedPrice).toNumber();\n else return BigNumber(params.amount).times(estimatedPrice).toNumber();\n }\n\n customLeverage(): number | null {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n const { customLeverage } = this.loadedData;\n\n return customLeverage;\n }\n\n estimatedPrice(params: EstimatedPriceParams): EstimatedPriceResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(params.amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n\n const price =\n this.loadedData.exposureDataAccount.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ];\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n return {\n estimatedPrice,\n markPrice: price,\n };\n }\n\n roundToBaseSpacing(amount: number, baseSpacing: number): number {\n const snappedAmount = BigNumber(amount)\n .abs()\n .dividedBy(baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(baseSpacing)\n .toNumber();\n\n if (amount < 0) {\n return -snappedAmount;\n }\n return snappedAmount;\n }\n\n amountToSnappedAmount(\n amountInRusd: number,\n spotPrice: number,\n baseSpacing: number,\n ): number {\n const amountInBase = BigNumber(amountInRusd)\n .div(BigNumber(spotPrice))\n .toNumber();\n\n return this.roundToBaseSpacing(amountInBase, baseSpacing) * spotPrice;\n }\n\n calculateIsolatedLMR(isolatedExposure: number): number {\n // todo: p2: consider removing the need to load the entire data just to get a few vars to calc leverage bounds\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n if (!this.loadedData.marketStorage) {\n throw new Error('Market storage not loaded');\n }\n\n // todo: p2: carefully test\n const marketRiskMatrix =\n this.loadedData.exposureDataAccount.riskMatrices.find(\n (riskMatrix: RiskMatrix) => {\n return (\n riskMatrix.risk_block_id ===\n BigNumber(\n String(this.loadedData?.marketStorage.risk_block_id),\n ).toNumber()\n );\n },\n );\n\n if (!marketRiskMatrix) {\n throw new Error('Failed to load risk matrix');\n }\n\n const marketDiagonalRiskParam =\n marketRiskMatrix.matrix[\n this.loadedData.marketConfiguration.risk_matrix_index\n ][this.loadedData.marketConfiguration.risk_matrix_index];\n const isolatedRiskMatrix: BigNumber[][] = [[marketDiagonalRiskParam]];\n const isolatedFilledExposures: BigNumber[] = [BigNumber(isolatedExposure)];\n\n return ExposureCommand.computeLiquidationMarginRequirement(\n isolatedRiskMatrix,\n isolatedFilledExposures,\n );\n }\n\n leverageBoundsAndAvailableMargin({\n amountTradedInRusd,\n }: LeverageBoundsAndAvailableMarginParams): LeverageBoundsAndAvailableMarginResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const spotPrice =\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ];\n const baseSpacing = amountNormalizer(\n this.loadedData.marketConfiguration.base_spacing,\n ).toNumber();\n const snappedAmountInRusd = this.amountToSnappedAmount(\n amountTradedInRusd,\n spotPrice,\n baseSpacing,\n );\n\n /*\n todo: p2: consider introducing buffer to the leverage (e.g. to account for the effect of trade on upnl\n and actually depending on the size of the trade the estimated price would change -> different upnl\n as upnl is calculated against oracle prioce + rpnl is also affected through the fees\n * once the trader knows their trade size (in base & rusd terms), they should be able to toggle isolated trade flow\n * which will prompt the user to choose a desired leverage value\n * 0.1 can be hardcoded to be the min bound\n * to get the maximum bound we need to calculate leverage that can be achieved when IMR is reached for position\n * with 1 rUSD exposure in the market -> max leverage = 1/IMR\n * */\n\n // set max bound\n\n const lmrUnitExposure = this.calculateIsolatedLMR(1);\n\n const imrUnitExposure: BigNumber = amountNormalizer(\n String(this.loadedData.exposureDataAccount.riskMultipliers.im_multiplier),\n ).multipliedBy(lmrUnitExposure);\n\n const maxBound = BigNumber(1).dividedBy(imrUnitExposure).toNumber();\n\n // set min bound\n\n const userAccountExposure =\n IsolatedOrderSimulationClient.genExposureCommandObject(\n this.loadedData.exposureDataAccount,\n );\n\n /*\n max amount of margin in rUSD terms that can be transferred from the source account to the destination account\n that performs the isolated position trade\n */\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const minBound = BigNumber(snappedAmountInRusd)\n .abs()\n .dividedBy(availableMargin)\n .toNumber();\n\n if (minBound > maxBound) {\n throw Error('Min leverage bound higher than max');\n }\n\n return {\n minBound: minBound,\n maxBound: maxBound,\n availableMargin: availableMargin,\n };\n }\n\n updatePrice(price: number): void {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n // update price\n const marketId = this.marketId;\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[marketId] =\n price;\n this.loadedData.exposureDataAccount.oraclePricePerMarket[marketId] = price;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["clients/modules/isolated-order.simulation/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,0CAMyB;AACzB,8DAAqC;AAQrC,0CAA0D;AAC1D,mDAAuD;AAEvD;IAKE,uCAAY,aAA4B;QAJhC,eAAU,GAAgC,IAAI,CAAC;QAE/C,aAAQ,GAAkB,IAAI,CAAC;QAGrC,oBAAoB;QACpB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IAED,qEAAqE;IAC/D,2CAAG,GAAT,UAAU,MAA6C;;;;;;wBACrD,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;wBAChC,KAAA,IAAI,CAAA;wBAAc,qBAAM,IAAI,CAAC,eAAe,CAC1C,MAAM,CAAC,QAAQ,EACf,MAAM,CAAC,eAAe,CACvB,EAAA;;wBAHD,GAAK,UAAU,GA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,CAAC;QAExD,IAAM,QAAQ,GAAG,IAAA,sBAAS,EAAC,mBAAmB,CAAC;aAC5C,GAAG,EAAE;aACL,SAAS,CAAC,eAAe,CAAC;aAC1B,QAAQ,EAAE,CAAC;QAEd,IAAI,QAAQ,GAAG,QAAQ,EAAE,CAAC;YACxB,MAAM,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACpD,CAAC;QAED,OAAO;YACL,QAAQ,EAAE,QAAQ;YAClB,QAAQ,EAAE,QAAQ;YAClB,eAAe,EAAE,eAAe;SACjC,CAAC;IACJ,CAAC;IAED,mDAAW,GAAX,UAAY,KAAa;QACvB,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACxD,CAAC;QACD,eAAe;QACf,IAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,IAAI,CAAC,UAAU,CAAC,uBAAuB,CAAC,oBAAoB,CAAC,QAAQ,CAAC;YACpE,KAAK,CAAC;QACR,IAAI,CAAC,UAAU,CAAC,mBAAmB,CAAC,oBAAoB,CAAC,QAAQ,CAAC,GAAG,KAAK,CAAC;IAC7E,CAAC;IACH,oCAAC;AAAD,CAAC,AA7cD,IA6cC","sourcesContent":["import {\n SimulateIsolatedOrderEntity,\n IsolatedOrderSimulationConvertValueParams,\n IsolatedOrderSimulationConvertValueResult,\n IsolatedOrderSimulationLoadDataParams,\n IsolatedOrderSimulationSimulateParams,\n LeverageBoundsAndAvailableMarginResult,\n LeverageBoundsAndAvailableMarginParams,\n} from './types';\nimport AccountClient from '../account';\nimport {\n amountNormalizer,\n ExposureCommand,\n ExposureCommandState,\n RiskMatrix,\n TradeSimulationState,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { EditCollateralAction } from '@reyaxyz/common';\nimport {\n EstimatedPriceParams,\n EstimatedPriceResult,\n TradeSimulationConvertValueEstimatedPriceParams,\n TradeSimulationConvertValueResult,\n} from '../trade.simulation/types';\nimport { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';\nimport { computeFee } from '../trade.simulation/utils';\n\nexport default class IsolatedOrderSimulationClient {\n private loadedData: TradeSimulationState | null = null;\n private accountClient: AccountClient;\n private marketId: number | null = null;\n\n constructor(accountClient: AccountClient) {\n // Constructor added\n this.accountClient = accountClient;\n }\n\n // Method to asynchronously load data based on marketId and accountId\n async arm(params: IsolatedOrderSimulationLoadDataParams): Promise<void> {\n this.marketId = params.marketId;\n this.loadedData = await this.fetchMarketData(\n params.marketId,\n params.marginAccountId,\n );\n }\n\n static genExposureCommandObject(\n exposureCommandState: ExposureCommandState,\n ): ExposureCommand {\n return new ExposureCommand(\n exposureCommandState.accountId,\n exposureCommandState.rootCollateralPoolId,\n exposureCommandState.oraclePricePerMarket,\n exposureCommandState.accountBalancePerAsset,\n exposureCommandState.groupedByCollateral,\n exposureCommandState.riskMultipliers,\n exposureCommandState.riskMatrices,\n exposureCommandState.exchangeInfoPerAsset,\n exposureCommandState.positionInfoMarketConfiguration,\n exposureCommandState.uniqueTokenAddresses,\n exposureCommandState.uniqueQuoteCollaterals,\n exposureCommandState.tokenMarginInfoPerAsset,\n exposureCommandState.realizedPnLSum,\n exposureCommandState.unrealizedPnLSum,\n exposureCommandState.mtmRpnlSum,\n exposureCommandState.collateralAddressToExchangePrice,\n );\n }\n\n private async fetchMarketData(\n marketId: number,\n accountId: number,\n ): Promise<TradeSimulationState> {\n return this.accountClient.getTransactionSimulationInitialData({\n marginAccountId: accountId,\n marketId: marketId,\n });\n }\n\n // Synchronous method to simulate operations\n simulate(\n params: IsolatedOrderSimulationSimulateParams,\n ): SimulateIsolatedOrderEntity {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const oraclePrice =\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ];\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount).div(oraclePrice).toNumber();\n }\n\n const userAccountExposure =\n IsolatedOrderSimulationClient.genExposureCommandObject(\n this.loadedData.exposureDataAccount,\n );\n\n const passivePoolExposure =\n IsolatedOrderSimulationClient.genExposureCommandObject(\n this.loadedData.exposureDataPassivePool,\n );\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n oraclePrice,\n slippage,\n );\n\n const amountSize = estimatedPrice * amount;\n\n const feesV2 = computeFee({\n tradeSimulationState: this.loadedData,\n marketId: this.marketId,\n orderBase: amount,\n });\n\n /*\n amount of margin in rUSD terms that needs to be transferred from the source account to the destination account,\n this value is equal to absolute size in rUSD terms / leverage\n */\n\n const requiredMargin = BigNumber(amountSize)\n .abs()\n .div(BigNumber(params.isolatedPositionLeverage))\n .toNumber();\n\n const editCollateralActions: EditCollateralAction[] =\n userAccountExposure.getEditCollateralActionsToCoverMargin(requiredMargin);\n\n const newMarginInfoSource =\n userAccountExposure.getUsdNodeMarginInfoPostEditCollaterals(\n editCollateralActions,\n );\n\n /*\n * Compute Isolated Account Liquidation Margin Requirement Post Transfer + Trade\n * */\n\n const isolatedLMR = this.calculateIsolatedLMR(amountSize);\n\n /*\n * margin balance of the destination account is the requiredMargin which is expected to be transferred\n * to the destination account that performs the isolated trade\n * the liquidation price in this case is trying to estimate what the liquidation price would be all else equal for\n * the market where the trade is being made by the isolated account that is going to be created as part of isolated\n * trade operation\n * */\n const liquidationPrice = ExposureCommand.calculateLiquidation(\n requiredMargin,\n isolatedLMR,\n oraclePrice,\n amount,\n );\n\n // todo: p1: margin ratio seems to be wrong on ui\n const marginRatio = ExposureCommand.getMarginRatio(newMarginInfoSource);\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const baseSpacing = amountNormalizer(\n this.loadedData.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * estimatedPrice;\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n estimatedPrice: estimatedPrice,\n estimatedSlippage: slippage * 100,\n fees: feesV2.fee,\n takerFeesPercentage: feesV2.feePercentage,\n feesV2,\n liquidationPrice: liquidationPrice.toNumber(),\n marginRatio: marginRatio * 100,\n marginRatioHealth: marginRatioHealth,\n snappedAmount,\n snappedAmountInBase,\n requiredMargin: requiredMargin,\n editCollateralActions: editCollateralActions,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n maxSlippage: 1,\n };\n }\n\n convertValue(\n params: IsolatedOrderSimulationConvertValueParams,\n ): IsolatedOrderSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n if (!params.fromBase)\n return BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n else\n return BigNumber(params.amount)\n .times(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n convertValueEstimatedPrice(\n params: TradeSimulationConvertValueEstimatedPriceParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n const amountForSlippage = params.fromBase\n ? params.amount\n : BigNumber(params.amount)\n .div(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n )\n .toNumber();\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amountForSlippage).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n if (!params.fromBase)\n return BigNumber(params.amount).div(estimatedPrice).toNumber();\n else return BigNumber(params.amount).times(estimatedPrice).toNumber();\n }\n\n customLeverage(): number | null {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n const { customLeverage } = this.loadedData;\n\n return customLeverage;\n }\n\n estimatedPrice(params: EstimatedPriceParams): EstimatedPriceResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const passivePoolExposure = new ExposureCommand(\n this.loadedData.exposureDataPassivePool.accountId,\n this.loadedData.exposureDataPassivePool.rootCollateralPoolId,\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket,\n this.loadedData.exposureDataPassivePool.accountBalancePerAsset,\n this.loadedData.exposureDataPassivePool.groupedByCollateral,\n this.loadedData.exposureDataPassivePool.riskMultipliers,\n this.loadedData.exposureDataPassivePool.riskMatrices,\n this.loadedData.exposureDataPassivePool.exchangeInfoPerAsset,\n this.loadedData.exposureDataPassivePool.positionInfoMarketConfiguration,\n this.loadedData.exposureDataPassivePool.uniqueTokenAddresses,\n this.loadedData.exposureDataPassivePool.uniqueQuoteCollaterals,\n this.loadedData.exposureDataPassivePool.tokenMarginInfoPerAsset,\n this.loadedData.exposureDataPassivePool.realizedPnLSum,\n this.loadedData.exposureDataPassivePool.unrealizedPnLSum,\n this.loadedData.exposureDataPassivePool.mtmRpnlSum,\n this.loadedData.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(params.amount).negated().toNumber(),\n this.loadedData.marketConfiguration,\n this.loadedData.marketStorage,\n );\n\n const price =\n this.loadedData.exposureDataAccount.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ];\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ],\n slippage,\n );\n\n return {\n estimatedPrice,\n markPrice: price,\n };\n }\n\n roundToBaseSpacing(amount: number, baseSpacing: number): number {\n const snappedAmount = BigNumber(amount)\n .abs()\n .dividedBy(baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(baseSpacing)\n .toNumber();\n\n if (amount < 0) {\n return -snappedAmount;\n }\n return snappedAmount;\n }\n\n amountToSnappedAmount(\n amountInRusd: number,\n spotPrice: number,\n baseSpacing: number,\n ): number {\n const amountInBase = BigNumber(amountInRusd)\n .div(BigNumber(spotPrice))\n .toNumber();\n\n return this.roundToBaseSpacing(amountInBase, baseSpacing) * spotPrice;\n }\n\n calculateIsolatedLMR(isolatedExposure: number): number {\n // todo: p2: consider removing the need to load the entire data just to get a few vars to calc leverage bounds\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n if (!this.loadedData.marketStorage) {\n throw new Error('Market storage not loaded');\n }\n\n // todo: p2: carefully test\n const marketRiskMatrix =\n this.loadedData.exposureDataAccount.riskMatrices.find(\n (riskMatrix: RiskMatrix) => {\n return (\n riskMatrix.risk_block_id ===\n BigNumber(\n String(this.loadedData?.marketStorage.risk_block_id),\n ).toNumber()\n );\n },\n );\n\n if (!marketRiskMatrix) {\n throw new Error('Failed to load risk matrix');\n }\n\n const marketDiagonalRiskParam =\n marketRiskMatrix.matrix[\n this.loadedData.marketConfiguration.risk_matrix_index\n ][this.loadedData.marketConfiguration.risk_matrix_index];\n const isolatedRiskMatrix: BigNumber[][] = [[marketDiagonalRiskParam]];\n const isolatedFilledExposures: BigNumber[] = [BigNumber(isolatedExposure)];\n\n return ExposureCommand.computeLiquidationMarginRequirement(\n isolatedRiskMatrix,\n isolatedFilledExposures,\n );\n }\n\n leverageBoundsAndAvailableMargin({\n amountTradedInRusd,\n }: LeverageBoundsAndAvailableMarginParams): LeverageBoundsAndAvailableMarginResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const spotPrice =\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[\n this.loadedData.marketConfiguration.market_id\n ];\n const baseSpacing = amountNormalizer(\n this.loadedData.marketConfiguration.base_spacing,\n ).toNumber();\n const snappedAmountInRusd = this.amountToSnappedAmount(\n amountTradedInRusd,\n spotPrice,\n baseSpacing,\n );\n\n /*\n todo: p2: consider introducing buffer to the leverage (e.g. to account for the effect of trade on upnl\n and actually depending on the size of the trade the estimated price would change -> different upnl\n as upnl is calculated against oracle prioce + rpnl is also affected through the fees\n * once the trader knows their trade size (in base & rusd terms), they should be able to toggle isolated trade flow\n * which will prompt the user to choose a desired leverage value\n * 0.1 can be hardcoded to be the min bound\n * to get the maximum bound we need to calculate leverage that can be achieved when IMR is reached for position\n * with 1 rUSD exposure in the market -> max leverage = 1/IMR\n * */\n\n // set max bound\n\n const lmrUnitExposure = this.calculateIsolatedLMR(1);\n\n const imrUnitExposure: BigNumber = amountNormalizer(\n String(this.loadedData.exposureDataAccount.riskMultipliers.im_multiplier),\n ).multipliedBy(lmrUnitExposure);\n\n const maxBound = BigNumber(1).dividedBy(imrUnitExposure).toNumber();\n\n // set min bound\n\n const userAccountExposure =\n IsolatedOrderSimulationClient.genExposureCommandObject(\n this.loadedData.exposureDataAccount,\n );\n\n /*\n max amount of margin in rUSD terms that can be transferred from the source account to the destination account\n that performs the isolated position trade\n */\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const minBound = BigNumber(snappedAmountInRusd)\n .abs()\n .dividedBy(availableMargin)\n .toNumber();\n\n if (minBound > maxBound) {\n throw Error('Min leverage bound higher than max');\n }\n\n return {\n minBound: minBound,\n maxBound: maxBound,\n availableMargin: availableMargin,\n };\n }\n\n updatePrice(price: number): void {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n // update price\n const marketId = this.marketId;\n this.loadedData.exposureDataPassivePool.oraclePricePerMarket[marketId] =\n price;\n this.loadedData.exposureDataAccount.oraclePricePerMarket[marketId] = price;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"/","sources":["clients/modules/isolated-order.simulation/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n MarginAccountEntity,\n MarketEntity,\n EditCollateralAction,\n} from '@reyaxyz/common';\n\nexport type IsolatedOrderSimulationLoadDataParams = {\n marketId: MarketEntity['id'];\n marginAccountId: MarginAccountEntity['id'];\n};\n\nexport type IsolatedOrderSimulationSimulateParams = {\n amount: number; // position size in rUSD / base terms, + for long | - for short\n isolatedPositionLeverage: number; // leverage chosen for isolated position trade\n fromBase?: boolean;\n};\n\nexport type IsolatedOrderSimulationConvertValueParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type SimulateIsolatedOrderEntity = {\n liquidationPrice: number;\n fees: number;\n takerFeesPercentage: number;\n estimatedPrice: number;\n estimatedSlippage: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n snappedAmount: number;\n snappedAmountInBase: number;\n requiredMargin: number;\n editCollateralActions: EditCollateralAction[];\n maxSlippage: number;\n xpEarnRange?: {\n min: number;\n max: number;\n };\n};\n\nexport type IsolatedOrderSimulationConvertValueResult = number;\n\nexport type LeverageBoundsAndAvailableMarginResult = {\n minBound: number;\n maxBound: number;\n availableMargin: number;\n};\n\nexport type LeverageBoundsAndAvailableMarginParams = {\n // Note, this amount is not expected to be snapped\n amountTradedInRusd: number;\n};\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"/","sources":["clients/modules/isolated-order.simulation/types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n MarginAccountEntity,\n MarketEntity,\n EditCollateralAction,\n} from '@reyaxyz/common';\nimport { SimulateTradeFeeEntity } from '../trade.simulation/types';\n\nexport type IsolatedOrderSimulationLoadDataParams = {\n marketId: MarketEntity['id'];\n marginAccountId: MarginAccountEntity['id'];\n};\n\nexport type IsolatedOrderSimulationSimulateParams = {\n amount: number; // position size in rUSD / base terms, + for long | - for short\n isolatedPositionLeverage: number; // leverage chosen for isolated position trade\n fromBase?: boolean;\n};\n\nexport type IsolatedOrderSimulationConvertValueParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type SimulateIsolatedOrderEntity = {\n liquidationPrice: number;\n fees: number;\n takerFeesPercentage: number;\n feesV2: SimulateTradeFeeEntity;\n estimatedPrice: number;\n estimatedSlippage: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n snappedAmount: number;\n snappedAmountInBase: number;\n requiredMargin: number;\n editCollateralActions: EditCollateralAction[];\n maxSlippage: number;\n xpEarnRange?: {\n min: number;\n max: number;\n };\n};\n\nexport type IsolatedOrderSimulationConvertValueResult = number;\n\nexport type LeverageBoundsAndAvailableMarginResult = {\n minBound: number;\n maxBound: number;\n availableMargin: number;\n};\n\nexport type LeverageBoundsAndAvailableMarginParams = {\n // Note, this amount is not expected to be snapped\n amountTradedInRusd: number;\n};\n"]}
@@ -42,6 +42,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
42
42
  var common_1 = require("@reyaxyz/common");
43
43
  var bignumber_js_1 = __importDefault(require("bignumber.js"));
44
44
  var common_2 = require("@reyaxyz/common");
45
+ var utils_1 = require("./utils");
45
46
  var TradeSimulationClient = /** @class */ (function () {
46
47
  function TradeSimulationClient(accountClient) {
47
48
  this.marketId = null;
@@ -86,18 +87,17 @@ var TradeSimulationClient = /** @class */ (function () {
86
87
  };
87
88
  // Synchronous method to simulate operations based on an amount
88
89
  TradeSimulationClient.prototype.simulate = function (params) {
89
- if (!this.loadedData) {
90
+ if (!this.loadedData || !this.marketId) {
90
91
  throw new Error('Data not loaded. Call arm() first.');
91
92
  }
92
93
  var _a = this.loadedData, tradeSimulationState = _a.tradeSimulationState, userAccountExposure = _a.userAccountExposure, passivePoolExposure = _a.passivePoolExposure;
94
+ var oraclePrice = tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[tradeSimulationState.marketConfiguration.market_id];
93
95
  var amount;
94
96
  if (params.fromBase) {
95
97
  amount = params.amount;
96
98
  }
97
99
  else {
98
- amount = (0, bignumber_js_1.default)(params.amount)
99
- .div(tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[tradeSimulationState.marketConfiguration.market_id])
100
- .toNumber();
100
+ amount = (0, bignumber_js_1.default)(params.amount).div(oraclePrice).toNumber();
101
101
  }
102
102
  /*
103
103
  max amount of margin in rUSD terms that can be transferred from the source account to the destination account
@@ -106,8 +106,12 @@ var TradeSimulationClient = /** @class */ (function () {
106
106
  var availableMargin = userAccountExposure.getUsdNodeMarginInfo.initialDelta;
107
107
  var marginBalance = userAccountExposure.getUsdNodeMarginInfo.marginBalance;
108
108
  var slippage = passivePoolExposure.getSlippage((0, bignumber_js_1.default)(amount).negated().toNumber(), tradeSimulationState.marketConfiguration, tradeSimulationState.marketStorage);
109
- var estimatedPrice = common_1.ExposureCommand.calculateEstimatedPrice(tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[tradeSimulationState.marketConfiguration.market_id], slippage);
110
- var fees = common_1.ExposureCommand.calculateFee(tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[tradeSimulationState.marketConfiguration.market_id], amount, tradeSimulationState.feeParameter);
109
+ var estimatedPrice = common_1.ExposureCommand.calculateEstimatedPrice(oraclePrice, slippage);
110
+ var feesV2 = (0, utils_1.computeFee)({
111
+ tradeSimulationState: tradeSimulationState,
112
+ marketId: this.marketId,
113
+ orderBase: amount,
114
+ });
111
115
  var _b = userAccountExposure.getUsdNodeMarginInfoPostTrade(amount, tradeSimulationState.marketStorage.quote_collateral, tradeSimulationState.marketConfiguration, tradeSimulationState.marketStorage.risk_block_id), newMarginInfo = _b.usdNodeMarginInfo, tokenMarginInfoPerAsset = _b.tokenMarginInfoPerAsset, positionInfoMarketConfiguration = _b.positionInfoMarketConfiguration;
112
116
  var newQuoteTokenMarginInfo = tokenMarginInfoPerAsset.find(function (marginInfo) {
113
117
  return (marginInfo.assetAddress ===
@@ -126,7 +130,7 @@ var TradeSimulationClient = /** @class */ (function () {
126
130
  * */
127
131
  var requiredMargin = newQuoteTokenMarginInfo.marginBalance -
128
132
  newQuoteTokenMarginInfo.initialDelta;
129
- var liquidationPrice = common_1.ExposureCommand.calculateLiquidation(newMarginInfo.marginBalance, newQuoteTokenMarginInfo.liquidationMarginRequirement, tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[tradeSimulationState.marketConfiguration.market_id], (0, bignumber_js_1.default)((positionInfo === null || positionInfo === void 0 ? void 0 : positionInfo.base) || 0).toNumber());
133
+ var liquidationPrice = common_1.ExposureCommand.calculateLiquidation(newMarginInfo.marginBalance, newQuoteTokenMarginInfo.liquidationMarginRequirement, oraclePrice, (0, bignumber_js_1.default)((positionInfo === null || positionInfo === void 0 ? void 0 : positionInfo.base) || 0).toNumber());
130
134
  var marginRatio = common_1.ExposureCommand.getMarginRatio(newMarginInfo);
131
135
  var marginRatioHealth = common_1.ExposureCommand.evaluateHealthStatus(marginRatio * 100);
132
136
  var baseSpacing = (0, common_1.amountNormalizer)(tradeSimulationState.marketConfiguration.base_spacing).toNumber();
@@ -137,8 +141,9 @@ var TradeSimulationClient = /** @class */ (function () {
137
141
  return {
138
142
  estimatedPrice: estimatedPrice,
139
143
  estimatedSlippage: slippage * 100,
140
- fees: fees,
141
- takerFeesPercentage: (0, bignumber_js_1.default)(tradeSimulationState.feeParameter).toNumber() * 100,
144
+ fees: feesV2.fee,
145
+ takerFeesPercentage: feesV2.feePercentage,
146
+ feesV2: feesV2,
142
147
  liquidationPrice: liquidationPrice.toNumber(),
143
148
  marginRatio: marginRatio * 100,
144
149
  marginRatioHealth: marginRatioHealth,
@@ -184,7 +189,13 @@ var TradeSimulationClient = /** @class */ (function () {
184
189
  var baseSpacing = (0, common_1.amountNormalizer)(tradeSimulationState.marketConfiguration.base_spacing).toNumber();
185
190
  var snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);
186
191
  var snappedAmount = snappedAmountInBase * params.triggerPrice;
187
- var fees = common_1.ExposureCommand.calculateFee(params.triggerPrice, amount, tradeSimulationState.feeParameter);
192
+ var fees = common_1.ExposureCommand.calculateFee({
193
+ oraclePrice: params.triggerPrice,
194
+ orderBase: amount,
195
+ poolBasePreTrade: 0,
196
+ feeParameter: tradeSimulationState.feeParameter,
197
+ rebalancingFeeParameter: (0, bignumber_js_1.default)(0),
198
+ }).fee;
188
199
  var marginBalance = userAccountExposure.getUsdNodeMarginInfo.marginBalance;
189
200
  var availableMargin = userAccountExposure.getUsdNodeMarginInfo.initialDelta;
190
201
  var imrMultiplier = (0, common_1.amountNormalizer)(String(userAccountExposure.riskMultipliers.im_multiplier)).toNumber();
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","s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,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,oBAAoB,CAAC,uBAAuB,CAAC,oBAAoB,CAC/D,QAAQ,CACT,GAAG,KAAK,CAAC;QACV,oBAAoB,CAAC,mBAAmB,CAAC,oBAAoB,CAAC,QAAQ,CAAC;YACrE,KAAK,CAAC;IACV,CAAC;IACH,4BAAC;AAAD,CAAC,AAhgBD,IAggBC","sourcesContent":["import {\n EstimatedPriceParams,\n EstimatedPriceResult,\n LimitTradeMaxOrderSizeParams,\n LimitTradeMaxOrderSizeResult,\n SimulateLimitTradeEntity,\n SimulateTradeEntity,\n TradeSimulationConvertValueEstimatedPriceParams,\n TradeSimulationConvertValueParams,\n TradeSimulationConvertValueResult,\n TradeSimulationLoadDataParams,\n TradeSimulationSimulateLimitParams,\n TradeSimulationSimulateParams,\n} from './types';\nimport AccountClient from '../account';\nimport {\n amountNormalizer,\n ExposureCommand,\n MarginInfo,\n PositionInfo,\n TradeSimulationState,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';\n\nexport default class TradeSimulationClient {\n private marketId: number | null = null;\n private accountId: number | null = null;\n private loadedData: {\n tradeSimulationState: TradeSimulationState;\n userAccountExposure: ExposureCommand;\n passivePoolExposure: ExposureCommand;\n } | null = null;\n private accountClient: AccountClient;\n\n constructor(accountClient: AccountClient) {\n // Constructor added\n this.accountClient = accountClient;\n }\n\n // Method to asynchronously load data based on marketId and accountId\n async arm(params: TradeSimulationLoadDataParams): Promise<void> {\n this.marketId = params.marketId;\n this.accountId = params.marginAccountId;\n\n const tradeSimulationState = await this.fetchMarketData(\n this.marketId,\n this.accountId,\n );\n\n const userAccountExposure = new ExposureCommand(\n tradeSimulationState.exposureDataAccount.accountId,\n tradeSimulationState.exposureDataAccount.rootCollateralPoolId,\n tradeSimulationState.exposureDataAccount.oraclePricePerMarket,\n tradeSimulationState.exposureDataAccount.accountBalancePerAsset,\n tradeSimulationState.exposureDataAccount.groupedByCollateral,\n tradeSimulationState.exposureDataAccount.riskMultipliers,\n tradeSimulationState.exposureDataAccount.riskMatrices,\n tradeSimulationState.exposureDataAccount.exchangeInfoPerAsset,\n tradeSimulationState.exposureDataAccount.positionInfoMarketConfiguration,\n tradeSimulationState.exposureDataAccount.uniqueTokenAddresses,\n tradeSimulationState.exposureDataAccount.uniqueQuoteCollaterals,\n tradeSimulationState.exposureDataAccount.tokenMarginInfoPerAsset,\n tradeSimulationState.exposureDataAccount.realizedPnLSum,\n tradeSimulationState.exposureDataAccount.unrealizedPnLSum,\n tradeSimulationState.exposureDataAccount.mtmRpnlSum,\n tradeSimulationState.exposureDataAccount.collateralAddressToExchangePrice,\n );\n\n const passivePoolExposure = new ExposureCommand(\n tradeSimulationState.exposureDataPassivePool.accountId,\n tradeSimulationState.exposureDataPassivePool.rootCollateralPoolId,\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket,\n tradeSimulationState.exposureDataPassivePool.accountBalancePerAsset,\n tradeSimulationState.exposureDataPassivePool.groupedByCollateral,\n tradeSimulationState.exposureDataPassivePool.riskMultipliers,\n tradeSimulationState.exposureDataPassivePool.riskMatrices,\n tradeSimulationState.exposureDataPassivePool.exchangeInfoPerAsset,\n tradeSimulationState.exposureDataPassivePool.positionInfoMarketConfiguration,\n tradeSimulationState.exposureDataPassivePool.uniqueTokenAddresses,\n tradeSimulationState.exposureDataPassivePool.uniqueQuoteCollaterals,\n tradeSimulationState.exposureDataPassivePool.tokenMarginInfoPerAsset,\n tradeSimulationState.exposureDataPassivePool.realizedPnLSum,\n tradeSimulationState.exposureDataPassivePool.unrealizedPnLSum,\n tradeSimulationState.exposureDataPassivePool.mtmRpnlSum,\n tradeSimulationState.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n this.loadedData = {\n tradeSimulationState,\n userAccountExposure,\n passivePoolExposure,\n };\n }\n\n private async fetchMarketData(\n marketId: number,\n accountId: number,\n ): Promise<TradeSimulationState> {\n return this.accountClient.getTransactionSimulationInitialData({\n marginAccountId: accountId,\n marketId: marketId,\n });\n }\n\n // Synchronous method to simulate operations based on an amount\n simulate(params: TradeSimulationSimulateParams): SimulateTradeEntity {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, userAccountExposure, passivePoolExposure } =\n this.loadedData;\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount)\n .div(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n /*\n max amount of margin in rUSD terms that can be transferred from the source account to the destination account\n that performs the isolated position trade (PRE TRADE)\n */\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const marginBalance =\n userAccountExposure.getUsdNodeMarginInfo.marginBalance;\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amount).negated().toNumber(),\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage,\n );\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n slippage,\n );\n\n const fees = ExposureCommand.calculateFee(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n amount,\n tradeSimulationState.feeParameter,\n );\n\n const {\n usdNodeMarginInfo: newMarginInfo,\n tokenMarginInfoPerAsset,\n positionInfoMarketConfiguration,\n } = userAccountExposure.getUsdNodeMarginInfoPostTrade(\n amount,\n tradeSimulationState.marketStorage.quote_collateral,\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage.risk_block_id,\n );\n\n const newQuoteTokenMarginInfo = tokenMarginInfoPerAsset.find(\n (marginInfo: MarginInfo) => {\n return (\n marginInfo.assetAddress ===\n tradeSimulationState.marketStorage.quote_collateral\n );\n },\n );\n\n const positionInfo = positionInfoMarketConfiguration.find(\n (positionInfo: PositionInfo) => {\n return (\n positionInfo.market_id ===\n tradeSimulationState.marketConfiguration.market_id\n );\n },\n );\n\n if (!newQuoteTokenMarginInfo) {\n throw new Error('Error performing simulation');\n }\n\n /*\n * Note, required margin is the initial margin requirement in rUSD terms of the account after the trade.\n * margin balance rusd - initial delta rusd = margin balance rusd - (margin balance rusd - imr rusd) = imr rusd\n * */\n\n const requiredMargin =\n newQuoteTokenMarginInfo.marginBalance -\n newQuoteTokenMarginInfo.initialDelta;\n\n const liquidationPrice = ExposureCommand.calculateLiquidation(\n newMarginInfo.marginBalance,\n newQuoteTokenMarginInfo.liquidationMarginRequirement,\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n BigNumber(positionInfo?.base || 0).toNumber(),\n );\n\n const marginRatio = ExposureCommand.getMarginRatio(newMarginInfo);\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const baseSpacing = amountNormalizer(\n tradeSimulationState.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * estimatedPrice;\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n estimatedPrice,\n estimatedSlippage: slippage * 100,\n fees,\n takerFeesPercentage:\n BigNumber(tradeSimulationState.feeParameter).toNumber() * 100,\n liquidationPrice: liquidationPrice.toNumber(),\n marginRatio: marginRatio * 100,\n marginRatioHealth,\n marginBalance,\n availableMargin,\n requiredMargin,\n snappedAmount,\n snappedAmountInBase,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n maxSlippage: 1,\n } as SimulateTradeEntity;\n }\n\n getRiskMatrixElement(): number {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n const riskBlockId = tradeSimulationState.marketStorage.risk_block_id;\n const riskMatrices = tradeSimulationState.exposureDataAccount.riskMatrices;\n\n const riskMatrix = riskMatrices.find(\n (riskMatrix) => riskMatrix.risk_block_id === riskBlockId,\n );\n\n if (!riskMatrix) {\n throw new Error('Risk matrix not found');\n }\n\n const riskMatrixIndex =\n tradeSimulationState.marketConfiguration.risk_matrix_index;\n\n return Number(riskMatrix.matrix[riskMatrixIndex][riskMatrixIndex]);\n }\n\n // Synchronous method to simulate operations based on an amount\n simulateLimit(\n params: TradeSimulationSimulateLimitParams,\n ): SimulateLimitTradeEntity {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, userAccountExposure } = this.loadedData;\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount).div(params.triggerPrice).toNumber();\n }\n\n const baseSpacing = amountNormalizer(\n tradeSimulationState.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * params.triggerPrice;\n\n const fees = ExposureCommand.calculateFee(\n params.triggerPrice,\n amount,\n tradeSimulationState.feeParameter,\n );\n\n const marginBalance =\n userAccountExposure.getUsdNodeMarginInfo.marginBalance;\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const imrMultiplier = amountNormalizer(\n String(userAccountExposure.riskMultipliers.im_multiplier),\n ).toNumber();\n\n const riskMatrixElement = this.getRiskMatrixElement();\n\n const accountLMR =\n userAccountExposure.getUsdNodeMarginInfo.liquidationMarginRequirement;\n const accountIMR = accountLMR * imrMultiplier;\n\n const limitOrderLMR =\n Math.sqrt(riskMatrixElement) * Math.abs(snappedAmount);\n const limitOrderIMR = limitOrderLMR * imrMultiplier;\n\n const requiredMargin = accountIMR + limitOrderIMR;\n\n const liquidationMarginRequirement =\n userAccountExposure.getUsdNodeMarginInfo.liquidationMarginRequirement +\n limitOrderLMR;\n\n const marginRatio = ExposureCommand.getMarginRatio({\n marginBalance,\n liquidationMarginRequirement,\n });\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n fees,\n takerFeesPercentage:\n BigNumber(tradeSimulationState.feeParameter).toNumber() * 100,\n snappedAmount,\n snappedAmountInBase,\n estimatedPrice: params.triggerPrice,\n marginRatio: marginRatio * 100,\n marginRatioHealth,\n availableMargin,\n marginBalance,\n requiredMargin,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n };\n }\n\n getMaxAmountForLimitOrder(\n params: LimitTradeMaxOrderSizeParams,\n ): LimitTradeMaxOrderSizeResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { userAccountExposure, tradeSimulationState } = this.loadedData;\n\n const riskMatrixElement = this.getRiskMatrixElement();\n\n const imrMultiplier = amountNormalizer(\n String(userAccountExposure.riskMultipliers.im_multiplier),\n ).toNumber();\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const maxAmountSize = Math.max(\n (availableMargin / Math.sqrt(riskMatrixElement) / imrMultiplier) * 0.97, // @todo implement dynamic buffer\n 0,\n );\n const maxAmountBase = maxAmountSize / params.triggerPrice;\n\n const minAmountBase = amountNormalizer(\n tradeSimulationState.marketConfiguration.minimum_order_base,\n ).toNumber();\n\n const minAmountSize = minAmountBase * params.triggerPrice;\n\n return {\n maxAmountBase,\n maxAmountSize,\n minAmountBase,\n minAmountSize,\n };\n }\n\n convertValue(\n params: TradeSimulationConvertValueParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n if (!params.fromBase)\n return BigNumber(params.amount)\n .div(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n )\n .toNumber();\n else\n return BigNumber(params.amount)\n .times(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n convertValueEstimatedPrice(\n params: TradeSimulationConvertValueEstimatedPriceParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, passivePoolExposure } = this.loadedData;\n\n const amountForSlippage = params.fromBase\n ? params.amount\n : BigNumber(params.amount)\n .div(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n )\n .toNumber();\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amountForSlippage).negated().toNumber(),\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n slippage,\n );\n\n if (!params.fromBase)\n return BigNumber(params.amount).div(estimatedPrice).toNumber();\n else return BigNumber(params.amount).times(estimatedPrice).toNumber();\n }\n\n customLeverage(): number | null {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n return tradeSimulationState.customLeverage;\n }\n\n estimatedPrice(params: EstimatedPriceParams): EstimatedPriceResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, passivePoolExposure } = this.loadedData;\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(params.amount).negated().toNumber(),\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage,\n );\n\n const price =\n tradeSimulationState.exposureDataAccount.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ];\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n slippage,\n );\n\n return {\n estimatedPrice,\n markPrice: price,\n };\n }\n\n roundToBaseSpacing(amount: number, baseSpacing: number): number {\n const snappedAmount = BigNumber(amount)\n .abs()\n .dividedBy(baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(baseSpacing)\n .toNumber();\n\n if (amount < 0) {\n return -snappedAmount;\n }\n return snappedAmount;\n }\n\n updatePrice(price: number): void {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n // update price\n const marketId = this.marketId;\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n marketId\n ] = price;\n tradeSimulationState.exposureDataAccount.oraclePricePerMarket[marketId] =\n price;\n }\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,0CAMyB;AACzB,8DAAqC;AACrC,0CAA0D;AAC1D,iCAAqC;AAErC;IAUE,+BAAY,aAA4B;QAThC,aAAQ,GAAkB,IAAI,CAAC;QAC/B,cAAS,GAAkB,IAAI,CAAC;QAChC,eAAU,GAIP,IAAI,CAAC;QAId,oBAAoB;QACpB,IAAI,CAAC,aAAa,GAAG,aAAa,CAAC;IACrC,CAAC;IAED,qEAAqE;IAC/D,mCAAG,GAAT,UAAU,MAAqC;;;;;;wBAC7C,IAAI,CAAC,QAAQ,GAAG,MAAM,CAAC,QAAQ,CAAC;wBACh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CAAC,mBAAmB,CAAC,SAAS,CACnD,EACD,QAAQ,CACT,CAAC;QAEF,OAAO;YACL,cAAc,gBAAA;YACd,SAAS,EAAE,KAAK;SACjB,CAAC;IACJ,CAAC;IAED,kDAAkB,GAAlB,UAAmB,MAAc,EAAE,WAAmB;QACpD,IAAM,aAAa,GAAG,IAAA,sBAAS,EAAC,MAAM,CAAC;aACpC,GAAG,EAAE;aACL,SAAS,CAAC,WAAW,CAAC;aACtB,YAAY,CAAC,sBAAS,CAAC,WAAW,CAAC;aACnC,YAAY,CAAC,WAAW,CAAC;aACzB,QAAQ,EAAE,CAAC;QAEd,IAAI,MAAM,GAAG,CAAC,EAAE,CAAC;YACf,OAAO,CAAC,aAAa,CAAC;QACxB,CAAC;QACD,OAAO,aAAa,CAAC;IACvB,CAAC;IAED,2CAAW,GAAX,UAAY,KAAa;QACvB,IAAI,CAAC,IAAI,CAAC,UAAU,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC;YACvC,MAAM,IAAI,KAAK,CAAC,oCAAoC,CAAC,CAAC;QACxD,CAAC;QAEO,IAAA,oBAAoB,GAAK,IAAI,CAAC,UAAU,qBAApB,CAAqB;QAEjD,eAAe;QACf,IAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAC/B,oBAAoB,CAAC,uBAAuB,CAAC,oBAAoB,CAC/D,QAAQ,CACT,GAAG,KAAK,CAAC;QACV,oBAAoB,CAAC,mBAAmB,CAAC,oBAAoB,CAAC,QAAQ,CAAC;YACrE,KAAK,CAAC;IACV,CAAC;IACH,4BAAC;AAAD,CAAC,AA3fD,IA2fC","sourcesContent":["import {\n EstimatedPriceParams,\n EstimatedPriceResult,\n LimitTradeMaxOrderSizeParams,\n LimitTradeMaxOrderSizeResult,\n SimulateLimitTradeEntity,\n SimulateTradeEntity,\n TradeSimulationConvertValueEstimatedPriceParams,\n TradeSimulationConvertValueParams,\n TradeSimulationConvertValueResult,\n TradeSimulationLoadDataParams,\n TradeSimulationSimulateLimitParams,\n TradeSimulationSimulateParams,\n} from './types';\nimport AccountClient from '../account';\nimport {\n amountNormalizer,\n ExposureCommand,\n MarginInfo,\n PositionInfo,\n TradeSimulationState,\n} from '@reyaxyz/common';\nimport BigNumber from 'bignumber.js';\nimport { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';\nimport { computeFee } from './utils';\n\nexport default class TradeSimulationClient {\n private marketId: number | null = null;\n private accountId: number | null = null;\n private loadedData: {\n tradeSimulationState: TradeSimulationState;\n userAccountExposure: ExposureCommand;\n passivePoolExposure: ExposureCommand;\n } | null = null;\n private accountClient: AccountClient;\n\n constructor(accountClient: AccountClient) {\n // Constructor added\n this.accountClient = accountClient;\n }\n\n // Method to asynchronously load data based on marketId and accountId\n async arm(params: TradeSimulationLoadDataParams): Promise<void> {\n this.marketId = params.marketId;\n this.accountId = params.marginAccountId;\n\n const tradeSimulationState = await this.fetchMarketData(\n this.marketId,\n this.accountId,\n );\n\n const userAccountExposure = new ExposureCommand(\n tradeSimulationState.exposureDataAccount.accountId,\n tradeSimulationState.exposureDataAccount.rootCollateralPoolId,\n tradeSimulationState.exposureDataAccount.oraclePricePerMarket,\n tradeSimulationState.exposureDataAccount.accountBalancePerAsset,\n tradeSimulationState.exposureDataAccount.groupedByCollateral,\n tradeSimulationState.exposureDataAccount.riskMultipliers,\n tradeSimulationState.exposureDataAccount.riskMatrices,\n tradeSimulationState.exposureDataAccount.exchangeInfoPerAsset,\n tradeSimulationState.exposureDataAccount.positionInfoMarketConfiguration,\n tradeSimulationState.exposureDataAccount.uniqueTokenAddresses,\n tradeSimulationState.exposureDataAccount.uniqueQuoteCollaterals,\n tradeSimulationState.exposureDataAccount.tokenMarginInfoPerAsset,\n tradeSimulationState.exposureDataAccount.realizedPnLSum,\n tradeSimulationState.exposureDataAccount.unrealizedPnLSum,\n tradeSimulationState.exposureDataAccount.mtmRpnlSum,\n tradeSimulationState.exposureDataAccount.collateralAddressToExchangePrice,\n );\n\n const passivePoolExposure = new ExposureCommand(\n tradeSimulationState.exposureDataPassivePool.accountId,\n tradeSimulationState.exposureDataPassivePool.rootCollateralPoolId,\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket,\n tradeSimulationState.exposureDataPassivePool.accountBalancePerAsset,\n tradeSimulationState.exposureDataPassivePool.groupedByCollateral,\n tradeSimulationState.exposureDataPassivePool.riskMultipliers,\n tradeSimulationState.exposureDataPassivePool.riskMatrices,\n tradeSimulationState.exposureDataPassivePool.exchangeInfoPerAsset,\n tradeSimulationState.exposureDataPassivePool.positionInfoMarketConfiguration,\n tradeSimulationState.exposureDataPassivePool.uniqueTokenAddresses,\n tradeSimulationState.exposureDataPassivePool.uniqueQuoteCollaterals,\n tradeSimulationState.exposureDataPassivePool.tokenMarginInfoPerAsset,\n tradeSimulationState.exposureDataPassivePool.realizedPnLSum,\n tradeSimulationState.exposureDataPassivePool.unrealizedPnLSum,\n tradeSimulationState.exposureDataPassivePool.mtmRpnlSum,\n tradeSimulationState.exposureDataPassivePool.collateralAddressToExchangePrice,\n );\n\n this.loadedData = {\n tradeSimulationState,\n userAccountExposure,\n passivePoolExposure,\n };\n }\n\n private async fetchMarketData(\n marketId: number,\n accountId: number,\n ): Promise<TradeSimulationState> {\n return this.accountClient.getTransactionSimulationInitialData({\n marginAccountId: accountId,\n marketId: marketId,\n });\n }\n\n // Synchronous method to simulate operations based on an amount\n simulate(params: TradeSimulationSimulateParams): SimulateTradeEntity {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, userAccountExposure, passivePoolExposure } =\n this.loadedData;\n\n const oraclePrice =\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ];\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount).div(oraclePrice).toNumber();\n }\n\n /*\n max amount of margin in rUSD terms that can be transferred from the source account to the destination account\n that performs the isolated position trade (PRE TRADE)\n */\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const marginBalance =\n userAccountExposure.getUsdNodeMarginInfo.marginBalance;\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amount).negated().toNumber(),\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage,\n );\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n oraclePrice,\n slippage,\n );\n\n const feesV2 = computeFee({\n tradeSimulationState,\n marketId: this.marketId,\n orderBase: amount,\n });\n\n const {\n usdNodeMarginInfo: newMarginInfo,\n tokenMarginInfoPerAsset,\n positionInfoMarketConfiguration,\n } = userAccountExposure.getUsdNodeMarginInfoPostTrade(\n amount,\n tradeSimulationState.marketStorage.quote_collateral,\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage.risk_block_id,\n );\n\n const newQuoteTokenMarginInfo = tokenMarginInfoPerAsset.find(\n (marginInfo: MarginInfo) => {\n return (\n marginInfo.assetAddress ===\n tradeSimulationState.marketStorage.quote_collateral\n );\n },\n );\n\n const positionInfo = positionInfoMarketConfiguration.find(\n (positionInfo: PositionInfo) => {\n return (\n positionInfo.market_id ===\n tradeSimulationState.marketConfiguration.market_id\n );\n },\n );\n\n if (!newQuoteTokenMarginInfo) {\n throw new Error('Error performing simulation');\n }\n\n /*\n * Note, required margin is the initial margin requirement in rUSD terms of the account after the trade.\n * margin balance rusd - initial delta rusd = margin balance rusd - (margin balance rusd - imr rusd) = imr rusd\n * */\n\n const requiredMargin =\n newQuoteTokenMarginInfo.marginBalance -\n newQuoteTokenMarginInfo.initialDelta;\n\n const liquidationPrice = ExposureCommand.calculateLiquidation(\n newMarginInfo.marginBalance,\n newQuoteTokenMarginInfo.liquidationMarginRequirement,\n oraclePrice,\n BigNumber(positionInfo?.base || 0).toNumber(),\n );\n\n const marginRatio = ExposureCommand.getMarginRatio(newMarginInfo);\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const baseSpacing = amountNormalizer(\n tradeSimulationState.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * estimatedPrice;\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n estimatedPrice,\n estimatedSlippage: slippage * 100,\n fees: feesV2.fee,\n takerFeesPercentage: feesV2.feePercentage,\n feesV2,\n liquidationPrice: liquidationPrice.toNumber(),\n marginRatio: marginRatio * 100,\n marginRatioHealth,\n marginBalance,\n availableMargin,\n requiredMargin,\n snappedAmount,\n snappedAmountInBase,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n maxSlippage: 1,\n };\n }\n\n getRiskMatrixElement(): number {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n const riskBlockId = tradeSimulationState.marketStorage.risk_block_id;\n const riskMatrices = tradeSimulationState.exposureDataAccount.riskMatrices;\n\n const riskMatrix = riskMatrices.find(\n (riskMatrix) => riskMatrix.risk_block_id === riskBlockId,\n );\n\n if (!riskMatrix) {\n throw new Error('Risk matrix not found');\n }\n\n const riskMatrixIndex =\n tradeSimulationState.marketConfiguration.risk_matrix_index;\n\n return Number(riskMatrix.matrix[riskMatrixIndex][riskMatrixIndex]);\n }\n\n // Synchronous method to simulate operations based on an amount\n simulateLimit(\n params: TradeSimulationSimulateLimitParams,\n ): SimulateLimitTradeEntity {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, userAccountExposure } = this.loadedData;\n\n let amount;\n if (params.fromBase) {\n amount = params.amount;\n } else {\n amount = BigNumber(params.amount).div(params.triggerPrice).toNumber();\n }\n\n const baseSpacing = amountNormalizer(\n tradeSimulationState.marketConfiguration.base_spacing,\n ).toNumber();\n\n const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);\n const snappedAmount = snappedAmountInBase * params.triggerPrice;\n\n const { fee: fees } = ExposureCommand.calculateFee({\n oraclePrice: params.triggerPrice,\n orderBase: amount,\n poolBasePreTrade: 0,\n feeParameter: tradeSimulationState.feeParameter,\n rebalancingFeeParameter: BigNumber(0),\n });\n\n const marginBalance =\n userAccountExposure.getUsdNodeMarginInfo.marginBalance;\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const imrMultiplier = amountNormalizer(\n String(userAccountExposure.riskMultipliers.im_multiplier),\n ).toNumber();\n\n const riskMatrixElement = this.getRiskMatrixElement();\n\n const accountLMR =\n userAccountExposure.getUsdNodeMarginInfo.liquidationMarginRequirement;\n const accountIMR = accountLMR * imrMultiplier;\n\n const limitOrderLMR =\n Math.sqrt(riskMatrixElement) * Math.abs(snappedAmount);\n const limitOrderIMR = limitOrderLMR * imrMultiplier;\n\n const requiredMargin = accountIMR + limitOrderIMR;\n\n const liquidationMarginRequirement =\n userAccountExposure.getUsdNodeMarginInfo.liquidationMarginRequirement +\n limitOrderLMR;\n\n const marginRatio = ExposureCommand.getMarginRatio({\n marginBalance,\n liquidationMarginRequirement,\n });\n\n const marginRatioHealth = ExposureCommand.evaluateHealthStatus(\n marginRatio * 100,\n );\n\n const xpEarnRangeMin = Math.round(\n Math.abs(snappedAmount) / INSTANT_TRADING_RATE_XP,\n );\n const xpEarnRangeMax = Math.round(\n (100 * Math.abs(snappedAmount)) / INSTANT_TRADING_RATE_XP,\n );\n\n return {\n fees,\n takerFeesPercentage:\n BigNumber(tradeSimulationState.feeParameter).toNumber() * 100,\n snappedAmount,\n snappedAmountInBase,\n estimatedPrice: params.triggerPrice,\n marginRatio: marginRatio * 100,\n marginRatioHealth,\n availableMargin,\n marginBalance,\n requiredMargin,\n xpEarnRange: {\n min: xpEarnRangeMin,\n max: xpEarnRangeMax,\n },\n };\n }\n\n getMaxAmountForLimitOrder(\n params: LimitTradeMaxOrderSizeParams,\n ): LimitTradeMaxOrderSizeResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { userAccountExposure, tradeSimulationState } = this.loadedData;\n\n const riskMatrixElement = this.getRiskMatrixElement();\n\n const imrMultiplier = amountNormalizer(\n String(userAccountExposure.riskMultipliers.im_multiplier),\n ).toNumber();\n\n const availableMargin =\n userAccountExposure.getUsdNodeMarginInfo.initialDelta;\n\n const maxAmountSize = Math.max(\n (availableMargin / Math.sqrt(riskMatrixElement) / imrMultiplier) * 0.97, // @todo implement dynamic buffer\n 0,\n );\n const maxAmountBase = maxAmountSize / params.triggerPrice;\n\n const minAmountBase = amountNormalizer(\n tradeSimulationState.marketConfiguration.minimum_order_base,\n ).toNumber();\n\n const minAmountSize = minAmountBase * params.triggerPrice;\n\n return {\n maxAmountBase,\n maxAmountSize,\n minAmountBase,\n minAmountSize,\n };\n }\n\n convertValue(\n params: TradeSimulationConvertValueParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n if (!params.fromBase)\n return BigNumber(params.amount)\n .div(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n )\n .toNumber();\n else\n return BigNumber(params.amount)\n .times(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n )\n .toNumber();\n }\n\n convertValueEstimatedPrice(\n params: TradeSimulationConvertValueEstimatedPriceParams,\n ): TradeSimulationConvertValueResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, passivePoolExposure } = this.loadedData;\n\n const amountForSlippage = params.fromBase\n ? params.amount\n : BigNumber(params.amount)\n .div(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n )\n .toNumber();\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(amountForSlippage).negated().toNumber(),\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage,\n );\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n slippage,\n );\n\n if (!params.fromBase)\n return BigNumber(params.amount).div(estimatedPrice).toNumber();\n else return BigNumber(params.amount).times(estimatedPrice).toNumber();\n }\n\n customLeverage(): number | null {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n return tradeSimulationState.customLeverage;\n }\n\n estimatedPrice(params: EstimatedPriceParams): EstimatedPriceResult {\n if (!this.loadedData) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState, passivePoolExposure } = this.loadedData;\n\n const slippage = passivePoolExposure.getSlippage(\n BigNumber(params.amount).negated().toNumber(),\n tradeSimulationState.marketConfiguration,\n tradeSimulationState.marketStorage,\n );\n\n const price =\n tradeSimulationState.exposureDataAccount.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ];\n\n const estimatedPrice = ExposureCommand.calculateEstimatedPrice(\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ],\n slippage,\n );\n\n return {\n estimatedPrice,\n markPrice: price,\n };\n }\n\n roundToBaseSpacing(amount: number, baseSpacing: number): number {\n const snappedAmount = BigNumber(amount)\n .abs()\n .dividedBy(baseSpacing)\n .integerValue(BigNumber.ROUND_FLOOR)\n .multipliedBy(baseSpacing)\n .toNumber();\n\n if (amount < 0) {\n return -snappedAmount;\n }\n return snappedAmount;\n }\n\n updatePrice(price: number): void {\n if (!this.loadedData || !this.marketId) {\n throw new Error('Data not loaded. Call arm() first.');\n }\n\n const { tradeSimulationState } = this.loadedData;\n\n // update price\n const marketId = this.marketId;\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n marketId\n ] = price;\n tradeSimulationState.exposureDataAccount.oraclePricePerMarket[marketId] =\n price;\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/types.ts"],"names":[],"mappings":"","sourcesContent":["import { MarginAccountEntity, MarketEntity } from '@reyaxyz/common';\n\nexport type TradeSimulationLoadDataParams = {\n marketId: MarketEntity['id'];\n marginAccountId: MarginAccountEntity['id'];\n};\n\nexport type TradeSimulationSimulateParams = {\n amount: number; // position size / base, + for long | - for short\n fromBase?: boolean;\n};\n\nexport type TradeSimulationConvertValueParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type EstimatedPriceParams = {\n amount: number; // amount in base\n};\n\nexport type EstimatedPriceResult = {\n estimatedPrice: number;\n markPrice: number;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceResult = number;\n\nexport type SimulateTradeEntity = {\n liquidationPrice: number;\n fees: number;\n takerFeesPercentage: number;\n estimatedPrice: number;\n estimatedSlippage: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n availableMargin: number;\n marginBalance: number;\n requiredMargin: number;\n snappedAmount: number;\n snappedAmountInBase: number;\n xpEarnRange?: {\n min: number;\n max: number;\n };\n maxSlippage: number;\n};\n\nexport type TradeSimulationSimulateLimitParams = {\n triggerPrice: number;\n amount: number; // position size / base, + for long | - for short\n fromBase?: boolean;\n};\n\nexport type SimulateLimitTradeEntity = {\n fees: number;\n takerFeesPercentage: number;\n snappedAmount: number;\n snappedAmountInBase: number;\n estimatedPrice: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n availableMargin: number;\n marginBalance: number;\n requiredMargin: number;\n xpEarnRange: {\n min: number;\n max: number;\n };\n};\n\nexport type LimitTradeMaxOrderSizeParams = {\n triggerPrice: number;\n};\n\nexport type LimitTradeMaxOrderSizeResult = {\n maxAmountBase: number;\n maxAmountSize: number;\n minAmountBase: number;\n minAmountSize: number;\n};\n\nexport type TradeSimulationConvertValueResult = number;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/types.ts"],"names":[],"mappings":"","sourcesContent":["import { MarginAccountEntity, MarketEntity } from '@reyaxyz/common';\n\nexport type TradeSimulationLoadDataParams = {\n marketId: MarketEntity['id'];\n marginAccountId: MarginAccountEntity['id'];\n};\n\nexport type TradeSimulationSimulateParams = {\n amount: number; // position size / base, + for long | - for short\n fromBase?: boolean;\n};\n\nexport type TradeSimulationConvertValueParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type EstimatedPriceParams = {\n amount: number; // amount in base\n};\n\nexport type EstimatedPriceResult = {\n estimatedPrice: number;\n markPrice: number;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceParams = {\n amount: number;\n fromBase: boolean;\n};\n\nexport type TradeSimulationConvertValueEstimatedPriceResult = number;\n\nexport type SimulateTradeFeeEntity = {\n feeTier: number;\n feePercentage: number;\n rebalancingFeePercentage: number;\n fee: number;\n imbalancingFee: number;\n rebalancingFee: number;\n};\n\nexport type SimulateTradeEntity = {\n liquidationPrice: number;\n fees: number; // TODO: deprecate when feeV2 is linked up\n takerFeesPercentage: number; // TODO: deprecate when feeV2 is linked up\n feesV2: SimulateTradeFeeEntity;\n estimatedPrice: number;\n estimatedSlippage: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n availableMargin: number;\n marginBalance: number;\n requiredMargin: number;\n snappedAmount: number;\n snappedAmountInBase: number;\n xpEarnRange?: {\n min: number;\n max: number;\n };\n maxSlippage: number;\n};\n\nexport type TradeSimulationSimulateLimitParams = {\n triggerPrice: number;\n amount: number; // position size / base, + for long | - for short\n fromBase?: boolean;\n};\n\nexport type SimulateLimitTradeEntity = {\n fees: number;\n takerFeesPercentage: number;\n snappedAmount: number;\n snappedAmountInBase: number;\n estimatedPrice: number;\n marginRatio: MarginAccountEntity['marginRatioPercentage'];\n marginRatioHealth: MarginAccountEntity['marginRatioHealth'];\n availableMargin: number;\n marginBalance: number;\n requiredMargin: number;\n xpEarnRange: {\n min: number;\n max: number;\n };\n};\n\nexport type LimitTradeMaxOrderSizeParams = {\n triggerPrice: number;\n};\n\nexport type LimitTradeMaxOrderSizeResult = {\n maxAmountBase: number;\n maxAmountSize: number;\n minAmountBase: number;\n minAmountSize: number;\n};\n\nexport type TradeSimulationConvertValueResult = number;\n"]}
@@ -0,0 +1,35 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.computeFee = void 0;
4
+ var common_1 = require("@reyaxyz/common");
5
+ var computeFee = function (_a) {
6
+ var tradeSimulationState = _a.tradeSimulationState, marketId = _a.marketId, orderBase = _a.orderBase;
7
+ var oraclePrice = tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[tradeSimulationState.marketConfiguration.market_id];
8
+ var poolPosition = tradeSimulationState.exposureDataPassivePool.positionInfoMarketConfiguration.find(function (p) { return p.market_id === marketId; });
9
+ var poolBasePreTrade = Number((poolPosition === null || poolPosition === void 0 ? void 0 : poolPosition.base) || 0);
10
+ // TODO: once api is updated, change to the following:
11
+ // const { feeParameter, rebalancingFeeParameter, feeTier } =
12
+ // tradeSimulationState.feeParameters;
13
+ var feeParameter = tradeSimulationState.feeParameter;
14
+ var rebalancingFeeParameter = tradeSimulationState.feeParameter;
15
+ var feeTier = 0;
16
+ var _b = common_1.ExposureCommand.calculateFee({
17
+ oraclePrice: oraclePrice,
18
+ orderBase: orderBase,
19
+ poolBasePreTrade: poolBasePreTrade,
20
+ feeParameter: feeParameter,
21
+ rebalancingFeeParameter: rebalancingFeeParameter,
22
+ }), fee = _b.fee, rebalancingFee = _b.rebalancingFee, imbalancingFee = _b.imbalancingFee;
23
+ var feePercentage = Number(feeParameter) * 100;
24
+ var rebalancingFeePercentage = Number(rebalancingFeeParameter) * 100;
25
+ return {
26
+ feeTier: feeTier,
27
+ feePercentage: feePercentage,
28
+ rebalancingFeePercentage: rebalancingFeePercentage,
29
+ fee: fee,
30
+ rebalancingFee: rebalancingFee,
31
+ imbalancingFee: imbalancingFee,
32
+ };
33
+ };
34
+ exports.computeFee = computeFee;
35
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sourceRoot":"/","sources":["clients/modules/trade.simulation/utils.ts"],"names":[],"mappings":";;;AAAA,0CAAwE;AAGjE,IAAM,UAAU,GAAG,UAAC,EAQ1B;QAPC,oBAAoB,0BAAA,EACpB,QAAQ,cAAA,EACR,SAAS,eAAA;IAMT,IAAM,WAAW,GACf,oBAAoB,CAAC,uBAAuB,CAAC,oBAAoB,CAC/D,oBAAoB,CAAC,mBAAmB,CAAC,SAAS,CACnD,CAAC;IAEJ,IAAM,YAAY,GAChB,oBAAoB,CAAC,uBAAuB,CAAC,+BAA+B,CAAC,IAAI,CAC/E,UAAC,CAAC,IAAK,OAAA,CAAC,CAAC,SAAS,KAAK,QAAQ,EAAxB,CAAwB,CAChC,CAAC;IAEJ,IAAM,gBAAgB,GAAG,MAAM,CAAC,CAAA,YAAY,aAAZ,YAAY,uBAAZ,YAAY,CAAE,IAAI,KAAI,CAAC,CAAC,CAAC;IAEzD,sDAAsD;IACtD,6DAA6D;IAC7D,wCAAwC;IAExC,IAAM,YAAY,GAAG,oBAAoB,CAAC,YAAY,CAAC;IACvD,IAAM,uBAAuB,GAAG,oBAAoB,CAAC,YAAY,CAAC;IAClE,IAAM,OAAO,GAAG,CAAC,CAAC;IAEZ,IAAA,KAA0C,wBAAe,CAAC,YAAY,CAAC;QAC3E,WAAW,aAAA;QACX,SAAS,WAAA;QACT,gBAAgB,kBAAA;QAChB,YAAY,cAAA;QACZ,uBAAuB,yBAAA;KACxB,CAAC,EANM,GAAG,SAAA,EAAE,cAAc,oBAAA,EAAE,cAAc,oBAMzC,CAAC;IAEH,IAAM,aAAa,GAAG,MAAM,CAAC,YAAY,CAAC,GAAG,GAAG,CAAC;IACjD,IAAM,wBAAwB,GAAG,MAAM,CAAC,uBAAuB,CAAC,GAAG,GAAG,CAAC;IAEvE,OAAO;QACL,OAAO,SAAA;QACP,aAAa,eAAA;QACb,wBAAwB,0BAAA;QACxB,GAAG,KAAA;QACH,cAAc,gBAAA;QACd,cAAc,gBAAA;KACf,CAAC;AACJ,CAAC,CAAC;AAhDW,QAAA,UAAU,cAgDrB","sourcesContent":["import { ExposureCommand, TradeSimulationState } from '@reyaxyz/common';\nimport { SimulateTradeFeeEntity } from './types';\n\nexport const computeFee = ({\n tradeSimulationState,\n marketId,\n orderBase,\n}: {\n marketId: number;\n tradeSimulationState: TradeSimulationState;\n orderBase: number;\n}): SimulateTradeFeeEntity => {\n const oraclePrice =\n tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[\n tradeSimulationState.marketConfiguration.market_id\n ];\n\n const poolPosition =\n tradeSimulationState.exposureDataPassivePool.positionInfoMarketConfiguration.find(\n (p) => p.market_id === marketId,\n );\n\n const poolBasePreTrade = Number(poolPosition?.base || 0);\n\n // TODO: once api is updated, change to the following:\n // const { feeParameter, rebalancingFeeParameter, feeTier } =\n // tradeSimulationState.feeParameters;\n\n const feeParameter = tradeSimulationState.feeParameter;\n const rebalancingFeeParameter = tradeSimulationState.feeParameter;\n const feeTier = 0;\n\n const { fee, rebalancingFee, imbalancingFee } = ExposureCommand.calculateFee({\n oraclePrice,\n orderBase,\n poolBasePreTrade,\n feeParameter,\n rebalancingFeeParameter,\n });\n\n const feePercentage = Number(feeParameter) * 100;\n const rebalancingFeePercentage = Number(rebalancingFeeParameter) * 100;\n\n return {\n feeTier,\n feePercentage,\n rebalancingFeePercentage,\n fee,\n rebalancingFee,\n imbalancingFee,\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"/","sources":["clients/modules/isolated-order.simulation/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,2BAA2B,EAC3B,yCAAyC,EACzC,yCAAyC,EACzC,qCAAqC,EACrC,qCAAqC,EACrC,sCAAsC,EACtC,sCAAsC,EACvC,MAAM,SAAS,CAAC;AACjB,OAAO,aAAa,MAAM,YAAY,CAAC;AACvC,OAAO,EAEL,eAAe,EACf,oBAAoB,EAGrB,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,+CAA+C,EAC/C,iCAAiC,EAClC,MAAM,2BAA2B,CAAC;AAGnC,MAAM,CAAC,OAAO,OAAO,6BAA6B;IAChD,OAAO,CAAC,UAAU,CAAqC;IACvD,OAAO,CAAC,aAAa,CAAgB;IACrC,OAAO,CAAC,QAAQ,CAAuB;gBAE3B,aAAa,EAAE,aAAa;IAMlC,GAAG,CAAC,MAAM,EAAE,qCAAqC,GAAG,OAAO,CAAC,IAAI,CAAC;IAQvE,MAAM,CAAC,wBAAwB,CAC7B,oBAAoB,EAAE,oBAAoB,GACzC,eAAe;YAqBJ,eAAe;IAW7B,QAAQ,CACN,MAAM,EAAE,qCAAqC,GAC5C,2BAA2B;IAmI9B,YAAY,CACV,MAAM,EAAE,yCAAyC,GAChD,yCAAyC;IAuB5C,0BAA0B,CACxB,MAAM,EAAE,+CAA+C,GACtD,iCAAiC;IAmDpC,cAAc,IAAI,MAAM,GAAG,IAAI;IAS/B,cAAc,CAAC,MAAM,EAAE,oBAAoB,GAAG,oBAAoB;IA+ClE,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM;IAc/D,qBAAqB,CACnB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,MAAM,GAClB,MAAM;IA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,MAAM,GAAG,MAAM;IAc/D,qBAAqB,CACnB,YAAY,EAAE,MAAM,EACpB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,MAAM,GAClB,MAAM;IAQT,oBAAoB,CAAC,gBAAgB,EAAE,MAAM,GAAG,MAAM;IAwCtD,gCAAgC,CAAC,EAC/B,kBAAkB,GACnB,EAAE,sCAAsC,GAAG,sCAAsC;IAsElF,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;CAUjC"}
@@ -1,4 +1,5 @@
1
1
  import { MarginAccountEntity, MarketEntity, EditCollateralAction } from '@reyaxyz/common';
2
+ import { SimulateTradeFeeEntity } from '../trade.simulation/types';
2
3
  export type IsolatedOrderSimulationLoadDataParams = {
3
4
  marketId: MarketEntity['id'];
4
5
  marginAccountId: MarginAccountEntity['id'];
@@ -16,6 +17,7 @@ export type SimulateIsolatedOrderEntity = {
16
17
  liquidationPrice: number;
17
18
  fees: number;
18
19
  takerFeesPercentage: number;
20
+ feesV2: SimulateTradeFeeEntity;
19
21
  estimatedPrice: number;
20
22
  estimatedSlippage: number;
21
23
  marginRatio: MarginAccountEntity['marginRatioPercentage'];
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"/","sources":["clients/modules/isolated-order.simulation/types.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,YAAY,EACZ,oBAAoB,EACrB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,qCAAqC,GAAG;IAClD,QAAQ,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC;IAC7B,eAAe,EAAE,mBAAmB,CAAC,IAAI,CAAC,CAAC;CAC5C,CAAC;AAEF,MAAM,MAAM,qCAAqC,GAAG;IAClD,MAAM,EAAE,MAAM,CAAC;IACf,wBAAwB,EAAE,MAAM,CAAC;IACjC,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,yCAAyC,GAAG;IACtD,MAAM,EAAE,MA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AAmB,EACnB,+CAA+C,EAC/C,iCAAiC,EACjC,iCAAiC,EACjC,6BAA6B,EAC7B,kCAAkC,EAClC,6BAA6B,EAC9B,MAAM,SAAS,CAAC;AACjB,OAAO,aAAa,MAAM,YAAY,CAAC;AAYvC,MAAM,CAAC,OAAO,OAAO,qBAAqB;IACxC,OAAO,CAAC,QAAQ,CAAuB;IACvC,OAAO,CAAC,SAAS,CAAuB;IACxC,OAAO,CAAC,UAAU,CAIF;IAChB,OAAO,CAAC,aAAa,CAAgB;gBAEzB,aAAa,EAAE,aAAa;IAMlC,GAAG,CAAC,MAAM,EAAE,6BAA6B,GAAG,OAAO,CAAC,IAAI,CAAC;YAsDjD,eAAe;IAW7B,QAAQ,CAAC,MAAM,EAAE,6BAA6B,GAAG,mBAAmB;IA0IpE,oBAAoB,IAAI,MAAM;IAyB9B,aAAa,CACX,MAAM,EAAE,kCAAkC,GACzC,wBAAwB;IA0F3B,yBAAyB,CACvB,MAAM,EAAE,4BAA4B,GACnC,4BAA4B;IAoC/B,YAAY,CACV,MAAM,EAAE,iCAAiC,GACxC,iCAAiC;IAyBpC,0BAA0B,CACxB,MAAM,EAAE,+CAA+C,GACtD,iCAAiC;IAkCpC,cAAc,IAAI,MAAM,GAAG,IAAI;IAU/B,cAAc,CAAC,MAAM,EAAE,oBAAoB,GAAG,oBAAoB;IA+BlE,kBAAkB,CAAC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,MAAM,GAAG,MAAM;IAc/D,WAAW,CAAC,KAAK,EAAE,MAAM,GAAG,IAAI;CAejC"}
@@ -23,10 +23,19 @@ export type TradeSimulationConvertValueEstimatedPriceParams = {
23
23
  fromBase: boolean;
24
24
  };
25
25
  export type TradeSimulationConvertValueEstimatedPriceResult = number;
26
+ export type SimulateTradeFeeEntity = {
27
+ feeTier: number;
28
+ feePercentage: number;
29
+ rebalancingFeePercentage: number;
30
+ fee: number;
31
+ imbalancingFee: number;
32
+ rebalancingFee: number;
33
+ };
26
34
  export type SimulateTradeEntity = {
27
35
  liquidationPrice: number;
28
36
  fees: number;
29
37
  takerFeesPercentage: number;
38
+ feesV2: SimulateTradeFeeEntity;
30
39
  estimatedPrice: number;
31
40
  estimatedSlippage: number;
32
41
  marginRatio: MarginAccountEntity['marginRatioPercentage'];
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"/","sources":["clients/modules/trade.simulation/types.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAEpE,MAAM,MAAM,6BAA6B,GAAG;IAC1C,QAAQ,EAAE,YAAY,CAAC,IAAI,CAAC,CAAC;IAC7B,eAAe,EAAE,mBAAmB,CAAC,IAAI,CAAC,CAAC;CAC5C,CAAC;AAEF,MAAM,MAAM,6BAA6B,GAAG;IAC1C,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,CAAC,EAAE,OAAO,CAAC;CACpB,CAAC;AAEF,MAAM,MAAM,iCAAiC,GAAG;IAC9C,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,oBAAoB,GAAG;IACjC,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,+CAA+C,GAAG;IAC5D,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,OAAO,CAAC;CACnB,CAAC;AAEF,MAAM,MAAM,+CAA+C,GAAG,MAAM,CAAC;AAErE,MAAM,MAAM,mBAAmB,GAAG;IAChC,gBAAgB,EAAE,MAAM,CAAC;IACzB,IAAI,EAAE,MAAM,CAAC;IACb,mBAAmB,EAAE,MAAM,CAAC;IAC5B,cAAc,EAAE,MAAM,CAAC;IACvB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,WAAW,E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CAAC;AAEF,MAAM,MAAM,4BAA4B,GAAG;IACzC,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;IACtB,aAAa,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,iCAAiC,GAAG,MAAM,CAAC"}
@@ -0,0 +1,8 @@
1
+ import { TradeSimulationState } from '@reyaxyz/common';
2
+ import { SimulateTradeFeeEntity } from './types';
3
+ export declare const computeFee: ({ tradeSimulationState, marketId, orderBase, }: {
4
+ marketId: number;
5
+ tradeSimulationState: TradeSimulationState;
6
+ orderBase: number;
7
+ }) => SimulateTradeFeeEntity;
8
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"/","sources":["clients/modules/trade.simulation/utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAAmB,oBAAoB,EAAE,MAAM,iBAAiB,CAAC;AACxE,OAAO,EAAE,sBAAsB,EAAE,MAAM,SAAS,CAAC;AAEjD,eAAO,MAAM,UAAU;cAKX,MAAM;0BACM,oBAAoB;eAC/B,MAAM;MACf,sBAwCH,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reyaxyz/api-sdk",
3
- "version": "0.143.2",
3
+ "version": "0.144.0",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "registry": "https://registry.npmjs.org"
@@ -33,7 +33,7 @@
33
33
  "generate:coverage-badges": "npx istanbul-badges-readme --silent"
34
34
  },
35
35
  "dependencies": {
36
- "@reyaxyz/common": "0.229.1",
36
+ "@reyaxyz/common": "0.230.0",
37
37
  "@simplewebauthn/types": "^10.0.0",
38
38
  "axios": "^1.6.2",
39
39
  "bignumber.js": "^9.1.2",
@@ -42,7 +42,7 @@
42
42
  "ws": "^8.16.0"
43
43
  },
44
44
  "packageManager": "pnpm@8.3.1",
45
- "gitHead": "638433b4e99693f2e9ad1ed50ca653526ca1a2f7",
45
+ "gitHead": "535fb6356a154bbe5dd57eecc42d7c0ba920c8b0",
46
46
  "devDependencies": {
47
47
  "@types/ws": "8.5.10"
48
48
  }
@@ -24,6 +24,7 @@ import {
24
24
  TradeSimulationConvertValueResult,
25
25
  } from '../trade.simulation/types';
26
26
  import { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';
27
+ import { computeFee } from '../trade.simulation/utils';
27
28
 
28
29
  export default class IsolatedOrderSimulationClient {
29
30
  private loadedData: TradeSimulationState | null = null;
@@ -81,21 +82,20 @@ export default class IsolatedOrderSimulationClient {
81
82
  simulate(
82
83
  params: IsolatedOrderSimulationSimulateParams,
83
84
  ): SimulateIsolatedOrderEntity {
84
- if (!this.loadedData) {
85
+ if (!this.loadedData || !this.marketId) {
85
86
  throw new Error('Data not loaded. Call arm() first.');
86
87
  }
87
88
 
89
+ const oraclePrice =
90
+ this.loadedData.exposureDataPassivePool.oraclePricePerMarket[
91
+ this.loadedData.marketConfiguration.market_id
92
+ ];
93
+
88
94
  let amount;
89
95
  if (params.fromBase) {
90
96
  amount = params.amount;
91
97
  } else {
92
- amount = BigNumber(params.amount)
93
- .div(
94
- this.loadedData.exposureDataPassivePool.oraclePricePerMarket[
95
- this.loadedData.marketConfiguration.market_id
96
- ],
97
- )
98
- .toNumber();
98
+ amount = BigNumber(params.amount).div(oraclePrice).toNumber();
99
99
  }
100
100
 
101
101
  const userAccountExposure =
@@ -114,21 +114,17 @@ export default class IsolatedOrderSimulationClient {
114
114
  this.loadedData.marketStorage,
115
115
  );
116
116
  const estimatedPrice = ExposureCommand.calculateEstimatedPrice(
117
- this.loadedData.exposureDataPassivePool.oraclePricePerMarket[
118
- this.loadedData.marketConfiguration.market_id
119
- ],
117
+ oraclePrice,
120
118
  slippage,
121
119
  );
122
120
 
123
121
  const amountSize = estimatedPrice * amount;
124
122
 
125
- const fees = ExposureCommand.calculateFee(
126
- this.loadedData.exposureDataPassivePool.oraclePricePerMarket[
127
- this.loadedData.marketConfiguration.market_id
128
- ],
129
- amount,
130
- this.loadedData.feeParameter,
131
- );
123
+ const feesV2 = computeFee({
124
+ tradeSimulationState: this.loadedData,
125
+ marketId: this.marketId,
126
+ orderBase: amount,
127
+ });
132
128
 
133
129
  /*
134
130
  amount of margin in rUSD terms that needs to be transferred from the source account to the destination account,
@@ -164,9 +160,7 @@ export default class IsolatedOrderSimulationClient {
164
160
  const liquidationPrice = ExposureCommand.calculateLiquidation(
165
161
  requiredMargin,
166
162
  isolatedLMR,
167
- this.loadedData.exposureDataPassivePool.oraclePricePerMarket[
168
- this.loadedData.marketConfiguration.market_id
169
- ],
163
+ oraclePrice,
170
164
  amount,
171
165
  );
172
166
 
@@ -193,9 +187,9 @@ export default class IsolatedOrderSimulationClient {
193
187
  return {
194
188
  estimatedPrice: estimatedPrice,
195
189
  estimatedSlippage: slippage * 100,
196
- fees: fees,
197
- takerFeesPercentage:
198
- BigNumber(this.loadedData.feeParameter).toNumber() * 100,
190
+ fees: feesV2.fee,
191
+ takerFeesPercentage: feesV2.feePercentage,
192
+ feesV2,
199
193
  liquidationPrice: liquidationPrice.toNumber(),
200
194
  marginRatio: marginRatio * 100,
201
195
  marginRatioHealth: marginRatioHealth,
@@ -208,7 +202,7 @@ export default class IsolatedOrderSimulationClient {
208
202
  max: xpEarnRangeMax,
209
203
  },
210
204
  maxSlippage: 1,
211
- } as SimulateIsolatedOrderEntity;
205
+ };
212
206
  }
213
207
 
214
208
  convertValue(
@@ -3,6 +3,7 @@ import {
3
3
  MarketEntity,
4
4
  EditCollateralAction,
5
5
  } from '@reyaxyz/common';
6
+ import { SimulateTradeFeeEntity } from '../trade.simulation/types';
6
7
 
7
8
  export type IsolatedOrderSimulationLoadDataParams = {
8
9
  marketId: MarketEntity['id'];
@@ -24,6 +25,7 @@ export type SimulateIsolatedOrderEntity = {
24
25
  liquidationPrice: number;
25
26
  fees: number;
26
27
  takerFeesPercentage: number;
28
+ feesV2: SimulateTradeFeeEntity;
27
29
  estimatedPrice: number;
28
30
  estimatedSlippage: number;
29
31
  marginRatio: MarginAccountEntity['marginRatioPercentage'];
@@ -22,6 +22,7 @@ import {
22
22
  } from '@reyaxyz/common';
23
23
  import BigNumber from 'bignumber.js';
24
24
  import { INSTANT_TRADING_RATE_XP } from '@reyaxyz/common';
25
+ import { computeFee } from './utils';
25
26
 
26
27
  export default class TradeSimulationClient {
27
28
  private marketId: number | null = null;
@@ -105,24 +106,23 @@ export default class TradeSimulationClient {
105
106
 
106
107
  // Synchronous method to simulate operations based on an amount
107
108
  simulate(params: TradeSimulationSimulateParams): SimulateTradeEntity {
108
- if (!this.loadedData) {
109
+ if (!this.loadedData || !this.marketId) {
109
110
  throw new Error('Data not loaded. Call arm() first.');
110
111
  }
111
112
 
112
113
  const { tradeSimulationState, userAccountExposure, passivePoolExposure } =
113
114
  this.loadedData;
114
115
 
116
+ const oraclePrice =
117
+ tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[
118
+ tradeSimulationState.marketConfiguration.market_id
119
+ ];
120
+
115
121
  let amount;
116
122
  if (params.fromBase) {
117
123
  amount = params.amount;
118
124
  } else {
119
- amount = BigNumber(params.amount)
120
- .div(
121
- tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[
122
- tradeSimulationState.marketConfiguration.market_id
123
- ],
124
- )
125
- .toNumber();
125
+ amount = BigNumber(params.amount).div(oraclePrice).toNumber();
126
126
  }
127
127
 
128
128
  /*
@@ -143,19 +143,15 @@ export default class TradeSimulationClient {
143
143
  );
144
144
 
145
145
  const estimatedPrice = ExposureCommand.calculateEstimatedPrice(
146
- tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[
147
- tradeSimulationState.marketConfiguration.market_id
148
- ],
146
+ oraclePrice,
149
147
  slippage,
150
148
  );
151
149
 
152
- const fees = ExposureCommand.calculateFee(
153
- tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[
154
- tradeSimulationState.marketConfiguration.market_id
155
- ],
156
- amount,
157
- tradeSimulationState.feeParameter,
158
- );
150
+ const feesV2 = computeFee({
151
+ tradeSimulationState,
152
+ marketId: this.marketId,
153
+ orderBase: amount,
154
+ });
159
155
 
160
156
  const {
161
157
  usdNodeMarginInfo: newMarginInfo,
@@ -202,9 +198,7 @@ export default class TradeSimulationClient {
202
198
  const liquidationPrice = ExposureCommand.calculateLiquidation(
203
199
  newMarginInfo.marginBalance,
204
200
  newQuoteTokenMarginInfo.liquidationMarginRequirement,
205
- tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[
206
- tradeSimulationState.marketConfiguration.market_id
207
- ],
201
+ oraclePrice,
208
202
  BigNumber(positionInfo?.base || 0).toNumber(),
209
203
  );
210
204
 
@@ -230,9 +224,9 @@ export default class TradeSimulationClient {
230
224
  return {
231
225
  estimatedPrice,
232
226
  estimatedSlippage: slippage * 100,
233
- fees,
234
- takerFeesPercentage:
235
- BigNumber(tradeSimulationState.feeParameter).toNumber() * 100,
227
+ fees: feesV2.fee,
228
+ takerFeesPercentage: feesV2.feePercentage,
229
+ feesV2,
236
230
  liquidationPrice: liquidationPrice.toNumber(),
237
231
  marginRatio: marginRatio * 100,
238
232
  marginRatioHealth,
@@ -246,7 +240,7 @@ export default class TradeSimulationClient {
246
240
  max: xpEarnRangeMax,
247
241
  },
248
242
  maxSlippage: 1,
249
- } as SimulateTradeEntity;
243
+ };
250
244
  }
251
245
 
252
246
  getRiskMatrixElement(): number {
@@ -297,11 +291,13 @@ export default class TradeSimulationClient {
297
291
  const snappedAmountInBase = this.roundToBaseSpacing(amount, baseSpacing);
298
292
  const snappedAmount = snappedAmountInBase * params.triggerPrice;
299
293
 
300
- const fees = ExposureCommand.calculateFee(
301
- params.triggerPrice,
302
- amount,
303
- tradeSimulationState.feeParameter,
304
- );
294
+ const { fee: fees } = ExposureCommand.calculateFee({
295
+ oraclePrice: params.triggerPrice,
296
+ orderBase: amount,
297
+ poolBasePreTrade: 0,
298
+ feeParameter: tradeSimulationState.feeParameter,
299
+ rebalancingFeeParameter: BigNumber(0),
300
+ });
305
301
 
306
302
  const marginBalance =
307
303
  userAccountExposure.getUsdNodeMarginInfo.marginBalance;
@@ -31,10 +31,20 @@ export type TradeSimulationConvertValueEstimatedPriceParams = {
31
31
 
32
32
  export type TradeSimulationConvertValueEstimatedPriceResult = number;
33
33
 
34
+ export type SimulateTradeFeeEntity = {
35
+ feeTier: number;
36
+ feePercentage: number;
37
+ rebalancingFeePercentage: number;
38
+ fee: number;
39
+ imbalancingFee: number;
40
+ rebalancingFee: number;
41
+ };
42
+
34
43
  export type SimulateTradeEntity = {
35
44
  liquidationPrice: number;
36
- fees: number;
37
- takerFeesPercentage: number;
45
+ fees: number; // TODO: deprecate when feeV2 is linked up
46
+ takerFeesPercentage: number; // TODO: deprecate when feeV2 is linked up
47
+ feesV2: SimulateTradeFeeEntity;
38
48
  estimatedPrice: number;
39
49
  estimatedSlippage: number;
40
50
  marginRatio: MarginAccountEntity['marginRatioPercentage'];
@@ -0,0 +1,52 @@
1
+ import { ExposureCommand, TradeSimulationState } from '@reyaxyz/common';
2
+ import { SimulateTradeFeeEntity } from './types';
3
+
4
+ export const computeFee = ({
5
+ tradeSimulationState,
6
+ marketId,
7
+ orderBase,
8
+ }: {
9
+ marketId: number;
10
+ tradeSimulationState: TradeSimulationState;
11
+ orderBase: number;
12
+ }): SimulateTradeFeeEntity => {
13
+ const oraclePrice =
14
+ tradeSimulationState.exposureDataPassivePool.oraclePricePerMarket[
15
+ tradeSimulationState.marketConfiguration.market_id
16
+ ];
17
+
18
+ const poolPosition =
19
+ tradeSimulationState.exposureDataPassivePool.positionInfoMarketConfiguration.find(
20
+ (p) => p.market_id === marketId,
21
+ );
22
+
23
+ const poolBasePreTrade = Number(poolPosition?.base || 0);
24
+
25
+ // TODO: once api is updated, change to the following:
26
+ // const { feeParameter, rebalancingFeeParameter, feeTier } =
27
+ // tradeSimulationState.feeParameters;
28
+
29
+ const feeParameter = tradeSimulationState.feeParameter;
30
+ const rebalancingFeeParameter = tradeSimulationState.feeParameter;
31
+ const feeTier = 0;
32
+
33
+ const { fee, rebalancingFee, imbalancingFee } = ExposureCommand.calculateFee({
34
+ oraclePrice,
35
+ orderBase,
36
+ poolBasePreTrade,
37
+ feeParameter,
38
+ rebalancingFeeParameter,
39
+ });
40
+
41
+ const feePercentage = Number(feeParameter) * 100;
42
+ const rebalancingFeePercentage = Number(rebalancingFeeParameter) * 100;
43
+
44
+ return {
45
+ feeTier,
46
+ feePercentage,
47
+ rebalancingFeePercentage,
48
+ fee,
49
+ rebalancingFee,
50
+ imbalancingFee,
51
+ };
52
+ };