@reyaxyz/common 0.362.0 → 0.363.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +1 -1
  2. package/dist/commands/exposure/command.js +8 -22
  3. package/dist/commands/exposure/command.js.map +1 -1
  4. package/dist/incentives-api-types.js.map +1 -1
  5. package/dist/services/getNativeToken.js +1 -0
  6. package/dist/services/getNativeToken.js.map +1 -1
  7. package/dist/services/getSocketAddresses.js +1 -0
  8. package/dist/services/getSocketAddresses.js.map +1 -1
  9. package/dist/trading-api-types.js.map +1 -1
  10. package/dist/transactions/abis/Errors.json +1638 -34
  11. package/dist/transactions/abis/OrdersGateway.json +729 -123
  12. package/dist/transactions/abis/PassivePerpProxy.json +542 -0
  13. package/dist/transactions/buildMulticallTx.js.map +1 -1
  14. package/dist/transactions/consts.js +1 -2
  15. package/dist/transactions/consts.js.map +1 -1
  16. package/dist/transactions/contractAddresses.js +45 -5
  17. package/dist/transactions/contractAddresses.js.map +1 -1
  18. package/dist/transactions/sign.js +237 -111
  19. package/dist/transactions/sign.js.map +1 -1
  20. package/dist/types/commands/exposure/command.d.ts +8 -7
  21. package/dist/types/commands/exposure/command.d.ts.map +1 -1
  22. package/dist/types/incentives-api-types.d.ts +61 -5
  23. package/dist/types/incentives-api-types.d.ts.map +1 -1
  24. package/dist/types/services/getNativeToken.d.ts.map +1 -1
  25. package/dist/types/services/getSocketAddresses.d.ts.map +1 -1
  26. package/dist/types/trading-api-types.d.ts +200 -32
  27. package/dist/types/trading-api-types.d.ts.map +1 -1
  28. package/dist/types/transactions/buildMulticallTx.d.ts +1 -0
  29. package/dist/types/transactions/buildMulticallTx.d.ts.map +1 -1
  30. package/dist/types/transactions/consts.d.ts +0 -1
  31. package/dist/types/transactions/consts.d.ts.map +1 -1
  32. package/dist/types/transactions/contractAddresses.d.ts +0 -1
  33. package/dist/types/transactions/contractAddresses.d.ts.map +1 -1
  34. package/dist/types/transactions/sign.d.ts +113 -9
  35. package/dist/types/transactions/sign.d.ts.map +1 -1
  36. package/dist/types/types.d.ts +62 -63
  37. package/dist/types/types.d.ts.map +1 -1
  38. package/dist/types/utils/calculate.d.ts.map +1 -1
  39. package/dist/types/utils/consts.d.ts +2 -2
  40. package/dist/types/utils/consts.d.ts.map +1 -1
  41. package/dist/types/utils/error-sanitizer.d.ts +15 -0
  42. package/dist/types/utils/error-sanitizer.d.ts.map +1 -0
  43. package/dist/types/utils/index.d.ts +3 -0
  44. package/dist/types/utils/index.d.ts.map +1 -1
  45. package/dist/types/utils/network.d.ts.map +1 -1
  46. package/dist/types/utils/number.d.ts +5 -0
  47. package/dist/types/utils/number.d.ts.map +1 -1
  48. package/dist/types/utils/realized-balance.d.ts +54 -0
  49. package/dist/types/utils/realized-balance.d.ts.map +1 -0
  50. package/dist/types/utils/throttled-error.d.ts +42 -0
  51. package/dist/types/utils/throttled-error.d.ts.map +1 -0
  52. package/dist/types/utils/token/normalize.d.ts +2 -1
  53. package/dist/types/utils/token/normalize.d.ts.map +1 -1
  54. package/dist/types/utils/token/token-info-getters.d.ts.map +1 -1
  55. package/dist/types/utils/token/token-info.d.ts.map +1 -1
  56. package/dist/types.js +25 -11
  57. package/dist/types.js.map +1 -1
  58. package/dist/utils/calculate.js +18 -9
  59. package/dist/utils/calculate.js.map +1 -1
  60. package/dist/utils/consts.js +2 -7
  61. package/dist/utils/consts.js.map +1 -1
  62. package/dist/utils/error-sanitizer.js +135 -0
  63. package/dist/utils/error-sanitizer.js.map +1 -0
  64. package/dist/utils/index.js +3 -0
  65. package/dist/utils/index.js.map +1 -1
  66. package/dist/utils/network.js +4 -0
  67. package/dist/utils/network.js.map +1 -1
  68. package/dist/utils/number.js +96 -1
  69. package/dist/utils/number.js.map +1 -1
  70. package/dist/utils/realized-balance.js +126 -0
  71. package/dist/utils/realized-balance.js.map +1 -0
  72. package/dist/utils/throttled-error.js +60 -0
  73. package/dist/utils/throttled-error.js.map +1 -0
  74. package/dist/utils/token/normalize.js +2 -2
  75. package/dist/utils/token/normalize.js.map +1 -1
  76. package/dist/utils/token/token-info-getters.js +80 -5
  77. package/dist/utils/token/token-info-getters.js.map +1 -1
  78. package/dist/utils/token/token-info.js +11 -0
  79. package/dist/utils/token/token-info.js.map +1 -1
  80. package/package.json +3 -3
  81. package/src/commands/exposure/command.ts +8 -38
  82. package/src/incentives-api-types.ts +60 -5
  83. package/src/services/getNativeToken.ts +1 -0
  84. package/src/services/getSocketAddresses.ts +1 -0
  85. package/src/trading-api-types.ts +258 -39
  86. package/src/transactions/abis/Errors.json +5478 -3874
  87. package/src/transactions/abis/OrdersGateway.json +730 -124
  88. package/src/transactions/abis/PassivePerpProxy.json +542 -0
  89. package/src/transactions/buildMulticallTx.ts +4 -0
  90. package/src/transactions/consts.ts +0 -1
  91. package/src/transactions/contractAddresses.ts +42 -7
  92. package/src/transactions/sign.ts +306 -150
  93. package/src/types.ts +102 -82
  94. package/src/utils/calculate.ts +21 -8
  95. package/src/utils/consts.ts +4 -16
  96. package/src/utils/error-sanitizer.ts +137 -0
  97. package/src/utils/index.ts +3 -0
  98. package/src/utils/network.ts +4 -0
  99. package/src/utils/number.ts +110 -0
  100. package/src/utils/realized-balance.ts +163 -0
  101. package/src/utils/throttled-error.ts +85 -0
  102. package/src/utils/token/normalize.ts +6 -1
  103. package/src/utils/token/token-info-getters.ts +104 -6
  104. package/src/utils/token/token-info.ts +78 -0
package/dist/types.js CHANGED
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isMarketPrice = exports.TierType = exports.ConditionalOrderStatus = exports.ConditionalOrderType = exports.OrdersGatewayOrderType = exports.CandleResolution = exports.FundingRateHistoryGranularity = exports.AllMarginAccountsBalanceGranularity = exports.MarginAccountCollateralsBalanceGranularity = exports.MarginAccountBalanceGranularity = exports.LpBalanceGranularity = exports.CandlesResolution = exports.MoneyInOutChainId = exports.ReyaChainId = void 0;
3
+ exports.isMarketPrice = exports.TierType = exports.ConditionalOrderStatus = exports.ConditionalOrderType = exports.ExecutionType = exports.MarketType = exports.OrderType = exports.CandleResolution = exports.FundingRateHistoryGranularity = exports.AllMarginAccountsBalanceGranularity = exports.MarginAccountCollateralsBalanceGranularity = exports.MarginAccountBalanceGranularity = exports.LpBalanceGranularity = exports.CandlesResolution = exports.MoneyInOutChainId = exports.ReyaChainId = void 0;
4
4
  var ReyaChainId;
5
5
  (function (ReyaChainId) {
6
6
  ReyaChainId[ReyaChainId["reyaNetwork"] = 1729] = "reyaNetwork";
7
+ ReyaChainId[ReyaChainId["reyaLocal"] = 31337] = "reyaLocal";
7
8
  ReyaChainId[ReyaChainId["reyaCronos"] = 89346162] = "reyaCronos";
8
9
  })(ReyaChainId || (exports.ReyaChainId = ReyaChainId = {}));
9
10
  var MoneyInOutChainId;
@@ -88,16 +89,29 @@ var CandleResolution;
88
89
  CandleResolution["FOUR_HOURS"] = "4HOURS";
89
90
  CandleResolution["ONE_DAY"] = "1DAY";
90
91
  })(CandleResolution || (exports.CandleResolution = CandleResolution = {}));
91
- var OrdersGatewayOrderType;
92
- (function (OrdersGatewayOrderType) {
93
- OrdersGatewayOrderType[OrdersGatewayOrderType["STOP_LOSS"] = 0] = "STOP_LOSS";
94
- OrdersGatewayOrderType[OrdersGatewayOrderType["TAKE_PROFIT"] = 1] = "TAKE_PROFIT";
95
- OrdersGatewayOrderType[OrdersGatewayOrderType["LIMIT_ORDER"] = 2] = "LIMIT_ORDER";
96
- OrdersGatewayOrderType[OrdersGatewayOrderType["MARKET_ORDER"] = 3] = "MARKET_ORDER";
97
- OrdersGatewayOrderType[OrdersGatewayOrderType["REDUCE_ONLY_MARKET_ORDER"] = 4] = "REDUCE_ONLY_MARKET_ORDER";
98
- OrdersGatewayOrderType[OrdersGatewayOrderType["FULL_CLOSE_ORDER"] = 5] = "FULL_CLOSE_ORDER";
99
- OrdersGatewayOrderType[OrdersGatewayOrderType["LIMIT_ORDER_SPOT"] = 6] = "LIMIT_ORDER_SPOT";
100
- })(OrdersGatewayOrderType || (exports.OrdersGatewayOrderType = OrdersGatewayOrderType = {}));
92
+ // PRO-126 Bug 5 retired the legacy `OrdersGatewayOrderType` enum (the
93
+ // 8-field `ConditionalOrderDetails` typehash discriminator). The
94
+ // on-chain `OrdersGateway.execute` selector that consumed those values
95
+ // is gone; every order class now uses `OrderType` below, whose values
96
+ // mirror the on-chain `OrderType` enum in
97
+ // orders-gateway/src/libraries/DataTypes.sol.
98
+ var OrderType;
99
+ (function (OrderType) {
100
+ OrderType[OrderType["Limit"] = 0] = "Limit";
101
+ OrderType[OrderType["StopLoss"] = 1] = "StopLoss";
102
+ OrderType[OrderType["TakeProfit"] = 2] = "TakeProfit";
103
+ })(OrderType || (exports.OrderType = OrderType = {}));
104
+ // Matches the on-chain `MarketType` enum. Used to discriminate spot vs perp
105
+ // in unified off-chain code paths and with the market-id namespace helpers in
106
+ // packages/common-backend/src/market-id-namespace.
107
+ var MarketType;
108
+ (function (MarketType) {
109
+ MarketType[MarketType["Spot"] = 0] = "Spot";
110
+ MarketType[MarketType["Perp"] = 1] = "Perp";
111
+ })(MarketType || (exports.MarketType = MarketType = {}));
112
+ // Canonical on-chain V3 codes, also written by the pre-cutover V2 indexer.
113
+ var canonical_execution_type_1 = require("./canonical-execution-type");
114
+ Object.defineProperty(exports, "ExecutionType", { enumerable: true, get: function () { return canonical_execution_type_1.CanonicalExecutionType; } });
101
115
  var ConditionalOrderType;
