@reyaxyz/common 0.364.0 → 0.364.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/commands/exposure/command.js +2 -340
- package/dist/commands/exposure/command.js.map +1 -1
- package/dist/commands/exposure/types.js.map +1 -1
- package/dist/incentives-api-types.js.map +1 -1
- package/dist/trading-api-types.js.map +1 -1
- package/dist/types/commands/exposure/command.d.ts +1 -44
- package/dist/types/commands/exposure/command.d.ts.map +1 -1
- package/dist/types/commands/exposure/types.d.ts +0 -7
- package/dist/types/commands/exposure/types.d.ts.map +1 -1
- package/dist/types/incentives-api-types.d.ts +1 -1
- package/dist/types/incentives-api-types.d.ts.map +1 -1
- package/dist/types/trading-api-types.d.ts +1 -23
- package/dist/types/trading-api-types.d.ts.map +1 -1
- package/dist/types/types.d.ts +0 -8
- package/dist/types/types.d.ts.map +1 -1
- package/dist/types/utils/calculate.d.ts +0 -125
- package/dist/types/utils/calculate.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/calculate.js +1 -324
- package/dist/utils/calculate.js.map +1 -1
- package/package.json +3 -5
- package/src/commands/exposure/command.ts +0 -550
- package/src/commands/exposure/types.ts +0 -9
- package/src/incentives-api-types.ts +1 -1
- package/src/trading-api-types.ts +1 -33
- package/src/types.ts +0 -10
- package/src/utils/calculate.ts +0 -497
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"command.js","sourceRoot":"/","sources":["commands/exposure/command.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,8DAAqC;AACrC,sEAAyC;AAiBzC,qCAKqB;AAER,QAAA,gBAAgB,GAAG,IAAA,sBAAS,EAAC,MAAM,CAAC,CAAC;AACrC,QAAA,gBAAgB,GAAG,IAAA,sBAAS,EAAC,OAAO,CAAC,CAAC;AAEnD,SAAgB,gBAAgB,CAAC,IAAe;IAC9C,IAAI,IAAI,CAAC,EAAE,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AM,0BAA0B,GAAG,eAAe,CAAC,qBAAqB,CACtE,IAAI,CAAC,oBAAoB,EACzB,eAAe,CAAC,YAAY,EAC5B,eAAe,CAAC,aAAa,CAC9B,CAAC;gBAEF,mBAAmB,IAAI,0BAA0B,CAAC;YACpD,CAAC;YAED,OAAO,mBAAmB,CAAC;QAC7B,CAAC;;;OAAA;IAED,uCAAa,GAAb;QACE,OAAO,IAAI,CAAC,UAAU,CAAC,QAAQ,EAAE,CAAC;IACpC,CAAC;IACH,sBAAC;AAAD,CAAC,AAvvCD,IAuvCC;AAvvCY,0CAAe","sourcesContent":["import BigNumber from 'bignumber.js';\nimport cloneDeep from 'lodash.clonedeep';\nimport {\n AccountAssetBalance,\n CollateralAddressToExchangePriceMap,\n CollateralInfo,\n ExchangeInfo,\n ExposureCommandState,\n MarginInfo,\n MarketConfiguration,\n MarketIdToOraclePriceMap,\n MarketStorage,\n PositionInfo,\n PositionInfoMarketConfiguration,\n RiskMatrix,\n RiskMultipliersConfiguration,\n EditCollateralAction,\n} from './types';\nimport {\n amountNormalizer,\n MA_HEALTH_DANGER_THRESHOLD,\n MA_HEALTH_WARNING_THRESHOLD,\n POOL_IMR,\n} from '../../utils';\n\nexport const MAX_FUNDING_RATE = BigNumber('0.07');\nexport const MIN_FUNDING_RATE = BigNumber('-0.07');\n\nexport function clampFundingRate(rate: BigNumber): BigNumber {\n if (rate.gt(MAX_FUNDING_RATE)) return MAX_FUNDING_RATE;\n if (rate.lt(MIN_FUNDING_RATE)) return MIN_FUNDING_RATE;\n return rate;\n}\n\nfunction trapezoidArea(r0: BigNumber, r1: BigNumber, t: BigNumber): BigNumber {\n return r0.plus(r1).div(2).times(t);\n}\n\nfunction clampedArea(\n r0: BigNumber,\n v: BigNumber,\n periods: BigNumber,\n boundary: BigNumber,\n): BigNumber {\n const tc = boundary.minus(r0).div(v);\n return trapezoidArea(r0, boundary, tc).plus(\n trapezoidArea(boundary, boundary, periods.minus(tc)),\n );\n}\n\nexport class ExposureCommand {\n accountId: number;\n rootCollateralPoolId: number;\n oraclePricePerMarket: MarketIdToOraclePriceMap;\n accountBalancePerAsset: AccountAssetBalance[];\n groupedByCollateral: Record<string, AccountAssetBalance>;\n riskMultipliers: RiskMultipliersConfiguration;\n riskMatrices: RiskMatrix[];\n exchangeInfoPerAsset: ExchangeInfo[];\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];\n uniqueTokenAddresses: string[];\n uniqueQuoteCollaterals: string[];\n tokenMarginInfoPerAsset: MarginInfo[];\n realizedPnLSum: BigNumber;\n unrealizedPnLSum: BigNumber;\n mtmRpnlSum: BigNumber;\n collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap;\n constructor(\n accountId: number,\n rootCollateralPoolId: number,\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n accountBalancePerAsset: AccountAssetBalance[],\n groupedByCollateral: Record<string, AccountAssetBalance>,\n riskMultipliers: RiskMultipliersConfiguration,\n riskMatrices: RiskMatrix[],\n exchangeInfoPerAsset: ExchangeInfo[],\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[],\n uniqueTokenAddresses: string[],\n uniqueQuoteCollaterals: string[],\n tokenMarginInfoPerAsset: MarginInfo[],\n realizedPnLSum: BigNumber,\n unrealizedPnLSum: BigNumber,\n mtmRpnlSum: BigNumber,\n collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap,\n ) {\n this.accountId = accountId;\n this.rootCollateralPoolId = rootCollateralPoolId;\n this.oraclePricePerMarket = oraclePricePerMarket;\n this.accountBalancePerAsset = accountBalancePerAsset;\n this.groupedByCollateral = groupedByCollateral;\n this.riskMultipliers = riskMultipliers;\n this.riskMatrices = riskMatrices;\n this.exchangeInfoPerAsset = exchangeInfoPerAsset;\n this.positionInfoMarketConfiguration = positionInfoMarketConfiguration;\n this.uniqueTokenAddresses = uniqueTokenAddresses;\n this.uniqueQuoteCollaterals = uniqueQuoteCollaterals;\n this.tokenMarginInfoPerAsset = tokenMarginInfoPerAsset;\n this.realizedPnLSum = realizedPnLSum;\n this.unrealizedPnLSum = unrealizedPnLSum;\n this.mtmRpnlSum = mtmRpnlSum;\n this.collateralAddressToExchangePrice = collateralAddressToExchangePrice;\n }\n\n getState(): ExposureCommandState {\n return {\n accountId: this.accountId,\n rootCollateralPoolId: this.rootCollateralPoolId,\n oraclePricePerMarket: this.oraclePricePerMarket,\n accountBalancePerAsset: this.accountBalancePerAsset,\n groupedByCollateral: this.groupedByCollateral,\n riskMultipliers: this.riskMultipliers,\n riskMatrices: this.riskMatrices,\n exchangeInfoPerAsset: this.exchangeInfoPerAsset,\n positionInfoMarketConfiguration: this.positionInfoMarketConfiguration,\n uniqueTokenAddresses: this.uniqueTokenAddresses,\n uniqueQuoteCollaterals: this.uniqueQuoteCollaterals,\n tokenMarginInfoPerAsset: this.tokenMarginInfoPerAsset,\n realizedPnLSum: this.realizedPnLSum,\n unrealizedPnLSum: this.unrealizedPnLSum,\n mtmRpnlSum: this.mtmRpnlSum,\n collateralAddressToExchangePrice: this.collateralAddressToExchangePrice,\n };\n }\n\n get getUsdNodeMarginInfo() {\n return ExposureCommand.getUsdNodeMarginInfo(\n this.rootCollateralPoolId,\n this.uniqueTokenAddresses,\n this.exchangeInfoPerAsset,\n this.tokenMarginInfoPerAsset,\n );\n }\n\n get balancePerAsset() {\n return this.tokenMarginInfoPerAsset;\n }\n get exchangePricePerAsset() {\n return this.exchangeInfoPerAsset;\n }\n\n getUsdNodeMarginInfoPostTrade(\n positionAmount: number,\n collateralAddress: string,\n marketConfiguration: MarketConfiguration,\n riskBlockId: number,\n ) {\n // perform deep copy of the object\n const positionInfoMarketConfiguration: PositionInfoMarketConfiguration[] =\n cloneDeep(this.positionInfoMarketConfiguration);\n\n // Check if the market_id already exists in the array\n const existingConfigIndex = positionInfoMarketConfiguration.findIndex(\n (config) =>\n config.market_id ===\n BigNumber(String(marketConfiguration.market_id)).toNumber(),\n );\n\n if (existingConfigIndex !== -1) {\n // If it exists, update the amount\n positionInfoMarketConfiguration[existingConfigIndex].base = BigNumber(\n positionInfoMarketConfiguration[existingConfigIndex].base,\n ).plus(positionAmount);\n } else {\n // If it doesn't exist, add a new element\n positionInfoMarketConfiguration.push({\n base: BigNumber(positionAmount),\n realized_pnl: BigNumber(0),\n realized_pnl_with_mtm: BigNumber(0),\n realized_pnl_latest_snapshot: BigNumber(0),\n latest_funding_cashflow: BigNumber(0),\n last_price: BigNumber(0),\n average_entry_price_off_chain_tracker: BigNumber(0),\n funding_value_off_chain_tracker: BigNumber(0),\n average_entry_price: BigNumber(0),\n last_timestamp: BigNumber(0),\n funding_value: BigNumber(0),\n base_multiplier: BigNumber(0),\n adl_unwind_price: BigNumber(0),\n market_id: BigNumber(String(marketConfiguration.market_id)).toNumber(),\n account_id: this.accountId,\n market_configuration: marketConfiguration,\n risk_block_id: riskBlockId,\n });\n }\n\n const uniqueQuoteCollaterals = new Set(this.uniqueQuoteCollaterals);\n uniqueQuoteCollaterals.add(collateralAddress);\n\n const tokenMarginInfoPerAsset =\n ExposureCommand.calculateTokenMarginInfoPerAsset(\n this.groupedByCollateral,\n this.rootCollateralPoolId,\n this.riskMatrices,\n this.riskMultipliers,\n uniqueQuoteCollaterals,\n this.realizedPnLSum,\n this.unrealizedPnLSum,\n positionInfoMarketConfiguration,\n this.oraclePricePerMarket,\n );\n\n const uniqueTokenAddresses = [...this.uniqueTokenAddresses];\n if (!this.uniqueTokenAddresses.includes(collateralAddress)) {\n uniqueTokenAddresses.push(collateralAddress);\n }\n\n return {\n usdNodeMarginInfo: ExposureCommand.getUsdNodeMarginInfo(\n this.rootCollateralPoolId,\n uniqueTokenAddresses,\n this.exchangeInfoPerAsset,\n tokenMarginInfoPerAsset,\n ),\n tokenMarginInfoPerAsset: tokenMarginInfoPerAsset,\n positionInfoMarketConfiguration: positionInfoMarketConfiguration,\n };\n }\n\n getEditCollateralActionsToCoverMargin(\n requiredMargin: number,\n ): EditCollateralAction[] {\n /*\n * Note, this function is implicitely making an assumption that required margin can be covered by\n * the account without breaching account IMR\n * */\n const editCollateralActions: EditCollateralAction[] = [];\n let marginToCover = requiredMargin;\n\n const uniqueQuoteCollaterals = new Set(this.uniqueQuoteCollaterals);\n\n const tokenMarginInfoPerAsset =\n ExposureCommand.calculateTokenMarginInfoPerAsset(\n this.groupedByCollateral,\n this.rootCollateralPoolId,\n this.riskMatrices,\n this.riskMultipliers,\n uniqueQuoteCollaterals,\n this.realizedPnLSum,\n this.unrealizedPnLSum,\n this.positionInfoMarketConfiguration,\n this.oraclePricePerMarket,\n );\n\n // todo: p2: consider prioritising rUSD when looping through token infos & document math in comments\n for (const tokenInfo of tokenMarginInfoPerAsset) {\n if (tokenInfo.marginBalance < 0) {\n continue;\n }\n\n // todo: p1: haircut and exchange rate adjustment should not be done for rUSD\n // does exchangeInfo currently return haircut as zero and price as 1?\n // todo: p2: can just look at net deposits rather than margin balance for non-rusd as non pnl\n\n const exchangeInfo = this.exchangeInfoPerAsset.find((exchangeInfo) => {\n return tokenInfo.assetAddress === exchangeInfo.tokenAddress;\n });\n\n if (!exchangeInfo) {\n throw new Error(\n 'Unable to retrieve exchange info when calculating collaterals needed to cover margin',\n );\n }\n\n const marginBalanceWithHaircutInRUSD =\n ExposureCommand.exchangeWithPriceHaircut(\n tokenInfo.marginBalance,\n exchangeInfo.price,\n exchangeInfo.priceHaircut,\n );\n\n if (marginBalanceWithHaircutInRUSD > marginToCover) {\n const collateralDelta =\n -ExposureCommand.reverseExchangeWithPriceHaircut(\n marginToCover,\n exchangeInfo.price,\n exchangeInfo.priceHaircut,\n );\n editCollateralActions.push({\n collateralAddress: tokenInfo.assetAddress,\n collateralDelta: collateralDelta,\n });\n break;\n } else {\n editCollateralActions.push({\n collateralAddress: tokenInfo.assetAddress,\n collateralDelta: -tokenInfo.marginBalance,\n });\n marginToCover = marginToCover - marginBalanceWithHaircutInRUSD;\n }\n }\n return editCollateralActions;\n }\n\n getUsdNodeMarginInfoPostEditCollaterals(\n editCollateralActions: EditCollateralAction[],\n ) {\n // todo: check if there's a way to simplify this function & deprecate the single edit collateral sim below as it's a\n // subset of this function\n\n // perform deep copy of the object\n const groupedByCollateral: Record<string, AccountAssetBalance> = cloneDeep(\n this.groupedByCollateral,\n );\n\n const uniqueQuoteCollaterals = new Set(this.uniqueQuoteCollaterals);\n const uniqueTokenAddresses = [...this.uniqueTokenAddresses];\n\n // counterfactual update deep copy\n\n for (const action of editCollateralActions) {\n if (groupedByCollateral[action.collateralAddress]) {\n groupedByCollateral[action.collateralAddress] = {\n ...groupedByCollateral[action.collateralAddress],\n amount:\n groupedByCollateral[action.collateralAddress].amount +\n action.collateralDelta,\n };\n } else {\n groupedByCollateral[action.collateralAddress] = {\n accountId: this.accountId,\n collateral: action.collateralAddress,\n amount: action.collateralDelta,\n };\n }\n\n uniqueQuoteCollaterals.add(action.collateralAddress);\n\n if (!this.uniqueTokenAddresses.includes(action.collateralAddress)) {\n uniqueTokenAddresses.push(action.collateralAddress);\n }\n }\n\n const tokenMarginInfoPerAsset =\n ExposureCommand.calculateTokenMarginInfoPerAsset(\n groupedByCollateral,\n this.rootCollateralPoolId,\n this.riskMatrices,\n this.riskMultipliers,\n uniqueQuoteCollaterals,\n this.realizedPnLSum,\n this.unrealizedPnLSum,\n this.positionInfoMarketConfiguration,\n this.oraclePricePerMarket,\n );\n\n return ExposureCommand.getUsdNodeMarginInfo(\n this.rootCollateralPoolId,\n uniqueTokenAddresses,\n this.exchangeInfoPerAsset,\n tokenMarginInfoPerAsset,\n );\n }\n\n getUsdNodeMarginInfoPostEditCollateral(\n collateralDelta: number,\n collateralAddress: string,\n ) {\n // perform deep copy of the object\n const groupedByCollateral: Record<string, AccountAssetBalance> = cloneDeep(\n this.groupedByCollateral,\n );\n\n // counterfactual update deep copy\n if (groupedByCollateral[collateralAddress]) {\n groupedByCollateral[collateralAddress] = {\n ...groupedByCollateral[collateralAddress],\n amount: groupedByCollateral[collateralAddress].amount + collateralDelta,\n };\n } else {\n groupedByCollateral[collateralAddress] = {\n accountId: this.accountId,\n collateral: collateralAddress,\n amount: collateralDelta,\n };\n }\n\n const uniqueQuoteCollaterals = new Set(this.uniqueQuoteCollaterals);\n const tokenMarginInfoPerAsset =\n ExposureCommand.calculateTokenMarginInfoPerAsset(\n groupedByCollateral,\n this.rootCollateralPoolId,\n this.riskMatrices,\n this.riskMultipliers,\n uniqueQuoteCollaterals,\n this.realizedPnLSum,\n this.unrealizedPnLSum,\n this.positionInfoMarketConfiguration,\n this.oraclePricePerMarket,\n );\n\n const uniqueTokenAddresses = [...this.uniqueTokenAddresses];\n if (!this.uniqueTokenAddresses.includes(collateralAddress)) {\n uniqueTokenAddresses.push(collateralAddress);\n }\n\n return ExposureCommand.getUsdNodeMarginInfo(\n this.rootCollateralPoolId,\n uniqueTokenAddresses,\n this.exchangeInfoPerAsset,\n tokenMarginInfoPerAsset,\n );\n }\n\n static calculateTokenMarginInfoPerAsset(\n groupedByCollateral: Record<string, AccountAssetBalance>,\n rootCollateralPoolId: number,\n riskMatrices: RiskMatrix[],\n riskMultipliers: RiskMultipliersConfiguration,\n uniqueQuoteCollaterals: Set<string>,\n realizedPnLSum: BigNumber,\n unrealizedPnLSum: BigNumber,\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[],\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n ): MarginInfo[] {\n const tokenMarginInfoPerAsset: MarginInfo[] = [];\n\n // todo: p2: investigate the ts-expect-error cases below\n // @ts-expect-error no easy way to make sure string can be casted to Lowercase<string> type\n const uniqueQuoteTokens: Lowercase<string>[] = Array.from(\n uniqueQuoteCollaterals,\n );\n\n // @ts-expect-error no easy way to make sure string can be casted to Lowercase<string> type\n const tokenUnion: Set<Lowercase<string>> = new Set([\n ...Object.keys(groupedByCollateral),\n ...uniqueQuoteTokens,\n ]); // get unique union of those arrays\n const uniqueTokenAddresses: Lowercase<string>[] = Array.from(tokenUnion);\n\n for (const token of uniqueTokenAddresses) {\n tokenMarginInfoPerAsset.push(\n ExposureCommand.getTokenMarginInfo(\n rootCollateralPoolId,\n riskMatrices,\n riskMultipliers,\n ExposureCommand.getCollateralInfo(\n token,\n uniqueQuoteCollaterals.has(token) ? realizedPnLSum : BigNumber(0),\n uniqueQuoteCollaterals.has(token) ? unrealizedPnLSum : BigNumber(0),\n groupedByCollateral[token]?.amount || 0,\n ),\n token,\n positionInfoMarketConfiguration,\n oraclePricePerMarket,\n uniqueQuoteTokens,\n ),\n );\n }\n\n return tokenMarginInfoPerAsset;\n }\n static calculateLiquidation(\n marginBalance: number,\n liquidationMarginRequirement: number,\n oraclePrice: number,\n positionBase: number,\n ): BigNumber {\n if (positionBase === 0 || liquidationMarginRequirement === 0) {\n return BigNumber(0);\n }\n const liquidationPrice = BigNumber(oraclePrice).minus(\n BigNumber(marginBalance)\n .minus(liquidationMarginRequirement)\n .div(positionBase),\n );\n\n return BigNumber.max(0, liquidationPrice);\n }\n\n static calculateImpliedLeverage(\n notionalExposure: number,\n oldIMR: number,\n newIMR: number,\n ): number {\n const changeInImr = BigNumber(newIMR).minus(oldIMR);\n\n if (changeInImr.eq(0)) {\n return 0;\n }\n return BigNumber(notionalExposure).div(changeInImr).toNumber();\n }\n\n static combineMarginInfo(\n parentMarginInfo: MarginInfo,\n sonMarginInfo: MarginInfo,\n sonParentExchangeInfo: ExchangeInfo,\n ): MarginInfo {\n return {\n assetAddress: parentMarginInfo.assetAddress,\n marginBalance: BigNumber(parentMarginInfo.marginBalance)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.marginBalance,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n realBalance: BigNumber(parentMarginInfo.realBalance)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.realBalance,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n initialDelta: BigNumber(parentMarginInfo.initialDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.realBalance,\n sonMarginInfo.initialDelta,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n maintenanceDelta: BigNumber(parentMarginInfo.maintenanceDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.maintenanceDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n liquidationDelta: BigNumber(parentMarginInfo.liquidationDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.liquidationDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n dutchDelta: BigNumber(parentMarginInfo.dutchDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.dutchDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n adlDelta: BigNumber(parentMarginInfo.adlDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.adlDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n\n initialBufferDelta: BigNumber(parentMarginInfo.initialBufferDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.initialBufferDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n liquidationMarginRequirement: BigNumber(\n parentMarginInfo.liquidationMarginRequirement,\n )\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.liquidationMarginRequirement,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n };\n }\n\n static getUsdNodeMarginInfo(\n accountCollateralPoolId: number,\n quoteTokens: string[],\n exchangeInfoPerAsset: ExchangeInfo[],\n marginInfoPerToken: MarginInfo[],\n ) {\n let usdNodeMarginInfo: MarginInfo = {\n assetAddress: '',\n marginBalance: 0,\n realBalance: 0,\n initialDelta: 0,\n maintenanceDelta: 0,\n liquidationDelta: 0,\n dutchDelta: 0,\n adlDelta: 0,\n initialBufferDelta: 0,\n liquidationMarginRequirement: 0,\n };\n for (const quoteToken of quoteTokens) {\n const exchangeInfo = exchangeInfoPerAsset.find((exchangeInfo) => {\n return quoteToken === exchangeInfo.tokenAddress;\n });\n\n const marginInfo = marginInfoPerToken.find((marginInfo) => {\n return quoteToken === marginInfo.assetAddress;\n });\n\n if (!exchangeInfo || !marginInfo) {\n throw Error(`Missing exchangeInfo/marginInfo for ${quoteToken}`);\n }\n\n usdNodeMarginInfo = ExposureCommand.combineMarginInfo(\n usdNodeMarginInfo,\n marginInfo,\n exchangeInfo,\n );\n }\n\n return usdNodeMarginInfo;\n }\n static getCollateralInfo(\n collateralAddress: string,\n realisedPnl: BigNumber,\n unrealizedPnL: BigNumber,\n netDeposits: number,\n ): CollateralInfo {\n return {\n netDeposits: netDeposits,\n marginBalance: BigNumber(netDeposits)\n .plus(realisedPnl)\n .plus(unrealizedPnL)\n .toNumber(),\n realBalance: BigNumber(netDeposits).plus(realisedPnl).toNumber(),\n };\n }\n\n static getTokenMarginInfo(\n rootCollateralPoolId: number,\n riskMatrices: RiskMatrix[],\n riskMultipliers: RiskMultipliersConfiguration,\n collateralInfo: CollateralInfo,\n collateralAddress: Lowercase<string>,\n positions: PositionInfoMarketConfiguration[],\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n uniqueQuoteTokens: string[],\n ): MarginInfo {\n const marginRequirements = {\n liquidationMarginRequirement: 0,\n initialMarginRequirement: 0,\n maintenanceMarginRequirement: 0,\n dutchMarginRequirement: 0,\n adlMarginRequirement: 0,\n initialBufferMarginRequirement: 0,\n };\n if (uniqueQuoteTokens.includes(collateralAddress)) {\n // uniqueQuoteTokens is list is active markets tokens\n for (const riskMatrix of riskMatrices) {\n const filledExposures = ExposureCommand.getBlockExposures(\n positions,\n oraclePricePerMarket,\n riskMatrix.risk_block_id,\n );\n\n marginRequirements.liquidationMarginRequirement = BigNumber(\n marginRequirements.liquidationMarginRequirement,\n )\n .plus(\n ExposureCommand.computeLiquidationMarginRequirement(\n riskMatrix.matrix,\n filledExposures,\n ),\n )\n .toNumber();\n }\n\n // Get the initial margin requirement\n marginRequirements.initialMarginRequirement = amountNormalizer(\n String(riskMultipliers.im_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n // Get the maintenance margin requirement\n marginRequirements.maintenanceMarginRequirement = amountNormalizer(\n String(riskMultipliers.mmr_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n // Get the dutch margin requirement\n marginRequirements.dutchMarginRequirement = amountNormalizer(\n String(riskMultipliers.dutch_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n\n // Get the adl margin requirement\n marginRequirements.adlMarginRequirement = amountNormalizer(\n String(riskMultipliers.adl_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n\n // Get the initial buffer margin requirement\n marginRequirements.initialBufferMarginRequirement = amountNormalizer(\n String(riskMultipliers.im_buffer_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n }\n return {\n assetAddress: collateralAddress,\n marginBalance: collateralInfo.marginBalance,\n realBalance: collateralInfo.realBalance,\n initialDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.initialMarginRequirement)\n .toNumber(),\n maintenanceDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.maintenanceMarginRequirement)\n .toNumber(),\n liquidationDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.liquidationMarginRequirement)\n .toNumber(),\n dutchDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.dutchMarginRequirement)\n .toNumber(),\n adlDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.adlMarginRequirement)\n .toNumber(),\n initialBufferDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.initialBufferMarginRequirement)\n .toNumber(),\n liquidationMarginRequirement:\n marginRequirements.liquidationMarginRequirement,\n };\n }\n\n static computeLiquidationMarginRequirement(\n matrix: BigNumber[][],\n filledExposures: BigNumber[],\n ): number {\n let lmrFilledSquared = 0;\n\n for (let i = 0; i < filledExposures.length; i++) {\n if (BigNumber(filledExposures[i]).eq(0)) {\n continue;\n }\n for (let j = 0; j < filledExposures.length; j++) {\n const riskParam = matrix[i][j];\n\n if (BigNumber(filledExposures[j]).eq(0) || BigNumber(riskParam).eq(0)) {\n continue;\n }\n\n lmrFilledSquared = BigNumber(lmrFilledSquared)\n .plus(\n BigNumber(filledExposures[i])\n .multipliedBy(filledExposures[j])\n .multipliedBy(riskParam),\n )\n .toNumber();\n }\n }\n return BigNumber(lmrFilledSquared).sqrt().toNumber();\n }\n\n static getBlockExposures(\n positions: PositionInfoMarketConfiguration[],\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n riskBlockId: number,\n ): BigNumber[] {\n const filledExposures: number[] = [];\n let maxIndex = 0; // Keep track of the highest riskMatrixIndex encountered\n\n for (const position of positions) {\n if (riskBlockId !== position.risk_block_id) continue;\n const marketFilledExposure = ExposureCommand.getAccountFilledExposures(\n position,\n position.market_configuration,\n oraclePricePerMarket[position.market_id],\n );\n const index = marketFilledExposure.riskMatrixIndex;\n filledExposures[index] = BigNumber(filledExposures[index] || 0)\n .plus(marketFilledExposure.exposure)\n .toNumber();\n\n if (index > maxIndex) maxIndex = index;\n }\n\n // Ensure filledExposures array is correctly populated up to maxIndex\n for (let i = 0; i <= maxIndex; i++) {\n if (filledExposures[i] === undefined) {\n filledExposures[i] = 0;\n }\n }\n return filledExposures.map((num) => BigNumber(num));\n }\n\n static getAccountFilledExposures(\n position: PositionInfo,\n marketConfiguration: MarketConfiguration,\n oraclePrice: number,\n ) {\n const base = position.base;\n return {\n exposure: BigNumber(oraclePrice).multipliedBy(base),\n riskMatrixIndex: BigNumber(\n String(marketConfiguration.risk_matrix_index),\n ).toNumber(),\n };\n }\n\n static computePricePnL(\n openBase: BigNumber,\n openPrice: BigNumber,\n exitPrice: BigNumber,\n ) {\n return BigNumber(\n BigNumber(exitPrice).minus(openPrice).multipliedBy(openBase),\n );\n }\n\n static getMarginRatio(\n marginInfo: Pick<\n MarginInfo,\n 'marginBalance' | 'liquidationMarginRequirement'\n >,\n ) {\n if (marginInfo.liquidationMarginRequirement === 0) {\n return 0;\n }\n\n if (marginInfo.marginBalance <= 0) {\n return 1;\n }\n\n const health = BigNumber(marginInfo.liquidationMarginRequirement).div(\n marginInfo.marginBalance,\n );\n\n if (health.gt(1)) {\n return 1;\n }\n return health.toNumber();\n }\n\n static exchangeWithPriceHaircut(\n quantity: number,\n price: number,\n haircut: number,\n ) {\n // For positive quantities, the haircut is `quantity * (1 - haircut)`\n // For negative values, the haircut is `quantity / (1 - haircut)` because a negative value means the haircut should be applied from B to A.\n const calHelper = BigNumber(quantity).gt(0)\n ? BigNumber(1).minus(haircut)\n : BigNumber(1).div(BigNumber(1).minus(haircut));\n const haircutPrice = BigNumber(price).multipliedBy(calHelper);\n\n return haircutPrice.multipliedBy(quantity).toNumber();\n }\n\n static reverseExchangeWithPriceHaircut(\n quantity: number,\n price: number,\n haircut: number,\n ) {\n /*\n * this operation takes quantity in rUSD terms, price between collateral token (e.g. weth) and rusd\n * alongside the haircut between weth and rusd\n * it then returns a quantity in collateral token terms (e.g. weth) which would return quantity if it were to be\n * passed through the exchangeWithPriceHaircut function\n * */\n // todo: p2: consider abstracting haircut price calculation into separate function as duplciated\n // For positive quantities, the haircut is `quantity * (1 - haircut)`\n // For negative values, the haircut is `quantity / (1 - haircut)` because a negative value means the haircut should be applied from B to A.\n const calHelper = BigNumber(quantity).gt(0)\n ? BigNumber(1).minus(haircut)\n : BigNumber(1).div(BigNumber(1).minus(haircut));\n const haircutPrice = BigNumber(price).multipliedBy(calHelper);\n\n return BigNumber(quantity).dividedBy(haircutPrice).toNumber();\n }\n\n static getBalanceWithHaircut(\n exchangeInfoPerAsset: ExchangeInfo[],\n assetAddress: string,\n marginBalance: number,\n ) {\n // todo: p1: haircut and exchange rate adjustment should not be done for rUSD\n // does exchangeInfo currently return haircut as zero and price as 1?\n // todo: p2: can just look at net deposits rather than margin balance for non-rusd as non pnl\n\n const exchangeInfo = exchangeInfoPerAsset.find((exchangeInfo) => {\n return assetAddress === exchangeInfo.tokenAddress;\n });\n\n if (!exchangeInfo) {\n throw new Error(\n 'Unable to retrieve exchange info when calculating collaterals needed to cover margin',\n );\n }\n\n return ExposureCommand.exchangeWithPriceHaircut(\n marginBalance,\n exchangeInfo.price,\n exchangeInfo.priceHaircut,\n );\n }\n\n getMaxExposure(\n marketConfiguration: MarketConfiguration,\n marketStorage: MarketStorage,\n isPool: boolean,\n ) {\n // todo: p2: cosider turning this into a hashmap vs. an array so that O(1) access\n const riskMatrix = this.riskMatrices.find((riskMatrix) => {\n return (\n riskMatrix.risk_block_id ===\n BigNumber(String(marketStorage.risk_block_id)).toNumber()\n );\n });\n\n if (!riskMatrix) {\n throw new Error(\"RiskMatrix Doesn't exist\");\n }\n\n const riskMatrixIndex = BigNumber(\n String(marketConfiguration.risk_matrix_index),\n ).toNumber();\n\n let imrMultiplier;\n if (isPool) {\n imrMultiplier = POOL_IMR;\n } else {\n imrMultiplier = amountNormalizer(\n String(this.riskMultipliers.im_multiplier),\n ).toNumber();\n }\n\n const marginInfo = this.tokenMarginInfoPerAsset.find((marginInfo) => {\n return marginInfo.assetAddress === marketStorage.quote_collateral;\n });\n\n if (!marginInfo) {\n throw new Error(\"marginInfo doesn't exist\");\n }\n\n const exposures = ExposureCommand.getBlockExposures(\n this.positionInfoMarketConfiguration,\n this.oraclePricePerMarket,\n BigNumber(String(marketStorage.risk_block_id)).toNumber(),\n );\n\n const { maxExposureShort, maxExposureLong } =\n ExposureCommand.computeMaxExposures(\n riskMatrix.matrix,\n exposures,\n marginInfo.liquidationMarginRequirement,\n marginInfo.marginBalance < 0 ? 0 : marginInfo.marginBalance,\n imrMultiplier,\n riskMatrixIndex,\n );\n\n return {\n maxExposureShort,\n maxExposureLong,\n exposures,\n riskMatrixIndex,\n };\n }\n\n static computeMaxExposures(\n riskMatrix: BigNumber[][],\n exposures: BigNumber[],\n lmr: number,\n balance: number,\n imrMultiplier: number,\n exposureIndex: number,\n ) {\n let b = BigNumber(0);\n\n for (let i = 0; i < exposures.length; i++) {\n b = BigNumber(b).plus(\n BigNumber(exposures[i]).multipliedBy(\n BigNumber(riskMatrix[exposureIndex][i]).plus(\n riskMatrix[i][exposureIndex],\n ),\n ),\n );\n }\n const { x1, x2 } = this.solveQuadraticEquation(\n BigNumber(riskMatrix[exposureIndex][exposureIndex]).toNumber(), // changes here\n b.toNumber(),\n this.computeC(lmr, balance, imrMultiplier),\n );\n\n const maxShortExposure = BigNumber(x1).plus(exposures[exposureIndex]);\n const maxLongExposure = BigNumber(x2).plus(exposures[exposureIndex]);\n\n const availableShortExposure = maxShortExposure.lt(0)\n ? maxShortExposure.negated().toNumber()\n : 0;\n\n const availableLongExposure = maxLongExposure.gt(0)\n ? maxLongExposure.toNumber()\n : 0;\n\n return {\n maxExposureShort: availableShortExposure,\n maxExposureLong: availableLongExposure,\n };\n }\n\n static solveQuadraticEquation(a: number, b: number, c: number) {\n if (BigNumber(a).eq(0)) {\n throw new Error('ZeroQuadraticCoefficient');\n }\n\n const delta = BigNumber(b)\n .multipliedBy(b)\n .minus(BigNumber(4).multipliedBy(a).multipliedBy(c));\n\n if (delta.lt(0)) {\n return {\n x1: BigNumber(0),\n x2: BigNumber(0),\n };\n }\n\n const rootDelta = delta.sqrt();\n\n const x1 = BigNumber(b)\n .multipliedBy(-1)\n .minus(rootDelta)\n .div(BigNumber(2).multipliedBy(a));\n\n const x2 = BigNumber(b)\n .multipliedBy(-1)\n .plus(rootDelta)\n .div(BigNumber(2).multipliedBy(a));\n\n return {\n x1,\n x2,\n };\n }\n\n static computeC(lmr: number, balance: number, imrMultiplier: number): number {\n const lmrSD = BigNumber(lmr);\n const lmrSquared = lmrSD.multipliedBy(lmrSD);\n\n const balanceSD = BigNumber(balance);\n const balanceSquared = balanceSD.multipliedBy(balanceSD);\n\n const imrMultiplierSD = BigNumber(imrMultiplier);\n const imrMultiplierSquared = imrMultiplierSD.multipliedBy(imrMultiplierSD);\n\n return lmrSquared\n .minus(balanceSquared.div(imrMultiplierSquared))\n .toNumber();\n }\n\n static calculateRebalancingOrderBase({\n poolBasePreTrade,\n orderBase,\n }: {\n poolBasePreTrade: number;\n orderBase: number;\n }): number {\n if (poolBasePreTrade > 0) {\n if (orderBase < 0) {\n return 0;\n }\n\n return Math.min(poolBasePreTrade, orderBase);\n }\n\n if (orderBase > 0) {\n return 0;\n }\n\n return Math.max(poolBasePreTrade, orderBase);\n }\n\n static calculateFee({\n oraclePrice,\n poolBasePreTrade,\n orderBase,\n feeParameter,\n rebalancingFeeParameter,\n }: {\n oraclePrice: number;\n poolBasePreTrade: number;\n orderBase: number;\n feeParameter: BigNumber;\n rebalancingFeeParameter: BigNumber;\n }): {\n rebalancingFee: number;\n imbalancingFee: number;\n fee: number;\n } {\n const rebalancingOrderBase = this.calculateRebalancingOrderBase({\n poolBasePreTrade,\n orderBase,\n });\n\n const imbalancingOrderBase = orderBase - rebalancingOrderBase;\n\n const imbalancingFee = BigNumber(oraclePrice)\n .times(imbalancingOrderBase)\n .times(feeParameter)\n .abs()\n .toNumber();\n\n const rebalancingFee = BigNumber(oraclePrice)\n .times(rebalancingOrderBase)\n .times(rebalancingFeeParameter)\n .abs()\n .toNumber();\n\n return {\n imbalancingFee,\n rebalancingFee,\n fee: imbalancingFee + rebalancingFee,\n };\n }\n\n static calculateEstimatedPrice(price: number, slippage: number): number {\n return BigNumber(price).times(BigNumber(1).plus(slippage)).toNumber();\n }\n\n static evaluateHealthStatus(marginRatioPercentage: number) {\n if (marginRatioPercentage >= MA_HEALTH_DANGER_THRESHOLD) {\n return 'danger';\n } else if (marginRatioPercentage >= MA_HEALTH_WARNING_THRESHOLD) {\n return 'warning';\n } else {\n return 'healthy';\n }\n }\n\n static getFundingPeriods(lastFundingTimeStamp: BigNumber) {\n const secondsElapsed = BigNumber(Date.now() / 1000).minus(\n lastFundingTimeStamp,\n );\n const ONE_DAY_IN_SECONDS = 86400;\n return BigNumber(secondsElapsed).div(ONE_DAY_IN_SECONDS);\n }\n\n static getHourlyFundingPeriods(lastFundingTimeStamp: BigNumber) {\n const secondsElapsed = BigNumber(Date.now() / 1000).minus(\n lastFundingTimeStamp,\n );\n const ONE_HOUR_IN_SECONDS = 3600;\n return BigNumber(secondsElapsed).div(ONE_HOUR_IN_SECONDS);\n }\n\n static getFundingRateDelta(\n fundingPeriods: BigNumber,\n lastFundingVelocity: BigNumber,\n ) {\n return lastFundingVelocity.multipliedBy(fundingPeriods);\n }\n\n static getCurrentFundingRate(\n last_funding_timestamp: BigNumber,\n lastFundingVelocity: BigNumber,\n lastFundingRate: BigNumber,\n ) {\n const fundingPeriods = ExposureCommand.getFundingPeriods(\n last_funding_timestamp,\n );\n const fundingRateDelta = ExposureCommand.getFundingRateDelta(\n fundingPeriods,\n lastFundingVelocity,\n );\n\n return clampFundingRate(lastFundingRate.plus(fundingRateDelta));\n }\n\n /**\n * @deprecated OB model reads funding rate directly from FundingRateProvider.\n * Remains for legacy AMM model consumers. To be removed in a future cleanup PR.\n */\n static getCurrentHourlyFundingRate(\n last_funding_timestamp: BigNumber,\n lastFundingVelocity: BigNumber,\n lastFundingRate: BigNumber,\n ) {\n const dailyFundingRate = this.getCurrentFundingRate(\n last_funding_timestamp,\n lastFundingVelocity,\n lastFundingRate,\n );\n return dailyFundingRate.div(24);\n }\n\n static getFundingValueDelta(\n periods: BigNumber,\n lastFundingRate: BigNumber,\n lastFundingVelocity: BigNumber,\n price: BigNumber,\n baseMultiplier: BigNumber,\n ): BigNumber {\n // gracefully clamp lastFundingRate into [MIN, MAX] so that markets whose\n // stored rate predates tighter bounds still settle correctly\n lastFundingRate = clampFundingRate(lastFundingRate);\n const rateDelta = this.getFundingRateDelta(periods, lastFundingVelocity);\n const unclampedEndRate = lastFundingRate.plus(rateDelta);\n\n let areaDelta: BigNumber;\n if (unclampedEndRate.gt(MAX_FUNDING_RATE)) {\n areaDelta = clampedArea(\n lastFundingRate,\n lastFundingVelocity,\n periods,\n MAX_FUNDING_RATE,\n );\n } else if (unclampedEndRate.lt(MIN_FUNDING_RATE)) {\n areaDelta = clampedArea(\n lastFundingRate,\n lastFundingVelocity,\n periods,\n MIN_FUNDING_RATE,\n );\n } else {\n areaDelta = trapezoidArea(lastFundingRate, unclampedEndRate, periods);\n }\n\n return areaDelta.times(price).times(baseMultiplier);\n }\n\n /**\n * @deprecated OB model reads funding value directly from market trackers.\n * Remains for legacy AMM model consumers. To be removed in a future cleanup PR.\n */\n static getCurrentFundingValue(\n spotPrice: BigNumber,\n lastFundingValue: BigNumber,\n baseMultiplier: BigNumber,\n lastFundingRate: BigNumber,\n lastFundingVelocity: BigNumber,\n lastFundingTimestamp: BigNumber,\n ) {\n const periods = this.getFundingPeriods(lastFundingTimestamp);\n const delta = this.getFundingValueDelta(\n periods,\n lastFundingRate,\n lastFundingVelocity,\n spotPrice,\n baseMultiplier,\n );\n return lastFundingValue.plus(delta);\n }\n\n convertToUsd(amount: number, tokenAddress: string): number {\n return BigNumber(amount)\n .times(this.collateralAddressToExchangePrice[tokenAddress])\n .toNumber();\n }\n\n getExchangeRate(tokenAddress: string): number {\n return this.collateralAddressToExchangePrice[tokenAddress];\n }\n\n get realisedPnl() {\n return this.realizedPnLSum.toNumber();\n }\n\n get unRealisedPnl() {\n return this.unrealizedPnLSum.toNumber();\n }\n\n get accountTotalBalanceUsd() {\n let accountTotalBalance = 0;\n\n for (const collateralAsset of this.tokenMarginInfoPerAsset) {\n const collateralPrice =\n this.collateralAddressToExchangePrice[collateralAsset.assetAddress] ||\n 0;\n\n const balanceInUSD = BigNumber(collateralPrice)\n .times(collateralAsset.marginBalance)\n .toNumber();\n accountTotalBalance += balanceInUSD;\n }\n\n return accountTotalBalance;\n }\n\n get accountTotalBalanceWithHaircutUsd() {\n let accountTotalBalance = 0;\n\n for (const collateralAsset of this.tokenMarginInfoPerAsset) {\n const collateralPriceWithHaircut = ExposureCommand.getBalanceWithHaircut(\n this.exchangeInfoPerAsset,\n collateralAsset.assetAddress,\n collateralAsset.marginBalance,\n );\n\n accountTotalBalance += collateralPriceWithHaircut;\n }\n\n return accountTotalBalance;\n }\n\n getMtmRpnlSum() {\n return this.mtmRpnlSum.toNumber();\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"command.js","sourceRoot":"/","sources":["commands/exposure/command.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,8DAAqC;AAcrC,qCAIqB;AAER,QAAA,gBAAgB,GAAG,IAAA,sBAAS,EAAC,MAAM,CAAC,CAAC;AACrC,QAAA,gBAAgB,GAAG,IAAA,sBAAS,EAAC,OAAO,CAAC,CAAC;AAEnD,SAAgB,gBAAgB,CAAC,IAAe;IAC9C,IAAI,IAAI,CAAC,EAAE,CAAC,wBAAgB,CAAC;QAAE,OAAO,wBAAgB,CAAC;IACvD,IAAI,IAAI,CAAC,EAAE,CAAC,wBAAgB,CAAC;QAAE,OAAO,wBAAgB,CAAC;IACvD,OAAO,IAAI,CAAC;AACd,CAAC;AAJD,4CAIC;AAED,SAAS,aAAa,CAAC,EAAa,EAAE,EAAa,EAAE,CAAY;IAC/D,OAAO,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,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igNumber from 'bignumber.js';\nimport {\n AccountAssetBalance,\n CollateralAddressToExchangePriceMap,\n CollateralInfo,\n ExchangeInfo,\n MarginInfo,\n MarketConfiguration,\n MarketIdToOraclePriceMap,\n PositionInfo,\n PositionInfoMarketConfiguration,\n RiskMatrix,\n RiskMultipliersConfiguration,\n} from './types';\nimport {\n amountNormalizer,\n MA_HEALTH_DANGER_THRESHOLD,\n MA_HEALTH_WARNING_THRESHOLD,\n} from '../../utils';\n\nexport const MAX_FUNDING_RATE = BigNumber('0.07');\nexport const MIN_FUNDING_RATE = BigNumber('-0.07');\n\nexport function clampFundingRate(rate: BigNumber): BigNumber {\n if (rate.gt(MAX_FUNDING_RATE)) return MAX_FUNDING_RATE;\n if (rate.lt(MIN_FUNDING_RATE)) return MIN_FUNDING_RATE;\n return rate;\n}\n\nfunction trapezoidArea(r0: BigNumber, r1: BigNumber, t: BigNumber): BigNumber {\n return r0.plus(r1).div(2).times(t);\n}\n\nfunction clampedArea(\n r0: BigNumber,\n v: BigNumber,\n periods: BigNumber,\n boundary: BigNumber,\n): BigNumber {\n const tc = boundary.minus(r0).div(v);\n return trapezoidArea(r0, boundary, tc).plus(\n trapezoidArea(boundary, boundary, periods.minus(tc)),\n );\n}\n\nexport class ExposureCommand {\n accountId: number;\n rootCollateralPoolId: number;\n oraclePricePerMarket: MarketIdToOraclePriceMap;\n accountBalancePerAsset: AccountAssetBalance[];\n groupedByCollateral: Record<string, AccountAssetBalance>;\n riskMultipliers: RiskMultipliersConfiguration;\n riskMatrices: RiskMatrix[];\n exchangeInfoPerAsset: ExchangeInfo[];\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];\n uniqueTokenAddresses: string[];\n uniqueQuoteCollaterals: string[];\n tokenMarginInfoPerAsset: MarginInfo[];\n realizedPnLSum: BigNumber;\n unrealizedPnLSum: BigNumber;\n mtmRpnlSum: BigNumber;\n collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap;\n constructor(\n accountId: number,\n rootCollateralPoolId: number,\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n accountBalancePerAsset: AccountAssetBalance[],\n groupedByCollateral: Record<string, AccountAssetBalance>,\n riskMultipliers: RiskMultipliersConfiguration,\n riskMatrices: RiskMatrix[],\n exchangeInfoPerAsset: ExchangeInfo[],\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[],\n uniqueTokenAddresses: string[],\n uniqueQuoteCollaterals: string[],\n tokenMarginInfoPerAsset: MarginInfo[],\n realizedPnLSum: BigNumber,\n unrealizedPnLSum: BigNumber,\n mtmRpnlSum: BigNumber,\n collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap,\n ) {\n this.accountId = accountId;\n this.rootCollateralPoolId = rootCollateralPoolId;\n this.oraclePricePerMarket = oraclePricePerMarket;\n this.accountBalancePerAsset = accountBalancePerAsset;\n this.groupedByCollateral = groupedByCollateral;\n this.riskMultipliers = riskMultipliers;\n this.riskMatrices = riskMatrices;\n this.exchangeInfoPerAsset = exchangeInfoPerAsset;\n this.positionInfoMarketConfiguration = positionInfoMarketConfiguration;\n this.uniqueTokenAddresses = uniqueTokenAddresses;\n this.uniqueQuoteCollaterals = uniqueQuoteCollaterals;\n this.tokenMarginInfoPerAsset = tokenMarginInfoPerAsset;\n this.realizedPnLSum = realizedPnLSum;\n this.unrealizedPnLSum = unrealizedPnLSum;\n this.mtmRpnlSum = mtmRpnlSum;\n this.collateralAddressToExchangePrice = collateralAddressToExchangePrice;\n }\n\n get getUsdNodeMarginInfo() {\n return ExposureCommand.getUsdNodeMarginInfo(\n this.rootCollateralPoolId,\n this.uniqueTokenAddresses,\n this.exchangeInfoPerAsset,\n this.tokenMarginInfoPerAsset,\n );\n }\n\n get balancePerAsset() {\n return this.tokenMarginInfoPerAsset;\n }\n static calculateTokenMarginInfoPerAsset(\n groupedByCollateral: Record<string, AccountAssetBalance>,\n rootCollateralPoolId: number,\n riskMatrices: RiskMatrix[],\n riskMultipliers: RiskMultipliersConfiguration,\n uniqueQuoteCollaterals: Set<string>,\n realizedPnLSum: BigNumber,\n unrealizedPnLSum: BigNumber,\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[],\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n ): MarginInfo[] {\n const tokenMarginInfoPerAsset: MarginInfo[] = [];\n\n // todo: p2: investigate the ts-expect-error cases below\n // @ts-expect-error no easy way to make sure string can be casted to Lowercase<string> type\n const uniqueQuoteTokens: Lowercase<string>[] = Array.from(\n uniqueQuoteCollaterals,\n );\n\n // @ts-expect-error no easy way to make sure string can be casted to Lowercase<string> type\n const tokenUnion: Set<Lowercase<string>> = new Set([\n ...Object.keys(groupedByCollateral),\n ...uniqueQuoteTokens,\n ]); // get unique union of those arrays\n const uniqueTokenAddresses: Lowercase<string>[] = Array.from(tokenUnion);\n\n for (const token of uniqueTokenAddresses) {\n tokenMarginInfoPerAsset.push(\n ExposureCommand.getTokenMarginInfo(\n rootCollateralPoolId,\n riskMatrices,\n riskMultipliers,\n ExposureCommand.getCollateralInfo(\n token,\n uniqueQuoteCollaterals.has(token) ? realizedPnLSum : BigNumber(0),\n uniqueQuoteCollaterals.has(token) ? unrealizedPnLSum : BigNumber(0),\n groupedByCollateral[token]?.amount || 0,\n ),\n token,\n positionInfoMarketConfiguration,\n oraclePricePerMarket,\n uniqueQuoteTokens,\n ),\n );\n }\n\n return tokenMarginInfoPerAsset;\n }\n static calculateLiquidation(\n marginBalance: number,\n liquidationMarginRequirement: number,\n oraclePrice: number,\n positionBase: number,\n ): BigNumber {\n if (positionBase === 0 || liquidationMarginRequirement === 0) {\n return BigNumber(0);\n }\n const liquidationPrice = BigNumber(oraclePrice).minus(\n BigNumber(marginBalance)\n .minus(liquidationMarginRequirement)\n .div(positionBase),\n );\n\n return BigNumber.max(0, liquidationPrice);\n }\n\n static combineMarginInfo(\n parentMarginInfo: MarginInfo,\n sonMarginInfo: MarginInfo,\n sonParentExchangeInfo: ExchangeInfo,\n ): MarginInfo {\n return {\n assetAddress: parentMarginInfo.assetAddress,\n marginBalance: BigNumber(parentMarginInfo.marginBalance)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.marginBalance,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n realBalance: BigNumber(parentMarginInfo.realBalance)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.realBalance,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n initialDelta: BigNumber(parentMarginInfo.initialDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.realBalance,\n sonMarginInfo.initialDelta,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n maintenanceDelta: BigNumber(parentMarginInfo.maintenanceDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.maintenanceDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n liquidationDelta: BigNumber(parentMarginInfo.liquidationDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.liquidationDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n dutchDelta: BigNumber(parentMarginInfo.dutchDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.dutchDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n adlDelta: BigNumber(parentMarginInfo.adlDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.adlDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n\n initialBufferDelta: BigNumber(parentMarginInfo.initialBufferDelta)\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n BigNumber.min(\n sonMarginInfo.initialBufferDelta,\n sonMarginInfo.realBalance,\n ).toNumber(),\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n liquidationMarginRequirement: BigNumber(\n parentMarginInfo.liquidationMarginRequirement,\n )\n .plus(\n ExposureCommand.exchangeWithPriceHaircut(\n sonMarginInfo.liquidationMarginRequirement,\n sonParentExchangeInfo.price,\n sonParentExchangeInfo.priceHaircut,\n ),\n )\n .toNumber(),\n };\n }\n\n static getUsdNodeMarginInfo(\n accountCollateralPoolId: number,\n quoteTokens: string[],\n exchangeInfoPerAsset: ExchangeInfo[],\n marginInfoPerToken: MarginInfo[],\n ) {\n let usdNodeMarginInfo: MarginInfo = {\n assetAddress: '',\n marginBalance: 0,\n realBalance: 0,\n initialDelta: 0,\n maintenanceDelta: 0,\n liquidationDelta: 0,\n dutchDelta: 0,\n adlDelta: 0,\n initialBufferDelta: 0,\n liquidationMarginRequirement: 0,\n };\n for (const quoteToken of quoteTokens) {\n const exchangeInfo = exchangeInfoPerAsset.find((exchangeInfo) => {\n return quoteToken === exchangeInfo.tokenAddress;\n });\n\n const marginInfo = marginInfoPerToken.find((marginInfo) => {\n return quoteToken === marginInfo.assetAddress;\n });\n\n if (!exchangeInfo || !marginInfo) {\n throw Error(`Missing exchangeInfo/marginInfo for ${quoteToken}`);\n }\n\n usdNodeMarginInfo = ExposureCommand.combineMarginInfo(\n usdNodeMarginInfo,\n marginInfo,\n exchangeInfo,\n );\n }\n\n return usdNodeMarginInfo;\n }\n static getCollateralInfo(\n collateralAddress: string,\n realisedPnl: BigNumber,\n unrealizedPnL: BigNumber,\n netDeposits: number,\n ): CollateralInfo {\n return {\n netDeposits: netDeposits,\n marginBalance: BigNumber(netDeposits)\n .plus(realisedPnl)\n .plus(unrealizedPnL)\n .toNumber(),\n realBalance: BigNumber(netDeposits).plus(realisedPnl).toNumber(),\n };\n }\n\n static getTokenMarginInfo(\n rootCollateralPoolId: number,\n riskMatrices: RiskMatrix[],\n riskMultipliers: RiskMultipliersConfiguration,\n collateralInfo: CollateralInfo,\n collateralAddress: Lowercase<string>,\n positions: PositionInfoMarketConfiguration[],\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n uniqueQuoteTokens: string[],\n ): MarginInfo {\n const marginRequirements = {\n liquidationMarginRequirement: 0,\n initialMarginRequirement: 0,\n maintenanceMarginRequirement: 0,\n dutchMarginRequirement: 0,\n adlMarginRequirement: 0,\n initialBufferMarginRequirement: 0,\n };\n if (uniqueQuoteTokens.includes(collateralAddress)) {\n // uniqueQuoteTokens is list is active markets tokens\n for (const riskMatrix of riskMatrices) {\n const filledExposures = ExposureCommand.getBlockExposures(\n positions,\n oraclePricePerMarket,\n riskMatrix.risk_block_id,\n );\n\n marginRequirements.liquidationMarginRequirement = BigNumber(\n marginRequirements.liquidationMarginRequirement,\n )\n .plus(\n ExposureCommand.computeLiquidationMarginRequirement(\n riskMatrix.matrix,\n filledExposures,\n ),\n )\n .toNumber();\n }\n\n // Get the initial margin requirement\n marginRequirements.initialMarginRequirement = amountNormalizer(\n String(riskMultipliers.im_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n // Get the maintenance margin requirement\n marginRequirements.maintenanceMarginRequirement = amountNormalizer(\n String(riskMultipliers.mmr_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n // Get the dutch margin requirement\n marginRequirements.dutchMarginRequirement = amountNormalizer(\n String(riskMultipliers.dutch_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n\n // Get the adl margin requirement\n marginRequirements.adlMarginRequirement = amountNormalizer(\n String(riskMultipliers.adl_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n\n // Get the initial buffer margin requirement\n marginRequirements.initialBufferMarginRequirement = amountNormalizer(\n String(riskMultipliers.im_buffer_multiplier),\n )\n .multipliedBy(marginRequirements.liquidationMarginRequirement)\n .toNumber();\n }\n return {\n assetAddress: collateralAddress,\n marginBalance: collateralInfo.marginBalance,\n realBalance: collateralInfo.realBalance,\n initialDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.initialMarginRequirement)\n .toNumber(),\n maintenanceDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.maintenanceMarginRequirement)\n .toNumber(),\n liquidationDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.liquidationMarginRequirement)\n .toNumber(),\n dutchDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.dutchMarginRequirement)\n .toNumber(),\n adlDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.adlMarginRequirement)\n .toNumber(),\n initialBufferDelta: BigNumber(collateralInfo.marginBalance)\n .minus(marginRequirements.initialBufferMarginRequirement)\n .toNumber(),\n liquidationMarginRequirement:\n marginRequirements.liquidationMarginRequirement,\n };\n }\n\n static computeLiquidationMarginRequirement(\n matrix: BigNumber[][],\n filledExposures: BigNumber[],\n ): number {\n let lmrFilledSquared = 0;\n\n for (let i = 0; i < filledExposures.length; i++) {\n if (BigNumber(filledExposures[i]).eq(0)) {\n continue;\n }\n for (let j = 0; j < filledExposures.length; j++) {\n const riskParam = matrix[i][j];\n\n if (BigNumber(filledExposures[j]).eq(0) || BigNumber(riskParam).eq(0)) {\n continue;\n }\n\n lmrFilledSquared = BigNumber(lmrFilledSquared)\n .plus(\n BigNumber(filledExposures[i])\n .multipliedBy(filledExposures[j])\n .multipliedBy(riskParam),\n )\n .toNumber();\n }\n }\n return BigNumber(lmrFilledSquared).sqrt().toNumber();\n }\n\n static getBlockExposures(\n positions: PositionInfoMarketConfiguration[],\n oraclePricePerMarket: MarketIdToOraclePriceMap,\n riskBlockId: number,\n ): BigNumber[] {\n const filledExposures: number[] = [];\n let maxIndex = 0; // Keep track of the highest riskMatrixIndex encountered\n\n for (const position of positions) {\n if (riskBlockId !== position.risk_block_id) continue;\n const marketFilledExposure = ExposureCommand.getAccountFilledExposures(\n position,\n position.market_configuration,\n oraclePricePerMarket[position.market_id],\n );\n const index = marketFilledExposure.riskMatrixIndex;\n filledExposures[index] = BigNumber(filledExposures[index] || 0)\n .plus(marketFilledExposure.exposure)\n .toNumber();\n\n if (index > maxIndex) maxIndex = index;\n }\n\n // Ensure filledExposures array is correctly populated up to maxIndex\n for (let i = 0; i <= maxIndex; i++) {\n if (filledExposures[i] === undefined) {\n filledExposures[i] = 0;\n }\n }\n return filledExposures.map((num) => BigNumber(num));\n }\n\n static getAccountFilledExposures(\n position: PositionInfo,\n marketConfiguration: MarketConfiguration,\n oraclePrice: number,\n ) {\n const base = position.base;\n return {\n exposure: BigNumber(oraclePrice).multipliedBy(base),\n riskMatrixIndex: BigNumber(\n String(marketConfiguration.risk_matrix_index),\n ).toNumber(),\n };\n }\n\n static computePricePnL(\n openBase: BigNumber,\n openPrice: BigNumber,\n exitPrice: BigNumber,\n ) {\n return BigNumber(\n BigNumber(exitPrice).minus(openPrice).multipliedBy(openBase),\n );\n }\n\n static getMarginRatio(\n marginInfo: Pick<\n MarginInfo,\n 'marginBalance' | 'liquidationMarginRequirement'\n >,\n ) {\n if (marginInfo.liquidationMarginRequirement === 0) {\n return 0;\n }\n\n if (marginInfo.marginBalance <= 0) {\n return 1;\n }\n\n const health = BigNumber(marginInfo.liquidationMarginRequirement).div(\n marginInfo.marginBalance,\n );\n\n if (health.gt(1)) {\n return 1;\n }\n return health.toNumber();\n }\n\n static exchangeWithPriceHaircut(\n quantity: number,\n price: number,\n haircut: number,\n ) {\n // For positive quantities, the haircut is `quantity * (1 - haircut)`\n // For negative values, the haircut is `quantity / (1 - haircut)` because a negative value means the haircut should be applied from B to A.\n const calHelper = BigNumber(quantity).gt(0)\n ? BigNumber(1).minus(haircut)\n : BigNumber(1).div(BigNumber(1).minus(haircut));\n const haircutPrice = BigNumber(price).multipliedBy(calHelper);\n\n return haircutPrice.multipliedBy(quantity).toNumber();\n }\n\n static getBalanceWithHaircut(\n exchangeInfoPerAsset: ExchangeInfo[],\n assetAddress: string,\n marginBalance: number,\n ) {\n // todo: p1: haircut and exchange rate adjustment should not be done for rUSD\n // does exchangeInfo currently return haircut as zero and price as 1?\n // todo: p2: can just look at net deposits rather than margin balance for non-rusd as non pnl\n\n const exchangeInfo = exchangeInfoPerAsset.find((exchangeInfo) => {\n return assetAddress === exchangeInfo.tokenAddress;\n });\n\n if (!exchangeInfo) {\n throw new Error(\n 'Unable to retrieve exchange info when calculating collaterals needed to cover margin',\n );\n }\n\n return ExposureCommand.exchangeWithPriceHaircut(\n marginBalance,\n exchangeInfo.price,\n exchangeInfo.priceHaircut,\n );\n }\n\n static evaluateHealthStatus(marginRatioPercentage: number) {\n if (marginRatioPercentage >= MA_HEALTH_DANGER_THRESHOLD) {\n return 'danger';\n } else if (marginRatioPercentage >= MA_HEALTH_WARNING_THRESHOLD) {\n return 'warning';\n } else {\n return 'healthy';\n }\n }\n\n static getFundingPeriods(lastFundingTimeStamp: BigNumber) {\n const secondsElapsed = BigNumber(Date.now() / 1000).minus(\n lastFundingTimeStamp,\n );\n const ONE_DAY_IN_SECONDS = 86400;\n return BigNumber(secondsElapsed).div(ONE_DAY_IN_SECONDS);\n }\n\n static getHourlyFundingPeriods(lastFundingTimeStamp: BigNumber) {\n const secondsElapsed = BigNumber(Date.now() / 1000).minus(\n lastFundingTimeStamp,\n );\n const ONE_HOUR_IN_SECONDS = 3600;\n return BigNumber(secondsElapsed).div(ONE_HOUR_IN_SECONDS);\n }\n\n static getFundingRateDelta(\n fundingPeriods: BigNumber,\n lastFundingVelocity: BigNumber,\n ) {\n return lastFundingVelocity.multipliedBy(fundingPeriods);\n }\n\n static getCurrentFundingRate(\n last_funding_timestamp: BigNumber,\n lastFundingVelocity: BigNumber,\n lastFundingRate: BigNumber,\n ) {\n const fundingPeriods = ExposureCommand.getFundingPeriods(\n last_funding_timestamp,\n );\n const fundingRateDelta = ExposureCommand.getFundingRateDelta(\n fundingPeriods,\n lastFundingVelocity,\n );\n\n return clampFundingRate(lastFundingRate.plus(fundingRateDelta));\n }\n\n /**\n * @deprecated OB model reads funding rate directly from FundingRateProvider.\n * Remains for legacy AMM model consumers. To be removed in a future cleanup PR.\n */\n static getCurrentHourlyFundingRate(\n last_funding_timestamp: BigNumber,\n lastFundingVelocity: BigNumber,\n lastFundingRate: BigNumber,\n ) {\n const dailyFundingRate = this.getCurrentFundingRate(\n last_funding_timestamp,\n lastFundingVelocity,\n lastFundingRate,\n );\n return dailyFundingRate.div(24);\n }\n\n static getFundingValueDelta(\n periods: BigNumber,\n lastFundingRate: BigNumber,\n lastFundingVelocity: BigNumber,\n price: BigNumber,\n baseMultiplier: BigNumber,\n ): BigNumber {\n // gracefully clamp lastFundingRate into [MIN, MAX] so that markets whose\n // stored rate predates tighter bounds still settle correctly\n lastFundingRate = clampFundingRate(lastFundingRate);\n const rateDelta = this.getFundingRateDelta(periods, lastFundingVelocity);\n const unclampedEndRate = lastFundingRate.plus(rateDelta);\n\n let areaDelta: BigNumber;\n if (unclampedEndRate.gt(MAX_FUNDING_RATE)) {\n areaDelta = clampedArea(\n lastFundingRate,\n lastFundingVelocity,\n periods,\n MAX_FUNDING_RATE,\n );\n } else if (unclampedEndRate.lt(MIN_FUNDING_RATE)) {\n areaDelta = clampedArea(\n lastFundingRate,\n lastFundingVelocity,\n periods,\n MIN_FUNDING_RATE,\n );\n } else {\n areaDelta = trapezoidArea(lastFundingRate, unclampedEndRate, periods);\n }\n\n return areaDelta.times(price).times(baseMultiplier);\n }\n\n /**\n * @deprecated OB model reads funding value directly from market trackers.\n * Remains for legacy AMM model consumers. To be removed in a future cleanup PR.\n */\n static getCurrentFundingValue(\n spotPrice: BigNumber,\n lastFundingValue: BigNumber,\n baseMultiplier: BigNumber,\n lastFundingRate: BigNumber,\n lastFundingVelocity: BigNumber,\n lastFundingTimestamp: BigNumber,\n ) {\n const periods = this.getFundingPeriods(lastFundingTimestamp);\n const delta = this.getFundingValueDelta(\n periods,\n lastFundingRate,\n lastFundingVelocity,\n spotPrice,\n baseMultiplier,\n );\n return lastFundingValue.plus(delta);\n }\n\n convertToUsd(amount: number, tokenAddress: string): number {\n return BigNumber(amount)\n .times(this.collateralAddressToExchangePrice[tokenAddress])\n .toNumber();\n }\n\n getExchangeRate(tokenAddress: string): number {\n return this.collateralAddressToExchangePrice[tokenAddress];\n }\n\n get realisedPnl() {\n return this.realizedPnLSum.toNumber();\n }\n\n get unRealisedPnl() {\n return this.unrealizedPnLSum.toNumber();\n }\n\n get accountTotalBalanceUsd() {\n let accountTotalBalance = 0;\n\n for (const collateralAsset of this.tokenMarginInfoPerAsset) {\n const collateralPrice =\n this.collateralAddressToExchangePrice[collateralAsset.assetAddress] ||\n 0;\n\n const balanceInUSD = BigNumber(collateralPrice)\n .times(collateralAsset.marginBalance)\n .toNumber();\n accountTotalBalance += balanceInUSD;\n }\n\n return accountTotalBalance;\n }\n\n get accountTotalBalanceWithHaircutUsd() {\n let accountTotalBalance = 0;\n\n for (const collateralAsset of this.tokenMarginInfoPerAsset) {\n const collateralPriceWithHaircut = ExposureCommand.getBalanceWithHaircut(\n this.exchangeInfoPerAsset,\n collateralAsset.assetAddress,\n collateralAsset.marginBalance,\n );\n\n accountTotalBalance += collateralPriceWithHaircut;\n }\n\n return accountTotalBalance;\n }\n\n getMtmRpnlSum() {\n return this.mtmRpnlSum.toNumber();\n }\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"/","sources":["commands/exposure/types.ts"],"names":[],"mappings":"","sourcesContent":["import BigNumber from 'bignumber.js';\n\nexport interface MarketStorage {\n market_id: number;\n quote_collateral: string;\n instrument_address: string;\n name: string;\n risk_block_id: number;\n collateral_pool_id: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport interface MarketConfiguration {\n market_id: number;\n risk_matrix_index: number;\n max_open_base: number;\n /** @deprecated Now sourced from Market.Data (MarketTrackers) */\n velocity_multiplier: number;\n minimum_order_base: number;\n base_spacing: number;\n price_spacing: number;\n oracle_node_id: string;\n mtm_window: number;\n dutch_config_lambda: number;\n dutch_config_min_base: number;\n slippage_params_phi: number;\n slippage_params_beta: number;\n depth_factor: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport type AccountAssetBalance = {\n accountId: number;\n collateral: string;\n amount: number;\n};\n\nexport interface RiskMultipliersConfiguration {\n collateral_pool_id: number;\n im_multiplier: number;\n mmr_multiplier: number;\n dutch_multiplier: number;\n adl_multiplier: number;\n im_buffer_multiplier: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport interface RiskMatrix {\n collateral_pool_id: number;\n risk_block_id: number;\n matrix: BigNumber[][];\n}\nexport type MarketIdToOraclePriceMap = {\n [marketId: number]: number;\n};\n\nexport type CollateralAddressToExchangePriceMap = {\n [address: string]: number;\n};\n\nexport interface ExchangeInfo {\n price: number;\n priceHaircut: number;\n autoExchangeDiscount: number;\n tokenAddress: string;\n}\n\nexport interface PositionInfo {\n base: BigNumber;\n realized_pnl: BigNumber;\n realized_pnl_with_mtm: BigNumber;\n realized_pnl_latest_snapshot: BigNumber;\n latest_funding_cashflow: BigNumber;\n last_price: BigNumber;\n average_entry_price: BigNumber;\n average_entry_price_off_chain_tracker: BigNumber;\n funding_value_off_chain_tracker: BigNumber;\n last_timestamp: BigNumber;\n funding_value: BigNumber;\n base_multiplier: BigNumber;\n adl_unwind_price: BigNumber;\n market_id: number;\n account_id: number;\n}\n\nexport type PositionInfoMarketConfiguration = PositionInfo & {\n market_configuration: MarketConfiguration;\n risk_block_id: number;\n};\n\nexport interface MarginInfo {\n assetAddress: Lowercase<string>;\n marginBalance: number;\n realBalance: number;\n initialDelta: number;\n maintenanceDelta: number;\n liquidationDelta: number;\n dutchDelta: number;\n adlDelta: number;\n initialBufferDelta: number;\n liquidationMarginRequirement: number;\n}\n\nexport interface CollateralInfo {\n netDeposits: number;\n marginBalance: number;\n realBalance: number;\n}\n\nexport type ExposureCommandState = {\n accountId: number;\n rootCollateralPoolId: number;\n oraclePricePerMarket: MarketIdToOraclePriceMap;\n accountBalancePerAsset: AccountAssetBalance[];\n groupedByCollateral: Record<string, AccountAssetBalance>;\n riskMultipliers: RiskMultipliersConfiguration;\n riskMatrices: RiskMatrix[];\n exchangeInfoPerAsset: ExchangeInfo[];\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];\n uniqueTokenAddresses: string[];\n uniqueQuoteCollaterals: string[];\n tokenMarginInfoPerAsset: MarginInfo[];\n realizedPnLSum: BigNumber;\n unrealizedPnLSum: BigNumber;\n mtmRpnlSum: BigNumber;\n collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap;\n};\n\nexport type TradeSimulationState = {\n feeParameters: {\n feeTier: number;\n feeParameter: BigNumber;\n rebalancingFeeParameter: BigNumber;\n };\n feeParameter: BigNumber; // TODO: deprecate once feeParameters is used in SDK\n customLeverage: number | null;\n marketStorage: MarketStorage;\n marketConfiguration: MarketConfiguration;\n exposureDataAccount: ExposureCommandState;\n exposureDataPassivePool: ExposureCommandState;\n};\n
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"/","sources":["commands/exposure/types.ts"],"names":[],"mappings":"","sourcesContent":["import BigNumber from 'bignumber.js';\n\nexport interface MarketStorage {\n market_id: number;\n quote_collateral: string;\n instrument_address: string;\n name: string;\n risk_block_id: number;\n collateral_pool_id: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport interface MarketConfiguration {\n market_id: number;\n risk_matrix_index: number;\n max_open_base: number;\n /** @deprecated Now sourced from Market.Data (MarketTrackers) */\n velocity_multiplier: number;\n minimum_order_base: number;\n base_spacing: number;\n price_spacing: number;\n oracle_node_id: string;\n mtm_window: number;\n dutch_config_lambda: number;\n dutch_config_min_base: number;\n slippage_params_phi: number;\n slippage_params_beta: number;\n depth_factor: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport type AccountAssetBalance = {\n accountId: number;\n collateral: string;\n amount: number;\n};\n\nexport interface RiskMultipliersConfiguration {\n collateral_pool_id: number;\n im_multiplier: number;\n mmr_multiplier: number;\n dutch_multiplier: number;\n adl_multiplier: number;\n im_buffer_multiplier: number;\n block_timestamp: number;\n block_number: number;\n}\n\nexport interface RiskMatrix {\n collateral_pool_id: number;\n risk_block_id: number;\n matrix: BigNumber[][];\n}\nexport type MarketIdToOraclePriceMap = {\n [marketId: number]: number;\n};\n\nexport type CollateralAddressToExchangePriceMap = {\n [address: string]: number;\n};\n\nexport interface ExchangeInfo {\n price: number;\n priceHaircut: number;\n autoExchangeDiscount: number;\n tokenAddress: string;\n}\n\nexport interface PositionInfo {\n base: BigNumber;\n realized_pnl: BigNumber;\n realized_pnl_with_mtm: BigNumber;\n realized_pnl_latest_snapshot: BigNumber;\n latest_funding_cashflow: BigNumber;\n last_price: BigNumber;\n average_entry_price: BigNumber;\n average_entry_price_off_chain_tracker: BigNumber;\n funding_value_off_chain_tracker: BigNumber;\n last_timestamp: BigNumber;\n funding_value: BigNumber;\n base_multiplier: BigNumber;\n adl_unwind_price: BigNumber;\n market_id: number;\n account_id: number;\n}\n\nexport type PositionInfoMarketConfiguration = PositionInfo & {\n market_configuration: MarketConfiguration;\n risk_block_id: number;\n};\n\nexport interface MarginInfo {\n assetAddress: Lowercase<string>;\n marginBalance: number;\n realBalance: number;\n initialDelta: number;\n maintenanceDelta: number;\n liquidationDelta: number;\n dutchDelta: number;\n adlDelta: number;\n initialBufferDelta: number;\n liquidationMarginRequirement: number;\n}\n\nexport interface CollateralInfo {\n netDeposits: number;\n marginBalance: number;\n realBalance: number;\n}\n\nexport type ExposureCommandState = {\n accountId: number;\n rootCollateralPoolId: number;\n oraclePricePerMarket: MarketIdToOraclePriceMap;\n accountBalancePerAsset: AccountAssetBalance[];\n groupedByCollateral: Record<string, AccountAssetBalance>;\n riskMultipliers: RiskMultipliersConfiguration;\n riskMatrices: RiskMatrix[];\n exchangeInfoPerAsset: ExchangeInfo[];\n positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];\n uniqueTokenAddresses: string[];\n uniqueQuoteCollaterals: string[];\n tokenMarginInfoPerAsset: MarginInfo[];\n realizedPnLSum: BigNumber;\n unrealizedPnLSum: BigNumber;\n mtmRpnlSum: BigNumber;\n collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap;\n};\n\nexport type TradeSimulationState = {\n feeParameters: {\n feeTier: number;\n feeParameter: BigNumber;\n rebalancingFeeParameter: BigNumber;\n };\n feeParameter: BigNumber; // TODO: deprecate once feeParameters is used in SDK\n customLeverage: number | null;\n marketStorage: MarketStorage;\n marketConfiguration: MarketConfiguration;\n exposureDataAccount: ExposureCommandState;\n exposureDataPassivePool: ExposureCommandState;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"incentives-api-types.js","sourceRoot":"/","sources":["incentives-api-types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n AddressParam,\n ApiEndpoint,\n ApiInfiniteListEndpoint,\n ApiListEndpoint,\n PaginatedQueryParams,\n FailableResult,\n Stringified,\n} from './api-types';\nimport { Rank, RankTrading } from './types';\n\nexport type PointsBreakdown = {\n totalPoints: number;\n tradingPoints: number;\n stakingPoints: number;\n signalPoints: number;\n rank: number;\n};\n\n/** A points season as served by the API. `endsAt` is null while the season is active. */\nexport type IncentivesSeason = {\n id: number;\n name: string;\n startsAt: string;\n endsAt: string | null;\n};\n\n/** A wallet's frozen result in a closed season. Forfeited wallets read zero in every figure. */\nexport type IncentivesClosedSeasonPoints = PointsBreakdown & {\n season: IncentivesSeason;\n forfeited: boolean;\n};\n\nexport type IncentivesUserPointsData = {\n /** Latest weekly leaderboard of the active season. */\n weekly: PointsBreakdown;\n /** Running cumulative total of the active season. */\n season: PointsBreakdown;\n /** Final results of every closed season, oldest first (zeros where the wallet never scored). */\n closedSeasons: IncentivesClosedSeasonPoints[];\n};\n\nexport type IncentivesUserRanks = {\n walletAddress: string;\n tradingRank: RankTrading;\n stakingRank: Rank;\n};\n\nexport type IncentivesUserBoosts = {\n walletAddress: string;\n tradingBoost: number;\n stakingBoost: number;\n loyaltyBoost: number;\n};\n\n/** Live retention progress in the scorer's current (windowStartedAt, asOf] period. */\nexport type IncentivesRetention = {\n /** Previous archival, or season start before the first archival; an ISO UTC instant. */\n windowStartedAt: string;\n /** Query cutoff, an ISO UTC instant. */\n asOf: string;\n /** Sorted distinct UTC YYYY-MM-DD dates of matched perp fills, using block time on either leg. */\n tradingDates: string[];\n tradingDays: number;\n requiredDays: number;\n boostMultiplier: number;\n /** Meets the retention day threshold; does not guarantee a points award. */\n qualified: boolean;\n /** Current retention factor on volume XP, before other scoring rules. */\n appliedMultiplier: number;\n};\n\nexport type IncentivesUserSummaryData = {\n walletAddress: string;\n /** The season `points.weekly` and `points.season` belong to. */\n activeSeason: IncentivesSeason;\n points: IncentivesUserPointsData;\n ranks: Omit<IncentivesUserRanks, 'walletAddress'>;\n boosts: Omit<IncentivesUserBoosts, 'walletAddress'>;\n /** Live progress, separate from archived points.weekly; null outside active V2 scoring. */\n retention: IncentivesRetention | null;\n};\n\nexport type IncentivesLeaderBoardEntry = {\n rank: number;\n walletAddress: string;\n totalPoints: number;\n tradingPoints: number;\n stakingPoints: number;\n signalPoints: number;\n isCurrentUser?: boolean;\n};\n\nexport type IncentivesPointsHistoryEntry = {\n walletAddress: string;\n totalXpOG: number;\n totalXpOGRanked: number;\n liquidityReferralXpOG: number;\n liquidityXpOG: number;\n rankMultiplierOG: number;\n rankOG: Rank;\n stakingPointsOG: number;\n liquidityReferralXpSeason1: number;\n liquidityXpSeason1: number;\n liquidityXpSeason1Ranked: number;\n rankMultiplierSeason1: number;\n rankSeason1: Rank;\n stakingPointsSeason1: number;\n tradingReferralXpSeason1: number;\n tradingXpSeason1: number;\n tradingXpSeason1Ranked: number;\n tradingRankMultiplierSeason1: number;\n tradingRankSeason1: RankTrading;\n tradingPointsSeason1: number;\n liquidityReferralXpSeason2: number;\n liquidityXpSeason2: number;\n rankSeason2: Rank;\n stakingPointsSeason2: number;\n tradingReferralXpSeason2: number;\n tradingXpSeason2: number;\n tradingRankSeason2: RankTrading;\n tradingPointsSeason2: number;\n totalLiquidityXp: number;\n totalLiquidityReferralXp: number;\n totalTradingXp: number;\n totalTradingReferralXp: number;\n totalXp: number;\n totalPoints: number;\n};\n\n/**\n * `weekly` = latest weekly leaderboard of the active season; `season` = a whole season: the\n * running cumulative of the active season by default, or the frozen result of the season selected\n * with the `seasonId` query parameter once it is closed.\n */\nexport type LeaderBoardType = 'weekly' | 'season';\nexport type LeaderBoardParams = { type: LeaderBoardType };\n/** `seasonId` selects the season for `type=season` (default: the active one); ignored for `weekly`. */\nexport type LeaderBoardQuery = { seasonId?: string };\n\nexport type TradingCompetitionRoundParams = { round: number };\n\nexport type TradingCompetitionUserSummaryData =\n | {\n status: 'out';\n }\n | {\n status: 'in';\n realizedPnl: number;\n position: number;\n volume: number;\n volumePosition: number;\n };\n\nexport type TradingCompetitionLeaderboardEntry = {\n walletAddress: string;\n realizedPnl: number;\n position: number;\n};\n\nexport type IncentivesStreakStatus = {\n currentStreakDay: number | 'upcoming' | 'ended';\n timeUntilNextStreakDay: number;\n};\n\nexport type IncentivesStreakMarketVolume = {\n symbol: string;\n volume: number;\n};\n\nexport type IncentivesStreakDayActivity = {\n day: number;\n markets: IncentivesStreakMarketVolume[];\n};\n\nexport type IncentivesStreakUserActivity = IncentivesStreakStatus & {\n walletAddress: string;\n days: IncentivesStreakDayActivity[];\n};\n\nexport type IncentivesApiSource = {\n 'incentives/points': ApiEndpoint<\n {\n activeSeason: IncentivesSeason;\n /** Points issued in the latest weekly leaderboard of the active season. */\n weekly: number;\n /** Running total of the active season. */\n season: number;\n /** Frozen totals of every closed season, oldest first (forfeited wallets excluded). */\n closedSeasons: { season: IncentivesSeason; totalPoints: number }[];\n },\n never\n >;\n\n 'incentives/leaderBoard/:type': ApiInfiniteListEndpoint<\n IncentivesLeaderBoardEntry,\n LeaderBoardParams,\n PaginatedQueryParams & LeaderBoardQuery\n >;\n\n 'incentives/wallet/:address': ApiEndpoint<\n IncentivesUserSummaryData,\n AddressParam\n >;\n\n 'incentives/wallet/:address/referralsLeaderBoard/:type': ApiListEndpoint<\n IncentivesLeaderBoardEntry,\n AddressParam & LeaderBoardParams,\n LeaderBoardQuery\n >;\n\n 'incentives/wallet/:address/pointsHistory': ApiEndpoint<\n IncentivesPointsHistoryEntry,\n AddressParam\n >;\n\n 'incentives/tradingCompetition/:round': ApiEndpoint<\n {\n entries: TradingCompetitionLeaderboardEntry[];\n status: 'live' | 'ended';\n refreshedAt: number;\n },\n TradingCompetitionRoundParams\n >;\n\n 'incentives/wallet/:address/tradingCompetition/:round': ApiEndpoint<\n TradingCompetitionUserSummaryData,\n AddressParam & TradingCompetitionRoundParams\n >;\n\n 'incentives/wallet/:address/tradingCompetition/:round/registration': ApiEndpoint<\n { registered: boolean },\n AddressParam & TradingCompetitionRoundParams\n >;\n\n 'incentives/wallet/:address/tradingCompetition/:round/claim': ApiEndpoint<\n FailableResult,\n AddressParam & TradingCompetitionRoundParams,\n { code: string }\n >;\n\n 'incentives/streak': ApiEndpoint<IncentivesStreakStatus, never>;\n\n 'incentives/streak/wallet/:address': ApiEndpoint<\n IncentivesStreakUserActivity,\n AddressParam\n >;\n\n 'incentives/vip/wallet/:address': ApiEndpoint<\n {\n walletAddress: string;\n isVip: boolean;\n registered: boolean;\n hasInviteLink: boolean;\n registeredAt: number | null;\n },\n AddressParam\n >;\n\n 'incentives/vip/wallet/:address/nonce': ApiEndpoint<\n FailableResult<{\n nonce: string;\n message: string;\n expiresAt: number;\n }>,\n AddressParam\n >;\n\n 'incentives/vip/wallet/:address/register': ApiEndpoint<\n FailableResult<{\n inviteLink: string;\n alreadyRegistered: boolean;\n }>,\n AddressParam\n >;\n\n 'incentives/waitlist/status/:address': ApiEndpoint<\n {\n status: 'none' | 'waiting' | 'admitted' | 'rejected';\n staked: boolean | null;\n x: { username: string; followedAt: string | null } | null;\n email: string | null;\n share: { lastAt: string | null; nextAt: string | null };\n /** tier * 10000 + min(125 + position in the tier, 9999); null when not ranked. */\n rank: number | null;\n },\n AddressParam\n >;\n};\n\nexport type IncentivesApi = {\n [K in keyof IncentivesApiSource]: {\n params: IncentivesApiSource[K]['params'];\n query: IncentivesApiSource[K]['query'];\n response: Stringified<IncentivesApiSource[K]['response']>;\n };\n};\n"]}
|
|
1
|
+
{"version":3,"file":"incentives-api-types.js","sourceRoot":"/","sources":["incentives-api-types.ts"],"names":[],"mappings":"","sourcesContent":["import {\n AddressParam,\n ApiEndpoint,\n ApiInfiniteListEndpoint,\n ApiListEndpoint,\n PaginatedQueryParams,\n FailableResult,\n Stringified,\n} from './api-types';\nimport { Rank, RankTrading } from './types';\n\nexport type PointsBreakdown = {\n totalPoints: number;\n tradingPoints: number;\n stakingPoints: number;\n signalPoints: number;\n rank: number;\n};\n\n/** A points season as served by the API. `endsAt` is null while the season is active. */\nexport type IncentivesSeason = {\n id: number;\n name: string;\n startsAt: string;\n endsAt: string | null;\n};\n\n/** A wallet's frozen result in a closed season. Forfeited wallets read zero in every figure. */\nexport type IncentivesClosedSeasonPoints = PointsBreakdown & {\n season: IncentivesSeason;\n forfeited: boolean;\n};\n\nexport type IncentivesUserPointsData = {\n /** Latest weekly leaderboard of the active season. */\n weekly: PointsBreakdown;\n /** Running cumulative total of the active season. */\n season: PointsBreakdown;\n /** Final results of every closed season, oldest first (zeros where the wallet never scored). */\n closedSeasons: IncentivesClosedSeasonPoints[];\n};\n\nexport type IncentivesUserRanks = {\n walletAddress: string;\n tradingRank: RankTrading;\n stakingRank: Rank;\n};\n\nexport type IncentivesUserBoosts = {\n walletAddress: string;\n tradingBoost: number;\n stakingBoost: number;\n loyaltyBoost: number;\n};\n\n/** Live retention progress in the scorer's current (windowStartedAt, asOf] period. */\nexport type IncentivesRetention = {\n /** Previous archival, or season start before the first archival; an ISO UTC instant. */\n windowStartedAt: string;\n /** Query cutoff, an ISO UTC instant. */\n asOf: string;\n /** Sorted distinct UTC YYYY-MM-DD dates of matched perp fills, using block time on either leg. */\n tradingDates: string[];\n tradingDays: number;\n requiredDays: number;\n boostMultiplier: number;\n /** Meets the retention day threshold; does not guarantee a points award. */\n qualified: boolean;\n /** Current retention factor on volume XP, before other scoring rules. */\n appliedMultiplier: number;\n};\n\nexport type IncentivesUserSummaryData = {\n walletAddress: string;\n /** The season `points.weekly` and `points.season` belong to. */\n activeSeason: IncentivesSeason;\n points: IncentivesUserPointsData;\n ranks: Omit<IncentivesUserRanks, 'walletAddress'>;\n boosts: Omit<IncentivesUserBoosts, 'walletAddress'>;\n /** Live progress, separate from archived points.weekly; null outside active V2 scoring. */\n retention: IncentivesRetention | null;\n};\n\nexport type IncentivesLeaderBoardEntry = {\n rank: number;\n walletAddress: string;\n totalPoints: number;\n tradingPoints: number;\n stakingPoints: number;\n signalPoints: number;\n isCurrentUser?: boolean;\n};\n\nexport type IncentivesPointsHistoryEntry = {\n walletAddress: string;\n totalXpOG: number;\n totalXpOGRanked: number;\n liquidityReferralXpOG: number;\n liquidityXpOG: number;\n rankMultiplierOG: number;\n rankOG: Rank;\n stakingPointsOG: number;\n liquidityReferralXpSeason1: number;\n liquidityXpSeason1: number;\n liquidityXpSeason1Ranked: number;\n rankMultiplierSeason1: number;\n rankSeason1: Rank;\n stakingPointsSeason1: number;\n tradingReferralXpSeason1: number;\n tradingXpSeason1: number;\n tradingXpSeason1Ranked: number;\n tradingRankMultiplierSeason1: number;\n tradingRankSeason1: RankTrading;\n tradingPointsSeason1: number;\n liquidityReferralXpSeason2: number;\n liquidityXpSeason2: number;\n rankSeason2: Rank;\n stakingPointsSeason2: number;\n tradingReferralXpSeason2: number;\n tradingXpSeason2: number;\n tradingRankSeason2: RankTrading;\n tradingPointsSeason2: number;\n totalLiquidityXp: number;\n totalLiquidityReferralXp: number;\n totalTradingXp: number;\n totalTradingReferralXp: number;\n totalXp: number;\n totalPoints: number;\n};\n\n/**\n * `weekly` = latest weekly leaderboard of the active season; `season` = a whole season: the\n * running cumulative of the active season by default, or the frozen result of the season selected\n * with the `seasonId` query parameter once it is closed.\n */\nexport type LeaderBoardType = 'weekly' | 'season';\nexport type LeaderBoardParams = { type: LeaderBoardType };\n/** `seasonId` selects the season for `type=season` (default: the active one); ignored for `weekly`. */\nexport type LeaderBoardQuery = { seasonId?: string };\n\nexport type TradingCompetitionRoundParams = { round: number };\n\nexport type TradingCompetitionUserSummaryData =\n | {\n status: 'out';\n }\n | {\n status: 'in';\n realizedPnl: number;\n position: number;\n volume: number;\n volumePosition: number;\n };\n\nexport type TradingCompetitionLeaderboardEntry = {\n walletAddress: string;\n realizedPnl: number;\n position: number;\n};\n\nexport type IncentivesStreakStatus = {\n currentStreakDay: number | 'upcoming' | 'ended';\n timeUntilNextStreakDay: number;\n};\n\nexport type IncentivesStreakMarketVolume = {\n symbol: string;\n volume: number;\n};\n\nexport type IncentivesStreakDayActivity = {\n day: number;\n markets: IncentivesStreakMarketVolume[];\n};\n\nexport type IncentivesStreakUserActivity = IncentivesStreakStatus & {\n walletAddress: string;\n days: IncentivesStreakDayActivity[];\n};\n\nexport type IncentivesApiSource = {\n 'incentives/points': ApiEndpoint<\n {\n activeSeason: IncentivesSeason;\n /** Points issued in the latest weekly leaderboard of the active season. */\n weekly: number;\n /** Running total of the active season. */\n season: number;\n /** Frozen totals of every closed season, oldest first (forfeited wallets excluded). */\n closedSeasons: { season: IncentivesSeason; totalPoints: number }[];\n },\n never\n >;\n\n 'incentives/leaderBoard/:type': ApiInfiniteListEndpoint<\n IncentivesLeaderBoardEntry,\n LeaderBoardParams,\n PaginatedQueryParams & LeaderBoardQuery\n >;\n\n 'incentives/wallet/:address': ApiEndpoint<\n IncentivesUserSummaryData,\n AddressParam\n >;\n\n 'incentives/wallet/:address/referralsLeaderBoard/:type': ApiListEndpoint<\n IncentivesLeaderBoardEntry,\n AddressParam & LeaderBoardParams,\n LeaderBoardQuery\n >;\n\n 'incentives/wallet/:address/pointsHistory': ApiEndpoint<\n IncentivesPointsHistoryEntry,\n AddressParam\n >;\n\n 'incentives/tradingCompetition/:round': ApiEndpoint<\n {\n entries: TradingCompetitionLeaderboardEntry[];\n status: 'live' | 'ended';\n refreshedAt: number;\n },\n TradingCompetitionRoundParams\n >;\n\n 'incentives/wallet/:address/tradingCompetition/:round': ApiEndpoint<\n TradingCompetitionUserSummaryData,\n AddressParam & TradingCompetitionRoundParams\n >;\n\n 'incentives/wallet/:address/tradingCompetition/:round/registration': ApiEndpoint<\n { registered: boolean },\n AddressParam & TradingCompetitionRoundParams\n >;\n\n 'incentives/wallet/:address/tradingCompetition/:round/claim': ApiEndpoint<\n FailableResult,\n AddressParam & TradingCompetitionRoundParams,\n { code: string }\n >;\n\n 'incentives/streak': ApiEndpoint<IncentivesStreakStatus, never>;\n\n 'incentives/streak/wallet/:address': ApiEndpoint<\n IncentivesStreakUserActivity,\n AddressParam\n >;\n\n 'incentives/vip/wallet/:address': ApiEndpoint<\n {\n walletAddress: string;\n isVip: boolean;\n registered: boolean;\n hasInviteLink: boolean;\n registeredAt: number | null;\n },\n AddressParam\n >;\n\n 'incentives/vip/wallet/:address/nonce': ApiEndpoint<\n FailableResult<{\n nonce: string;\n message: string;\n expiresAt: number;\n }>,\n AddressParam\n >;\n\n 'incentives/vip/wallet/:address/register': ApiEndpoint<\n FailableResult<{\n inviteLink: string;\n alreadyRegistered: boolean;\n }>,\n AddressParam\n >;\n\n 'incentives/waitlist/status/:address': ApiEndpoint<\n {\n status: 'none' | 'waiting' | 'admitted' | 'rejected';\n staked: boolean | null;\n x: { username: string; followedAt: string | null } | null;\n email: string | null;\n share: { lastAt: string | null; nextAt: string | null };\n /** (tier - 1) * 10000 + min(125 + position in the tier, 9999); null when not ranked. */\n rank: number | null;\n },\n AddressParam\n >;\n};\n\nexport type IncentivesApi = {\n [K in keyof IncentivesApiSource]: {\n params: IncentivesApiSource[K]['params'];\n query: IncentivesApiSource[K]['query'];\n response: Stringified<IncentivesApiSource[K]['response']>;\n };\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"trading-api-types.js","sourceRoot":"/","sources":["trading-api-types.ts"],"names":[],"mappings":";;;AAYa,QAAA,mBAAmB,GAAG;IACjC,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;CACjB,CAAC","sourcesContent":["import { ParamsDictionary, Query } from 'express-serve-static-core';\nimport { Address, AssetPair, CollateralPrice, MarketPrice } from './types';\nimport {\n AddressParam,\n ApiEndpoint,\n ApiInfiniteListEndpoint,\n ApiListEndpoint,\n Decimal,\n PaginatedQueryParams,\n Stringified,\n} from './api-types';\n\nexport const AccountStatusValues = {\n OPEN: 'OPEN',\n CLOSED: 'CLOSED',\n};\n\nexport type AccountStatus =\n (typeof AccountStatusValues)[keyof typeof AccountStatusValues];\n\ntype CandleResolution = '1' | '5' | '15' | '30' | '60' | '240' | '1D';\n\ntype Candle = {\n time: number;\n open: number;\n high: number;\n low: number;\n close: number;\n assetPairId: AssetPair;\n resolution: CandleResolution;\n};\n\n// Database-shaped perp execution row exposed by provider and API types.\ntype Order = {\n id: string;\n market_id: Decimal | null;\n account_id: Decimal | null;\n executed_base: Decimal | null;\n fee: Decimal | null;\n price: Decimal | null;\n is_match_order: boolean | null;\n liquidation_type: Decimal | null;\n execution_type: number | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n event_sequence_number: bigint | null;\n exchange_id: Decimal | null;\n created_at: Date;\n counterparty_account_id: Decimal | null;\n counterparty_adl_unwind_price: Decimal | null;\n counterparty_average_entry_funding_value: Decimal | null;\n counterparty_base: Decimal | null;\n counterparty_base_multiplier: Decimal | null;\n counterparty_funding_value: Decimal | null;\n counterparty_last_price: Decimal | null;\n counterparty_last_price_timestamp: Decimal | null;\n counterparty_previous_adl_unwind_price: Decimal | null;\n counterparty_previous_average_entry_funding_value: Decimal | null;\n counterparty_previous_base_multiplier: Decimal | null;\n counterparty_previous_funding_value: Decimal | null;\n counterparty_previous_last_price: Decimal | null;\n counterparty_previous_realized_pnl: Decimal | null;\n counterparty_realized_pnl: Decimal | null;\n counterparty_session: Decimal | null;\n position_adl_unwind_price: Decimal | null;\n position_average_entry_funding_value: Decimal | null;\n position_base: Decimal | null;\n position_base_multiplier: Decimal | null;\n position_funding_value: Decimal | null;\n position_last_price: Decimal | null;\n position_last_price_timestamp: Decimal | null;\n position_previous_adl_unwind_price: Decimal | null;\n position_previous_average_entry_funding_value: Decimal | null;\n position_previous_base_multiplier: Decimal | null;\n position_previous_funding_value: Decimal | null;\n position_previous_last_price: Decimal | null;\n position_previous_realized_pnl: Decimal | null;\n position_realized_pnl: Decimal | null;\n position_session: Decimal | null;\n referrer_account_id: Decimal | null;\n referrer_fee_credit: Decimal | null;\n // V3 fields\n protocol_fee_credit: Decimal | null;\n taker_rebate_credit: Decimal | null;\n pool_fee_credit: Decimal | null;\n exchange_fee_credit: Decimal | null;\n maker_fee_credit: Decimal | null;\n maker_fee_debit: Decimal | null;\n account_order_id: bigint | null;\n counterparty_order_id: bigint | null;\n me_nonce: Decimal | null;\n};\n\ntype Position = {\n market_id: Decimal;\n account_id: Decimal;\n base: Decimal | null;\n realized_pnl: Decimal | null;\n last_price: Decimal | null;\n last_price_timestamp: Decimal | null;\n funding_value: Decimal | null;\n base_multiplier: Decimal | null;\n adl_unwind_price: Decimal | null;\n average_entry_funding_value: Decimal | null;\n session: Decimal | null;\n exchange_id: Decimal | null;\n event_sequence_number: bigint | null;\n referrer_account_id: Decimal | null;\n referrer_fee_credit: Decimal | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n adjusted_base: Decimal | null;\n adl_realized_pnl: Decimal | null;\n};\n\n// PRO-126 Bug 7: `ConditionalOrder` + `ConditionalOrderSensitive`\n// trading-api-types retired with the rest of the legacy\n// `ConditionalOrders` DB pipeline. They modeled the legacy row shape\n// for the dead V1 `/wallet/:address/openOrders` endpoint + the dead\n// `replication:ConditionalOrdersSensitive` broadcast channel; both\n// callers have been removed.\n\ntype Account = {\n account_id: Decimal;\n name: string;\n status: AccountStatus;\n updated_timestamp_ms: Decimal;\n source: string | null;\n};\n\ntype AccountBalance = {\n account_id: Decimal | null;\n collateral: string | null;\n balance?: Decimal | null;\n delta?: Decimal | null;\n};\n\ntype spot_execution = {\n account_id: Decimal;\n counterparty_account_id: Decimal;\n // Order attribution is absent for auto-exchange executions: there is no\n // matched order, so the chain emits no exchange/order ids and the DB\n // columns are NULL. Matches the `spot_executions` Prisma model.\n exchange_id: Decimal | null;\n executed_base: Decimal;\n price: Decimal;\n account_order_id: bigint | null;\n counterparty_order_id: bigint | null;\n me_nonce: Decimal | null;\n spot_market_id: Decimal;\n is_auto_exchange: boolean;\n is_long: boolean;\n event_sequence_number: bigint;\n parent_event_sequence_number: bigint | null;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n created_at: string;\n};\n\ntype account_real_balance = {\n account_id: Decimal;\n collateral: string;\n balance: Decimal;\n rpnl: Decimal;\n event_sequence_number: bigint | null;\n transfer_event_sequence_number: bigint | null;\n parent_event_sequence_number: bigint | null;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n};\n\n// `Leverage` is still referenced by the `wallet/:address/leverages`\n// endpoint below, so it is kept; `AutoExchange` (a dead legacy type with\n// no remaining references) was removed in #2713/#2710.\ntype Leverage = {\n accountId: Decimal;\n marketId: Decimal;\n leverage: number;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype WalletStats = {\n volume_14d: Decimal;\n lookback_volume: Decimal;\n lookback_window_seconds: number;\n};\n\ntype MarketData = {\n marketId: string;\n updatedAt: number;\n longOI: number;\n shortOI: number;\n longSkewPercentage: number;\n shortSkewPercentage: number;\n openInterest?: number;\n fundingRate?: number;\n fundingRateVelocity?: number;\n longFundingValue?: number;\n shortFundingValue?: number;\n last24hVolume: number;\n priceChange24H?: number;\n priceChange24HPercentage?: number;\n maxAmountBaseLong?: number;\n maxAmountSizeLong?: number;\n maxAmountBaseShort?: number;\n maxAmountSizeShort?: number;\n /** ME mark price, despite the name. Surfaced as v2 `MarketSummary.markPrice`. */\n oraclePrice?: number;\n /**\n * Orderbook mid. Absent on an empty or one-sided book\n */\n poolPrice?: number;\n /**\n * Stork index price, rUSD-quoted (divided by USDCUSD, like the collateral\n * feeds). Surfaced as v2 `MarketSummary.oraclePrice` — the name differs\n * because the v1 `oraclePrice` above is already taken by the mark price.\n * Absent when the index feed has no fresh tick.\n */\n indexPrice?: number;\n pricesUpdatedAt?: number;\n longBaseMultiplier?: number;\n shortBaseMultiplier?: number;\n longAdlUnwindPrice?: number;\n shortAdlUnwindPrice?: number;\n depthFactor?: number;\n priceSpread?: number;\n logPriceMultiplier?: number;\n};\n\ntype SpotMarketData = {\n spotMarketId: string;\n symbol: string;\n updatedAt: number;\n volume24h: number;\n pxChange24h?: number;\n /** Stork price for the base token, rUSD-quoted (divided by USDCUSD). */\n oraclePrice?: number;\n /**\n * Spot orderbook mid, read from the ME `{depth}:bbo:<id>` key. Absent on an\n * empty or one-sided book — spot has no mark price to fall back to, unlike\n * the perp `poolPrice` above.\n */\n throttledMidPrice?: number;\n};\n\ntype MarketTrackers = {\n market_data_id: Decimal;\n passive_pool_id: Decimal | null;\n pool_account_id: Decimal | null;\n quote_token: string | null;\n quote_token_decimals: Decimal | null;\n last_funding_velocity: Decimal | null;\n last_funding_timestamp: Decimal | null;\n last_mtm_price: Decimal | null;\n last_mtm_timestamp: Decimal | null;\n long_trackers_funding_value: Decimal | null;\n last_funding_rate: Decimal | null;\n long_trackers_base_multiplier: Decimal | null;\n long_trackers_adl_unwind_price: Decimal | null;\n short_trackers_funding_value: Decimal | null;\n short_trackers_base_multiplier: Decimal | null;\n short_trackers_adl_unwind_price: Decimal | null;\n open_interest: Decimal | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n price_spread: Decimal | null;\n depth_factor: Decimal | null;\n log_price_multiplier: Decimal | null;\n mark_price: Decimal | null;\n mark_price_timestamp: Decimal | null;\n funding_rate: Decimal | null;\n funding_rate_timestamp: Decimal | null;\n};\n\nexport type TradingApiReplication<\n ReplicationTable extends ReplicationModel = never,\n Replication = never,\n> = {\n replication: ReplicationTable extends never\n ? never\n : GenericReplicationMessage<Replication, ReplicationTable>;\n};\n\nexport type TradingApiEndpoint<\n Response,\n Params,\n ReplicationTable extends ReplicationModel = never,\n Replication = Response,\n Query = never,\n> = ApiEndpoint<Response, Params, Query> &\n TradingApiReplication<ReplicationTable, Replication>;\n\nexport type TradingApiListEndpoint<\n Response,\n Params = never,\n ReplicationTable extends ReplicationModel = never,\n Replication = Response,\n Query = never,\n> = ApiListEndpoint<Response, Params, Query> &\n TradingApiReplication<ReplicationTable, Replication>;\n\nexport type TradingApiInfiniteListEndpoint<\n Response,\n Params = never,\n ReplicationTable extends ReplicationModel = never,\n Replication = Response,\n Query = PaginatedQueryParams,\n> = ApiInfiniteListEndpoint<Response, Params, Query> &\n TradingApiReplication<ReplicationTable, Replication>;\n\nexport type TradingApiSource = {\n 'poolBalance/:poolId': TradingApiEndpoint<\n {\n id: number;\n timestamp: bigint;\n pool_id: number;\n value: Decimal;\n apy: Decimal;\n share_price: Decimal;\n share_price_index: Decimal;\n } | null,\n {\n poolId?: string;\n }\n >;\n 'poolBalance/:poolId/apy-history': TradingApiEndpoint<\n { timestampInMs: number; apy: number }[],\n { poolId?: string },\n never,\n { timestampInMs: number; apy: number }[],\n { timeframeMs: string; granularity: string }\n >;\n 'wallet/:address/leverages': TradingApiListEndpoint<\n Leverage,\n { address: string },\n 'accountLeveragePerMarket'\n >;\n 'markets/data': TradingApiListEndpoint<MarketData, never, 'marketData'>;\n 'spotMarkets/data': TradingApiListEndpoint<\n SpotMarketData,\n never,\n 'spotMarketData'\n >;\n 'markets/configuration': TradingApiListEndpoint<{\n market_id: Decimal;\n risk_matrix_index: Decimal | null;\n max_open_base: Decimal | null;\n velocity_multiplier: Decimal | null;\n minimum_order_base: Decimal | null;\n base_spacing: Decimal | null;\n price_spacing: Decimal | null;\n oracle_node_id: string | null;\n mtm_window: Decimal | null;\n dutch_config_lambda: Decimal | null;\n dutch_config_min_base: Decimal | null;\n slippage_params_phi: Decimal | null;\n slippage_params_beta: Decimal | null;\n depth_factor: Decimal | null;\n max_exposure_factor: Decimal | null;\n max_p_slippage: Decimal | null;\n price_spread: Decimal | null;\n volatility_index_multiplier: Decimal | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n }>;\n 'markets/storage': TradingApiListEndpoint<{\n market_id: Decimal;\n quote_collateral: string | null;\n instrument_address: string | null;\n name: string | null;\n risk_block_id: Decimal | null;\n collateral_pool_id: Decimal | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n }>;\n 'markets/trackers': TradingApiListEndpoint<\n MarketTrackers,\n never,\n 'marketTrackers'\n >;\n 'market/:marketId/trackers': TradingApiEndpoint<\n MarketTrackers,\n {\n marketId: string;\n },\n 'marketTrackers'\n >;\n 'market/:marketId/data': TradingApiEndpoint<\n MarketData,\n {\n marketId: string;\n },\n 'marketData'\n >;\n 'wallet/:address/positions': TradingApiListEndpoint<\n Position,\n AddressParam,\n 'position',\n Omit<Position, 'adjusted_base' | 'adl_realized_pnl'>\n >;\n // PRO-126 Bug 7: V1 `/wallet/:address/openOrders` endpoint type\n // retired. The route+controller were removed in trading.router.ts +\n // trading.controller.ts. V2 callers should use\n // `/v2/wallet/:address/openOrders` which serves both spot and perp\n // orders from the unified ME stream via AccountOrdersMap.\n assets: TradingApiListEndpoint<{\n address: string;\n name: string;\n short: string;\n createdAt: Date;\n updatedAt: Date;\n asset_price_contract_id: string | null;\n asset_price_usdc_contract_id: string | null;\n decimals: number;\n }>;\n prices: TradingApiEndpoint<\n Partial<Record<AssetPair, MarketPrice | CollateralPrice>>,\n never\n >;\n 'prices/:assetPairId': TradingApiEndpoint<\n MarketPrice | CollateralPrice | undefined,\n {\n assetPairId: string;\n },\n 'price'\n >;\n // Bridge deposits and withdrawals for a wallet. Rows are registered by the\n // Reya app when it broadcasts the source-chain transaction, and reconciled\n // by the pending-transaction cron -- nothing else writes them, which is why\n // this is a v1 app endpoint rather than part of the general v2 API.\n 'wallet/:address/bridgeTransactions': TradingApiListEndpoint<\n bridge_transactions_margin_account,\n AddressParam,\n 'BridgeTransactionsMarginAccount'\n >;\n 'wallet/:address/accounts': TradingApiListEndpoint<\n Account,\n AddressParam,\n 'AccountProfile'\n >;\n 'wallet/:address/accounts/balances': TradingApiListEndpoint<\n AccountBalance,\n AddressParam,\n 'account_balances'\n >;\n 'wallet/:address/balanceHistory/:timestamp': TradingApiListEndpoint<\n {\n timestamp: number;\n balance: number;\n },\n {\n address: string;\n timestamp: string;\n }\n >;\n riskMatrices: TradingApiListEndpoint<\n {\n blockId: Decimal;\n matrix: string[][];\n },\n {\n poolId: string;\n }\n >;\n 'candle/:assetPairId/:resolution': TradingApiEndpoint<\n Candle | null,\n {\n resolution: CandleResolution;\n assetPairId: AssetPair;\n },\n 'storkPriceCandle',\n Candle\n >;\n 'candles/:assetPairId/:resolution': TradingApiEndpoint<\n {\n t: number[];\n o: number[];\n h: number[];\n l: number[];\n c: number[];\n },\n {\n resolution: CandleResolution;\n assetPairId: AssetPair;\n },\n never,\n never,\n {\n to: string;\n from: string;\n countBack?: string;\n }\n >;\n feeTierParameters: TradingApiListEndpoint<{\n tier_id: Decimal;\n taker_fee: Decimal;\n maker_fee: Decimal;\n volume: Decimal;\n }>;\n globalFeeParameters: TradingApiEndpoint<\n {\n og_discount: Decimal;\n vltz_discount: Decimal;\n referee_discount: Decimal;\n referrer_rebate: Decimal;\n affiliate_referrer_rebate: Decimal;\n },\n never\n >;\n dynamicDepthConfig: TradingApiEndpoint<\n {\n markets: {\n marketId: number;\n baseDepth: number;\n thresholds: number[];\n ratios: number[];\n }[];\n },\n never\n >;\n 'wallet/:address/configuration': TradingApiEndpoint<\n {\n tier_id: Decimal;\n og_status: boolean;\n vltz_status: boolean;\n affiliate_status: boolean;\n referee_status: boolean;\n spread_discount_status: boolean;\n main_account_id: Decimal;\n },\n {\n address: string;\n }\n >;\n 'wallet/:address/stats': TradingApiEndpoint<\n WalletStats,\n {\n address: string;\n }\n >;\n 'wallet/:address/apiWalletStatus': TradingApiEndpoint<\n {\n enabledApiWallets: string[];\n },\n {\n address: string;\n }\n >;\n rlp: TradingApiEndpoint<\n {\n tvlInUsdc: number;\n tvlInRlp: number;\n rlpUsdcPrice: number;\n apy: {\n '1d': number;\n '7d': number;\n '30d': number;\n '365d': number;\n };\n numberOfDepositors: number;\n ageSeconds: number;\n },\n never\n >;\n 'wallet/:address/rlp': TradingApiEndpoint<\n {\n balanceInUsdc: number;\n balanceInRlp: number;\n },\n {\n address: string;\n }\n >;\n 'collaterals/definitions': TradingApiEndpoint<\n {\n collaterals: CollateralDefinition[];\n },\n never\n >;\n 'collaterals/balances/wallet/:address': TradingApiEndpoint<\n {\n collaterals: CollateralWalletBalance[];\n },\n {\n address: string;\n }\n >;\n};\n\nexport type Req<P = ParamsDictionary, ReqQuery = Query> = {\n params: P;\n query: ReqQuery;\n};\n\nexport type TradingApi = {\n [K in keyof TradingApiSource as K]: {\n params: TradingApiSource[K]['params'];\n query: TradingApiSource[K]['query'];\n response: Stringified<TradingApiSource[K]['response']>;\n replication: Stringified<TradingApiSource[K]['replication']>;\n };\n};\n\ntype ReplicationModel = string | never;\n\nexport type GenericReplicationMessage<T, model extends ReplicationModel> =\n | {\n model: model;\n result: T;\n operation: 'create' | 'update' | 'upsert' | 'delete';\n }\n | {\n model: model;\n result: T[];\n operation: 'updateMany';\n }\n | {\n model: model;\n result: T[];\n operation: 'createMany';\n };\n\ntype account_collateral_balance_entries = {\n id: string;\n account_id: Decimal | null;\n collateral: string | null;\n amount: Decimal | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n};\n\ntype account_owner_updated_snapshot = {\n account_id: Decimal;\n transaction_hash: string;\n new_owner: string | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n event_sequence_number: bigint | null;\n};\n\nexport interface OrdersGatewayPermissionUpdatedStreamResult {\n owner: string;\n delegate: string;\n permission_state: boolean;\n event_sequence_number: string;\n block_number: string;\n block_timestamp: string;\n transaction_hash: string | null;\n}\n\nexport interface PerpTradeStreamPosition {\n account_id: Decimal;\n base: Decimal;\n base_multiplier: Decimal;\n funding_value: Decimal;\n adl_unwind_price: Decimal;\n last_price: Decimal;\n last_price_timestamp: Decimal;\n realized_pnl: Decimal;\n average_entry_funding_value: Decimal;\n session: Decimal;\n}\n\nexport interface PerpTradeStreamResult {\n id: string;\n event_sequence_number: Decimal;\n me_nonce: Decimal;\n market_id: Decimal;\n account_id: Decimal;\n counterparty_account_id: Decimal;\n executed_base: Decimal;\n fee: Decimal;\n price: Decimal;\n is_match_order: boolean;\n liquidation_type: Decimal;\n execution_type: number;\n protocol_fee_credit: Decimal;\n taker_rebate_credit: Decimal;\n pool_fee_credit: Decimal;\n exchange_fee_credit: null;\n maker_fee_credit: null;\n maker_fee_debit: null;\n account_order_id: Decimal;\n counterparty_order_id: Decimal;\n position_previous_average_entry_funding_value: Decimal;\n position_previous_adl_unwind_price: Decimal;\n position_previous_base_multiplier: Decimal;\n position_previous_funding_value: Decimal;\n position_previous_last_price: Decimal;\n position_previous_realized_pnl: Decimal;\n counterparty_previous_average_entry_funding_value: Decimal;\n counterparty_previous_adl_unwind_price: Decimal;\n counterparty_previous_base_multiplier: Decimal;\n counterparty_previous_funding_value: Decimal;\n counterparty_previous_last_price: Decimal;\n counterparty_previous_realized_pnl: Decimal;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n unique_id: bigint;\n exchange_id: Decimal;\n referrer_account_id: Decimal;\n referrer_fee_credit: Decimal;\n account: PerpTradeStreamPosition;\n counterparty: PerpTradeStreamPosition;\n}\n\nexport type PerpTradeStreamMessage = GenericReplicationMessage<\n PerpTradeStreamResult,\n 'trade'\n>;\n\nexport interface BalanceStreamSide {\n account_id: Decimal;\n balance: Decimal;\n /** Lowercased owner address (address(0) for account 0); part of the ledger enrichment. */\n owner?: string;\n}\n\n/**\n * One built leg of a Transfers event. The account ledger fields (PRO-852,\n * design §3.2) label and link the leg the same way its account_transfers row\n * is: `type` from command type and leg position, `fill_id` (ME nonce) and\n * `market_id` for perp fills settled after reya-network#752,\n * `spot_execution_sequence_number` / `spot_market_id` for spot trades and\n * auto-exchanges. Consumers that only track balances ignore them.\n */\nexport interface BalanceStreamTransfer {\n transfer_event_sequence_number: Decimal;\n collateral: string;\n from: BalanceStreamSide;\n to: BalanceStreamSide;\n // The ledger enrichment (PRO-852), included on all newly published legs;\n // a leg without it feeds the balances rail and nothing else.\n /** Position of the leg in the event's array. */\n leg_index?: number;\n /** Amount moved (`netDepositsDelta`), raw token units, always positive. */\n amount?: Decimal;\n /** TransferType label; OTHER when the leg is not recognised. */\n type?: string;\n fill_id?: Decimal | null;\n market_id?: Decimal | null;\n spot_execution_sequence_number?: Decimal | null;\n spot_market_id?: Decimal | null;\n}\n\n/** A leg as published while the ledger is on: every enrichment field present. */\nexport type EnrichedBalanceStreamTransfer = Required<\n Omit<BalanceStreamTransfer, 'from' | 'to'>\n> & {\n from: Required<BalanceStreamSide>;\n to: Required<BalanceStreamSide>;\n};\n\nexport interface BalanceStreamResult {\n event_sequence_number: Decimal;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n command_type: Decimal;\n me_nonce: Decimal | null;\n spot_market_id: Decimal | null;\n account_id: Decimal | null;\n counterparty_account_id: Decimal | null;\n transfers: BalanceStreamTransfer[];\n}\n\nexport type BalanceStreamMessage = GenericReplicationMessage<\n BalanceStreamResult,\n 'transfers'\n>;\n\ntype positions_migration = {\n market_id: Decimal;\n account_id: Decimal;\n base: Decimal | null;\n realized_pnl: Decimal | null;\n last_price: Decimal | null;\n last_price_timestamp: Decimal | null;\n funding_value: Decimal | null;\n base_multiplier: Decimal | null;\n adl_unwind_price: Decimal | null;\n average_entry_funding_value: Decimal | null;\n session: Decimal | null;\n exchange_id: Decimal | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n event_sequence_number: bigint | null;\n referrer_account_id: Decimal | null;\n referrer_fee_credit: Decimal | null;\n};\n\ntype execution_bust = {\n event_sequence_number: bigint;\n market_id: Decimal;\n market_type: string;\n account_id: Decimal;\n counterparty_account_id: Decimal;\n account_order_id: bigint;\n counterparty_order_id: bigint;\n me_nonce: Decimal | null;\n exchange_id: Decimal;\n failed_base: Decimal;\n price: Decimal;\n is_long: boolean;\n reason: string;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n created_at: string;\n};\n\n// Bridge-carried money-in/out transactions, recorded as soon as the source\n// chain tx is broadcast and reconciled once the bridge delivers. Declared with\n// the database's own types; `Stringified<>` maps Date and Decimal to strings\n// for the replication payload.\ntype bridge_transactions_margin_account = {\n source_tx_hash: string;\n destination_tx_hash: string | null;\n source_chain_id: number;\n destination_chain_id: number;\n account_id: Decimal;\n status: string;\n amount: Decimal;\n type: string;\n asset_id: string;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype ReplicationMessage =\n // Extract the union of all `replication` values from TradingApiSource\n | Exclude<TradingApiSource[keyof TradingApiSource]['replication'], never>\n // add messages that do not exists in TradingApiSource\n | GenericReplicationMessage<\n account_owner_updated_snapshot,\n 'account_owner_updated_snapshot'\n >\n | GenericReplicationMessage<\n account_collateral_balance_entries,\n 'account_collateral_balance_entries'\n >\n | GenericReplicationMessage<account_real_balance, 'account_real_balances'>\n | GenericReplicationMessage<\n OrdersGatewayPermissionUpdatedStreamResult,\n 'orders_gateway_permission'\n >\n // PRO-126 Bug 7: `ConditionalOrdersSensitive` replication channel\n // retired with the rest of the `ConditionalOrders` DB pipeline.\n // Order data flows through the ME's `{orders}:changes` stream.\n | GenericReplicationMessage<\n // Todo: remove after migration\n positions_migration,\n 'positions_migration'\n >\n | GenericReplicationMessage<spot_execution, 'spot_executions'>\n | GenericReplicationMessage<Order, 'orders'>\n | GenericReplicationMessage<execution_bust, 'execution_busts'>\n | GenericReplicationMessage<\n bridge_transactions_margin_account,\n 'BridgeTransactionsMarginAccount'\n >;\n\nexport type SocketDepositChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaPeriphery: Address;\n vaultAddress: Address;\n connectorAddress: Address;\n msgGasLimit: string;\n bridgeTime: number;\n};\n\nexport type SocketWithdrawChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaCore: Address;\n msgGasLimit: string;\n bridgeFee: string;\n bridgeTime: number;\n};\n\nexport type LayerzeroDepositChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaPeriphery: Address;\n dstEid: number;\n extraOptions: string;\n bridgeTime: number;\n};\n\nexport type LayerzeroWithdrawChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaCore: Address;\n dstEid: number;\n bridgeFee: string;\n bridgeTime: number;\n};\n\nexport type SocketDepositInfo =\n | { enabled: false }\n | { enabled: true; chains: SocketDepositChainDetails[]; minAmount: number };\n\nexport type SocketWithdrawInfo =\n | { enabled: false }\n | { enabled: true; chains: SocketWithdrawChainDetails[]; minAmount: number };\n\nexport type LayerzeroDepositInfo =\n | { enabled: false }\n | {\n enabled: true;\n minAmount: number;\n chains: LayerzeroDepositChainDetails[];\n };\n\nexport type LayerzeroWithdrawInfo =\n | { enabled: false }\n | {\n enabled: true;\n minAmount: number;\n chains: LayerzeroWithdrawChainDetails[];\n };\n\nexport type TransferInfo = { enabled: boolean };\n\nexport type SpotInfo =\n | { enabled: false }\n | { enabled: true; spotMarketSymbol: string };\n\nexport type DisplayInfo = {\n advertisedInSpot: boolean;\n advertisedInPerp: boolean;\n displayName: string;\n displayDecimals: number;\n};\n\nexport type CollateralDefinition = {\n id: Uppercase<string>;\n address: Address;\n assetPairId: string;\n priceHaircut: string;\n liquidationDiscount: string;\n decimals: number;\n socketDepositInfo: SocketDepositInfo;\n socketWithdrawInfo: SocketWithdrawInfo;\n layerzeroDepositInfo: LayerzeroDepositInfo;\n layerzeroWithdrawInfo: LayerzeroWithdrawInfo;\n transferInfo: TransferInfo;\n spotInfo: SpotInfo;\n displayInfo: DisplayInfo;\n};\n\n// Per-collateral, per-source-chain wallet balance available to deposit. This is\n// the user's ERC20 balance of the collateral's source-chain token (what a\n// deposit spends), read via `balanceOf`. `balance` is a human-readable decimal\n// string; it is `null` when every RPC for that chain failed.\nexport type CollateralChainBalance = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n balance: string | null;\n};\n\nexport type CollateralWalletBalance = {\n id: Uppercase<string>;\n chains: CollateralChainBalance[];\n};\n\nexport type Replication = {\n [K in ReplicationMessage as `replication:${K['model']}`]: Extract<\n ReplicationMessage,\n { model: K['model'] }\n >;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"trading-api-types.js","sourceRoot":"/","sources":["trading-api-types.ts"],"names":[],"mappings":";;;AAYa,QAAA,mBAAmB,GAAG;IACjC,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,QAAQ;CACjB,CAAC","sourcesContent":["import { ParamsDictionary, Query } from 'express-serve-static-core';\nimport { Address, AssetPair } from './types';\nimport {\n AddressParam,\n ApiEndpoint,\n ApiInfiniteListEndpoint,\n ApiListEndpoint,\n Decimal,\n PaginatedQueryParams,\n Stringified,\n} from './api-types';\n\nexport const AccountStatusValues = {\n OPEN: 'OPEN',\n CLOSED: 'CLOSED',\n};\n\nexport type AccountStatus =\n (typeof AccountStatusValues)[keyof typeof AccountStatusValues];\n\ntype CandleResolution = '1' | '5' | '15' | '30' | '60' | '240' | '1D';\n\ntype Candle = {\n time: number;\n open: number;\n high: number;\n low: number;\n close: number;\n assetPairId: AssetPair;\n resolution: CandleResolution;\n};\n\n// Database-shaped perp execution row exposed by provider and API types.\ntype Order = {\n id: string;\n market_id: Decimal | null;\n account_id: Decimal | null;\n executed_base: Decimal | null;\n fee: Decimal | null;\n price: Decimal | null;\n is_match_order: boolean | null;\n liquidation_type: Decimal | null;\n execution_type: number | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n event_sequence_number: bigint | null;\n exchange_id: Decimal | null;\n created_at: Date;\n counterparty_account_id: Decimal | null;\n counterparty_adl_unwind_price: Decimal | null;\n counterparty_average_entry_funding_value: Decimal | null;\n counterparty_base: Decimal | null;\n counterparty_base_multiplier: Decimal | null;\n counterparty_funding_value: Decimal | null;\n counterparty_last_price: Decimal | null;\n counterparty_last_price_timestamp: Decimal | null;\n counterparty_previous_adl_unwind_price: Decimal | null;\n counterparty_previous_average_entry_funding_value: Decimal | null;\n counterparty_previous_base_multiplier: Decimal | null;\n counterparty_previous_funding_value: Decimal | null;\n counterparty_previous_last_price: Decimal | null;\n counterparty_previous_realized_pnl: Decimal | null;\n counterparty_realized_pnl: Decimal | null;\n counterparty_session: Decimal | null;\n position_adl_unwind_price: Decimal | null;\n position_average_entry_funding_value: Decimal | null;\n position_base: Decimal | null;\n position_base_multiplier: Decimal | null;\n position_funding_value: Decimal | null;\n position_last_price: Decimal | null;\n position_last_price_timestamp: Decimal | null;\n position_previous_adl_unwind_price: Decimal | null;\n position_previous_average_entry_funding_value: Decimal | null;\n position_previous_base_multiplier: Decimal | null;\n position_previous_funding_value: Decimal | null;\n position_previous_last_price: Decimal | null;\n position_previous_realized_pnl: Decimal | null;\n position_realized_pnl: Decimal | null;\n position_session: Decimal | null;\n referrer_account_id: Decimal | null;\n referrer_fee_credit: Decimal | null;\n // V3 fields\n protocol_fee_credit: Decimal | null;\n taker_rebate_credit: Decimal | null;\n pool_fee_credit: Decimal | null;\n exchange_fee_credit: Decimal | null;\n maker_fee_credit: Decimal | null;\n maker_fee_debit: Decimal | null;\n account_order_id: bigint | null;\n counterparty_order_id: bigint | null;\n me_nonce: Decimal | null;\n};\n\ntype Position = {\n market_id: Decimal;\n account_id: Decimal;\n base: Decimal | null;\n realized_pnl: Decimal | null;\n last_price: Decimal | null;\n last_price_timestamp: Decimal | null;\n funding_value: Decimal | null;\n base_multiplier: Decimal | null;\n adl_unwind_price: Decimal | null;\n average_entry_funding_value: Decimal | null;\n session: Decimal | null;\n exchange_id: Decimal | null;\n event_sequence_number: bigint | null;\n referrer_account_id: Decimal | null;\n referrer_fee_credit: Decimal | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n adjusted_base: Decimal | null;\n adl_realized_pnl: Decimal | null;\n};\n\n// PRO-126 Bug 7: `ConditionalOrder` + `ConditionalOrderSensitive`\n// trading-api-types retired with the rest of the legacy\n// `ConditionalOrders` DB pipeline. They modeled the legacy row shape\n// for the dead V1 `/wallet/:address/openOrders` endpoint + the dead\n// `replication:ConditionalOrdersSensitive` broadcast channel; both\n// callers have been removed.\n\ntype Account = {\n account_id: Decimal;\n name: string;\n status: AccountStatus;\n updated_timestamp_ms: Decimal;\n source: string | null;\n};\n\ntype AccountBalance = {\n account_id: Decimal | null;\n collateral: string | null;\n balance?: Decimal | null;\n delta?: Decimal | null;\n};\n\ntype spot_execution = {\n account_id: Decimal;\n counterparty_account_id: Decimal;\n // Order attribution is absent for auto-exchange executions: there is no\n // matched order, so the chain emits no exchange/order ids and the DB\n // columns are NULL. Matches the `spot_executions` Prisma model.\n exchange_id: Decimal | null;\n executed_base: Decimal;\n price: Decimal;\n account_order_id: bigint | null;\n counterparty_order_id: bigint | null;\n me_nonce: Decimal | null;\n spot_market_id: Decimal;\n is_auto_exchange: boolean;\n is_long: boolean;\n event_sequence_number: bigint;\n parent_event_sequence_number: bigint | null;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n created_at: string;\n};\n\ntype account_real_balance = {\n account_id: Decimal;\n collateral: string;\n balance: Decimal;\n rpnl: Decimal;\n event_sequence_number: bigint | null;\n transfer_event_sequence_number: bigint | null;\n parent_event_sequence_number: bigint | null;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n};\n\n// `Leverage` is still referenced by the `wallet/:address/leverages`\n// endpoint below, so it is kept; `AutoExchange` (a dead legacy type with\n// no remaining references) was removed in #2713/#2710.\ntype Leverage = {\n accountId: Decimal;\n marketId: Decimal;\n leverage: number;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype WalletStats = {\n volume_14d: Decimal;\n lookback_volume: Decimal;\n lookback_window_seconds: number;\n};\n\ntype MarketData = {\n marketId: string;\n updatedAt: number;\n longOI: number;\n shortOI: number;\n longSkewPercentage: number;\n shortSkewPercentage: number;\n openInterest?: number;\n fundingRate?: number;\n fundingRateVelocity?: number;\n longFundingValue?: number;\n shortFundingValue?: number;\n last24hVolume: number;\n priceChange24H?: number;\n priceChange24HPercentage?: number;\n maxAmountBaseLong?: number;\n maxAmountSizeLong?: number;\n maxAmountBaseShort?: number;\n maxAmountSizeShort?: number;\n /** ME mark price, despite the name. Surfaced as v2 `MarketSummary.markPrice`. */\n oraclePrice?: number;\n /**\n * Orderbook mid. Absent on an empty or one-sided book\n */\n poolPrice?: number;\n /**\n * Stork index price, rUSD-quoted (divided by USDCUSD, like the collateral\n * feeds). Surfaced as v2 `MarketSummary.oraclePrice` — the name differs\n * because the v1 `oraclePrice` above is already taken by the mark price.\n * Absent when the index feed has no fresh tick.\n */\n indexPrice?: number;\n pricesUpdatedAt?: number;\n longBaseMultiplier?: number;\n shortBaseMultiplier?: number;\n longAdlUnwindPrice?: number;\n shortAdlUnwindPrice?: number;\n depthFactor?: number;\n priceSpread?: number;\n logPriceMultiplier?: number;\n};\n\ntype SpotMarketData = {\n spotMarketId: string;\n symbol: string;\n updatedAt: number;\n volume24h: number;\n pxChange24h?: number;\n /** Stork price for the base token, rUSD-quoted (divided by USDCUSD). */\n oraclePrice?: number;\n /**\n * Spot orderbook mid, read from the ME `{depth}:bbo:<id>` key. Absent on an\n * empty or one-sided book — spot has no mark price to fall back to, unlike\n * the perp `poolPrice` above.\n */\n throttledMidPrice?: number;\n};\n\ntype MarketTrackers = {\n market_data_id: Decimal;\n passive_pool_id: Decimal | null;\n pool_account_id: Decimal | null;\n quote_token: string | null;\n quote_token_decimals: Decimal | null;\n last_funding_velocity: Decimal | null;\n last_funding_timestamp: Decimal | null;\n last_mtm_price: Decimal | null;\n last_mtm_timestamp: Decimal | null;\n long_trackers_funding_value: Decimal | null;\n last_funding_rate: Decimal | null;\n long_trackers_base_multiplier: Decimal | null;\n long_trackers_adl_unwind_price: Decimal | null;\n short_trackers_funding_value: Decimal | null;\n short_trackers_base_multiplier: Decimal | null;\n short_trackers_adl_unwind_price: Decimal | null;\n open_interest: Decimal | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n price_spread: Decimal | null;\n depth_factor: Decimal | null;\n log_price_multiplier: Decimal | null;\n mark_price: Decimal | null;\n mark_price_timestamp: Decimal | null;\n funding_rate: Decimal | null;\n funding_rate_timestamp: Decimal | null;\n};\n\nexport type TradingApiReplication<\n ReplicationTable extends ReplicationModel = never,\n Replication = never,\n> = {\n replication: ReplicationTable extends never\n ? never\n : GenericReplicationMessage<Replication, ReplicationTable>;\n};\n\nexport type TradingApiEndpoint<\n Response,\n Params,\n ReplicationTable extends ReplicationModel = never,\n Replication = Response,\n Query = never,\n> = ApiEndpoint<Response, Params, Query> &\n TradingApiReplication<ReplicationTable, Replication>;\n\nexport type TradingApiListEndpoint<\n Response,\n Params = never,\n ReplicationTable extends ReplicationModel = never,\n Replication = Response,\n Query = never,\n> = ApiListEndpoint<Response, Params, Query> &\n TradingApiReplication<ReplicationTable, Replication>;\n\nexport type TradingApiInfiniteListEndpoint<\n Response,\n Params = never,\n ReplicationTable extends ReplicationModel = never,\n Replication = Response,\n Query = PaginatedQueryParams,\n> = ApiInfiniteListEndpoint<Response, Params, Query> &\n TradingApiReplication<ReplicationTable, Replication>;\n\nexport type TradingApiSource = {\n 'poolBalance/:poolId': TradingApiEndpoint<\n {\n id: number;\n timestamp: bigint;\n pool_id: number;\n value: Decimal;\n apy: Decimal;\n share_price: Decimal;\n share_price_index: Decimal;\n } | null,\n {\n poolId?: string;\n }\n >;\n 'poolBalance/:poolId/apy-history': TradingApiEndpoint<\n { timestampInMs: number; apy: number }[],\n { poolId?: string },\n never,\n { timestampInMs: number; apy: number }[],\n { timeframeMs: string; granularity: string }\n >;\n 'wallet/:address/leverages': TradingApiListEndpoint<\n Leverage,\n { address: string },\n 'accountLeveragePerMarket'\n >;\n 'markets/data': TradingApiListEndpoint<MarketData, never, 'marketData'>;\n 'spotMarkets/data': TradingApiListEndpoint<\n SpotMarketData,\n never,\n 'spotMarketData'\n >;\n 'markets/configuration': TradingApiListEndpoint<{\n market_id: Decimal;\n risk_matrix_index: Decimal | null;\n max_open_base: Decimal | null;\n velocity_multiplier: Decimal | null;\n minimum_order_base: Decimal | null;\n base_spacing: Decimal | null;\n price_spacing: Decimal | null;\n oracle_node_id: string | null;\n mtm_window: Decimal | null;\n dutch_config_lambda: Decimal | null;\n dutch_config_min_base: Decimal | null;\n slippage_params_phi: Decimal | null;\n slippage_params_beta: Decimal | null;\n depth_factor: Decimal | null;\n max_exposure_factor: Decimal | null;\n max_p_slippage: Decimal | null;\n price_spread: Decimal | null;\n volatility_index_multiplier: Decimal | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n }>;\n 'markets/storage': TradingApiListEndpoint<{\n market_id: Decimal;\n quote_collateral: string | null;\n instrument_address: string | null;\n name: string | null;\n risk_block_id: Decimal | null;\n collateral_pool_id: Decimal | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n }>;\n 'markets/trackers': TradingApiListEndpoint<\n MarketTrackers,\n never,\n 'marketTrackers'\n >;\n 'market/:marketId/trackers': TradingApiEndpoint<\n MarketTrackers,\n {\n marketId: string;\n },\n 'marketTrackers'\n >;\n 'market/:marketId/data': TradingApiEndpoint<\n MarketData,\n {\n marketId: string;\n },\n 'marketData'\n >;\n 'wallet/:address/positions': TradingApiListEndpoint<\n Position,\n AddressParam,\n 'position',\n Omit<Position, 'adjusted_base' | 'adl_realized_pnl'>\n >;\n // PRO-126 Bug 7: V1 `/wallet/:address/openOrders` endpoint type\n // retired. The route+controller were removed in trading.router.ts +\n // trading.controller.ts. V2 callers should use\n // `/v2/wallet/:address/openOrders` which serves both spot and perp\n // orders from the unified ME stream via AccountOrdersMap.\n // Bridge deposits and withdrawals for a wallet. Rows are registered by the\n // Reya app when it broadcasts the source-chain transaction, and reconciled\n // by the pending-transaction cron -- nothing else writes them, which is why\n // this is a v1 app endpoint rather than part of the general v2 API.\n 'wallet/:address/bridgeTransactions': TradingApiListEndpoint<\n bridge_transactions_margin_account,\n AddressParam,\n 'BridgeTransactionsMarginAccount'\n >;\n 'wallet/:address/accounts': TradingApiListEndpoint<\n Account,\n AddressParam,\n 'AccountProfile'\n >;\n 'wallet/:address/accounts/balances': TradingApiListEndpoint<\n AccountBalance,\n AddressParam,\n 'account_balances'\n >;\n 'wallet/:address/balanceHistory/:timestamp': TradingApiListEndpoint<\n {\n timestamp: number;\n balance: number;\n },\n {\n address: string;\n timestamp: string;\n }\n >;\n riskMatrices: TradingApiListEndpoint<\n {\n blockId: Decimal;\n matrix: string[][];\n },\n {\n poolId: string;\n }\n >;\n 'candle/:assetPairId/:resolution': TradingApiEndpoint<\n Candle | null,\n {\n resolution: CandleResolution;\n assetPairId: AssetPair;\n },\n 'storkPriceCandle',\n Candle\n >;\n 'candles/:assetPairId/:resolution': TradingApiEndpoint<\n {\n t: number[];\n o: number[];\n h: number[];\n l: number[];\n c: number[];\n },\n {\n resolution: CandleResolution;\n assetPairId: AssetPair;\n },\n never,\n never,\n {\n to: string;\n from: string;\n countBack?: string;\n }\n >;\n feeTierParameters: TradingApiListEndpoint<{\n tier_id: Decimal;\n taker_fee: Decimal;\n maker_fee: Decimal;\n volume: Decimal;\n }>;\n globalFeeParameters: TradingApiEndpoint<\n {\n og_discount: Decimal;\n vltz_discount: Decimal;\n referee_discount: Decimal;\n referrer_rebate: Decimal;\n affiliate_referrer_rebate: Decimal;\n },\n never\n >;\n 'wallet/:address/configuration': TradingApiEndpoint<\n {\n tier_id: Decimal;\n og_status: boolean;\n vltz_status: boolean;\n affiliate_status: boolean;\n referee_status: boolean;\n spread_discount_status: boolean;\n main_account_id: Decimal;\n },\n {\n address: string;\n }\n >;\n 'wallet/:address/stats': TradingApiEndpoint<\n WalletStats,\n {\n address: string;\n }\n >;\n 'wallet/:address/apiWalletStatus': TradingApiEndpoint<\n {\n enabledApiWallets: string[];\n },\n {\n address: string;\n }\n >;\n rlp: TradingApiEndpoint<\n {\n tvlInUsdc: number;\n tvlInRlp: number;\n rlpUsdcPrice: number;\n apy: {\n '1d': number;\n '7d': number;\n '30d': number;\n '365d': number;\n };\n numberOfDepositors: number;\n ageSeconds: number;\n },\n never\n >;\n 'wallet/:address/rlp': TradingApiEndpoint<\n {\n balanceInUsdc: number;\n balanceInRlp: number;\n },\n {\n address: string;\n }\n >;\n 'collaterals/definitions': TradingApiEndpoint<\n {\n collaterals: CollateralDefinition[];\n },\n never\n >;\n 'collaterals/balances/wallet/:address': TradingApiEndpoint<\n {\n collaterals: CollateralWalletBalance[];\n },\n {\n address: string;\n }\n >;\n};\n\nexport type Req<P = ParamsDictionary, ReqQuery = Query> = {\n params: P;\n query: ReqQuery;\n};\n\nexport type TradingApi = {\n [K in keyof TradingApiSource as K]: {\n params: TradingApiSource[K]['params'];\n query: TradingApiSource[K]['query'];\n response: Stringified<TradingApiSource[K]['response']>;\n replication: Stringified<TradingApiSource[K]['replication']>;\n };\n};\n\ntype ReplicationModel = string | never;\n\nexport type GenericReplicationMessage<T, model extends ReplicationModel> =\n | {\n model: model;\n result: T;\n operation: 'create' | 'update' | 'upsert' | 'delete';\n }\n | {\n model: model;\n result: T[];\n operation: 'updateMany';\n }\n | {\n model: model;\n result: T[];\n operation: 'createMany';\n };\n\ntype account_collateral_balance_entries = {\n id: string;\n account_id: Decimal | null;\n collateral: string | null;\n amount: Decimal | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n};\n\ntype account_owner_updated_snapshot = {\n account_id: Decimal;\n transaction_hash: string;\n new_owner: string | null;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n event_sequence_number: bigint | null;\n};\n\nexport interface OrdersGatewayPermissionUpdatedStreamResult {\n owner: string;\n delegate: string;\n permission_state: boolean;\n event_sequence_number: string;\n block_number: string;\n block_timestamp: string;\n transaction_hash: string | null;\n}\n\nexport interface PerpTradeStreamPosition {\n account_id: Decimal;\n base: Decimal;\n base_multiplier: Decimal;\n funding_value: Decimal;\n adl_unwind_price: Decimal;\n last_price: Decimal;\n last_price_timestamp: Decimal;\n realized_pnl: Decimal;\n average_entry_funding_value: Decimal;\n session: Decimal;\n}\n\nexport interface PerpTradeStreamResult {\n id: string;\n event_sequence_number: Decimal;\n me_nonce: Decimal;\n market_id: Decimal;\n account_id: Decimal;\n counterparty_account_id: Decimal;\n executed_base: Decimal;\n fee: Decimal;\n price: Decimal;\n is_match_order: boolean;\n liquidation_type: Decimal;\n execution_type: number;\n protocol_fee_credit: Decimal;\n taker_rebate_credit: Decimal;\n pool_fee_credit: Decimal;\n exchange_fee_credit: null;\n maker_fee_credit: null;\n maker_fee_debit: null;\n account_order_id: Decimal;\n counterparty_order_id: Decimal;\n position_previous_average_entry_funding_value: Decimal;\n position_previous_adl_unwind_price: Decimal;\n position_previous_base_multiplier: Decimal;\n position_previous_funding_value: Decimal;\n position_previous_last_price: Decimal;\n position_previous_realized_pnl: Decimal;\n counterparty_previous_average_entry_funding_value: Decimal;\n counterparty_previous_adl_unwind_price: Decimal;\n counterparty_previous_base_multiplier: Decimal;\n counterparty_previous_funding_value: Decimal;\n counterparty_previous_last_price: Decimal;\n counterparty_previous_realized_pnl: Decimal;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n unique_id: bigint;\n exchange_id: Decimal;\n referrer_account_id: Decimal;\n referrer_fee_credit: Decimal;\n account: PerpTradeStreamPosition;\n counterparty: PerpTradeStreamPosition;\n}\n\nexport type PerpTradeStreamMessage = GenericReplicationMessage<\n PerpTradeStreamResult,\n 'trade'\n>;\n\nexport interface BalanceStreamSide {\n account_id: Decimal;\n balance: Decimal;\n /** Lowercased owner address (address(0) for account 0); part of the ledger enrichment. */\n owner?: string;\n}\n\n/**\n * One built leg of a Transfers event. The account ledger fields (PRO-852,\n * design §3.2) label and link the leg the same way its account_transfers row\n * is: `type` from command type and leg position, `fill_id` (ME nonce) and\n * `market_id` for perp fills settled after reya-network#752,\n * `spot_execution_sequence_number` / `spot_market_id` for spot trades and\n * auto-exchanges. Consumers that only track balances ignore them.\n */\nexport interface BalanceStreamTransfer {\n transfer_event_sequence_number: Decimal;\n collateral: string;\n from: BalanceStreamSide;\n to: BalanceStreamSide;\n // The ledger enrichment (PRO-852), included on all newly published legs;\n // a leg without it feeds the balances rail and nothing else.\n /** Position of the leg in the event's array. */\n leg_index?: number;\n /** Amount moved (`netDepositsDelta`), raw token units, always positive. */\n amount?: Decimal;\n /** TransferType label; OTHER when the leg is not recognised. */\n type?: string;\n fill_id?: Decimal | null;\n market_id?: Decimal | null;\n spot_execution_sequence_number?: Decimal | null;\n spot_market_id?: Decimal | null;\n}\n\n/** A leg as published while the ledger is on: every enrichment field present. */\nexport type EnrichedBalanceStreamTransfer = Required<\n Omit<BalanceStreamTransfer, 'from' | 'to'>\n> & {\n from: Required<BalanceStreamSide>;\n to: Required<BalanceStreamSide>;\n};\n\nexport interface BalanceStreamResult {\n event_sequence_number: Decimal;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n command_type: Decimal;\n me_nonce: Decimal | null;\n spot_market_id: Decimal | null;\n account_id: Decimal | null;\n counterparty_account_id: Decimal | null;\n transfers: BalanceStreamTransfer[];\n}\n\nexport type BalanceStreamMessage = GenericReplicationMessage<\n BalanceStreamResult,\n 'transfers'\n>;\n\ntype positions_migration = {\n market_id: Decimal;\n account_id: Decimal;\n base: Decimal | null;\n realized_pnl: Decimal | null;\n last_price: Decimal | null;\n last_price_timestamp: Decimal | null;\n funding_value: Decimal | null;\n base_multiplier: Decimal | null;\n adl_unwind_price: Decimal | null;\n average_entry_funding_value: Decimal | null;\n session: Decimal | null;\n exchange_id: Decimal | null;\n transaction_hash: string;\n block_timestamp: Decimal | null;\n block_number: Decimal;\n unique_id: bigint | null;\n event_sequence_number: bigint | null;\n referrer_account_id: Decimal | null;\n referrer_fee_credit: Decimal | null;\n};\n\ntype execution_bust = {\n event_sequence_number: bigint;\n market_id: Decimal;\n market_type: string;\n account_id: Decimal;\n counterparty_account_id: Decimal;\n account_order_id: bigint;\n counterparty_order_id: bigint;\n me_nonce: Decimal | null;\n exchange_id: Decimal;\n failed_base: Decimal;\n price: Decimal;\n is_long: boolean;\n reason: string;\n block_timestamp: Decimal;\n block_number: Decimal;\n transaction_hash: string;\n created_at: string;\n};\n\n// Bridge-carried money-in/out transactions, recorded as soon as the source\n// chain tx is broadcast and reconciled once the bridge delivers. Declared with\n// the database's own types; `Stringified<>` maps Date and Decimal to strings\n// for the replication payload.\ntype bridge_transactions_margin_account = {\n source_tx_hash: string;\n destination_tx_hash: string | null;\n source_chain_id: number;\n destination_chain_id: number;\n account_id: Decimal;\n status: string;\n amount: Decimal;\n type: string;\n asset_id: string;\n createdAt: Date;\n updatedAt: Date;\n};\n\ntype ReplicationMessage =\n // Extract the union of all `replication` values from TradingApiSource\n | Exclude<TradingApiSource[keyof TradingApiSource]['replication'], never>\n // add messages that do not exists in TradingApiSource\n | GenericReplicationMessage<\n account_owner_updated_snapshot,\n 'account_owner_updated_snapshot'\n >\n | GenericReplicationMessage<\n account_collateral_balance_entries,\n 'account_collateral_balance_entries'\n >\n | GenericReplicationMessage<account_real_balance, 'account_real_balances'>\n | GenericReplicationMessage<\n OrdersGatewayPermissionUpdatedStreamResult,\n 'orders_gateway_permission'\n >\n // PRO-126 Bug 7: `ConditionalOrdersSensitive` replication channel\n // retired with the rest of the `ConditionalOrders` DB pipeline.\n // Order data flows through the ME's `{orders}:changes` stream.\n | GenericReplicationMessage<\n // Todo: remove after migration\n positions_migration,\n 'positions_migration'\n >\n | GenericReplicationMessage<spot_execution, 'spot_executions'>\n | GenericReplicationMessage<Order, 'orders'>\n | GenericReplicationMessage<execution_bust, 'execution_busts'>\n | GenericReplicationMessage<\n bridge_transactions_margin_account,\n 'BridgeTransactionsMarginAccount'\n >;\n\nexport type SocketDepositChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaPeriphery: Address;\n vaultAddress: Address;\n connectorAddress: Address;\n msgGasLimit: string;\n bridgeTime: number;\n};\n\nexport type SocketWithdrawChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaCore: Address;\n msgGasLimit: string;\n bridgeFee: string;\n bridgeTime: number;\n};\n\nexport type LayerzeroDepositChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaPeriphery: Address;\n dstEid: number;\n extraOptions: string;\n bridgeTime: number;\n};\n\nexport type LayerzeroWithdrawChainDetails = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n collateralName: string;\n collateralAddressInReyaCore: Address;\n dstEid: number;\n bridgeFee: string;\n bridgeTime: number;\n};\n\nexport type SocketDepositInfo =\n | { enabled: false }\n | { enabled: true; chains: SocketDepositChainDetails[]; minAmount: number };\n\nexport type SocketWithdrawInfo =\n | { enabled: false }\n | { enabled: true; chains: SocketWithdrawChainDetails[]; minAmount: number };\n\nexport type LayerzeroDepositInfo =\n | { enabled: false }\n | {\n enabled: true;\n minAmount: number;\n chains: LayerzeroDepositChainDetails[];\n };\n\nexport type LayerzeroWithdrawInfo =\n | { enabled: false }\n | {\n enabled: true;\n minAmount: number;\n chains: LayerzeroWithdrawChainDetails[];\n };\n\nexport type TransferInfo = { enabled: boolean };\n\nexport type SpotInfo =\n | { enabled: false }\n | { enabled: true; spotMarketSymbol: string };\n\nexport type DisplayInfo = {\n advertisedInSpot: boolean;\n advertisedInPerp: boolean;\n displayName: string;\n displayDecimals: number;\n};\n\nexport type CollateralDefinition = {\n id: Uppercase<string>;\n address: Address;\n assetPairId: string;\n priceHaircut: string;\n liquidationDiscount: string;\n decimals: number;\n socketDepositInfo: SocketDepositInfo;\n socketWithdrawInfo: SocketWithdrawInfo;\n layerzeroDepositInfo: LayerzeroDepositInfo;\n layerzeroWithdrawInfo: LayerzeroWithdrawInfo;\n transferInfo: TransferInfo;\n spotInfo: SpotInfo;\n displayInfo: DisplayInfo;\n};\n\n// Per-collateral, per-source-chain wallet balance available to deposit. This is\n// the user's ERC20 balance of the collateral's source-chain token (what a\n// deposit spends), read via `balanceOf`. `balance` is a human-readable decimal\n// string; it is `null` when every RPC for that chain failed.\nexport type CollateralChainBalance = {\n chainId: number;\n chainName: string;\n collateralAddress: Address;\n balance: string | null;\n};\n\nexport type CollateralWalletBalance = {\n id: Uppercase<string>;\n chains: CollateralChainBalance[];\n};\n\nexport type Replication = {\n [K in ReplicationMessage as `replication:${K['model']}`]: Extract<\n ReplicationMessage,\n { model: K['model'] }\n >;\n};\n"]}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import BigNumber from 'bignumber.js';
|
|
2
|
-
import { AccountAssetBalance, CollateralAddressToExchangePriceMap, CollateralInfo, ExchangeInfo,
|
|
2
|
+
import { AccountAssetBalance, CollateralAddressToExchangePriceMap, CollateralInfo, ExchangeInfo, MarginInfo, MarketConfiguration, MarketIdToOraclePriceMap, PositionInfo, PositionInfoMarketConfiguration, RiskMatrix, RiskMultipliersConfiguration } from './types';
|
|
3
3
|
export declare const MAX_FUNDING_RATE: BigNumber;
|
|
4
4
|
export declare const MIN_FUNDING_RATE: BigNumber;
|
|
5
5
|
export declare function clampFundingRate(rate: BigNumber): BigNumber;
|
|
@@ -21,21 +21,10 @@ export declare class ExposureCommand {
|
|
|
21
21
|
mtmRpnlSum: BigNumber;
|
|
22
22
|
collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap;
|
|
23
23
|
constructor(accountId: number, rootCollateralPoolId: number, oraclePricePerMarket: MarketIdToOraclePriceMap, accountBalancePerAsset: AccountAssetBalance[], groupedByCollateral: Record<string, AccountAssetBalance>, riskMultipliers: RiskMultipliersConfiguration, riskMatrices: RiskMatrix[], exchangeInfoPerAsset: ExchangeInfo[], positionInfoMarketConfiguration: PositionInfoMarketConfiguration[], uniqueTokenAddresses: string[], uniqueQuoteCollaterals: string[], tokenMarginInfoPerAsset: MarginInfo[], realizedPnLSum: BigNumber, unrealizedPnLSum: BigNumber, mtmRpnlSum: BigNumber, collateralAddressToExchangePrice: CollateralAddressToExchangePriceMap);
|
|
24
|
-
getState(): ExposureCommandState;
|
|
25
24
|
get getUsdNodeMarginInfo(): MarginInfo;
|
|
26
25
|
get balancePerAsset(): MarginInfo[];
|
|
27
|
-
get exchangePricePerAsset(): ExchangeInfo[];
|
|
28
|
-
getUsdNodeMarginInfoPostTrade(positionAmount: number, collateralAddress: string, marketConfiguration: MarketConfiguration, riskBlockId: number): {
|
|
29
|
-
usdNodeMarginInfo: MarginInfo;
|
|
30
|
-
tokenMarginInfoPerAsset: MarginInfo[];
|
|
31
|
-
positionInfoMarketConfiguration: PositionInfoMarketConfiguration[];
|
|
32
|
-
};
|
|
33
|
-
getEditCollateralActionsToCoverMargin(requiredMargin: number): EditCollateralAction[];
|
|
34
|
-
getUsdNodeMarginInfoPostEditCollaterals(editCollateralActions: EditCollateralAction[]): MarginInfo;
|
|
35
|
-
getUsdNodeMarginInfoPostEditCollateral(collateralDelta: number, collateralAddress: string): MarginInfo;
|
|
36
26
|
static calculateTokenMarginInfoPerAsset(groupedByCollateral: Record<string, AccountAssetBalance>, rootCollateralPoolId: number, riskMatrices: RiskMatrix[], riskMultipliers: RiskMultipliersConfiguration, uniqueQuoteCollaterals: Set<string>, realizedPnLSum: BigNumber, unrealizedPnLSum: BigNumber, positionInfoMarketConfiguration: PositionInfoMarketConfiguration[], oraclePricePerMarket: MarketIdToOraclePriceMap): MarginInfo[];
|
|
37
27
|
static calculateLiquidation(marginBalance: number, liquidationMarginRequirement: number, oraclePrice: number, positionBase: number): BigNumber;
|
|
38
|
-
static calculateImpliedLeverage(notionalExposure: number, oldIMR: number, newIMR: number): number;
|
|
39
28
|
static combineMarginInfo(parentMarginInfo: MarginInfo, sonMarginInfo: MarginInfo, sonParentExchangeInfo: ExchangeInfo): MarginInfo;
|
|
40
29
|
static getUsdNodeMarginInfo(accountCollateralPoolId: number, quoteTokens: string[], exchangeInfoPerAsset: ExchangeInfo[], marginInfoPerToken: MarginInfo[]): MarginInfo;
|
|
41
30
|
static getCollateralInfo(collateralAddress: string, realisedPnl: BigNumber, unrealizedPnL: BigNumber, netDeposits: number): CollateralInfo;
|
|
@@ -49,39 +38,7 @@ export declare class ExposureCommand {
|
|
|
49
38
|
static computePricePnL(openBase: BigNumber, openPrice: BigNumber, exitPrice: BigNumber): BigNumber;
|
|
50
39
|
static getMarginRatio(marginInfo: Pick<MarginInfo, 'marginBalance' | 'liquidationMarginRequirement'>): number;
|
|
51
40
|
static exchangeWithPriceHaircut(quantity: number, price: number, haircut: number): number;
|
|
52
|
-
static reverseExchangeWithPriceHaircut(quantity: number, price: number, haircut: number): number;
|
|
53
41
|
static getBalanceWithHaircut(exchangeInfoPerAsset: ExchangeInfo[], assetAddress: string, marginBalance: number): number;
|
|
54
|
-
getMaxExposure(marketConfiguration: MarketConfiguration, marketStorage: MarketStorage, isPool: boolean): {
|
|
55
|
-
maxExposureShort: number;
|
|
56
|
-
maxExposureLong: number;
|
|
57
|
-
exposures: BigNumber[];
|
|
58
|
-
riskMatrixIndex: number;
|
|
59
|
-
};
|
|
60
|
-
static computeMaxExposures(riskMatrix: BigNumber[][], exposures: BigNumber[], lmr: number, balance: number, imrMultiplier: number, exposureIndex: number): {
|
|
61
|
-
maxExposureShort: number;
|
|
62
|
-
maxExposureLong: number;
|
|
63
|
-
};
|
|
64
|
-
static solveQuadraticEquation(a: number, b: number, c: number): {
|
|
65
|
-
x1: BigNumber;
|
|
66
|
-
x2: BigNumber;
|
|
67
|
-
};
|
|
68
|
-
static computeC(lmr: number, balance: number, imrMultiplier: number): number;
|
|
69
|
-
static calculateRebalancingOrderBase({ poolBasePreTrade, orderBase, }: {
|
|
70
|
-
poolBasePreTrade: number;
|
|
71
|
-
orderBase: number;
|
|
72
|
-
}): number;
|
|
73
|
-
static calculateFee({ oraclePrice, poolBasePreTrade, orderBase, feeParameter, rebalancingFeeParameter, }: {
|
|
74
|
-
oraclePrice: number;
|
|
75
|
-
poolBasePreTrade: number;
|
|
76
|
-
orderBase: number;
|
|
77
|
-
feeParameter: BigNumber;
|
|
78
|
-
rebalancingFeeParameter: BigNumber;
|
|
79
|
-
}): {
|
|
80
|
-
rebalancingFee: number;
|
|
81
|
-
imbalancingFee: number;
|
|
82
|
-
fee: number;
|
|
83
|
-
};
|
|
84
|
-
static calculateEstimatedPrice(price: number, slippage: number): number;
|
|
85
42
|
static evaluateHealthStatus(marginRatioPercentage: number): "danger" | "healthy" | "warning";
|
|
86
43
|
static getFundingPeriods(lastFundingTimeStamp: BigNumber): BigNumber;
|
|
87
44
|
static getHourlyFundingPeriods(lastFundingTimeStamp: BigNumber): BigNumber;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"command.d.ts","sourceRoot":"/","sources":["commands/exposure/command.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,MAAM,cAAc,CAAC;
|
|
1
|
+
{"version":3,"file":"command.d.ts","sourceRoot":"/","sources":["commands/exposure/command.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C,mBAAmB,CACxB,cAAc,EAAE,SAAS,EACzB,mBAAmB,EAAE,SAAS;IAKhC,MAAM,CAAC,qBAAqB,CAC1B,sBAAsB,EAAE,SAAS,EACjC,mBAAmB,EAAE,SAAS,EAC9B,eAAe,EAAE,SAAS;IAa5B;;;OAGG;IACH,MAAM,CAAC,2BAA2B,CAChC,sBAAsB,EAAE,SAAS,EACjC,mBAAmB,EAAE,SAAS,EAC9B,eAAe,EAAE,SAAS;IAU5B,MAAM,CAAC,oBAAoB,CACzB,OAAO,EAAE,SAAS,EAClB,eAAe,EAAE,SAAS,EAC1B,mBAAmB,EAAE,SAAS,EAC9B,KAAK,EAAE,SAAS,EAChB,cAAc,EAAE,SAAS,GACxB,SAAS;IA6BZ;;;OAGG;IACH,MAAM,CAAC,sBAAsB,CAC3B,SAAS,EAAE,SAAS,EACpB,gBAAgB,EAAE,SAAS,EAC3B,cAAc,EAAE,SAAS,EACzB,eAAe,EAAE,SAAS,EAC1B,mBAAmB,EAAE,SAAS,EAC9B,oBAAoB,EAAE,SAAS;IAajC,YAAY,CAAC,MAAM,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM;IAM1D,eAAe,CAAC,YAAY,EAAE,MAAM,GAAG,MAAM;IAI7C,IAAI,WAAW,WAEd;IAED,IAAI,aAAa,WAEhB;IAED,IAAI,sBAAsB,WAezB;IAED,IAAI,iCAAiC,WAcpC;IAED,aAAa;CAGd"}
|
|
@@ -129,11 +129,4 @@ export type TradeSimulationState = {
|
|
|
129
129
|
exposureDataAccount: ExposureCommandState;
|
|
130
130
|
exposureDataPassivePool: ExposureCommandState;
|
|
131
131
|
};
|
|
132
|
-
export type EditCollateralSimulationState = {
|
|
133
|
-
exposureDataAccount: ExposureCommandState;
|
|
134
|
-
};
|
|
135
|
-
export type EditCollateralAction = {
|
|
136
|
-
collateralDelta: number;
|
|
137
|
-
collateralAddress: Lowercase<string>;
|
|
138
|
-
};
|
|
139
132
|
//# sourceMappingURL=types.d.ts.map
|