102
116
  (function (ConditionalOrderType) {
103
117
  ConditionalOrderType[ConditionalOrderType["STOP_LOSS"] = 0] = "STOP_LOSS";
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"/","sources":["types.ts"],"names":[],"mappings":";;;AAiDA,IAAY,WAGX;AAHD,WAAY,WAAW;IACrB,8DAAkB,CAAA;IAClB,gEAAqB,CAAA;AACvB,CAAC,EAHW,WAAW,2BAAX,WAAW,QAGtB;AAED,IAAY,iBAWX;A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AAW,CAAA;AACb,CAAC,EAHW,QAAQ,wBAAR,QAAQ,QAGnB;AA2RM,IAAM,aAAa,GAAG,UAC3B,KAAoC;IAEpC,OAAA,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,UAAU,CAAC;AAAvD,CAAuD,CAAC;AAH7C,QAAA,aAAa,iBAGgC","sourcesContent":["import { TradingApiSource, Replication } from './trading-api-types';\nimport { Stringified } from './api-types';\n\nimport {\n CoreCommandsEIP712SignatureAndPayload,\n EIP712Signature,\n} from './transactions';\nimport { JsonRpcSigner, Signer } from 'ethers';\n\nexport type Address = Lowercase<string>;\nexport type TokenName = Uppercase<string>;\n\n// -- Markets --\nexport type MarketOrderInfo = {\n counterpartyAccountIds: number[];\n exchangeId: number;\n};\n\nexport type MarketEntity = {\n id: number;\n ticker: string;\n underlyingAsset: string;\n quoteToken: string;\n quoteTokenId: string;\n markPrice: number;\n isActive: boolean;\n maxLeverage: number;\n volume24H: number;\n priceChange24H: number;\n priceChange24HPercentage: number;\n marketPriceDeviation: number;\n openInterest: number;\n fundingRate: number;\n fundingRateAnnualized: number;\n description: string;\n orderInfo: MarketOrderInfo;\n tickSizeDecimals: number;\n minOrderSize: number;\n minOrderSizeBase: number;\n baseSpacing: number;\n priceSpacing: number;\n longOI: number;\n shortOI: number;\n longSkewPercentage: number;\n shortSkewPercentage: number;\n availableLong: number;\n availableShort: number;\n};\n\nexport enum ReyaChainId {\n reyaNetwork = 1729,\n reyaCronos = 89346162,\n}\n\nexport enum MoneyInOutChainId {\n // mainnet\n ethereumMainnet = 1,\n opMainnet = 10,\n polygonMainnet = 137,\n arbitrumOne = 42161,\n baseMainnet = 8453,\n // testnet\n arbitrumSepolia = 421614,\n opSepolia = 11155420,\n ethereumSepolia = 11155111,\n}\n\nexport enum CandlesResolution {\n ONE_MINUTE = '1MIN',\n FIVE_MINUTES = '5MINS',\n FIFTEEN_MINUTES = '15MINS',\n THIRTY_MINUTES = '30MINS',\n ONE_HOUR = '1HOUR',\n FOUR_HOURS = '4HOURS',\n ONE_DAY = '1DAY',\n}\n\n// -- Candles --\nexport interface Candle {\n id: string;\n startedAt: string;\n ticker: string;\n resolution: CandlesResolution;\n low: string;\n high: string;\n open: string;\n close: string;\n baseTokenVolume: string;\n usdVolume: string;\n trades: number;\n startingOpenInterest: string;\n}\n\n// -- Account --\n\nexport type Status = 'OPEN' | 'CLOSED' | 'LIQUIDATED' | 'FILLED';\nexport type Side = 'long' | 'short';\n\nexport type CollateralEntity = {\n token: string;\n address: string;\n percentage: number;\n balance: number;\n balanceRUSD: number;\n balanceWithHaircutRUSD: number;\n exchangeRate: number;\n exchangeRateWithHaircut: number;\n exchangeRateChange24HPercentage: number;\n yieldPercentage?: number;\n};\n\nexport type CollateralWithHaircut = {\n address: string;\n priceHaircut: number;\n};\n\nexport type MarginRatioHealth = 'danger' | 'healthy' | 'warning';\n\nexport type MarginAccountEntity = {\n id: number;\n name: string;\n marginRatioHealth: MarginRatioHealth;\n marginRatioPercentage: number;\n marginRatioHealthDangerThreshold: number;\n marginRatioHealthWarningThreshold: number;\n isApproachingLiquidation: boolean;\n isLiquidationImminent: boolean;\n totalBalance: number;\n liquidationMarginRequirement: number;\n totalBalanceUnderlyingAsset: string;\n totalBalanceChange24HPercentage: number;\n totalBalanceWithHaircut: number;\n livePnL: number;\n livePnLUnderlyingAsset: string;\n realizedPnL: number;\n realizedPnLUnderlyingAsset: string;\n realizedPnlHistoryTotal: number;\n totalPositionsCount: number;\n collaterals: CollateralEntity[];\n positions?: PositionEntity[];\n};\n\nexport type StrippedMarginAccountEntity = Pick<\n MarginAccountEntity,\n 'id' | 'name'\n>;\n\nexport type ConditionalOrdersInfo = {\n stopLoss?: {\n stopLossPrice: number;\n orderId: string;\n };\n takeProfit?: {\n takeProfitPrice: number;\n orderId: string;\n };\n};\n\nexport type PositionEntity = {\n id: number;\n side: Side;\n size: number;\n base: number;\n price: number;\n conditionalOrdersInfo?: ConditionalOrdersInfo;\n markPrice: number;\n orderStatus: Status;\n realisedPnl: number;\n priceVariationPnl: number;\n livePnL: number;\n fundingPnl: number;\n unrealisedPnl: number;\n liquidationPrice: number;\n marketId: number;\n accountId: number;\n};\n\nexport type OrderType = 'market';\n\nexport type OrderHistoryType =\n | 'long-trade'\n | 'short-trade'\n | 'long-liquidation'\n | 'short-liquidation';\n\nexport type OrderHistoryEntity = {\n id: string;\n action: OrderHistoryType;\n orderType: OrderType;\n base: number;\n executionPrice: number;\n realisedPnl?: number | null;\n priceVariationPnl: number;\n fundingPnl: number;\n fees: number;\n openingFees: number;\n timestamp: number;\n marketId?: number;\n xpEarned: number;\n};\n\nexport type ApyDetails = {\n dailyApy: number;\n weeklyApy: number;\n monthlyApy: number;\n yearlyApy: number;\n};\n\nexport type LpPoolEntity = {\n id: number;\n name: string;\n description: string;\n longDescription: string;\n readMoreLink: string;\n currentAPY: number;\n apyDetails: ApyDetails;\n apyChange24H: number;\n tokenAddress: Address;\n token: string;\n minDepositAmount: number;\n minWithdrawAmount: number;\n stepSize: number;\n allowedChainsForLiquidity: MoneyInOutChainId[];\n moneyInOutConfiguration: MoneyInOutConfiguration;\n};\n\nexport type MoneyInOutConfiguration = {\n [key in MoneyInOutChainId]?: {\n minWithdrawAmount?: number;\n };\n};\n\nexport type MoneyInOutConfigurationPerTokenName = {\n [key in TokenName]?: MoneyInOutConfiguration;\n};\n\nexport type LpWithdrawBalanceEntity = {\n withdrawableBalance: number;\n poolSharePrice: number;\n accountShareBalance: number;\n balanceBreakdown: {\n [coinName: string]: {\n balance: number;\n priceTokenToRusd: number;\n tokenAddress: string;\n };\n };\n};\n\nexport type TransactionHistoryType = 'deposit' | 'withdrawal';\n\nexport type LpTransactionHistoryEntity = {\n id: number;\n type: TransactionHistoryType;\n token: string;\n share: number;\n tokenAddress: string;\n amount: number;\n transactionLink: string;\n timestamp: number;\n};\n\nexport type MarginAccountTransactionHistoryType =\n | 'deposit'\n | 'withdrawal'\n | 'transfer'\n | 'auto_exchange_deposit'\n | 'auto_exchange_withdrawal';\n\nexport type MarginAccountTransactionStatus = 'confirmed' | 'pending';\n\nexport type MarginAccountTransactionHistoryEntity = {\n id: number;\n type: MarginAccountTransactionHistoryType;\n token: string;\n amount: number;\n transactionLink: string;\n status: MarginAccountTransactionStatus;\n timestamp: number;\n};\n\nexport type ReferralFeeTransactionHistoryEntity = {\n id: number;\n referee_wallet_address: string;\n token: string;\n amount: number;\n transactionLink: string;\n timestamp: number;\n};\n\nexport type TokenEntity = {\n name: TokenName;\n address: Address;\n};\n\n// --- Lp Pool Balance ---\nexport enum LpBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\n// - LP Account Performance -\nexport type GetLpPoolPerformanceChartDataResult = {\n capitalInvestedData: {\n timestampInMs: number;\n value: number;\n }[];\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n balance: number;\n balanceChangePercentage: number;\n capitalInvested: number;\n capitalInvestedChangePercentage: number;\n};\n\nexport type SocketTokenConnectors = {\n deposit: Address;\n withdraw: Address;\n};\n\nexport type GetSocketConnectorsParams = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n};\n\nexport type GetSocketVaultParams = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n};\n\nexport type GetMoneyInOutChainIdFromReyaConnectorParams = {\n reyaChainId: ReyaChainId;\n tokenName: TokenName;\n socketConnector: Address;\n};\n\nexport type GetSocketBridgeTimeParams = {\n moneyInOutChainId: MoneyInOutChainId;\n};\n\nexport type GetSocketBridgeTimeResult = {\n bridgeTimeInMS: number;\n};\n\nexport type GetSocketWithdrawMsgGasLimitParams = {\n moneyInOutChainId: MoneyInOutChainId;\n};\n\nexport type GetSocketWithdrawMsgGasLimitResult = {\n msgGasLimit: bigint;\n};\n\nexport type SocketDepositFeesEntry = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n fees: bigint;\n};\n\nexport type SocketWithdrawFeesEntry = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n fees: bigint;\n};\n\nexport type SocketDepositFees = {\n fees: bigint;\n feesInUnderlyingToken: number;\n underlyingTokenName: TokenName;\n};\n\nexport type SocketWithdrawFees = {\n fees: bigint;\n feesInUnderlyingToken: number;\n underlyingTokenName: TokenName;\n};\n\nexport type GetSocketWithdrawFeesParams = {\n reyaChainId: ReyaChainId;\n tokenAddress: TokenEntity['address'];\n};\n\nexport type GetSocketWithdrawFeesResult = {\n fees: number;\n};\n\n// --- Margin Account Balance ---\nexport enum MarginAccountBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\nexport type GetMarginAccountBalanceChartDataResult = {\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n balance: number;\n balanceChangePercentage: number;\n};\n\n// --- Margin Account Collaterals Balance ---\nexport enum MarginAccountCollateralsBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\nexport type GetMarginAccountCollateralsBalanceChartDataResult = {\n data: {\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n token: string;\n }[];\n balance: number;\n balanceChangePercentage: number;\n};\n\nexport type OwnerMetadataEntity = {\n address: Address;\n coreSigNonce: number;\n poolSigNonce: number;\n};\n\nexport type GetAllMarginAccountsBalanceChartDataResult = {\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n balance: number;\n balanceChangePercentage: number;\n};\n\nexport enum AllMarginAccountsBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\n// --- Funding Rate History ----\nexport enum FundingRateHistoryGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\nexport type GetFundingRateChartDataResult = {\n fundingRateData: {\n timestampInMs: number;\n value: number;\n }[];\n fundingRate: number;\n};\nexport type GetCurrentFundingRateResult = {\n value: number;\n timestamp: number;\n};\n\nexport type GetInstantPoolPriceResult = {\n poolPrice: number;\n poolSlippage: number;\n oraclePrice: number;\n};\n\nexport type GetBalancesForBridgeArgs = {\n walletAddress: string;\n};\n\nexport type DepthSimulationState = {\n spotPrice: number;\n depthFactor: number;\n maxOrderSizeLong: number;\n maxOrderSizeShort: number;\n netExposure: number;\n};\n\nexport type GetLpPoolDepthChartSimulationDataResult = DepthSimulationState;\n\nexport type SignatureData = {\n signature: string;\n timestamp: number;\n walletAddress: Address;\n version: string;\n};\n\nexport type SaveSignatureResult = {\n signatureSavedSuccessfully: boolean;\n};\n\n// --- Community ----\nexport type VoteDetailsEntity = {\n id: number;\n startDate: number; // timestamp in UTC milliseconds\n endDate: number; // timestamp in UTC milliseconds\n percentageToPass: number; // Example: 4%\n yesCount: number;\n noCount: number;\n voteCountToPass: number; // Example: 1453\n slug: string;\n title: string;\n // Free text, each newline represents paragraph. UI splits by \\n atm to keep stuff simple\n description: string;\n};\n\nexport type VoteContractDetailsEntity = {\n id: number;\n contractAddress: Address;\n};\n\nexport type VoteStatusEntity = {\n votingPower: number;\n hasVoted: boolean;\n};\n\nexport type GetLpTvlResult = {\n currentTVL: number;\n currentLiquidity: number;\n};\n\nexport type Rank = {\n rankNumber: number;\n rankLetter: string;\n rankName: string;\n};\n\nexport type RankTrading = {\n rankNumber: number;\n rankName: string;\n};\n\nexport type GetWalletReferralDetailsParams = {\n address: string;\n};\n\nexport type GetWalletReferralDetailsResult = {\n totalReferralsCount: number;\n totalReferralXP: number;\n tradingRebateFee: number;\n tradingXp: number;\n liquidityXp: number;\n isAffiliate: boolean;\n};\n\nexport type GetWalletReferralCodeParams = {\n address: string;\n};\n\nexport type GetWalletReferralCodeResult = {\n referralCode: string;\n};\n\nexport type TokenEntityWithMinValue = TokenEntity & {\n minDepositAmount: number;\n minWithdrawAmount: number;\n minTransferAmount: number;\n};\n\nexport type TokenInfo = {\n name: TokenName;\n address: Address;\n decimals: number;\n isRUSDUnderlying: boolean;\n minDepositAmount: number;\n minWithdrawAmount: number;\n minTransferAmount: number;\n whitelistedWalletOnly?: boolean;\n isElixirToken?: boolean;\n isLmToken?: boolean;\n isPoolToken?: boolean;\n isOFT?: boolean;\n};\n\nexport type GetReyaCheckerResult = {\n isEligibleForRcp: boolean;\n isEligibleForVltz: boolean;\n isEligibleForCommunity: boolean;\n};\n\nexport type TgeAllocatedAmount = {\n total: number;\n vltz: number;\n rcp: number;\n community: number;\n};\n\nexport type TrancheInfo = {\n trancheId: number;\n amount: number;\n deadlineMs: number;\n released: boolean;\n};\n\nexport type GetTgeClaimingInfoResult = {\n wallet: string;\n amount: TgeAllocatedAmount;\n hasClaimed?: boolean;\n hasLocked?: boolean;\n distributorContract?: string;\n merkleRoot?: string;\n tranches?: TrancheInfo[];\n};\n\nexport type TgeClaimTokensResult = {\n success: boolean;\n wallet: string;\n amount: TgeAllocatedAmount;\n transactionHash: string;\n};\n\n// --- TOS ----\n\nexport type TRMRiskAssessment = {\n accountExternalId: string;\n address: string;\n addressRiskIndicators: TMRRiskIndicator[];\n addressSubmitted: string;\n chain: string;\n entities: unknown[];\n trmAppUrl: string;\n};\n\nexport type TMRRiskIndicator = {\n category: string;\n categoryId: string;\n categoryRiskScoreLevel: number;\n categoryRiskScoreLevelLabel: string;\n incomingVolumeUsd: string;\n outgoingVolumeUsd: string;\n riskType: string;\n totalVolumeUsd: string;\n};\n\n// todo: deprecate after 1st tac client is deprecated\nexport type ToSVersionDetails = {\n text: string;\n version: string;\n creationTimestamp: number; // in MS\n};\n\nexport type ToSProductVersionDetails = {\n shortText: string;\n longText: string;\n version: string;\n creationTimestamp: number; // in MS\n product: string;\n};\n\nexport type SocketBridgeTransactionPoolStatus =\n | 'pending'\n | 'confirmed'\n | 'failed';\n\nexport type IpInfo = {\n ip: string;\n hostname: string;\n city: string;\n region: string;\n country: string;\n loc: string;\n org: string;\n postal: string;\n timezone: string;\n privacy: {\n vpn: boolean;\n proxy: boolean;\n tor: boolean;\n relay: boolean;\n hosting: boolean;\n service: string;\n };\n countryCode: string;\n countryFlag: {\n emoji: string;\n unicode: string;\n };\n countryFlagURL: string;\n countryCurrency: {\n code: string;\n symbol: string;\n };\n continent: {\n code: string;\n name: string;\n };\n isEU: boolean;\n};\n\nexport interface CandleMessage {\n /** Stringified JSON object of all events to be streamed. */\n contents: string;\n /** Clob pair id of the Candle message. */\n\n clobPairId: string;\n /** Resolution of the candle update. */\n\n resolution: string;\n /** Version of the websocket message. */\n\n version: string;\n}\n\nexport interface PriceMessage {\n contents: string;\n assetPairId: string;\n version: string;\n}\n\nexport interface FundingRateMessage {\n contents: string;\n assetPairId: string;\n version: string;\n}\n\nexport interface MarketsUpdateMessage {\n contents: string;\n version: string;\n id: string;\n}\n\nexport enum CandleResolution {\n ONE_MINUTE = '1MIN',\n FIVE_MINUTES = '5MINS',\n FIFTEEN_MINUTES = '15MINS',\n THIRTY_MINUTES = '30MINS',\n ONE_HOUR = '1HOUR',\n FOUR_HOURS = '4HOURS',\n ONE_DAY = '1DAY',\n}\n\nexport type TransactionExecutionMetadata = {\n accountName?: string;\n accountSource?: string;\n accountId?: number;\n marketId?: number;\n destinationType?: 'pool' | 'account';\n action?:\n | 'matchOrder'\n | 'closeOrder'\n | 'createAccount'\n | 'ioc-order-ui'\n | 'ioc-order-api-v2'\n | 'ioc-reduce-only-order-ui'\n | 'ioc-reduce-only-order-api-v2'\n | 'enable-api-wallet'\n | 'disable-api-wallet';\n tradeSource?: 'reya' | 'rage' | 'other';\n sender?: string;\n clientSentTimestamp?: number; // Timestamp (ms) when client sent the request\n clientTimezone?: string; // Client's timezone (e.g., 'America/New_York', 'Europe/London')\n matchOrder?: {\n eip712Payload: CoreCommandsEIP712SignatureAndPayload['payload'];\n userEIP712Signature: EIP712Signature;\n };\n};\n\nexport type TransactionExecutionOutput = {\n txHash: string | null;\n txSubmitted?: boolean;\n errorMessage?: string;\n accountId?: string | null;\n coreSigNonce?: string | null;\n poolSigNonce?: string | null;\n miscellaneous?: {\n tradeXpBoost?: number;\n lotteryXpBoost?: number;\n xpNftAwarded?: boolean;\n xpEarned?: number;\n };\n tradeDetails?: {\n executionPrice?: number;\n base?: number;\n };\n positions?: {\n market_id: string;\n account_id: string;\n base: string | null;\n realized_pnl: string | null;\n last_price: string | null;\n position_data_last_price_data_timestamp: string | null;\n funding_value: string | null;\n base_multiplier: string | null;\n adl_unwind_price: string | null;\n transaction_hash: string;\n block_timestamp: string | null;\n block_number: string;\n unique_id: string | null;\n }[];\n orders?: {\n id: string;\n market_id: string | null;\n account_id: string | null;\n order_base: string | null;\n fee: string | null;\n price: string | null;\n type: string;\n processed: boolean;\n transaction_hash: string;\n block_timestamp: string | null;\n block_number: string;\n source: string | null;\n unique_id: string | null;\n }[];\n accounts?: Omit<\n Stringified<TradingApiSource['wallet/:address/accounts']['response'][0]>,\n 'status'\n >[];\n //orderAndPositionUpdate?: Stringified<PassivePerpOrderAndPositionUpdate>[];\n};\n\nexport type CanonicalReleaseStatus = 'pending' | 'ready' | 'completed';\n\ntype PendingWithdrawalStatus = {\n status: 'pending';\n};\n\ntype ReadyWithdrawalStatus = {\n status: 'ready';\n txHash: string;\n};\n\nexport type PendingWithdrawal = {\n tokenAmount: number;\n} & (PendingWithdrawalStatus | ReadyWithdrawalStatus);\n\nexport enum OrdersGatewayOrderType {\n STOP_LOSS = 0,\n TAKE_PROFIT = 1,\n LIMIT_ORDER = 2,\n MARKET_ORDER = 3,\n REDUCE_ONLY_MARKET_ORDER = 4,\n FULL_CLOSE_ORDER = 5,\n LIMIT_ORDER_SPOT = 6,\n}\n\nexport enum ConditionalOrderType {\n STOP_LOSS = 0,\n TAKE_PROFIT = 1,\n LIMIT_ORDER = 2,\n}\n\nexport type ConditionalOrderTypeName =\n | 'Stop Loss'\n | 'Take Profit'\n | 'Limit Order';\n\nexport enum ConditionalOrderStatus {\n PENDING = 'pending',\n FILLED = 'filled',\n CANCELLED = 'cancelled',\n REJECTED = 'rejected',\n}\n\nexport enum TierType {\n REGULAR = 'REGULAR',\n VIP = 'VIP',\n}\n\nexport type ConditionalOrder = {\n orderId: string;\n accountId: number;\n marketId: number;\n orderType: ConditionalOrderTypeName;\n isLong: boolean;\n triggerPrice: number;\n signerWallet: string;\n nonce: string;\n signature: string;\n eip712Signature: EIP712Signature;\n status: ConditionalOrderStatus;\n creationTimestampMs: number;\n lastUpdateTimestampMs: number;\n base: number;\n exchangeId: number;\n inputs: string;\n counterpartyAccountId: number;\n};\n\nexport type UnifiedConditionalOrderType = {\n orderId: string;\n accountId: number;\n marketId: number;\n base: number | null; // null when order is cancelled\n isLong: boolean;\n price: number;\n status: ConditionalOrderStatus;\n orderType: ConditionalOrderTypeName;\n timestampMs: number;\n};\n\nexport type IsDiscordLinkedParams = {\n address: string;\n};\nexport type IsDiscordLinkedResult = {\n isLinked: boolean;\n};\nexport type LinkDiscordParams = {\n discordAccessToken: string;\n signer: Signer | JsonRpcSigner;\n};\nexport type LinkDiscordResult = void;\nexport type UnlinkDiscordParams = {\n address: string;\n discordAccessToken: string;\n};\nexport type UnlinkDiscordResult = void;\nexport type ClaimDiscordRankParams = {\n address: string;\n discordAccessToken: string;\n};\nexport type ClaimDiscordRankResult = void;\n\nexport type IsDiscordRankClaimedParams = {\n address: string;\n};\nexport type IsDiscordRankClaimedResult = {\n isClaimed: boolean;\n};\n\nexport interface ApiErrorResponse {\n response: {\n status: number;\n data: {\n error: string;\n };\n };\n}\n\n// ref: https://github.com/tkhq/sdk/blob/08e2b8c30848498ed0850aa1e1ede67775b001e5/packages/http/src/__generated__/\n// services/coordinator/public/v1/public_api.types.ts\nexport type V1Attestation = {\n /** @description The cbor encoded then base64 url encoded id of the credential. */\n credentialId: string;\n /** @description A base64 url encoded payload containing metadata about the signing context and the challenge. */\n clientDataJson: string;\n /** @description A base64 url encoded payload containing authenticator data and any attestation the webauthn provider chooses. */\n attestationObject: string;\n /** @description The type of authenticator transports. */\n transports: V1AuthenticatorTransport[];\n};\n\nexport type V1AuthenticatorTransport =\n | 'AUTHENTICATOR_TRANSPORT_BLE'\n | 'AUTHENTICATOR_TRANSPORT_INTERNAL'\n | 'AUTHENTICATOR_TRANSPORT_NFC'\n | 'AUTHENTICATOR_TRANSPORT_USB'\n | 'AUTHENTICATOR_TRANSPORT_HYBRID';\n\n// on-chain events (consider pushing into a separate file)\nexport type PositionDataUpdatedDetails = {\n marketId: string;\n accountId: string;\n // todo: p1: argument names don't align with the on-chain event\n orderBase: string;\n realisedPnl: string;\n lastPrice: string;\n lastPriceTimestamp: string;\n fundingValue: string;\n baseMultiplier: string;\n adlUnwindPrice: string;\n blockTimestamp: string;\n transactionHash: string;\n blockNumber: number;\n uniqueId: string;\n};\n\nexport type MatchOrderDetails = {\n uniqueId: string;\n transactionHash: string;\n accountId: number;\n marketId: number;\n sizeNotional: number;\n base: number;\n price: number;\n};\n\nexport type GetLpPoolPositionRPCResponse = {\n poolPositionShareBalance: number; // amount of srUSD in the pool held by the account\n poolPositionBalance: number; // amount of rUSD in the pool held by the account\n poolTotalBalance: number; // total amount of rUSD in the pool\n sharePrice: number; // share price of the pool\n};\n\ninterface MatchOrderFees {\n protocolFeeCredit: bigint;\n exchangeFeeCredit: bigint;\n takerFeeDebit: bigint;\n makerPayments: bigint[];\n referrerFeeCredit: bigint;\n}\n\ninterface PositionDataOld {\n base: bigint;\n realizedPnL: bigint;\n lastPriceData: {\n price: bigint;\n timestamp: bigint;\n };\n trackers: {\n fundingValue: bigint;\n baseMultiplier: bigint;\n adlUnwindPrice: bigint;\n };\n}\n\nexport interface PassivePerpOrderAndPositionUpdate {\n id: string;\n marketId: bigint;\n accountId: bigint;\n counterpartyAccountId: bigint;\n executedBase: bigint;\n matchOrderFees: MatchOrderFees;\n executedPrice: bigint;\n referrerAccountId: bigint;\n isMatchOrder: boolean;\n liquidationType: bigint;\n positionData: PositionDataOld;\n counterpartyPositionData: PositionDataOld;\n blockTimestamp: bigint;\n blockNumber: string;\n transactionHash: string;\n uniqueId: bigint;\n}\n\nexport type AssetPair =\n | 'ETHUSD'\n | 'WSTETHUSD'\n | 'WBTCUSD'\n | 'USDCUSD'\n | 'USDEUSD'\n | 'SUSDEUSD'\n | 'DEUSDUSD'\n | 'SDEUSDDEUSD'\n | 'REYALM#SELINIUSDC'\n | 'REYALM#AMBERUSDC'\n | 'REYALM#HEDGEUSDC'\n | 'SRUSDRUSD_RR'\n | 'REYAPOOL#1'\n | 'REYARUSD'\n | 'SREYARUSD'\n | 'ETHUSDMARK'\n | 'BTCUSDMARK'\n | 'SOLUSDMARK'\n | 'ARBUSDMARK'\n | 'OPUSDMARK'\n | 'AVAXUSDMARK'\n | 'MKRUSDMARK'\n | 'LINKUSDMARK'\n | 'AAVEUSDMARK'\n | 'CRVUSDMARK'\n | 'UNIUSDMARK'\n | 'SUIUSDMARK'\n | 'TIAUSDMARK'\n | 'SEIUSDMARK'\n | 'ZROUSDMARK'\n | 'XRPUSDMARK'\n | 'WIFUSDMARK'\n | '1000PEPEUSDMARK'\n | 'POPCATUSDMARK'\n | 'DOGEUSDMARK'\n | '1000SHIBUSDMARK'\n | '1000BONKUSDMARK'\n | 'APTUSDMARK'\n | 'BNBUSDMARK'\n | 'JTOUSDMARK'\n | 'ADAUSDMARK'\n | 'LDOUSDMARK'\n | 'POLUSDMARK'\n | 'NEARUSDMARK'\n | 'FTMUSD'\n | 'ENAUSDMARK'\n | 'EIGENUSDMARK'\n | 'PENDLEUSDMARK'\n | 'GOATUSDMARK'\n | 'GRASSUSDMARK'\n | '1000NEIROUSDMARK'\n | 'DOTUSDMARK'\n | 'LTCUSDMARK'\n | 'PYTHUSDMARK'\n | 'JUPUSDMARK'\n | 'PENGUUSDMARK'\n | 'TRUMPUSDMARK'\n | 'HYPEUSDMARK'\n | 'VIRTUALUSDMARK'\n | 'AI16ZUSDMARK'\n | 'AIXBTUSDMARK'\n | 'SUSDMARK'\n | 'FARTCOINUSDMARK'\n | 'GRIFFAINUSDMARK'\n | 'WLDUSDMARK'\n | 'ATOMUSDMARK'\n | 'APEUSDMARK'\n | 'TONUSDMARK'\n | 'ONDOUSDMARK'\n | 'TRXUSDMARK'\n | 'INJUSDMARK'\n | 'MOVEUSDMARK'\n | 'BERAUSDMARK'\n | 'LAYERUSDMARK'\n | 'TAOUSDMARK'\n | 'IPUSDMARK'\n | 'MEUSDMARK'\n | 'PUMPUSDMARK'\n | 'MORPHOUSDMARK'\n | 'SYRUPUSDMARK'\n | 'AEROUSDMARK'\n | 'KAITOUSDMARK'\n | 'ZORAUSDMARK'\n | 'PROVEUSDMARK'\n | 'PAXGUSDMARK'\n | 'YZYUSDMARK'\n | 'XPLUSDMARK'\n | 'WLFIUSDMARK'\n | 'LINEAUSDMARK'\n | 'MEGAUSDMARK';\n\nexport type ContractId = string;\n\nexport type Price = {\n symbol: number;\n oraclePrice: string;\n poolPrice: string | null;\n updatedAt: number;\n};\n\nexport type MarketPrice = {\n marketId: number;\n price: string;\n oraclePrice: string;\n poolPrice: string;\n updatedAt: number;\n};\n\nexport type CollateralPrice = {\n address: string;\n oraclePrice: string;\n updatedAt: number;\n};\n\nexport const isMarketPrice = (\n price: MarketPrice | CollateralPrice,\n): price is MarketPrice =>\n Object.prototype.hasOwnProperty.call(price, 'marketId');\n\n// Replication-derived types\ntype Unpacked<T> = T extends (infer U)[] ? U : T;\n\nexport type ConditionalOrderSensitive = Unpacked<\n Replication['replication:ConditionalOrdersSensitive']['result']\n>;\n\nexport type Position = Unpacked<Replication['replication:position']['result']>;\n\n// Stringified replication data types for WebSocket transformers\nexport type PositionReplicationData = Stringified<\n Unpacked<Replication['replication:position']['result']>\n>;\n\nexport type OrderReplicationData = Stringified<\n Unpacked<Replication['replication:ConditionalOrdersSensitive']['result']>\n>;\n\nexport type PerpExecutionReplicationData = Stringified<\n Unpacked<Replication['replication:orders']['result']>\n>;\n\nexport type AccountRealBalanceReplicationData = Stringified<\n Unpacked<Replication['replication:account_real_balances']['result']>\n>;\n\nexport type SpotExecutionReplicationData = Stringified<\n Unpacked<Replication['replication:spot_executions']['result']>\n>;\n\nexport type SpotExecutionBustReplicationData = Stringified<\n Unpacked<Replication['replication:spot_execution_busts']['result']>\n>;\n\nexport type MarketDataReplicationData = Stringified<\n Unpacked<Replication['replication:marketData']['result']>\n>;\n\nexport type SpotMarketDataReplicationData = Stringified<\n Unpacked<Replication['replication:spotMarketData']['result']>\n>;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"/","sources":["types.ts"],"names":[],"mappings":";;;AAiDA,IAAY,WAIX;AAJD,WAAY,WAAW;IACrB,8DAAkB,CAAA;IAClB,2DAAiB,CAAA;IACjB,gEAAqB,CAAA;AACvB,CAAC,EAJW,WAAW,2BAAX,WAAW,QAItB;AAED,IAAY,iBAWX;AAXD,WAAY,iBAAiB;IAC3B,UAAU;IACV,+EAAmB,CAAA;IACnB,oEAAc,CAAA;IACd,+EAAoB,CAAA;IACpB,2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+CAAqB,CAAA;AACvB,CAAC,EALW,sBAAsB,sCAAtB,sBAAsB,QAKjC;AAED,IAAY,QAGX;AAHD,WAAY,QAAQ;IAClB,+BAAmB,CAAA;IACnB,uBAAW,CAAA;AACb,CAAC,EAHW,QAAQ,wBAAR,QAAQ,QAGnB;AA8SM,IAAM,aAAa,GAAG,UAC3B,KAAoC;IAEpC,OAAA,MAAM,CAAC,SAAS,CAAC,cAAc,CAAC,IAAI,CAAC,KAAK,EAAE,UAAU,CAAC;AAAvD,CAAuD,CAAC;AAH7C,QAAA,aAAa,iBAGgC","sourcesContent":["import { TradingApiSource, Replication } from './trading-api-types';\nimport { Stringified } from './api-types';\n\nimport {\n CoreCommandsEIP712SignatureAndPayload,\n EIP712Signature,\n} from './transactions';\nimport { JsonRpcSigner, Signer } from 'ethers';\n\nexport type Address = Lowercase<string>;\nexport type TokenName = Uppercase<string>;\n\n// -- Markets --\nexport type MarketOrderInfo = {\n counterpartyAccountIds: number[];\n exchangeId: number;\n};\n\nexport type MarketEntity = {\n id: number;\n ticker: string;\n underlyingAsset: string;\n quoteToken: string;\n quoteTokenId: string;\n markPrice: number;\n isActive: boolean;\n maxLeverage: number;\n volume24H: number;\n priceChange24H: number;\n priceChange24HPercentage: number;\n marketPriceDeviation: number;\n openInterest: number;\n fundingRate: number;\n fundingRateAnnualized: number;\n description: string;\n orderInfo: MarketOrderInfo;\n tickSizeDecimals: number;\n minOrderSize: number;\n minOrderSizeBase: number;\n baseSpacing: number;\n priceSpacing: number;\n longOI: number;\n shortOI: number;\n longSkewPercentage: number;\n shortSkewPercentage: number;\n availableLong: number;\n availableShort: number;\n};\n\nexport enum ReyaChainId {\n reyaNetwork = 1729,\n reyaLocal = 31337,\n reyaCronos = 89346162,\n}\n\nexport enum MoneyInOutChainId {\n // mainnet\n ethereumMainnet = 1,\n opMainnet = 10,\n polygonMainnet = 137,\n arbitrumOne = 42161,\n baseMainnet = 8453,\n // testnet\n arbitrumSepolia = 421614,\n opSepolia = 11155420,\n ethereumSepolia = 11155111,\n}\n\nexport enum CandlesResolution {\n ONE_MINUTE = '1MIN',\n FIVE_MINUTES = '5MINS',\n FIFTEEN_MINUTES = '15MINS',\n THIRTY_MINUTES = '30MINS',\n ONE_HOUR = '1HOUR',\n FOUR_HOURS = '4HOURS',\n ONE_DAY = '1DAY',\n}\n\n// -- Candles --\nexport interface Candle {\n id: string;\n startedAt: string;\n ticker: string;\n resolution: CandlesResolution;\n low: string;\n high: string;\n open: string;\n close: string;\n baseTokenVolume: string;\n usdVolume: string;\n trades: number;\n startingOpenInterest: string;\n}\n\n// -- Account --\n\nexport type Status = 'OPEN' | 'CLOSED' | 'LIQUIDATED' | 'FILLED';\nexport type Side = 'long' | 'short';\n\nexport type CollateralEntity = {\n token: string;\n address: string;\n percentage: number;\n balance: number;\n balanceRUSD: number;\n balanceWithHaircutRUSD: number;\n exchangeRate: number;\n exchangeRateWithHaircut: number;\n exchangeRateChange24HPercentage: number;\n yieldPercentage?: number;\n};\n\nexport type CollateralWithHaircut = {\n address: string;\n priceHaircut: number;\n};\n\nexport type MarginRatioHealth = 'danger' | 'healthy' | 'warning';\n\nexport type MarginAccountEntity = {\n id: number;\n name: string;\n marginRatioHealth: MarginRatioHealth;\n marginRatioPercentage: number;\n marginRatioHealthDangerThreshold: number;\n marginRatioHealthWarningThreshold: number;\n isApproachingLiquidation: boolean;\n isLiquidationImminent: boolean;\n totalBalance: number;\n liquidationMarginRequirement: number;\n totalBalanceUnderlyingAsset: string;\n totalBalanceChange24HPercentage: number;\n totalBalanceWithHaircut: number;\n livePnL: number;\n livePnLUnderlyingAsset: string;\n realizedPnL: number;\n realizedPnLUnderlyingAsset: string;\n realizedPnlHistoryTotal: number;\n totalPositionsCount: number;\n collaterals: CollateralEntity[];\n positions?: PositionEntity[];\n};\n\nexport type StrippedMarginAccountEntity = Pick<\n MarginAccountEntity,\n 'id' | 'name'\n>;\n\n// PRO-126 Bug 5: `ConditionalOrdersInfo` and the\n// `PositionEntity.conditionalOrdersInfo` field that surfaced\n// pending SL/TP info on positions were retired alongside the\n// `OrdersGateway.execute` / conditional-orders DB pipeline. The\n// off-chain API no longer has a backing source for live trigger\n// metadata; once the ME exposes pending trigger info via its own\n// surface, an equivalent field can be reintroduced sourcing from\n// there.\n\nexport type PositionEntity = {\n id: number;\n side: Side;\n size: number;\n base: number;\n price: number;\n markPrice: number;\n orderStatus: Status;\n realisedPnl: number;\n priceVariationPnl: number;\n livePnL: number;\n fundingPnl: number;\n unrealisedPnl: number;\n liquidationPrice: number;\n marketId: number;\n accountId: number;\n};\n\nexport type OrderHistoryType =\n | 'long-trade'\n | 'short-trade'\n | 'long-liquidation'\n | 'short-liquidation';\n\nexport type OrderHistoryEntity = {\n id: string;\n action: OrderHistoryType;\n orderType: 'market';\n base: number;\n executionPrice: number;\n realisedPnl?: number | null;\n priceVariationPnl: number;\n fundingPnl: number;\n fees: number;\n openingFees: number;\n timestamp: number;\n marketId?: number;\n xpEarned: number;\n};\n\nexport type ApyDetails = {\n dailyApy: number;\n weeklyApy: number;\n monthlyApy: number;\n yearlyApy: number;\n};\n\nexport type LpPoolEntity = {\n id: number;\n name: string;\n description: string;\n longDescription: string;\n readMoreLink: string;\n currentAPY: number;\n apyDetails: ApyDetails;\n apyChange24H: number;\n tokenAddress: Address;\n token: string;\n minDepositAmount: number;\n minWithdrawAmount: number;\n stepSize: number;\n allowedChainsForLiquidity: MoneyInOutChainId[];\n moneyInOutConfiguration: MoneyInOutConfiguration;\n};\n\nexport type MoneyInOutConfiguration = {\n [key in MoneyInOutChainId]?: {\n minWithdrawAmount?: number;\n };\n};\n\nexport type MoneyInOutConfigurationPerTokenName = {\n [key in TokenName]?: MoneyInOutConfiguration;\n};\n\nexport type LpWithdrawBalanceEntity = {\n withdrawableBalance: number;\n poolSharePrice: number;\n accountShareBalance: number;\n balanceBreakdown: {\n [coinName: string]: {\n balance: number;\n priceTokenToRusd: number;\n tokenAddress: string;\n };\n };\n};\n\nexport type TransactionHistoryType = 'deposit' | 'withdrawal';\n\nexport type LpTransactionHistoryEntity = {\n id: number;\n type: TransactionHistoryType;\n token: string;\n share: number;\n tokenAddress: string;\n amount: number;\n transactionLink: string;\n timestamp: number;\n};\n\nexport type TokenEntity = {\n name: TokenName;\n address: Address;\n};\n\n// --- Lp Pool Balance ---\nexport enum LpBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\n// - LP Account Performance -\nexport type GetLpPoolPerformanceChartDataResult = {\n capitalInvestedData: {\n timestampInMs: number;\n value: number;\n }[];\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n balance: number;\n balanceChangePercentage: number;\n capitalInvested: number;\n capitalInvestedChangePercentage: number;\n};\n\nexport type SocketTokenConnectors = {\n deposit: Address;\n withdraw: Address;\n};\n\nexport type GetSocketConnectorsParams = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n};\n\nexport type GetSocketVaultParams = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n};\n\nexport type GetMoneyInOutChainIdFromReyaConnectorParams = {\n reyaChainId: ReyaChainId;\n tokenName: TokenName;\n socketConnector: Address;\n};\n\nexport type GetSocketBridgeTimeParams = {\n moneyInOutChainId: MoneyInOutChainId;\n};\n\nexport type GetSocketBridgeTimeResult = {\n bridgeTimeInMS: number;\n};\n\nexport type GetSocketWithdrawMsgGasLimitParams = {\n moneyInOutChainId: MoneyInOutChainId;\n};\n\nexport type GetSocketWithdrawMsgGasLimitResult = {\n msgGasLimit: bigint;\n};\n\nexport type SocketDepositFeesEntry = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n fees: bigint;\n};\n\nexport type SocketWithdrawFeesEntry = {\n moneyInOutChainId: MoneyInOutChainId;\n tokenName: TokenName;\n fees: bigint;\n};\n\nexport type SocketDepositFees = {\n fees: bigint;\n feesInUnderlyingToken: number;\n underlyingTokenName: TokenName;\n};\n\nexport type SocketWithdrawFees = {\n fees: bigint;\n feesInUnderlyingToken: number;\n underlyingTokenName: TokenName;\n};\n\nexport type GetSocketWithdrawFeesParams = {\n reyaChainId: ReyaChainId;\n tokenAddress: TokenEntity['address'];\n};\n\nexport type GetSocketWithdrawFeesResult = {\n fees: number;\n};\n\n// --- Margin Account Balance ---\nexport enum MarginAccountBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\nexport type GetMarginAccountBalanceChartDataResult = {\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n balance: number;\n balanceChangePercentage: number;\n};\n\n// --- Margin Account Collaterals Balance ---\nexport enum MarginAccountCollateralsBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\nexport type GetMarginAccountCollateralsBalanceChartDataResult = {\n data: {\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n token: string;\n }[];\n balance: number;\n balanceChangePercentage: number;\n};\n\nexport type OwnerMetadataEntity = {\n address: Address;\n coreSigNonce: number;\n poolSigNonce: number;\n};\n\nexport type GetAllMarginAccountsBalanceChartDataResult = {\n balanceData: {\n timestampInMs: number;\n value: number;\n }[];\n balance: number;\n balanceChangePercentage: number;\n};\n\nexport enum AllMarginAccountsBalanceGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\n\n// --- Funding Rate History ----\nexport enum FundingRateHistoryGranularity {\n ONE_MINUTE = 60 * 1000,\n ONE_HOUR = 60 * 60 * 1000,\n ONE_DAY = 24 * 60 * 60 * 1000,\n ONE_WEEK = 7 * 24 * 60 * 60 * 1000,\n ONE_MONTH = 30 * 24 * 60 * 60 * 1000,\n ONE_YEAR = 365 * 24 * 60 * 60 * 1000,\n}\nexport type GetFundingRateChartDataResult = {\n fundingRateData: {\n timestampInMs: number;\n value: number;\n }[];\n fundingRate: number;\n};\nexport type GetCurrentFundingRateResult = {\n value: number;\n timestamp: number;\n};\n\nexport type GetInstantPoolPriceResult = {\n poolPrice: number;\n poolSlippage: number;\n oraclePrice: number;\n};\n\nexport type GetBalancesForBridgeArgs = {\n walletAddress: string;\n};\n\nexport type DepthSimulationState = {\n spotPrice: number;\n depthFactor: number;\n maxOrderSizeLong: number;\n maxOrderSizeShort: number;\n netExposure: number;\n};\n\nexport type GetLpPoolDepthChartSimulationDataResult = DepthSimulationState;\n\nexport type SignatureData = {\n signature: string;\n timestamp: number;\n walletAddress: Address;\n version: string;\n};\n\nexport type SaveSignatureResult = {\n signatureSavedSuccessfully: boolean;\n};\n\n// --- Community ----\nexport type VoteDetailsEntity = {\n id: number;\n startDate: number; // timestamp in UTC milliseconds\n endDate: number; // timestamp in UTC milliseconds\n percentageToPass: number; // Example: 4%\n yesCount: number;\n noCount: number;\n voteCountToPass: number; // Example: 1453\n slug: string;\n title: string;\n // Free text, each newline represents paragraph. UI splits by \\n atm to keep stuff simple\n description: string;\n};\n\nexport type VoteContractDetailsEntity = {\n id: number;\n contractAddress: Address;\n};\n\nexport type VoteStatusEntity = {\n votingPower: number;\n hasVoted: boolean;\n};\n\nexport type GetLpTvlResult = {\n currentTVL: number;\n currentLiquidity: number;\n};\n\nexport type Rank = {\n rankNumber: number;\n rankLetter: string;\n rankName: string;\n};\n\nexport type RankTrading = {\n rankNumber: number;\n rankName: string;\n};\n\nexport type GetWalletReferralDetailsParams = {\n address: string;\n};\n\nexport type GetWalletReferralDetailsResult = {\n totalReferralsCount: number;\n totalReferralXP: number;\n tradingRebateFee: number;\n tradingXp: number;\n liquidityXp: number;\n isAffiliate: boolean;\n};\n\nexport type GetWalletReferralCodeParams = {\n address: string;\n};\n\nexport type GetWalletReferralCodeResult = {\n referralCode: string;\n};\n\nexport type TokenEntityWithMinValue = TokenEntity & {\n minDepositAmount: number;\n minWithdrawAmount: number;\n minTransferAmount: number;\n};\n\nexport type TokenInfo = {\n name: TokenName;\n address: Address;\n decimals: number;\n isRUSDUnderlying: boolean;\n minDepositAmount: number;\n minWithdrawAmount: number;\n minTransferAmount: number;\n whitelistedWalletOnly?: boolean;\n isElixirToken?: boolean;\n isLmToken?: boolean;\n isPoolToken?: boolean;\n isOFT?: boolean;\n};\n\nexport type GetReyaCheckerResult = {\n isEligibleForRcp: boolean;\n isEligibleForVltz: boolean;\n isEligibleForCommunity: boolean;\n};\n\nexport type TgeAllocatedAmount = {\n total: number;\n vltz: number;\n rcp: number;\n community: number;\n};\n\nexport type TrancheInfo = {\n trancheId: number;\n amount: number;\n deadlineMs: number;\n released: boolean;\n};\n\nexport type GetTgeClaimingInfoResult = {\n wallet: string;\n amount: TgeAllocatedAmount;\n hasClaimed?: boolean;\n hasLocked?: boolean;\n distributorContract?: string;\n merkleRoot?: string;\n tranches?: TrancheInfo[];\n};\n\nexport type TgeClaimTokensResult = {\n success: boolean;\n wallet: string;\n amount: TgeAllocatedAmount;\n transactionHash: string;\n};\n\n// --- TOS ----\n\nexport type TRMRiskAssessment = {\n accountExternalId: string;\n address: string;\n addressRiskIndicators: TMRRiskIndicator[];\n addressSubmitted: string;\n chain: string;\n entities: unknown[];\n trmAppUrl: string;\n};\n\nexport type TMRRiskIndicator = {\n category: string;\n categoryId: string;\n categoryRiskScoreLevel: number;\n categoryRiskScoreLevelLabel: string;\n incomingVolumeUsd: string;\n outgoingVolumeUsd: string;\n riskType: string;\n totalVolumeUsd: string;\n};\n\n// todo: deprecate after 1st tac client is deprecated\nexport type ToSVersionDetails = {\n text: string;\n version: string;\n creationTimestamp: number; // in MS\n};\n\nexport type ToSProductVersionDetails = {\n shortText: string;\n longText: string;\n version: string;\n creationTimestamp: number; // in MS\n product: string;\n};\n\nexport type SocketBridgeTransactionPoolStatus =\n | 'pending'\n | 'confirmed'\n | 'failed';\n\nexport type IpInfo = {\n ip: string;\n hostname: string;\n city: string;\n region: string;\n country: string;\n loc: string;\n org: string;\n postal: string;\n timezone: string;\n privacy: {\n vpn: boolean;\n proxy: boolean;\n tor: boolean;\n relay: boolean;\n hosting: boolean;\n service: string;\n };\n countryCode: string;\n countryFlag: {\n emoji: string;\n unicode: string;\n };\n countryFlagURL: string;\n countryCurrency: {\n code: string;\n symbol: string;\n };\n continent: {\n code: string;\n name: string;\n };\n isEU: boolean;\n};\n\nexport interface CandleMessage {\n /** Stringified JSON object of all events to be streamed. */\n contents: string;\n /** Clob pair id of the Candle message. */\n\n clobPairId: string;\n /** Resolution of the candle update. */\n\n resolution: string;\n /** Version of the websocket message. */\n\n version: string;\n}\n\nexport interface PriceMessage {\n contents: string;\n assetPairId: string;\n version: string;\n}\n\nexport interface FundingRateMessage {\n contents: string;\n assetPairId: string;\n version: string;\n}\n\nexport interface MarketsUpdateMessage {\n contents: string;\n version: string;\n id: string;\n}\n\nexport enum CandleResolution {\n ONE_MINUTE = '1MIN',\n FIVE_MINUTES = '5MINS',\n FIFTEEN_MINUTES = '15MINS',\n THIRTY_MINUTES = '30MINS',\n ONE_HOUR = '1HOUR',\n FOUR_HOURS = '4HOURS',\n ONE_DAY = '1DAY',\n}\n\nexport type TransactionExecutionMetadata = {\n accountName?: string;\n accountSource?: string;\n accountId?: number;\n marketId?: number;\n destinationType?: 'pool' | 'account';\n action?:\n | 'matchOrder'\n | 'closeOrder'\n | 'createAccount'\n | 'ioc-order-ui'\n | 'ioc-order-api-v2'\n | 'ioc-reduce-only-order-ui'\n | 'ioc-reduce-only-order-api-v2'\n | 'enable-api-wallet'\n | 'disable-api-wallet';\n tradeSource?: 'reya' | 'rage' | 'other';\n sender?: string;\n clientSentTimestamp?: number; // Timestamp (ms) when client sent the request\n clientTimezone?: string; // Client's timezone (e.g., 'America/New_York', 'Europe/London')\n matchOrder?: {\n eip712Payload: CoreCommandsEIP712SignatureAndPayload['payload'];\n userEIP712Signature: EIP712Signature;\n };\n};\n\nexport type TransactionExecutionOutput = {\n txHash: string | null;\n txSubmitted?: boolean;\n errorMessage?: string;\n /**\n * Structured error discriminator surfaced by the slim\n * `executeReyaTransaction` core. One of\n * `TRANSACTION_FAILED_TO_SEND` (pre-send: wallet manager rejected),\n * `RECEIPT_NOT_FOUND` (post-send: receipt fetch failed),\n * `TRANSACTION_REVERTED` (post-send: receipt.status === 0), or\n * `FAILED_FILL` (post-send: FailedUnifiedFillBytes / FailedFillBytes).\n * Optional — populated when the slim core returned a discriminated\n * failure. May coexist with a non-null `txHash` on post-send failures\n * (the on-chain hash is surfaced for `RECEIPT_NOT_FOUND`,\n * `TRANSACTION_REVERTED`, and `FAILED_FILL`). UI consumers should prefer\n * `errorMessage` for display; this field is for analytics + logs.\n *\n * `FAILED_ORDER` (used to be: FailedOrderBytes) is retired alongside\n * the legacy `OrdersGateway.execute` IOC handler in PRO-126 Bug 5.\n */\n errorCode?: string;\n accountId?: string | null;\n coreSigNonce?: string | null;\n poolSigNonce?: string | null;\n miscellaneous?: {\n tradeXpBoost?: number;\n lotteryXpBoost?: number;\n xpNftAwarded?: boolean;\n xpEarned?: number;\n };\n tradeDetails?: {\n executionPrice?: number;\n base?: number;\n };\n positions?: {\n market_id: string;\n account_id: string;\n base: string | null;\n realized_pnl: string | null;\n last_price: string | null;\n position_data_last_price_data_timestamp: string | null;\n funding_value: string | null;\n base_multiplier: string | null;\n adl_unwind_price: string | null;\n transaction_hash: string;\n block_timestamp: string | null;\n block_number: string;\n unique_id: string | null;\n }[];\n orders?: {\n id: string;\n market_id: string | null;\n account_id: string | null;\n order_base: string | null;\n fee: string | null;\n price: string | null;\n type: string;\n processed: boolean;\n transaction_hash: string;\n block_timestamp: string | null;\n block_number: string;\n source: string | null;\n unique_id: string | null;\n }[];\n accounts?: Omit<\n Stringified<TradingApiSource['wallet/:address/accounts']['response'][0]>,\n 'status'\n >[];\n //orderAndPositionUpdate?: Stringified<PassivePerpOrderAndPositionUpdate>[];\n};\n\nexport type CanonicalReleaseStatus = 'pending' | 'ready' | 'completed';\n\ntype PendingWithdrawalStatus = {\n status: 'pending';\n};\n\ntype ReadyWithdrawalStatus = {\n status: 'ready';\n txHash: string;\n};\n\nexport type PendingWithdrawal = {\n tokenAmount: number;\n} & (PendingWithdrawalStatus | ReadyWithdrawalStatus);\n\n// PRO-126 Bug 5 retired the legacy `OrdersGatewayOrderType` enum (the\n// 8-field `ConditionalOrderDetails` typehash discriminator). The\n// on-chain `OrdersGateway.execute` selector that consumed those values\n// is gone; every order class now uses `OrderType` below, whose values\n// mirror the on-chain `OrderType` enum in\n// orders-gateway/src/libraries/DataTypes.sol.\nexport enum OrderType {\n Limit = 0,\n StopLoss = 1,\n TakeProfit = 2,\n}\n\n// Matches the on-chain `MarketType` enum. Used to discriminate spot vs perp\n// in unified off-chain code paths and with the market-id namespace helpers in\n// packages/common-backend/src/market-id-namespace.\nexport enum MarketType {\n Spot = 0,\n Perp = 1,\n}\n\n// Canonical on-chain V3 codes, also written by the pre-cutover V2 indexer.\nexport { CanonicalExecutionType as ExecutionType } from './canonical-execution-type';\n\nexport enum ConditionalOrderType {\n STOP_LOSS = 0,\n TAKE_PROFIT = 1,\n LIMIT_ORDER = 2,\n}\n\nexport type ConditionalOrderTypeName =\n | 'Stop Loss'\n | 'Take Profit'\n | 'Limit Order';\n\nexport enum ConditionalOrderStatus {\n PENDING = 'pending',\n FILLED = 'filled',\n CANCELLED = 'cancelled',\n REJECTED = 'rejected',\n}\n\nexport enum TierType {\n REGULAR = 'REGULAR',\n VIP = 'VIP',\n}\n\nexport type ConditionalOrder = {\n orderId: string;\n accountId: number;\n marketId: number;\n orderType: ConditionalOrderTypeName;\n isLong: boolean;\n triggerPrice: number;\n signerWallet: string;\n nonce: string;\n signature: string;\n eip712Signature: EIP712Signature;\n status: ConditionalOrderStatus;\n creationTimestampMs: number;\n lastUpdateTimestampMs: number;\n base: number;\n exchangeId: number;\n inputs: string;\n counterpartyAccountId: number;\n};\n\nexport type UnifiedConditionalOrderType = {\n orderId: string;\n accountId: number;\n marketId: number;\n base: number | null; // null when order is cancelled\n isLong: boolean;\n price: number;\n status: ConditionalOrderStatus;\n orderType: ConditionalOrderTypeName;\n timestampMs: number;\n};\n\nexport type IsDiscordLinkedParams = {\n address: string;\n};\nexport type IsDiscordLinkedResult = {\n isLinked: boolean;\n};\nexport type LinkDiscordParams = {\n discordAccessToken: string;\n signer: Signer | JsonRpcSigner;\n};\nexport type LinkDiscordResult = void;\nexport type UnlinkDiscordParams = {\n address: string;\n discordAccessToken: string;\n};\nexport type UnlinkDiscordResult = void;\nexport type ClaimDiscordRankParams = {\n address: string;\n discordAccessToken: string;\n};\nexport type ClaimDiscordRankResult = void;\n\nexport type IsDiscordRankClaimedParams = {\n address: string;\n};\nexport type IsDiscordRankClaimedResult = {\n isClaimed: boolean;\n};\n\nexport interface ApiErrorResponse {\n response: {\n status: number;\n data: {\n error: string;\n };\n };\n}\n\n// ref: https://github.com/tkhq/sdk/blob/08e2b8c30848498ed0850aa1e1ede67775b001e5/packages/http/src/__generated__/\n// services/coordinator/public/v1/public_api.types.ts\nexport type V1Attestation = {\n /** @description The cbor encoded then base64 url encoded id of the credential. */\n credentialId: string;\n /** @description A base64 url encoded payload containing metadata about the signing context and the challenge. */\n clientDataJson: string;\n /** @description A base64 url encoded payload containing authenticator data and any attestation the webauthn provider chooses. */\n attestationObject: string;\n /** @description The type of authenticator transports. */\n transports: V1AuthenticatorTransport[];\n};\n\nexport type V1AuthenticatorTransport =\n | 'AUTHENTICATOR_TRANSPORT_BLE'\n | 'AUTHENTICATOR_TRANSPORT_INTERNAL'\n | 'AUTHENTICATOR_TRANSPORT_NFC'\n | 'AUTHENTICATOR_TRANSPORT_USB'\n | 'AUTHENTICATOR_TRANSPORT_HYBRID';\n\n// on-chain events (consider pushing into a separate file)\nexport type MatchOrderDetails = {\n uniqueId: string;\n transactionHash: string;\n accountId: number;\n marketId: number;\n sizeNotional: number;\n base: number;\n price: number;\n};\n\nexport type GetLpPoolPositionRPCResponse = {\n poolPositionShareBalance: number; // amount of srUSD in the pool held by the account\n poolPositionBalance: number; // amount of rUSD in the pool held by the account\n poolTotalBalance: number; // total amount of rUSD in the pool\n sharePrice: number; // share price of the pool\n};\n\ninterface MatchOrderFees {\n protocolFeeCredit: bigint;\n exchangeFeeCredit: bigint;\n takerFeeDebit: bigint;\n makerPayments: bigint[];\n referrerFeeCredit: bigint;\n}\n\ninterface PositionDataOld {\n base: bigint;\n realizedPnL: bigint;\n lastPriceData: {\n price: bigint;\n timestamp: bigint;\n };\n trackers: {\n fundingValue: bigint;\n baseMultiplier: bigint;\n adlUnwindPrice: bigint;\n };\n}\n\nexport interface PassivePerpOrderAndPositionUpdate {\n id: string;\n marketId: bigint;\n accountId: bigint;\n counterpartyAccountId: bigint;\n executedBase: bigint;\n matchOrderFees: MatchOrderFees;\n executedPrice: bigint;\n referrerAccountId: bigint;\n isMatchOrder: boolean;\n liquidationType: bigint;\n positionData: PositionDataOld;\n counterpartyPositionData: PositionDataOld;\n blockTimestamp: bigint;\n blockNumber: string;\n transactionHash: string;\n uniqueId: bigint;\n}\n\nexport type ConfiguredAssetPair =\n | 'ETHUSD'\n | 'WSTETHUSD'\n | 'WBTCUSD'\n | 'BTCUSD' // Localnet's mock BTC collateral feed\n | 'USDCUSD'\n | 'USDEUSD'\n | 'SUSDEUSD'\n | 'DEUSDUSD'\n | 'SDEUSDDEUSD'\n | 'REYALM#SELINIUSDC'\n | 'REYALM#AMBERUSDC'\n | 'REYALM#HEDGEUSDC'\n | 'SRUSDRUSD_RR'\n | 'REYAPOOL#1'\n | 'REYARUSD'\n | 'SREYARUSD'\n | 'ETHUSDMARK'\n | 'BTCUSDMARK'\n | 'SOLUSDMARK'\n | 'ARBUSDMARK'\n | 'OPUSDMARK'\n | 'AVAXUSDMARK'\n | 'MKRUSDMARK'\n | 'LINKUSDMARK'\n | 'AAVEUSDMARK'\n | 'CRVUSDMARK'\n | 'UNIUSDMARK'\n | 'SUIUSDMARK'\n | 'TIAUSDMARK'\n | 'SEIUSDMARK'\n | 'ZROUSDMARK'\n | 'XRPUSDMARK'\n | 'WIFUSDMARK'\n | '1000PEPEUSDMARK'\n | 'POPCATUSDMARK'\n | 'DOGEUSDMARK'\n | '1000SHIBUSDMARK'\n | '1000BONKUSDMARK'\n | 'APTUSDMARK'\n | 'BNBUSDMARK'\n | 'JTOUSDMARK'\n | 'ADAUSDMARK'\n | 'LDOUSDMARK'\n | 'POLUSDMARK'\n | 'NEARUSDMARK'\n | 'FTMUSD'\n | 'ENAUSDMARK'\n | 'EIGENUSDMARK'\n | 'PENDLEUSDMARK'\n | 'GOATUSDMARK'\n | 'GRASSUSDMARK'\n | '1000NEIROUSDMARK'\n | 'DOTUSDMARK'\n | 'LTCUSDMARK'\n | 'PYTHUSDMARK'\n | 'JUPUSDMARK'\n | 'PENGUUSDMARK'\n | 'TRUMPUSDMARK'\n | 'HYPEUSDMARK'\n | 'VIRTUALUSDMARK'\n | 'AI16ZUSDMARK'\n | 'AIXBTUSDMARK'\n | 'SUSDMARK'\n | 'FARTCOINUSDMARK'\n | 'GRIFFAINUSDMARK'\n | 'WLDUSDMARK'\n | 'ATOMUSDMARK'\n | 'APEUSDMARK'\n | 'TONUSDMARK'\n | 'ONDOUSDMARK'\n | 'TRXUSDMARK'\n | 'INJUSDMARK'\n | 'MOVEUSDMARK'\n | 'BERAUSDMARK'\n | 'LAYERUSDMARK'\n | 'TAOUSDMARK'\n | 'IPUSDMARK'\n | 'MEUSDMARK'\n | 'PUMPUSDMARK'\n | 'MORPHOUSDMARK'\n | 'SYRUPUSDMARK'\n | 'AEROUSDMARK'\n | 'KAITOUSDMARK'\n | 'ZORAUSDMARK'\n | 'PROVEUSDMARK'\n | 'PAXGUSDMARK'\n | 'YZYUSDMARK'\n | 'XPLUSDMARK'\n | 'WLFIUSDMARK'\n | 'LINEAUSDMARK'\n | 'MEGAUSDMARK';\n\ntype SpotPair<T extends string> = T extends `${infer Base}USDMARK`\n ? `${Base}USD`\n : never;\n\n/** Internal cache keys whose prices mirror an existing reference feed. */\nexport type MirroredAssetPair = 'REYALM#KEYROCKRUSD' | 'REYALM#FLOWRUSD';\n\n/** Includes Stork spot feeds and mirrored price cache keys. */\nexport type AssetPair =\n | ConfiguredAssetPair\n | SpotPair<ConfiguredAssetPair>\n | MirroredAssetPair;\n\nexport type ContractId = string;\n\nexport type Price = {\n symbol: number;\n oraclePrice: string;\n poolPrice: string | null;\n updatedAt: number;\n};\n\nexport type MarketPrice = {\n marketId: number;\n /** @deprecated No longer written; will be removed when V1 prices endpoints are dropped. */\n price?: string;\n /**\n * ME mark price (E18), despite the name — the pool-price task has written the\n * matching-engine mark here since the perpOB rewire. Surfaced as the v2\n * `MarketSummary.markPrice`. The genuine index price is `indexPrice`.\n */\n oraclePrice: string;\n /**\n * Orderbook mid (E18). Absent on an empty or one-sided book — there is\n * deliberately no mark-price fallback, because publishing the mark under the\n * name \"mid\" makes a book with no two-sided quote indistinguishable from one\n * trading exactly at the mark. Consumers must treat it as optional, the same\n * way `SpotMarketSummary.throttledMidPrice` has always been treated.\n */\n poolPrice?: string;\n /**\n * Stork spot `*USD` index price (E18), rUSD-quoted — divided by USDCUSD the\n * same way the collateral prices are, since Stork publishes it as X/USD and\n * every price this API serves is X/USDC. Absent when the feed has no fresh\n * tick, when the USDCUSD cross-rate is unavailable, and permanently on\n * markets with no Stork feed, so consumers must treat it as optional rather\n * than substituting a stale value.\n */\n indexPrice?: string;\n updatedAt: number;\n};\n\nexport type CollateralPrice = {\n address: string;\n oraclePrice: string;\n updatedAt: number;\n};\n\nexport const isMarketPrice = (\n price: MarketPrice | CollateralPrice,\n): price is MarketPrice =>\n Object.prototype.hasOwnProperty.call(price, 'marketId');\n\n// Replication-derived types\ntype Unpacked<T> = T extends (infer U)[] ? U : T;\n\n// PRO-126 Bug 7: `ConditionalOrderSensitive` + `OrderReplicationData`\n// retired with the rest of the `ConditionalOrders` DB pipeline. The\n// `replication:ConditionalOrdersSensitive` channel is no longer\n// subscribed (bun-socket/index.ts) and no longer publishes\n// (common-backend/src/config/database.ts). Order data flows through\n// the ME's `{orders}:changes` stream consumed by AccountOrdersMap;\n// callers should derive types from the ME's protobuf `Order` schema.\n\nexport type Position = Unpacked<Replication['replication:position']['result']>;\n\n// Stringified replication data types for WebSocket transformers\nexport type PositionReplicationData = Stringified<\n Unpacked<Replication['replication:position']['result']>\n>;\n\nexport type PerpExecutionReplicationData = Omit<\n Stringified<Unpacked<Replication['replication:orders']['result']>>,\n 'created_at'\n> & {\n created_at?: string;\n};\n\nexport type AccountRealBalanceReplicationData = Stringified<\n Unpacked<Replication['replication:account_real_balances']['result']>\n>;\n\nexport type SpotExecutionReplicationData = Stringified<\n Unpacked<Replication['replication:spot_executions']['result']>\n>;\n\nexport type ExecutionBustReplicationData = Stringified<\n Unpacked<Replication['replication:execution_busts']['result']>\n>;\n\nexport type MarketDataReplicationData = Stringified<\n Unpacked<Replication['replication:marketData']['result']>\n>;\n\nexport type SpotMarketDataReplicationData = Stringified<\n Unpacked<Replication['replication:spotMarketData']['result']>\n>;\n"]}
@@ -354,14 +354,17 @@ var calculateTotalMargin = function (_a) {
354
354
  var pnl = new Map();
355
355
  var rUSDPrice = (_b = (rUSDAddress && assetPrices.get(rUSDAddress))) !== null && _b !== void 0 ? _b : 1;
356
356
  positions.forEach(function (position) {
357
- var _a, _b;
357
+ var _a;
358
358
  var marketTracker = marketsTrackers === null || marketsTrackers === void 0 ? void 0 : marketsTrackers.get(position.marketId);
359
359
  var tokenInfo = marketsTokenInfo.get(position.marketId);
360
360
  if (!tokenInfo)
361
361
  return;
362
362
  var fundingCashFlow = 0;
363
363
  var adlCashFlow = 0;
364
- if (marketTracker) {
364
+ // Mirrors calculateSettledPositionPnl: a flat position accrues nothing, and
365
+ // a zero position multiplier (reopened after full ADL) cannot be divided by,
366
+ // so only realized and mark PnL count for it.
367
+ if (marketTracker && position.base !== 0 && position.baseMultiplier > 0) {
365
368
  // fundingCashFlow
366
369
  var marketTrackerFundingValue = position.base < 0
367
370
  ? marketTracker.shortFundingValue
@@ -382,19 +385,25 @@ var calculateTotalMargin = function (_a) {
382
385
  var initialPrice = lastPriceCoefficient * position.lastPrice;
383
386
  adlCashFlow = (adlUnwindPrice - initialPrice) * position.base;
384
387
  }
385
- var unrealizedPnl = (((_a = markPrices.get(tokenInfo.quoteTokenId)) !== null && _a !== void 0 ? _a : 0) - position.lastPrice) *
386
- position.base;
387
- pnl.set(tokenInfo.underlyingAssetId, ((_b = pnl.get(tokenInfo.underlyingAssetId)) !== null && _b !== void 0 ? _b : 0) +
388
+ // The underlying supplies the mark; all position cashflows are in the quote token.
389
+ // A missing mark means "no price for this bucket", not a price of zero:
390
+ // carry the position at its last price rather than swinging by its notional.
391
+ var markPrice = markPrices.get(tokenInfo.underlyingAssetId);
392
+ var unrealizedPnl = markPrice === undefined
393
+ ? 0
394
+ : (markPrice - position.lastPrice) * position.base;
395
+ pnl.set(tokenInfo.quoteTokenId, ((_a = pnl.get(tokenInfo.quoteTokenId)) !== null && _a !== void 0 ? _a : 0) +
388
396
  position.realizedPnl +
389
397
  fundingCashFlow +
390
398
  adlCashFlow +
391
399
  unrealizedPnl);
392
400
  });
393
- return Array.from(accountBalances.entries()).reduce(function (sum, _a) {
394
- var _b, _c;
395
- var address = _a[0], balance = _a[1];
401
+ // A quote-token PnL balance can exist without a collateral deposit row.
402
+ var assets = new Set(__spreadArray(__spreadArray([], Array.from(accountBalances.keys()), true), Array.from(pnl.keys()), true));
403
+ return Array.from(assets).reduce(function (sum, address) {
404
+ var _a, _b, _c;
396
405
  return sum +
397
- (balance + ((_b = pnl.get(address)) !== null && _b !== void 0 ? _b : 0)) *
406
+ (((_a = accountBalances.get(address)) !== null && _a !== void 0 ? _a : 0) + ((_b = pnl.get(address)) !== null && _b !== void 0 ? _b : 0)) *
398
407
  (address === rUSDAddress
399
408
  ? 1
400
409
  : ((_c = assetPrices.get(address)) !== null && _c !== void 0 ? _c : 0) / (rUSDPrice || 1));
@@ -1 +1 @@
1
- {"version":3,"file":"calculate.js","sourceRoot":"/","sources":["utils/calculate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,mCAAoC;AACpC,8DAAqC;AAExB,QAAA,QAAQ,GAAG,GAAG,CAAC;AAK5B;;;GAGG;AACI,IAAM,oBAAoB,GAAG,UAAC,EAwBpC;QAvBC,UAAU,gBAAA,EACV,aAAa,mBAAA,EACb,WAAW,iBAAA,EACX,OAAO,aAAA,EACP,KAAK,WAAA;IAoBL,IAAI,UAAU,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IAED,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjC,OAAO,CAAC,CAAC;IACX,CAAC;IAED,IAAM,eAAe,GAAG,aAAa,GAAG,UAAU,CAAC;IACnD,IAAM,aAAa,GAAG,eAAe,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAEhE,OAAO,IAAI,CAAC,GAAG,CAAC,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,OAAO,UAAU,GAAG,SAAS,CAAC;AAChC,CAAC,CAAC;AArBW,QAAA,2BAA2B,+BAqBtC;AAEK,IAAM,uBAAuB,GAAG,UAAC,EAcvC;QAbC,2BAA2B,iCAAA,EAC3B,2BAA2B,iCAAA,EAC3B,YAAY,kBAAA,EACZ,qBAAqB,2BAAA,EACrB,6BAA6B,mCAAA,EAC7B,6BAA6B,mCAAA;IAS7B,IAAM,qBAAqB,GAAG,2BAA2B;SACtD,KAAK,CAAC,6BAA6B,CAAC;SACpC,YAAY,CAAC,IAAI,CAAC;SAClB,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAEtC,IAAM,YAAY,GAAG,qBAAqB;SACvC,KAAK,CACJ,IAAA,sBAAS,EAAC,IAAI,CAAC,CAAC,KAAK,CACnB,2BAA2B;SACxB,YAAY,CAAC,IAAI,CAAC;SAClB,GAAG,CAAC,6BAA6B,CAAC,CACtC,CACF;SACA,GAAG,CAAC,IAAI,CAAC,CAAC;IAEb,IAAM,MAAM,GAAG,YAAY;SACxB,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;SAChD,GAAG,CAAC,IAAI,CAAC,CAAC;IAEb,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAnCW,QAAA,uBAAuB,2BAmClC","sourcesContent":["import { mergeMap } from './struct';\nimport BigNumber from 'bignumber.js';\n\nexport const POOL_IMR = 9.1;\n\ntype MarketId = string;\ntype Address = string;\n\n/**\n * Calculates the maximum amount that can be withdrawn in terms of the token\n * (e.g., if rUSD then in rUSD terms, if WETH then in WETH terms)\n */\nexport const calculateMaxWithdraw = ({\n currentIMR,\n marginBalance,\n realBalance,\n haircut,\n price,\n}: {\n /** Current Initial Margin Requirement of the account in rUSD terms */\n currentIMR: number;\n /** Current margin balance of the account (expected to already include haircuts) in rUSD terms */\n marginBalance: number;\n /**\n * Current real balance of the token the user wants to withdraw in token terms.\n * For rUSD: this equals net deposits (balanceDeprecated from v2 endpoints + realized PnL).\n * For all other tokens: this equals balanceDeprecated (since realized PnL is 0 for them).\n */\n realBalance: number;\n /**\n * Haircut parameter of the token.\n * Note: haircut for rUSD is always expected to be 0.\n */\n haircut: number;\n /** Price of the token in rUSD terms */\n price: number;\n}): number => {\n if (currentIMR < 0 || price < 0 || haircut < 0) {\n throw new Error('currentIMR, price, and haircut cannot be negative');\n }\n\n if (currentIMR === 0) {\n return realBalance;\n }\n\n if (haircut === 1 || price === 0) {\n return 0;\n }\n\n const availableMargin = marginBalance - currentIMR;\n const maxFromMargin = availableMargin / (price * (1 - haircut));\n\n return Math.max(0, Math.min(realBalance, maxFromMargin));\n};\n\nexport const calculateMaxExposure = ({\n poolBalance,\n riskFactor,\n poolIMR = POOL_IMR,\n}: {\n poolBalance: number;\n poolIMR?: number;\n riskFactor: number;\n}) => poolBalance / (poolIMR * Math.sqrt(riskFactor));\n\n/**\n * Splits a trade exposure into rebalancing and unbalancing portions relative to pool net exposure.\n * Rebalancing reduces pool's absolute exposure; unbalancing increases it.\n */\nexport const splitTradeExposure = (\n tradeExposure: number,\n poolNetExposure: number,\n): { rebalancing: number; unbalancing: number } => {\n if (tradeExposure === 0) {\n return { rebalancing: 0, unbalancing: 0 };\n }\n\n // If pool has no exposure, entire trade is unbalancing\n if (poolNetExposure === 0) {\n return { rebalancing: 0, unbalancing: tradeExposure };\n }\n\n // Opposite sign means trade increases pool exposure → pure unbalancing\n const sameSign =\n (poolNetExposure > 0 && tradeExposure > 0) ||\n (poolNetExposure < 0 && tradeExposure < 0);\n if (!sameSign) {\n return { rebalancing: 0, unbalancing: tradeExposure };\n }\n\n // Same sign: trade reduces pool exposure (pool takes opposite side)\n const absPool = Math.abs(poolNetExposure);\n const absTrade = Math.abs(tradeExposure);\n\n if (absTrade <= absPool) {\n // Pure rebalancing — trade doesn't cross zero\n return { rebalancing: tradeExposure, unbalancing: 0 };\n }\n\n // Mixed: rebalance up to pool exposure, then unbalance the rest\n const rebalancing = poolNetExposure;\n const unbalancing = tradeExposure - rebalancing;\n return { rebalancing, unbalancing };\n};\n\n/**\n * Computes the new log price multiplier (logF) after a trade, handling both\n * rebalancing and unbalancing portions.\n *\n * Mirrors on-chain logic in PriceMultiplier.sol:computeNewLogPriceMultiplier.\n */\nexport const computeNewLogF = ({\n currentLogF,\n tradeExposure,\n poolNetExposure,\n depthFactor,\n maxExposure,\n}: {\n currentLogF: number;\n tradeExposure: number;\n poolNetExposure: number;\n depthFactor: number;\n maxExposure: number;\n}): number => {\n if (tradeExposure === 0) return currentLogF;\n\n const { rebalancing, unbalancing } = splitTradeExposure(\n tradeExposure,\n poolNetExposure,\n );\n\n // Case 1: Has unbalancing portion (includes mixed trades)\n if (unbalancing !== 0) {\n // If also rebalancing, it brings logF to 0 by definition (trade crosses zero)\n const startLogF = rebalancing === 0 ? currentLogF : 0;\n return startLogF + unbalancing / (depthFactor * maxExposure);\n }\n\n // Case 2: Only rebalancing\n // Both rebalancing and poolNetExposure have the same sign, so ratio is in [0, 1]\n if (rebalancing !== 0 && poolNetExposure !== 0) {\n const ratio = rebalancing / poolNetExposure;\n return currentLogF * (1 - ratio);\n }\n\n return currentLogF;\n};\n\n/**\n * Estimates the execution price for a trade using the exponential logPriceMultiplier formula.\n *\n * Mirrors on-chain logic:\n * 1. computeNewLogPriceMultiplier (PriceMultiplier.sol)\n * 2. computeAmmPrice: ammPrice = oraclePrice * exp(logF)\n * 3. computeSignedSpread: executionPrice = ammPrice * (1 + signedSpread)\n *\n * @audit spreadDiscount not applied — known limitation, to be addressed later\n * @audit priceSpacing rounding not applied\n */\nexport const calculateEstimatedExecutionPrice = ({\n oraclePrice,\n currentLogF,\n tradeExposure,\n poolNetExposure,\n depthFactor,\n maxExposure,\n priceSpread,\n}: {\n oraclePrice: number;\n currentLogF: number;\n tradeExposure: number;\n poolNetExposure: number;\n depthFactor: number;\n maxExposure: number;\n priceSpread: number;\n}): number => {\n if (tradeExposure === 0) {\n return oraclePrice * Math.exp(currentLogF);\n }\n\n // 1. Compute new logF after trade impact\n const newLogF = computeNewLogF({\n currentLogF,\n tradeExposure,\n poolNetExposure,\n depthFactor,\n maxExposure,\n });\n\n // 2. Compute AMM price: oraclePrice * exp(newLogF)\n const ammPrice = oraclePrice * Math.exp(newLogF);\n\n // 3. Apply signed spread\n const signedSpread = tradeExposure > 0 ? priceSpread : -priceSpread;\n return Math.max(0, ammPrice * (1 + signedSpread));\n};\n\nexport const calculateTradeFee = ({\n feeRate,\n tradeNotional,\n}: {\n feeRate: number;\n tradeNotional: number;\n}) => feeRate * Math.abs(tradeNotional);\n\nexport const calculateSpread = ({\n depthFactor,\n maxExposure,\n oraclePrice,\n poolPrice,\n tradeNotional,\n}: {\n depthFactor: number;\n maxExposure: number;\n oraclePrice: number;\n poolPrice: number;\n tradeNotional: number;\n}) =>\n (poolPrice / oraclePrice) *\n (1 + tradeNotional / (depthFactor * maxExposure) - 1) *\n tradeNotional;\n\nexport const calculateEstimatedLiquidationPrice = ({\n LMR,\n accountBalance,\n isShort,\n notional,\n oraclePrice,\n}: {\n LMR: number;\n accountBalance: number;\n isShort: boolean;\n notional: number;\n oraclePrice: number;\n}) =>\n Math.max(\n 0,\n oraclePrice *\n (1 - ((accountBalance - LMR) / notional) * (isShort ? -1 : 1)),\n );\n\nexport const calculateLeverage = ({\n imrMultiplier,\n riskFactor,\n}: {\n imrMultiplier: number;\n riskFactor: number;\n}) => 1 / (imrMultiplier * Math.sqrt(riskFactor));\n\nexport const calculateRequiredMargin = ({\n currIMR,\n currentNotional,\n leverage,\n tradeNotional,\n}: {\n currIMR: number;\n currentNotional: number;\n leverage: number;\n tradeNotional: number;\n}) =>\n currIMR +\n (Math.abs(currentNotional + tradeNotional) - Math.abs(currentNotional)) /\n leverage;\n\n/**\n * Calculates the maximum notional trade size (unsigned, always ≥ 0).\n *\n * Implements the UI quant spec v2 (\"Maximum trade\") with two cases:\n * Case 1 — Extending: trade same direction as existing position.\n * Case 2 — Reverting: decompose into (a) close position exactly, then\n * (b) extend from zero in the opposite direction.\n *\n * All quadratics use the unsigned convention (t = |tradeNotional|) so the\n * positive root always corresponds to the correct direction.\n */\nexport const calculateMaxOrderSize = ({\n currIMR,\n currNodeBalance,\n currNotional,\n depthFactor,\n feeRate,\n isShortTrade,\n leverage,\n maxExposure,\n oraclePrice,\n poolPrice,\n currentLogF,\n netExposure,\n}: {\n currIMR: number;\n currNodeBalance: number;\n currNotional: number;\n depthFactor: number;\n feeRate: number;\n isShortTrade: boolean;\n leverage: number;\n maxExposure: number;\n oraclePrice: number;\n poolPrice: number;\n currentLogF: number;\n netExposure: number;\n}): number => {\n const D = depthFactor * maxExposure;\n const rho = poolPrice / oraclePrice;\n const tradeSign = isShortTrade ? -1 : 1;\n const s0 = currNotional > 0 ? 1 : currNotional < 0 ? -1 : tradeSign;\n const absN0 = Math.abs(currNotional);\n\n /**\n * Solve the extending quadratic (spec §Case 1) for max trade size.\n * a·t² + b·t + c = 0 where a = ρ·γ, b = s₀·(1/lev + fee) + (ρ−1), c = −surplus.\n * Root selection: pick the root whose sign matches s₀ (dir).\n * For rebalancing (a < 0), caps at |NE| (beyond which γ switches to unbalancing).\n */\n const solveExtending = (\n dir: number,\n surplus: number, // aka, IMRDelta\n rho_: number,\n gamma_: number,\n isRebal: boolean,\n absNE: number,\n ): number => {\n if (surplus <= 0) return 0;\n const a = rho_ * gamma_;\n const b = dir * (1 / leverage + feeRate) + (rho_ - 1);\n const c = -surplus;\n // Degenerate: γ = 0 → linear equation b·t + c = 0 (rebalancing with f = 0)\n if (a === 0) {\n if (b === 0) return isRebal ? absNE : 0;\n const t = -c / b;\n if (t * dir <= 0) return isRebal ? absNE : 0;\n return isRebal ? Math.min(Math.abs(t), absNE) : Math.abs(t);\n }\n const disc = b * b - 4 * a * c;\n if (isRebal) {\n if (disc < 0) return absNE;\n const t = (-b + dir * Math.sqrt(disc)) / (2 * a);\n return t * dir <= 0 ? absNE : Math.min(Math.abs(t), absNE);\n }\n if (disc < 0)\n throw new Error(`calculateMaxOrderSize: negative discriminant (${disc})`);\n const t = (-b + dir * Math.sqrt(disc)) / (2 * a);\n if (t * dir <= 0)\n throw new Error(`calculateMaxOrderSize: no valid root (${t})`);\n return Math.abs(t);\n };\n\n // Determine γ for a trade of given direction against the current pool state\n const getGamma = (dir: number, logF: number, ne: number) => {\n const isRebal = ne !== 0 && dir === Math.sign(ne);\n const gamma = isRebal ? -logF / ne : 1 / D;\n return { gamma, isRebal };\n };\n\n /**\n * Like solveExtending, but when the rebalancing leg is capped at |NE|\n * (pool-flip), continues with the unbalancing leg from NE = 0.\n *\n * For the exact rebalancing trade to NE = 0:\n * execRatio = ρ·exp(γ·dir·|NE|) = exp(f)·exp(−f) = 1\n * so only fee and IMR consume margin. Then extend with γ = 1/D and ρ' = 1.\n */\n const extendWithFlip = (\n dir: number,\n surplus: number,\n rho_: number,\n gamma_: number,\n isRebal: boolean,\n absNE: number,\n ): number => {\n const result = solveExtending(dir, surplus, rho_, gamma_, isRebal, absNE);\n if (!isRebal || result < absNE || absNE === 0) return result;\n\n // Pool-flip: rebalancing consumed absNE, continue unbalancing from NE = 0\n const surplusAfter = surplus - absNE * (1 / leverage + feeRate);\n if (surplusAfter <= 0) return absNE;\n return absNE + solveExtending(dir, surplusAfter, 1, 1 / D, false, 0);\n };\n\n // ── Case 1: Extending ──────────────────────────────────────────────────\n if (tradeSign === s0) {\n const { gamma, isRebal } = getGamma(tradeSign, currentLogF, netExposure);\n return extendWithFlip(\n s0,\n currNodeBalance - currIMR,\n rho,\n gamma,\n isRebal,\n Math.abs(netExposure),\n );\n }\n\n // ── Case 2: Reverting — close N₀, then re-extend ──────────────────────\n\n // Step 1: Close N₀ entirely (spec §Case 2, Step 1)\n const closeTrade = -currNotional;\n const closeDir = -s0;\n const { gamma: gammaC, isRebal: closeIsRebal } = getGamma(\n closeDir,\n currentLogF,\n netExposure,\n );\n const closeFlipsPool = closeIsRebal && absN0 > Math.abs(netExposure);\n\n // Exec price ratio: ρ·exp(γ_c·closeTrade) for non-flip, dedicated formula for flip\n const closeExecRatio = closeFlipsPool\n ? Math.exp((closeTrade - netExposure) / D)\n : rho * Math.exp(gammaC * closeTrade);\n\n const balClose =\n currNodeBalance - feeRate * absN0 + closeTrade * (1 - closeExecRatio);\n const imrClose = currIMR - absN0 / leverage;\n const surplusClose = balClose - imrClose;\n\n // Insolvency: can't fully close without going under margin.\n // Solve partial-close quadratic (spec appendix): b has flipped feeRate sign.\n // Falls back to full close (|N₀|) when no valid partial-close root exists.\n if (surplusClose <= 0) {\n const IMRDelta = currNodeBalance - currIMR;\n const { gamma: gammaP } = getGamma(closeDir, currentLogF, netExposure);\n const a = rho * gammaP;\n const b = s0 * (1 / leverage - feeRate) + (rho - 1);\n const c = -IMRDelta;\n\n if (a === 0) {\n if (b === 0) return absN0;\n const t = -c / b;\n if (t * closeDir <= 0) return absN0;\n return Math.min(Math.abs(t), absN0);\n }\n\n const disc = b * b - 4 * a * c;\n if (disc < 0) return absN0;\n const t = (-b + closeDir * Math.sqrt(disc)) / (2 * a);\n if (t * closeDir <= 0) return absN0;\n return Math.min(Math.abs(t), absN0);\n }\n\n // Step 2: Extend from zero in -s₀ direction with post-close pool state\n const neAfter = netExposure + currNotional;\n let fPrime: number;\n if (closeFlipsPool) {\n fPrime = (closeTrade - netExposure) / D;\n } else if (closeIsRebal) {\n fPrime = currentLogF * (1 + currNotional / netExposure);\n } else {\n fPrime = currentLogF + closeTrade / D;\n }\n const rhoPrime = Math.exp(fPrime);\n\n const extDir = -s0;\n const { gamma: gammaPrime, isRebal: isExtRebal } = getGamma(\n extDir,\n fPrime,\n neAfter,\n );\n\n return (\n absN0 +\n extendWithFlip(\n extDir,\n surplusClose,\n rhoPrime,\n gammaPrime,\n isExtRebal,\n Math.abs(neAfter),\n )\n );\n};\n\nexport const calculateIMR = ({\n marketLeverages,\n marketPrices,\n positions,\n}: {\n marketLeverages: Map<MarketId, number>;\n marketPrices: Map<MarketId, number>;\n positions: Map<MarketId, number>;\n}) => {\n return Array.from(positions.entries()).reduce(\n (sum, [marketId, positionSize]) => {\n const leverage = marketLeverages.get(marketId);\n return leverage\n ? sum +\n (Math.abs(positionSize) * (marketPrices.get(marketId) ?? 0)) /\n leverage\n : sum;\n },\n 0,\n );\n};\n\nexport const calculateLMR = ({\n marketPrices,\n positions,\n riskFactors,\n marketId,\n tradeSize,\n}: {\n marketId?: string;\n marketPrices: Map<MarketId, number>;\n positions: Map<MarketId, number>;\n riskFactors: Map<MarketId, number>;\n tradeSize?: number;\n}) =>\n Array.from(\n (marketId && tradeSize\n ? mergeMap(positions, [\n [marketId, (positions.get(marketId) ?? 0) + tradeSize],\n ])\n : positions\n ).entries(),\n ).reduce((sum, [marketId, positionSize]) => {\n const riskFactor = riskFactors.get(marketId);\n return riskFactor\n ? sum +\n Math.abs(positionSize) *\n (marketPrices.get(marketId) ?? 0) *\n Math.sqrt(riskFactor)\n : sum;\n }, 0);\n\n// if account balance is below LMR position is liquidable\n\nexport const calculateMarginRatio = ({\n LMR,\n totalBalance,\n tradeCost,\n}: {\n LMR: number;\n totalBalance: number;\n tradeCost: number;\n}) => {\n if (LMR === 0) {\n return 0;\n }\n if (tradeCost > totalBalance) {\n return 1;\n }\n if (totalBalance === tradeCost) {\n return Infinity;\n }\n return Math.min(1, LMR / (totalBalance - tradeCost));\n};\n\nexport const calculateTotalMargin = ({\n marketsTrackers,\n accountBalances,\n assetPrices,\n markPrices,\n marketsTokenInfo,\n positions,\n rUSDAddress,\n}: {\n accountBalances: Map<Address, number>;\n assetPrices: Map<Address, number>;\n markPrices: Map<Address, number>;\n marketsTokenInfo: Map<\n MarketId,\n {\n quoteTokenId: string;\n underlyingAssetId: string;\n }\n >;\n marketsTrackers: Map<\n MarketId,\n {\n longADLUnwindPrice: number;\n longBaseMultiplier: number;\n longFundingValue: number;\n shortADLUnwindPrice: number;\n shortBaseMultiplier: number;\n shortFundingValue: number;\n }\n >;\n positions: {\n adlUnwindPrice: number;\n base: number;\n baseMultiplier: number;\n fundingValue: number;\n lastPrice: number;\n marketId: string;\n realizedPnl: number;\n }[];\n rUSDAddress?: string;\n}) => {\n const pnl = new Map<Address, number>();\n const rUSDPrice = (rUSDAddress && assetPrices.get(rUSDAddress)) ?? 1;\n positions.forEach((position) => {\n const marketTracker = marketsTrackers?.get(position.marketId);\n const tokenInfo = marketsTokenInfo.get(position.marketId);\n if (!tokenInfo) return;\n let fundingCashFlow = 0;\n let adlCashFlow = 0;\n\n if (marketTracker) {\n // fundingCashFlow\n const marketTrackerFundingValue =\n position.base < 0\n ? marketTracker.shortFundingValue\n : marketTracker.longFundingValue;\n const trackerDelta = marketTrackerFundingValue - position.fundingValue;\n fundingCashFlow =\n (trackerDelta / position.baseMultiplier) * -1 * position.base;\n\n // adlCashFlow\n const adlUnwindPrice =\n ((position.base < 0\n ? marketTracker.shortADLUnwindPrice\n : marketTracker.longADLUnwindPrice) -\n position.adlUnwindPrice) /\n position.baseMultiplier;\n const baseMultiplier =\n (position.base < 0\n ? marketTracker.shortBaseMultiplier\n : marketTracker.longBaseMultiplier) / position.baseMultiplier;\n const lastPriceCoefficient = 1 - baseMultiplier;\n const initialPrice = lastPriceCoefficient * position.lastPrice;\n adlCashFlow = (adlUnwindPrice - initialPrice) * position.base;\n }\n\n const unrealizedPnl =\n ((markPrices.get(tokenInfo.quoteTokenId) ?? 0) - position.lastPrice) *\n position.base;\n\n pnl.set(\n tokenInfo.underlyingAssetId,\n (pnl.get(tokenInfo.underlyingAssetId) ?? 0) +\n position.realizedPnl +\n fundingCashFlow +\n adlCashFlow +\n unrealizedPnl,\n );\n });\n\n return Array.from(accountBalances.entries()).reduce(\n (sum, [address, balance]) =>\n sum +\n (balance + (pnl.get(address) ?? 0)) *\n (address === rUSDAddress\n ? 1\n : (assetPrices.get(address) ?? 0) / (rUSDPrice || 1)),\n 0,\n );\n};\n\nexport const calculateFundingPnl = ({\n marketFundingValue,\n marketBaseMultiplier,\n positionAvgEntryFundingValue,\n positionAdjustedBase,\n}: {\n marketFundingValue: number;\n marketBaseMultiplier: number;\n positionAvgEntryFundingValue: number;\n positionAdjustedBase: number;\n}): number => {\n return (\n -1 *\n (((marketFundingValue - positionAvgEntryFundingValue) *\n positionAdjustedBase) /\n marketBaseMultiplier)\n );\n};\n\nexport const calculatePricePnl = ({\n price,\n positionAvgEntryPrice,\n positionAdjustedBase,\n}: {\n price: number;\n positionAvgEntryPrice: number;\n positionAdjustedBase: number;\n}): number => {\n return (price - positionAvgEntryPrice) * positionAdjustedBase;\n};\n\nexport const calculateRealBalance = (\n netDeposits: BigNumber,\n realized_pnl: BigNumber,\n) => {\n return netDeposits.plus(realized_pnl);\n};\n\nexport const calculatePositionAdjustedQty = (\n origQty: BigNumber,\n marketBaseMultiplier: BigNumber,\n positionBaseMultiplier: BigNumber,\n): BigNumber => {\n return origQty.times(marketBaseMultiplier).div(positionBaseMultiplier);\n};\n\n/**\n * Linearly interpolate a depth ratio from a (thresholds, ratios) curve.\n * The curve implicitly starts at (exposure=0, ratio=1.0).\n * - Between thresholds: linear interpolation\n * - Above last threshold: last ratio (flat extrapolation)\n *\n * @param thresholds - Sorted ascending exposure thresholds in notional USD (must be non-empty)\n * @param ratios - Depth ratio at each threshold (same length as thresholds, must be non-empty)\n * @param exposure - Absolute exposure notional (must be >= 0)\n * @throws if thresholds or ratios are empty, or if they have different lengths\n */\nexport const interpolateDepthRatio = (\n thresholds: number[],\n ratios: number[],\n exposure: number,\n): number => {\n if (exposure < 0) {\n throw new Error('interpolateDepthRatio: exposure must be >= 0');\n }\n if (thresholds.length === 0 || ratios.length === 0) {\n throw new Error(\n 'interpolateDepthRatio: thresholds and ratios must be non-empty',\n );\n }\n if (thresholds.length !== ratios.length) {\n throw new Error(\n 'interpolateDepthRatio: thresholds and ratios must have equal length',\n );\n }\n\n const allThresholds = [0, ...thresholds];\n const allRatios = [1.0, ...ratios];\n\n if (exposure === 0) return 1.0;\n if (exposure >= allThresholds[allThresholds.length - 1]) {\n return allRatios[allRatios.length - 1];\n }\n\n for (let i = 0; i < allThresholds.length - 1; i++) {\n if (exposure <= allThresholds[i + 1]) {\n const t =\n (exposure - allThresholds[i]) /\n (allThresholds[i + 1] - allThresholds[i]);\n return allRatios[i] + t * (allRatios[i + 1] - allRatios[i]);\n }\n }\n\n throw new Error('interpolateDepthRatio: unreachable');\n};\n\n/**\n * Calculate the dynamic depth factor for a trade given pool state and config.\n *\n * The pool takes the opposite side of the trade, so:\n * poolNotionalAfterTrade = currentPoolNotional - signedTradeNotional\n *\n * The depth ratio is interpolated from the exposure curve, then multiplied\n * by baseDepth to produce the final depth factor.\n *\n * @param baseDepth - Base depth multiplier for this market\n * @param thresholds - Sorted ascending exposure thresholds (notional USD)\n * @param ratios - Depth ratio at each threshold\n * @param currentPoolNotional - Pool's current notional in this market (signed)\n * @param signedTradeNotional - Trade notional (positive=buy, negative=sell)\n */\nexport const calculateDynamicDepthFactor = ({\n baseDepth,\n thresholds,\n ratios,\n currentPoolNotional,\n signedTradeNotional,\n}: {\n baseDepth: number;\n thresholds: number[];\n ratios: number[];\n currentPoolNotional: number;\n signedTradeNotional: number;\n}): number => {\n const poolNotionalAfterTrade = currentPoolNotional - signedTradeNotional;\n const absExposureNotional = Math.abs(poolNotionalAfterTrade);\n const depthRatio = interpolateDepthRatio(\n thresholds,\n ratios,\n absExposureNotional,\n );\n return depthRatio * baseDepth;\n};\n\nexport const calculatePositionAdlPnL = ({\n marketTrackerAdlUnwindPrice,\n marketTrackerBaseMultiplier,\n positionBase,\n positionAvgEntryPrice,\n positionTrackerBaseMultiplier,\n positionTrackerAdlUnwindPrice,\n}: {\n marketTrackerAdlUnwindPrice: BigNumber;\n marketTrackerBaseMultiplier: BigNumber;\n positionBase: BigNumber;\n positionAvgEntryPrice: BigNumber;\n positionTrackerBaseMultiplier: BigNumber;\n positionTrackerAdlUnwindPrice: BigNumber;\n}): BigNumber => {\n const currentAdlUnwindPrice = marketTrackerAdlUnwindPrice\n .minus(positionTrackerAdlUnwindPrice)\n .multipliedBy(1e18)\n .div(positionTrackerBaseMultiplier);\n\n const initialPrice = positionAvgEntryPrice\n .times(\n BigNumber(1e18).minus(\n marketTrackerBaseMultiplier\n .multipliedBy(1e18)\n .div(positionTrackerBaseMultiplier),\n ),\n )\n .div(1e18);\n\n const adlPnL = positionBase\n .times(currentAdlUnwindPrice.minus(initialPrice))\n .div(1e18);\n\n return adlPnL;\n};\n"]}
1
+ {"version":3,"file":"calculate.js","sourceRoot":"/","sources":["utils/calculate.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,mCAAoC;AACpC,8DAAqC;AAExB,QAAA,QAAQ,GAAG,GAAG,CAAC;AAK5B;;;GAGG;AACI,IAAM,oBAAoB,GAAG,UAAC,EAwBpC;QAvBC,UAAU,gBAAA,EACV,aAAa,mBAAA,EACb,WAAW,iBAAA,EACX,OAAO,aAAA,EACP,KAAK,WAAA;IAoBL,IAAI,UAAU,GAAG,CAAC,IAAI,KAAK,GAAG,CAAC,IAAI,OAAO,GAAG,CAAC,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,mDAAmD,CAAC,CAAC;IACvE,CAAC;IAED,IAAI,UAAU,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,IAAI,OAAO,KAAK,CAAC,IAAI,KAAK,KAAK,CAAC,EAAE,CAAC;QACjC,OAAO,CAAC,CAAC;IACX,CAAC;IAED,IAAM,eAAe,GAAG,aAAa,GAAG,UAAU,CAAC;IACnD,IAAM,aAAa,GAAG,eAAe,GAAG,CAAC,KAAK,GAAG,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC;IAEhE,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,CAAC,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC;AAC3D,CAAC,CAAC;AAzCW,QAAA,oBAAoB,wBAyC/B;AAEK,IAAM,oBAAoB,GAAG,UAAC,EAQpC;QAPC,WAAW,iBAAA,EACX,UAAU,gBAAA,EACV,e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AAM,sBAAsB,GAAG,mBAAmB,GAAG,mBAAmB,CAAC;IACzE,IAAM,mBAAmB,GAAG,IAAI,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC;IAC7D,IAAM,UAAU,GAAG,IAAA,6BAAqB,EACtC,UAAU,EACV,MAAM,EACN,mBAAmB,CACpB,CAAC;IACF,OAAO,UAAU,GAAG,SAAS,CAAC;AAChC,CAAC,CAAC;AArBW,QAAA,2BAA2B,+BAqBtC;AAEK,IAAM,uBAAuB,GAAG,UAAC,EAcvC;QAbC,2BAA2B,iCAAA,EAC3B,2BAA2B,iCAAA,EAC3B,YAAY,kBAAA,EACZ,qBAAqB,2BAAA,EACrB,6BAA6B,mCAAA,EAC7B,6BAA6B,mCAAA;IAS7B,IAAM,qBAAqB,GAAG,2BAA2B;SACtD,KAAK,CAAC,6BAA6B,CAAC;SACpC,YAAY,CAAC,IAAI,CAAC;SAClB,GAAG,CAAC,6BAA6B,CAAC,CAAC;IAEtC,IAAM,YAAY,GAAG,qBAAqB;SACvC,KAAK,CACJ,IAAA,sBAAS,EAAC,IAAI,CAAC,CAAC,KAAK,CACnB,2BAA2B;SACxB,YAAY,CAAC,IAAI,CAAC;SAClB,GAAG,CAAC,6BAA6B,CAAC,CACtC,CACF;SACA,GAAG,CAAC,IAAI,CAAC,CAAC;IAEb,IAAM,MAAM,GAAG,YAAY;SACxB,KAAK,CAAC,qBAAqB,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;SAChD,GAAG,CAAC,IAAI,CAAC,CAAC;IAEb,OAAO,MAAM,CAAC;AAChB,CAAC,CAAC;AAnCW,QAAA,uBAAuB,2BAmClC","sourcesContent":["import { mergeMap } from './struct';\nimport BigNumber from 'bignumber.js';\n\nexport const POOL_IMR = 9.1;\n\ntype MarketId = string;\ntype Address = string;\n\n/**\n * Calculates the maximum amount that can be withdrawn in terms of the token\n * (e.g., if rUSD then in rUSD terms, if WETH then in WETH terms)\n */\nexport const calculateMaxWithdraw = ({\n currentIMR,\n marginBalance,\n realBalance,\n haircut,\n price,\n}: {\n /** Current Initial Margin Requirement of the account in rUSD terms */\n currentIMR: number;\n /** Current margin balance of the account (expected to already include haircuts) in rUSD terms */\n marginBalance: number;\n /**\n * Current real balance of the token the user wants to withdraw in token terms.\n * For rUSD: this equals net deposits (balanceDeprecated from v2 endpoints + realized PnL).\n * For all other tokens: this equals balanceDeprecated (since realized PnL is 0 for them).\n */\n realBalance: number;\n /**\n * Haircut parameter of the token.\n * Note: haircut for rUSD is always expected to be 0.\n */\n haircut: number;\n /** Price of the token in rUSD terms */\n price: number;\n}): number => {\n if (currentIMR < 0 || price < 0 || haircut < 0) {\n throw new Error('currentIMR, price, and haircut cannot be negative');\n }\n\n if (currentIMR === 0) {\n return realBalance;\n }\n\n if (haircut === 1 || price === 0) {\n return 0;\n }\n\n const availableMargin = marginBalance - currentIMR;\n const maxFromMargin = availableMargin / (price * (1 - haircut));\n\n return Math.max(0, Math.min(realBalance, maxFromMargin));\n};\n\nexport const calculateMaxExposure = ({\n poolBalance,\n riskFactor,\n poolIMR = POOL_IMR,\n}: {\n poolBalance: number;\n poolIMR?: number;\n riskFactor: number;\n}) => poolBalance / (poolIMR * Math.sqrt(riskFactor));\n\n/**\n * Splits a trade exposure into rebalancing and unbalancing portions relative to pool net exposure.\n * Rebalancing reduces pool's absolute exposure; unbalancing increases it.\n */\nexport const splitTradeExposure = (\n tradeExposure: number,\n poolNetExposure: number,\n): { rebalancing: number; unbalancing: number } => {\n if (tradeExposure === 0) {\n return { rebalancing: 0, unbalancing: 0 };\n }\n\n // If pool has no exposure, entire trade is unbalancing\n if (poolNetExposure === 0) {\n return { rebalancing: 0, unbalancing: tradeExposure };\n }\n\n // Opposite sign means trade increases pool exposure → pure unbalancing\n const sameSign =\n (poolNetExposure > 0 && tradeExposure > 0) ||\n (poolNetExposure < 0 && tradeExposure < 0);\n if (!sameSign) {\n return { rebalancing: 0, unbalancing: tradeExposure };\n }\n\n // Same sign: trade reduces pool exposure (pool takes opposite side)\n const absPool = Math.abs(poolNetExposure);\n const absTrade = Math.abs(tradeExposure);\n\n if (absTrade <= absPool) {\n // Pure rebalancing — trade doesn't cross zero\n return { rebalancing: tradeExposure, unbalancing: 0 };\n }\n\n // Mixed: rebalance up to pool exposure, then unbalance the rest\n const rebalancing = poolNetExposure;\n const unbalancing = tradeExposure - rebalancing;\n return { rebalancing, unbalancing };\n};\n\n/**\n * Computes the new log price multiplier (logF) after a trade, handling both\n * rebalancing and unbalancing portions.\n *\n * Mirrors on-chain logic in PriceMultiplier.sol:computeNewLogPriceMultiplier.\n */\nexport const computeNewLogF = ({\n currentLogF,\n tradeExposure,\n poolNetExposure,\n depthFactor,\n maxExposure,\n}: {\n currentLogF: number;\n tradeExposure: number;\n poolNetExposure: number;\n depthFactor: number;\n maxExposure: number;\n}): number => {\n if (tradeExposure === 0) return currentLogF;\n\n const { rebalancing, unbalancing } = splitTradeExposure(\n tradeExposure,\n poolNetExposure,\n );\n\n // Case 1: Has unbalancing portion (includes mixed trades)\n if (unbalancing !== 0) {\n // If also rebalancing, it brings logF to 0 by definition (trade crosses zero)\n const startLogF = rebalancing === 0 ? currentLogF : 0;\n return startLogF + unbalancing / (depthFactor * maxExposure);\n }\n\n // Case 2: Only rebalancing\n // Both rebalancing and poolNetExposure have the same sign, so ratio is in [0, 1]\n if (rebalancing !== 0 && poolNetExposure !== 0) {\n const ratio = rebalancing / poolNetExposure;\n return currentLogF * (1 - ratio);\n }\n\n return currentLogF;\n};\n\n/**\n * Estimates the execution price for a trade using the exponential logPriceMultiplier formula.\n *\n * Mirrors on-chain logic:\n * 1. computeNewLogPriceMultiplier (PriceMultiplier.sol)\n * 2. computeAmmPrice: ammPrice = oraclePrice * exp(logF)\n * 3. computeSignedSpread: executionPrice = ammPrice * (1 + signedSpread)\n *\n * @audit spreadDiscount not applied — known limitation, to be addressed later\n * @audit priceSpacing rounding not applied\n */\nexport const calculateEstimatedExecutionPrice = ({\n oraclePrice,\n currentLogF,\n tradeExposure,\n poolNetExposure,\n depthFactor,\n maxExposure,\n priceSpread,\n}: {\n oraclePrice: number;\n currentLogF: number;\n tradeExposure: number;\n poolNetExposure: number;\n depthFactor: number;\n maxExposure: number;\n priceSpread: number;\n}): number => {\n if (tradeExposure === 0) {\n return oraclePrice * Math.exp(currentLogF);\n }\n\n // 1. Compute new logF after trade impact\n const newLogF = computeNewLogF({\n currentLogF,\n tradeExposure,\n poolNetExposure,\n depthFactor,\n maxExposure,\n });\n\n // 2. Compute AMM price: oraclePrice * exp(newLogF)\n const ammPrice = oraclePrice * Math.exp(newLogF);\n\n // 3. Apply signed spread\n const signedSpread = tradeExposure > 0 ? priceSpread : -priceSpread;\n return Math.max(0, ammPrice * (1 + signedSpread));\n};\n\nexport const calculateTradeFee = ({\n feeRate,\n tradeNotional,\n}: {\n feeRate: number;\n tradeNotional: number;\n}) => feeRate * Math.abs(tradeNotional);\n\nexport const calculateSpread = ({\n depthFactor,\n maxExposure,\n oraclePrice,\n poolPrice,\n tradeNotional,\n}: {\n depthFactor: number;\n maxExposure: number;\n oraclePrice: number;\n poolPrice: number;\n tradeNotional: number;\n}) =>\n (poolPrice / oraclePrice) *\n (1 + tradeNotional / (depthFactor * maxExposure) - 1) *\n tradeNotional;\n\nexport const calculateEstimatedLiquidationPrice = ({\n LMR,\n accountBalance,\n isShort,\n notional,\n oraclePrice,\n}: {\n LMR: number;\n accountBalance: number;\n isShort: boolean;\n notional: number;\n oraclePrice: number;\n}) =>\n Math.max(\n 0,\n oraclePrice *\n (1 - ((accountBalance - LMR) / notional) * (isShort ? -1 : 1)),\n );\n\nexport const calculateLeverage = ({\n imrMultiplier,\n riskFactor,\n}: {\n imrMultiplier: number;\n riskFactor: number;\n}) => 1 / (imrMultiplier * Math.sqrt(riskFactor));\n\nexport const calculateRequiredMargin = ({\n currIMR,\n currentNotional,\n leverage,\n tradeNotional,\n}: {\n currIMR: number;\n currentNotional: number;\n leverage: number;\n tradeNotional: number;\n}) =>\n currIMR +\n (Math.abs(currentNotional + tradeNotional) - Math.abs(currentNotional)) /\n leverage;\n\n/**\n * Calculates the maximum notional trade size (unsigned, always ≥ 0).\n *\n * Implements the UI quant spec v2 (\"Maximum trade\") with two cases:\n * Case 1 — Extending: trade same direction as existing position.\n * Case 2 — Reverting: decompose into (a) close position exactly, then\n * (b) extend from zero in the opposite direction.\n *\n * All quadratics use the unsigned convention (t = |tradeNotional|) so the\n * positive root always corresponds to the correct direction.\n */\nexport const calculateMaxOrderSize = ({\n currIMR,\n currNodeBalance,\n currNotional,\n depthFactor,\n feeRate,\n isShortTrade,\n leverage,\n maxExposure,\n oraclePrice,\n poolPrice,\n currentLogF,\n netExposure,\n}: {\n currIMR: number;\n currNodeBalance: number;\n currNotional: number;\n depthFactor: number;\n feeRate: number;\n isShortTrade: boolean;\n leverage: number;\n maxExposure: number;\n oraclePrice: number;\n poolPrice: number;\n currentLogF: number;\n netExposure: number;\n}): number => {\n const D = depthFactor * maxExposure;\n const rho = poolPrice / oraclePrice;\n const tradeSign = isShortTrade ? -1 : 1;\n const s0 = currNotional > 0 ? 1 : currNotional < 0 ? -1 : tradeSign;\n const absN0 = Math.abs(currNotional);\n\n /**\n * Solve the extending quadratic (spec §Case 1) for max trade size.\n * a·t² + b·t + c = 0 where a = ρ·γ, b = s₀·(1/lev + fee) + (ρ−1), c = −surplus.\n * Root selection: pick the root whose sign matches s₀ (dir).\n * For rebalancing (a < 0), caps at |NE| (beyond which γ switches to unbalancing).\n */\n const solveExtending = (\n dir: number,\n surplus: number, // aka, IMRDelta\n rho_: number,\n gamma_: number,\n isRebal: boolean,\n absNE: number,\n ): number => {\n if (surplus <= 0) return 0;\n const a = rho_ * gamma_;\n const b = dir * (1 / leverage + feeRate) + (rho_ - 1);\n const c = -surplus;\n // Degenerate: γ = 0 → linear equation b·t + c = 0 (rebalancing with f = 0)\n if (a === 0) {\n if (b === 0) return isRebal ? absNE : 0;\n const t = -c / b;\n if (t * dir <= 0) return isRebal ? absNE : 0;\n return isRebal ? Math.min(Math.abs(t), absNE) : Math.abs(t);\n }\n const disc = b * b - 4 * a * c;\n if (isRebal) {\n if (disc < 0) return absNE;\n const t = (-b + dir * Math.sqrt(disc)) / (2 * a);\n return t * dir <= 0 ? absNE : Math.min(Math.abs(t), absNE);\n }\n if (disc < 0)\n throw new Error(`calculateMaxOrderSize: negative discriminant (${disc})`);\n const t = (-b + dir * Math.sqrt(disc)) / (2 * a);\n if (t * dir <= 0)\n throw new Error(`calculateMaxOrderSize: no valid root (${t})`);\n return Math.abs(t);\n };\n\n // Determine γ for a trade of given direction against the current pool state\n const getGamma = (dir: number, logF: number, ne: number) => {\n const isRebal = ne !== 0 && dir === Math.sign(ne);\n const gamma = isRebal ? -logF / ne : 1 / D;\n return { gamma, isRebal };\n };\n\n /**\n * Like solveExtending, but when the rebalancing leg is capped at |NE|\n * (pool-flip), continues with the unbalancing leg from NE = 0.\n *\n * For the exact rebalancing trade to NE = 0:\n * execRatio = ρ·exp(γ·dir·|NE|) = exp(f)·exp(−f) = 1\n * so only fee and IMR consume margin. Then extend with γ = 1/D and ρ' = 1.\n */\n const extendWithFlip = (\n dir: number,\n surplus: number,\n rho_: number,\n gamma_: number,\n isRebal: boolean,\n absNE: number,\n ): number => {\n const result = solveExtending(dir, surplus, rho_, gamma_, isRebal, absNE);\n if (!isRebal || result < absNE || absNE === 0) return result;\n\n // Pool-flip: rebalancing consumed absNE, continue unbalancing from NE = 0\n const surplusAfter = surplus - absNE * (1 / leverage + feeRate);\n if (surplusAfter <= 0) return absNE;\n return absNE + solveExtending(dir, surplusAfter, 1, 1 / D, false, 0);\n };\n\n // ── Case 1: Extending ──────────────────────────────────────────────────\n if (tradeSign === s0) {\n const { gamma, isRebal } = getGamma(tradeSign, currentLogF, netExposure);\n return extendWithFlip(\n s0,\n currNodeBalance - currIMR,\n rho,\n gamma,\n isRebal,\n Math.abs(netExposure),\n );\n }\n\n // ── Case 2: Reverting — close N₀, then re-extend ──────────────────────\n\n // Step 1: Close N₀ entirely (spec §Case 2, Step 1)\n const closeTrade = -currNotional;\n const closeDir = -s0;\n const { gamma: gammaC, isRebal: closeIsRebal } = getGamma(\n closeDir,\n currentLogF,\n netExposure,\n );\n const closeFlipsPool = closeIsRebal && absN0 > Math.abs(netExposure);\n\n // Exec price ratio: ρ·exp(γ_c·closeTrade) for non-flip, dedicated formula for flip\n const closeExecRatio = closeFlipsPool\n ? Math.exp((closeTrade - netExposure) / D)\n : rho * Math.exp(gammaC * closeTrade);\n\n const balClose =\n currNodeBalance - feeRate * absN0 + closeTrade * (1 - closeExecRatio);\n const imrClose = currIMR - absN0 / leverage;\n const surplusClose = balClose - imrClose;\n\n // Insolvency: can't fully close without going under margin.\n // Solve partial-close quadratic (spec appendix): b has flipped feeRate sign.\n // Falls back to full close (|N₀|) when no valid partial-close root exists.\n if (surplusClose <= 0) {\n const IMRDelta = currNodeBalance - currIMR;\n const { gamma: gammaP } = getGamma(closeDir, currentLogF, netExposure);\n const a = rho * gammaP;\n const b = s0 * (1 / leverage - feeRate) + (rho - 1);\n const c = -IMRDelta;\n\n if (a === 0) {\n if (b === 0) return absN0;\n const t = -c / b;\n if (t * closeDir <= 0) return absN0;\n return Math.min(Math.abs(t), absN0);\n }\n\n const disc = b * b - 4 * a * c;\n if (disc < 0) return absN0;\n const t = (-b + closeDir * Math.sqrt(disc)) / (2 * a);\n if (t * closeDir <= 0) return absN0;\n return Math.min(Math.abs(t), absN0);\n }\n\n // Step 2: Extend from zero in -s₀ direction with post-close pool state\n const neAfter = netExposure + currNotional;\n let fPrime: number;\n if (closeFlipsPool) {\n fPrime = (closeTrade - netExposure) / D;\n } else if (closeIsRebal) {\n fPrime = currentLogF * (1 + currNotional / netExposure);\n } else {\n fPrime = currentLogF + closeTrade / D;\n }\n const rhoPrime = Math.exp(fPrime);\n\n const extDir = -s0;\n const { gamma: gammaPrime, isRebal: isExtRebal } = getGamma(\n extDir,\n fPrime,\n neAfter,\n );\n\n return (\n absN0 +\n extendWithFlip(\n extDir,\n surplusClose,\n rhoPrime,\n gammaPrime,\n isExtRebal,\n Math.abs(neAfter),\n )\n );\n};\n\nexport const calculateIMR = ({\n marketLeverages,\n marketPrices,\n positions,\n}: {\n marketLeverages: Map<MarketId, number>;\n marketPrices: Map<MarketId, number>;\n positions: Map<MarketId, number>;\n}) => {\n return Array.from(positions.entries()).reduce(\n (sum, [marketId, positionSize]) => {\n const leverage = marketLeverages.get(marketId);\n return leverage\n ? sum +\n (Math.abs(positionSize) * (marketPrices.get(marketId) ?? 0)) /\n leverage\n : sum;\n },\n 0,\n );\n};\n\nexport const calculateLMR = ({\n marketPrices,\n positions,\n riskFactors,\n marketId,\n tradeSize,\n}: {\n marketId?: string;\n marketPrices: Map<MarketId, number>;\n positions: Map<MarketId, number>;\n riskFactors: Map<MarketId, number>;\n tradeSize?: number;\n}) =>\n Array.from(\n (marketId && tradeSize\n ? mergeMap(positions, [\n [marketId, (positions.get(marketId) ?? 0) + tradeSize],\n ])\n : positions\n ).entries(),\n ).reduce((sum, [marketId, positionSize]) => {\n const riskFactor = riskFactors.get(marketId);\n return riskFactor\n ? sum +\n Math.abs(positionSize) *\n (marketPrices.get(marketId) ?? 0) *\n Math.sqrt(riskFactor)\n : sum;\n }, 0);\n\n// if account balance is below LMR position is liquidable\n\nexport const calculateMarginRatio = ({\n LMR,\n totalBalance,\n tradeCost,\n}: {\n LMR: number;\n totalBalance: number;\n tradeCost: number;\n}) => {\n if (LMR === 0) {\n return 0;\n }\n if (tradeCost > totalBalance) {\n return 1;\n }\n if (totalBalance === tradeCost) {\n return Infinity;\n }\n return Math.min(1, LMR / (totalBalance - tradeCost));\n};\n\nexport const calculateTotalMargin = ({\n marketsTrackers,\n accountBalances,\n assetPrices,\n markPrices,\n marketsTokenInfo,\n positions,\n rUSDAddress,\n}: {\n accountBalances: Map<Address, number>;\n assetPrices: Map<Address, number>;\n markPrices: Map<Address, number>;\n marketsTokenInfo: Map<\n MarketId,\n {\n quoteTokenId: string;\n underlyingAssetId: string;\n }\n >;\n marketsTrackers: Map<\n MarketId,\n {\n longADLUnwindPrice: number;\n longBaseMultiplier: number;\n longFundingValue: number;\n shortADLUnwindPrice: number;\n shortBaseMultiplier: number;\n shortFundingValue: number;\n }\n >;\n positions: {\n adlUnwindPrice: number;\n base: number;\n baseMultiplier: number;\n fundingValue: number;\n lastPrice: number;\n marketId: string;\n realizedPnl: number;\n }[];\n rUSDAddress?: string;\n}) => {\n const pnl = new Map<Address, number>();\n const rUSDPrice = (rUSDAddress && assetPrices.get(rUSDAddress)) ?? 1;\n positions.forEach((position) => {\n const marketTracker = marketsTrackers?.get(position.marketId);\n const tokenInfo = marketsTokenInfo.get(position.marketId);\n if (!tokenInfo) return;\n let fundingCashFlow = 0;\n let adlCashFlow = 0;\n\n // Mirrors calculateSettledPositionPnl: a flat position accrues nothing, and\n // a zero position multiplier (reopened after full ADL) cannot be divided by,\n // so only realized and mark PnL count for it.\n if (marketTracker && position.base !== 0 && position.baseMultiplier > 0) {\n // fundingCashFlow\n const marketTrackerFundingValue =\n position.base < 0\n ? marketTracker.shortFundingValue\n : marketTracker.longFundingValue;\n const trackerDelta = marketTrackerFundingValue - position.fundingValue;\n fundingCashFlow =\n (trackerDelta / position.baseMultiplier) * -1 * position.base;\n\n // adlCashFlow\n const adlUnwindPrice =\n ((position.base < 0\n ? marketTracker.shortADLUnwindPrice\n : marketTracker.longADLUnwindPrice) -\n position.adlUnwindPrice) /\n position.baseMultiplier;\n const baseMultiplier =\n (position.base < 0\n ? marketTracker.shortBaseMultiplier\n : marketTracker.longBaseMultiplier) / position.baseMultiplier;\n const lastPriceCoefficient = 1 - baseMultiplier;\n const initialPrice = lastPriceCoefficient * position.lastPrice;\n adlCashFlow = (adlUnwindPrice - initialPrice) * position.base;\n }\n\n // The underlying supplies the mark; all position cashflows are in the quote token.\n // A missing mark means \"no price for this bucket\", not a price of zero:\n // carry the position at its last price rather than swinging by its notional.\n const markPrice = markPrices.get(tokenInfo.underlyingAssetId);\n const unrealizedPnl =\n markPrice === undefined\n ? 0\n : (markPrice - position.lastPrice) * position.base;\n\n pnl.set(\n tokenInfo.quoteTokenId,\n (pnl.get(tokenInfo.quoteTokenId) ?? 0) +\n position.realizedPnl +\n fundingCashFlow +\n adlCashFlow +\n unrealizedPnl,\n );\n });\n\n // A quote-token PnL balance can exist without a collateral deposit row.\n const assets = new Set([\n ...Array.from(accountBalances.keys()),\n ...Array.from(pnl.keys()),\n ]);\n return Array.from(assets).reduce(\n (sum, address) =>\n sum +\n ((accountBalances.get(address) ?? 0) + (pnl.get(address) ?? 0)) *\n (address === rUSDAddress\n ? 1\n : (assetPrices.get(address) ?? 0) / (rUSDPrice || 1)),\n 0,\n );\n};\n\nexport const calculateFundingPnl = ({\n marketFundingValue,\n marketBaseMultiplier,\n positionAvgEntryFundingValue,\n positionAdjustedBase,\n}: {\n marketFundingValue: number;\n marketBaseMultiplier: number;\n positionAvgEntryFundingValue: number;\n positionAdjustedBase: number;\n}): number => {\n return (\n -1 *\n (((marketFundingValue - positionAvgEntryFundingValue) *\n positionAdjustedBase) /\n marketBaseMultiplier)\n );\n};\n\nexport const calculatePricePnl = ({\n price,\n positionAvgEntryPrice,\n positionAdjustedBase,\n}: {\n price: number;\n positionAvgEntryPrice: number;\n positionAdjustedBase: number;\n}): number => {\n return (price - positionAvgEntryPrice) * positionAdjustedBase;\n};\n\nexport const calculateRealBalance = (\n netDeposits: BigNumber,\n realized_pnl: BigNumber,\n) => {\n return netDeposits.plus(realized_pnl);\n};\n\nexport const calculatePositionAdjustedQty = (\n origQty: BigNumber,\n marketBaseMultiplier: BigNumber,\n positionBaseMultiplier: BigNumber,\n): BigNumber => {\n return origQty.times(marketBaseMultiplier).div(positionBaseMultiplier);\n};\n\n/**\n * Linearly interpolate a depth ratio from a (thresholds, ratios) curve.\n * The curve implicitly starts at (exposure=0, ratio=1.0).\n * - Between thresholds: linear interpolation\n * - Above last threshold: last ratio (flat extrapolation)\n *\n * @param thresholds - Sorted ascending exposure thresholds in notional USD (must be non-empty)\n * @param ratios - Depth ratio at each threshold (same length as thresholds, must be non-empty)\n * @param exposure - Absolute exposure notional (must be >= 0)\n * @throws if thresholds or ratios are empty, or if they have different lengths\n */\nexport const interpolateDepthRatio = (\n thresholds: number[],\n ratios: number[],\n exposure: number,\n): number => {\n if (exposure < 0) {\n throw new Error('interpolateDepthRatio: exposure must be >= 0');\n }\n if (thresholds.length === 0 || ratios.length === 0) {\n throw new Error(\n 'interpolateDepthRatio: thresholds and ratios must be non-empty',\n );\n }\n if (thresholds.length !== ratios.length) {\n throw new Error(\n 'interpolateDepthRatio: thresholds and ratios must have equal length',\n );\n }\n\n const allThresholds = [0, ...thresholds];\n const allRatios = [1.0, ...ratios];\n\n if (exposure === 0) return 1.0;\n if (exposure >= allThresholds[allThresholds.length - 1]) {\n return allRatios[allRatios.length - 1];\n }\n\n for (let i = 0; i < allThresholds.length - 1; i++) {\n if (exposure <= allThresholds[i + 1]) {\n const t =\n (exposure - allThresholds[i]) /\n (allThresholds[i + 1] - allThresholds[i]);\n return allRatios[i] + t * (allRatios[i + 1] - allRatios[i]);\n }\n }\n\n throw new Error('interpolateDepthRatio: unreachable');\n};\n\n/**\n * Calculate the dynamic depth factor for a trade given pool state and config.\n *\n * The pool takes the opposite side of the trade, so:\n * poolNotionalAfterTrade = currentPoolNotional - signedTradeNotional\n *\n * The depth ratio is interpolated from the exposure curve, then multiplied\n * by baseDepth to produce the final depth factor.\n *\n * @param baseDepth - Base depth multiplier for this market\n * @param thresholds - Sorted ascending exposure thresholds (notional USD)\n * @param ratios - Depth ratio at each threshold\n * @param currentPoolNotional - Pool's current notional in this market (signed)\n * @param signedTradeNotional - Trade notional (positive=buy, negative=sell)\n */\nexport const calculateDynamicDepthFactor = ({\n baseDepth,\n thresholds,\n ratios,\n currentPoolNotional,\n signedTradeNotional,\n}: {\n baseDepth: number;\n thresholds: number[];\n ratios: number[];\n currentPoolNotional: number;\n signedTradeNotional: number;\n}): number => {\n const poolNotionalAfterTrade = currentPoolNotional - signedTradeNotional;\n const absExposureNotional = Math.abs(poolNotionalAfterTrade);\n const depthRatio = interpolateDepthRatio(\n thresholds,\n ratios,\n absExposureNotional,\n );\n return depthRatio * baseDepth;\n};\n\nexport const calculatePositionAdlPnL = ({\n marketTrackerAdlUnwindPrice,\n marketTrackerBaseMultiplier,\n positionBase,\n positionAvgEntryPrice,\n positionTrackerBaseMultiplier,\n positionTrackerAdlUnwindPrice,\n}: {\n marketTrackerAdlUnwindPrice: BigNumber;\n marketTrackerBaseMultiplier: BigNumber;\n positionBase: BigNumber;\n positionAvgEntryPrice: BigNumber;\n positionTrackerBaseMultiplier: BigNumber;\n positionTrackerAdlUnwindPrice: BigNumber;\n}): BigNumber => {\n const currentAdlUnwindPrice = marketTrackerAdlUnwindPrice\n .minus(positionTrackerAdlUnwindPrice)\n .multipliedBy(1e18)\n .div(positionTrackerBaseMultiplier);\n\n const initialPrice = positionAvgEntryPrice\n .times(\n BigNumber(1e18).minus(\n marketTrackerBaseMultiplier\n .multipliedBy(1e18)\n .div(positionTrackerBaseMultiplier),\n ),\n )\n .div(1e18);\n\n const adlPnL = positionBase\n .times(currentAdlUnwindPrice.minus(initialPrice))\n .div(1e18);\n\n return adlPnL;\n};\n"]}
@@ -1,7 +1,6 @@
1
1
  "use strict";
2
- var _a;
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
- exports.getPoolAccountId = exports.REYA_DEX_ID = exports.applySocketFeeBuffer = exports.SOCKET_EMPTY_PAYLOAD_SIZE = exports.SOCKET_BRIDGE_IN_MSG_GAS_LIMIT = exports.MA_HEALTH_WARNING_THRESHOLD = exports.MA_HEALTH_DANGER_THRESHOLD = exports.SPECIAL_TIER_THRESHOLD = exports.TIER_TYPE_MAP = exports.VOLUME_TIER_MAP = exports.VOLUME_LOOKBACK_WINDOW_IN_SECONDS = exports.TRADING_LOTTERY_BOOST = exports.INSTANT_TRADING_RATE_XP = exports.conditionalOrderTypeNames = exports.RANKS_TRADING = exports.RANKS = exports.WHITELISTED_WALLETS = exports.CHANNEL_NAME = exports.ONE_DAY_IN_SECONDS = exports.API_TIMEOUT = exports.MAX_UINT128 = void 0;
3
+ exports.getPoolAccountId = exports.REYA_DEX_ID = exports.applySocketFeeBuffer = exports.SOCKET_EMPTY_PAYLOAD_SIZE = exports.SOCKET_BRIDGE_IN_MSG_GAS_LIMIT = exports.MA_HEALTH_WARNING_THRESHOLD = exports.MA_HEALTH_DANGER_THRESHOLD = exports.SPECIAL_TIER_THRESHOLD = exports.TIER_TYPE_MAP = exports.FEE_TIER_VOLUME_LOOKBACK_WINDOW_IN_SECONDS = exports.VOLUME_TIER_MAP = exports.VOLUME_LOOKBACK_WINDOW_IN_SECONDS = exports.TRADING_LOTTERY_BOOST = exports.INSTANT_TRADING_RATE_XP = exports.RANKS_TRADING = exports.RANKS = exports.WHITELISTED_WALLETS = exports.CHANNEL_NAME = exports.ONE_DAY_IN_SECONDS = exports.API_TIMEOUT = exports.MAX_UINT128 = void 0;
5
4
  var types_1 = require("../types");
6
5
  exports.MAX_UINT128 = Math.pow(2, 128) - 1;
7
6
  exports.API_TIMEOUT = 2500;
@@ -102,11 +101,6 @@ exports.RANKS_TRADING = {
102
101
  rankName: 'Achilles',
103
102
  },
104
103
  };
105
- exports.conditionalOrderTypeNames = (_a = {},
106
- _a[types_1.ConditionalOrderType.STOP_LOSS] = 'Stop Loss',
107
- _a[types_1.ConditionalOrderType.TAKE_PROFIT] = 'Take Profit',
108
- _a[types_1.ConditionalOrderType.LIMIT_ORDER] = 'Limit Order',
109
- _a);
110
104
  exports.INSTANT_TRADING_RATE_XP = 2;
111
105
  exports.TRADING_LOTTERY_BOOST = 10;
112
106
  exports.VOLUME_LOOKBACK_WINDOW_IN_SECONDS = 30 * 24 * 60 * 60;
@@ -119,6 +113,7 @@ exports.VOLUME_TIER_MAP = {
119
113
  5: 1000000000, // Tier 5: $1,000,000,000 volume
120
114
  6: 5000000000, // Tier 6: $5,000,000,000 volume
121
115
  };
116
+ exports.FEE_TIER_VOLUME_LOOKBACK_WINDOW_IN_SECONDS = 30 * exports.ONE_DAY_IN_SECONDS;
122
117
  exports.TIER_TYPE_MAP = {
123
118
  0: types_1.TierType.REGULAR,
124
119
  1: types_1.TierType.REGULAR,
@@ -1 +1 @@
1
- {"version":3,"file":"consts.js","sourceRoot":"/","sources":["utils/consts.ts"],"names":[],"mappings":";;;;AAAA,kCAMkB;AAEL,QAAA,WAAW,GAAG,SAAA,CAAC,EAAI,GAAG,CAAA,GAAG,CAAC,CAAC;AAC3B,QAAA,WAAW,GAAW,IAAI,CAAC;AAE3B,QAAA,kBAAkB,GAAW,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;AAE1C,QAAA,YAAY,GAAG,eAAwB,CAAC;AAExC,QAAA,mBAAmB,GAAG;IACjC,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C,EAAE,mCAAmC;IACjF,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C,EAAE,mBAAmB;IACjE,4CAA4C,EAAE,UAAU;IACxD,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C,EAAE,SAAS;CACxD,CAAC;AAEW,QAAA,KAAK,GAAyB;IACzC,CAAC,EAAE;QACD,UAAU,EAAE,CAAC;QACb,QAAQ,EAAE,EAAE;QACZ,UAAU,EAAE,EAAE;KACf;IACD,CAAC,EAAE;QACD,UAAU,EAAE,CAAC;QACb,QAAQ,EAAE,OAAO;QACjB,UAAU,EAAE,GAAG;KAChB;IACD,CAAC,EAAE;QACD,UAAU,EAAE,CAAC;QACb,QAAQ,EAAE,MAAM;QAChB,UAAU,EAAE,GAAG;KAChB;IACD,CAAC,EAAE;QACD,UAAU,EAAE,CAAC;QACb,QAAQ,EAAE,OAAO;QACjB,UAAU,EAAE,GAAG;KAChB;IACD,CAA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AAC,YAAqB;IACpD,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9B,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B","sourcesContent":["import {\n ConditionalOrderType,\n ConditionalOrderTypeName,\n Rank,\n RankTrading,\n TierType,\n} from '../types';\n\nexport const MAX_UINT128 = 2 ** 128 - 1;\nexport const API_TIMEOUT: number = 2500;\n\nexport const ONE_DAY_IN_SECONDS: number = 60 * 60 * 24;\n\nexport const CHANNEL_NAME = 'redis-pub-sub' as const;\n\nexport const WHITELISTED_WALLETS = [\n '0xE116e2c0c2B0e7cd88060F06e2b2D7981Ef897ef',\n '0xb9db1789e8998eEDB6a53348Fe57Dcd080405cD4',\n '0x9A47F123916fC4745aCC6868D88450DC6056d335',\n '0x8d24B1663E80B4d1aB85e6B710Cd9178e475fd60',\n '0x1A0E5AbE817FDC9C000176183FA54e4B86940a83',\n '0x2b38d2d4FEcf085Eb7552607b5A5D631180015D6',\n '0xFcC63268172cDcf1Ae6D9dC572a10d0De7303C92',\n '0xDa0aA49cA0ca58939b76BaeCDcbfDb04b40CF6e8',\n '0xe33340635435BCA1E7686af89971D23525b2d8F8',\n '0xF8F6B70a36f4398f0853a311dC6699Aba8333Cc1', // internal dev account for testing\n '0x564aa5a2e98bdfcb876e8bcce129c18b6f052a0d',\n '0xaE173a960084903b1d278Ff9E3A81DeD82275556',\n '0x7aa47a9737395ae9e98E8b25aC97ee04b205dC22',\n '0xfd4295c1a0b07e6b706f0ab83dc9eb461b7f17b3', // input from simon\n '0x2fa11ef008c4b585ccf0a76861794ac7ae5a3a67', // brokoli\n '0x423063ed854736ae151B79032e4275AB57245173',\n '0xb89b383C26c2514907b6De5B6df96b2d97f425eC',\n '0x6C51275FD01d5DbD2DA194E92f920f8598306dF2', // Daniel\n];\n\nexport const RANKS: Record<number, Rank> = {\n 0: {\n rankNumber: 0,\n rankName: '',\n rankLetter: '',\n },\n 1: {\n rankNumber: 1,\n rankName: 'Alpha',\n rankLetter: 'α',\n },\n 2: {\n rankNumber: 2,\n rankName: 'Beta',\n rankLetter: 'β',\n },\n 3: {\n rankNumber: 3,\n rankName: 'Gamma',\n rankLetter: 'γ',\n },\n 4: {\n rankNumber: 4,\n rankName: 'Delta',\n rankLetter: 'δ',\n },\n 5: {\n rankNumber: 5,\n rankName: 'Epsilon',\n rankLetter: 'ε',\n },\n 6: {\n rankNumber: 6,\n rankName: 'Zeta',\n rankLetter: 'ζ',\n },\n 7: {\n rankNumber: 7,\n rankName: 'Eta',\n rankLetter: 'η',\n },\n 8: {\n rankNumber: 8,\n rankName: 'Theta',\n rankLetter: 'θ',\n },\n 9: {\n rankNumber: 9,\n rankName: 'Iota',\n rankLetter: 'ι',\n },\n 10: {\n rankNumber: 10,\n rankName: 'Kappa',\n rankLetter: 'κ',\n },\n};\n\nexport const RANKS_TRADING: Record<number, RankTrading> = {\n 0: {\n rankNumber: 0,\n rankName: '',\n },\n 1: {\n rankNumber: 1,\n rankName: 'Heracles',\n },\n 2: {\n rankNumber: 2,\n rankName: 'Perseus',\n },\n 3: {\n rankNumber: 3,\n rankName: 'Achilles',\n },\n};\n\nexport const conditionalOrderTypeNames: Record<\n ConditionalOrderType,\n ConditionalOrderTypeName\n> = {\n [ConditionalOrderType.STOP_LOSS]: 'Stop Loss',\n [ConditionalOrderType.TAKE_PROFIT]: 'Take Profit',\n [ConditionalOrderType.LIMIT_ORDER]: 'Limit Order',\n};\n\nexport const INSTANT_TRADING_RATE_XP = 2;\nexport const TRADING_LOTTERY_BOOST = 10;\n\nexport const VOLUME_LOOKBACK_WINDOW_IN_SECONDS = 30 * 24 * 60 * 60;\n\nexport const VOLUME_TIER_MAP: Record<number, number> = {\n 0: 0, // Tier 0: $0 volume\n 1: 1_000_000, // Tier 1: $1,000,000 volume\n 2: 10_000_000, // Tier 2: $10,000,000 volume\n 3: 50_000_000, // Tier 3: $50,000,000 volume\n 4: 250_000_000, // Tier 4: $250,000,000 volume\n 5: 1_000_000_000, // Tier 5: $1,000,000,000 volume\n 6: 5_000_000_000, // Tier 6: $5,000,000,000 volume\n};\n\nexport const TIER_TYPE_MAP: Record<number, TierType> = {\n 0: TierType.REGULAR,\n 1: TierType.REGULAR,\n 2: TierType.REGULAR,\n 3: TierType.REGULAR,\n 4: TierType.REGULAR,\n 5: TierType.REGULAR,\n 6: TierType.REGULAR,\n 100: TierType.VIP,\n 101: TierType.VIP,\n};\n\nexport const SPECIAL_TIER_THRESHOLD = 100;\n\nexport const MA_HEALTH_DANGER_THRESHOLD = 95;\nexport const MA_HEALTH_WARNING_THRESHOLD = 80;\n\nexport const SOCKET_BRIDGE_IN_MSG_GAS_LIMIT = BigInt('50000000');\nexport const SOCKET_EMPTY_PAYLOAD_SIZE = 160;\nexport const applySocketFeeBuffer = (fees: bigint): bigint => {\n // apply 10% buffer\n return (fees * BigInt(110)) / BigInt(100);\n};\n\nexport const REYA_DEX_ID = 2;\n\nexport const getPoolAccountId = (isProduction: boolean): number => {\n return isProduction ? 2 : 4;\n};\n"]}
1
+ {"version":3,"file":"consts.js","sourceRoot":"/","sources":["utils/consts.ts"],"names":[],"mappings":";;;AAAA,kCAAuD;AAE1C,QAAA,WAAW,GAAG,SAAA,CAAC,EAAI,GAAG,CAAA,GAAG,CAAC,CAAC;AAC3B,QAAA,WAAW,GAAW,IAAI,CAAC;AAE3B,QAAA,kBAAkB,GAAW,EAAE,GAAG,EAAE,GAAG,EAAE,CAAC;AAE1C,QAAA,YAAY,GAAG,eAAwB,CAAC;AAExC,QAAA,mBAAmB,GAAG;IACjC,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C,EAAE,mCAAmC;IACjF,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C;IAC5C,4CAA4C,EAAE,mBAAmB;IACjE,4CAA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BAA2B,GAAG,EAAE,CAAC;AAEjC,QAAA,8BAA8B,GAAG,MAAM,CAAC,UAAU,CAAC,CAAC;AACpD,QAAA,yBAAyB,GAAG,GAAG,CAAC;AACtC,IAAM,oBAAoB,GAAG,UAAC,IAAY;IAC/C,mBAAmB;IACnB,OAAO,CAAC,IAAI,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC,GAAG,MAAM,CAAC,GAAG,CAAC,CAAC;AAC5C,CAAC,CAAC;AAHW,QAAA,oBAAoB,wBAG/B;AAEW,QAAA,WAAW,GAAG,CAAC,CAAC;AAEtB,IAAM,gBAAgB,GAAG,UAAC,YAAqB;IACpD,OAAO,YAAY,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAC9B,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B","sourcesContent":["import { Rank, RankTrading, TierType } from '../types';\n\nexport const MAX_UINT128 = 2 ** 128 - 1;\nexport const API_TIMEOUT: number = 2500;\n\nexport const ONE_DAY_IN_SECONDS: number = 60 * 60 * 24;\n\nexport const CHANNEL_NAME = 'redis-pub-sub' as const;\n\nexport const WHITELISTED_WALLETS = [\n '0xE116e2c0c2B0e7cd88060F06e2b2D7981Ef897ef',\n '0xb9db1789e8998eEDB6a53348Fe57Dcd080405cD4',\n '0x9A47F123916fC4745aCC6868D88450DC6056d335',\n '0x8d24B1663E80B4d1aB85e6B710Cd9178e475fd60',\n '0x1A0E5AbE817FDC9C000176183FA54e4B86940a83',\n '0x2b38d2d4FEcf085Eb7552607b5A5D631180015D6',\n '0xFcC63268172cDcf1Ae6D9dC572a10d0De7303C92',\n '0xDa0aA49cA0ca58939b76BaeCDcbfDb04b40CF6e8',\n '0xe33340635435BCA1E7686af89971D23525b2d8F8',\n '0xF8F6B70a36f4398f0853a311dC6699Aba8333Cc1', // internal dev account for testing\n '0x564aa5a2e98bdfcb876e8bcce129c18b6f052a0d',\n '0xaE173a960084903b1d278Ff9E3A81DeD82275556',\n '0x7aa47a9737395ae9e98E8b25aC97ee04b205dC22',\n '0xfd4295c1a0b07e6b706f0ab83dc9eb461b7f17b3', // input from simon\n '0x2fa11ef008c4b585ccf0a76861794ac7ae5a3a67', // brokoli\n '0x423063ed854736ae151B79032e4275AB57245173',\n '0xb89b383C26c2514907b6De5B6df96b2d97f425eC',\n '0x6C51275FD01d5DbD2DA194E92f920f8598306dF2', // Daniel\n];\n\nexport const RANKS: Record<number, Rank> = {\n 0: {\n rankNumber: 0,\n rankName: '',\n rankLetter: '',\n },\n 1: {\n rankNumber: 1,\n rankName: 'Alpha',\n rankLetter: 'α',\n },\n 2: {\n rankNumber: 2,\n rankName: 'Beta',\n rankLetter: 'β',\n },\n 3: {\n rankNumber: 3,\n rankName: 'Gamma',\n rankLetter: 'γ',\n },\n 4: {\n rankNumber: 4,\n rankName: 'Delta',\n rankLetter: 'δ',\n },\n 5: {\n rankNumber: 5,\n rankName: 'Epsilon',\n rankLetter: 'ε',\n },\n 6: {\n rankNumber: 6,\n rankName: 'Zeta',\n rankLetter: 'ζ',\n },\n 7: {\n rankNumber: 7,\n rankName: 'Eta',\n rankLetter: 'η',\n },\n 8: {\n rankNumber: 8,\n rankName: 'Theta',\n rankLetter: 'θ',\n },\n 9: {\n rankNumber: 9,\n rankName: 'Iota',\n rankLetter: 'ι',\n },\n 10: {\n rankNumber: 10,\n rankName: 'Kappa',\n rankLetter: 'κ',\n },\n};\n\nexport const RANKS_TRADING: Record<number, RankTrading> = {\n 0: {\n rankNumber: 0,\n rankName: '',\n },\n 1: {\n rankNumber: 1,\n rankName: 'Heracles',\n },\n 2: {\n rankNumber: 2,\n rankName: 'Perseus',\n },\n 3: {\n rankNumber: 3,\n rankName: 'Achilles',\n },\n};\n\nexport const INSTANT_TRADING_RATE_XP = 2;\nexport const TRADING_LOTTERY_BOOST = 10;\n\nexport const VOLUME_LOOKBACK_WINDOW_IN_SECONDS = 30 * 24 * 60 * 60;\n\nexport const VOLUME_TIER_MAP: Record<number, number> = {\n 0: 0, // Tier 0: $0 volume\n 1: 1_000_000, // Tier 1: $1,000,000 volume\n 2: 10_000_000, // Tier 2: $10,000,000 volume\n 3: 50_000_000, // Tier 3: $50,000,000 volume\n 4: 250_000_000, // Tier 4: $250,000,000 volume\n 5: 1_000_000_000, // Tier 5: $1,000,000,000 volume\n 6: 5_000_000_000, // Tier 6: $5,000,000,000 volume\n};\n\nexport const FEE_TIER_VOLUME_LOOKBACK_WINDOW_IN_SECONDS =\n 30 * ONE_DAY_IN_SECONDS;\n\nexport const TIER_TYPE_MAP: Record<number, TierType> = {\n 0: TierType.REGULAR,\n 1: TierType.REGULAR,\n 2: TierType.REGULAR,\n 3: TierType.REGULAR,\n 4: TierType.REGULAR,\n 5: TierType.REGULAR,\n 6: TierType.REGULAR,\n 100: TierType.VIP,\n 101: TierType.VIP,\n};\n\nexport const SPECIAL_TIER_THRESHOLD = 100;\n\nexport const MA_HEALTH_DANGER_THRESHOLD = 95;\nexport const MA_HEALTH_WARNING_THRESHOLD = 80;\n\nexport const SOCKET_BRIDGE_IN_MSG_GAS_LIMIT = BigInt('50000000');\nexport const SOCKET_EMPTY_PAYLOAD_SIZE = 160;\nexport const applySocketFeeBuffer = (fees: bigint): bigint => {\n // apply 10% buffer\n return (fees * BigInt(110)) / BigInt(100);\n};\n\nexport const REYA_DEX_ID = 2;\n\nexport const getPoolAccountId = (isProduction: boolean): number => {\n return isProduction ? 2 : 4;\n};\n"]}