@reyaxyz/common 0.364.0 → 0.364.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/types.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"/","sources":["types.ts"],"names":[],"mappings":"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","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"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"/","sources":["types.ts"],"names":[],"mappings":"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","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 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"]}
@@ -12,10 +12,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
12
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.calculatePositionAdlPnL = exports.calculateDynamicDepthFactor = exports.interpolateDepthRatio = exports.calculatePositionAdjustedQty = exports.calculateRealBalance = exports.calculatePricePnl = exports.calculateFundingPnl = exports.calculateTotalMargin = exports.calculateMarginRatio = exports.calculateLMR = exports.calculateIMR = exports.calculateMaxOrderSize = exports.calculateRequiredMargin = exports.calculateLeverage = exports.calculateEstimatedLiquidationPrice = exports.calculateSpread = exports.calculateTradeFee = exports.calculateEstimatedExecutionPrice = exports.computeNewLogF = exports.splitTradeExposure = exports.calculateMaxExposure = exports.calculateMaxWithdraw = exports.POOL_IMR = void 0;
15
+ exports.calculatePositionAdlPnL = exports.calculatePositionAdjustedQty = exports.calculateRealBalance = exports.calculatePricePnl = exports.calculateFundingPnl = exports.calculateTotalMargin = exports.calculateLMR = exports.calculateIMR = exports.calculateRequiredMargin = exports.calculateLeverage = exports.calculateTradeFee = exports.calculateMaxWithdraw = void 0;
16
16
  var struct_1 = require("./struct");
17
17
  var bignumber_js_1 = __importDefault(require("bignumber.js"));
18
- exports.POOL_IMR = 9.1;
19
18
  /**
20
19
  * Calculates the maximum amount that can be withdrawn in terms of the token
21
20
  * (e.g., if rUSD then in rUSD terms, if WETH then in WETH terms)
@@ -36,117 +35,11 @@ var calculateMaxWithdraw = function (_a) {
36
35
  return Math.max(0, Math.min(realBalance, maxFromMargin));
37
36
  };
38
37
  exports.calculateMaxWithdraw = calculateMaxWithdraw;
39
- var calculateMaxExposure = function (_a) {
40
- var poolBalance = _a.poolBalance, riskFactor = _a.riskFactor, _b = _a.poolIMR, poolIMR = _b === void 0 ? exports.POOL_IMR : _b;
41
- return poolBalance / (poolIMR * Math.sqrt(riskFactor));
42
- };
43
- exports.calculateMaxExposure = calculateMaxExposure;
44
- /**
45
- * Splits a trade exposure into rebalancing and unbalancing portions relative to pool net exposure.
46
- * Rebalancing reduces pool's absolute exposure; unbalancing increases it.
47
- */
48
- var splitTradeExposure = function (tradeExposure, poolNetExposure) {
49
- if (tradeExposure === 0) {
50
- return { rebalancing: 0, unbalancing: 0 };
51
- }
52
- // If pool has no exposure, entire trade is unbalancing
53
- if (poolNetExposure === 0) {
54
- return { rebalancing: 0, unbalancing: tradeExposure };
55
- }
56
- // Opposite sign means trade increases pool exposure → pure unbalancing
57
- var sameSign = (poolNetExposure > 0 && tradeExposure > 0) ||
58
- (poolNetExposure < 0 && tradeExposure < 0);
59
- if (!sameSign) {
60
- return { rebalancing: 0, unbalancing: tradeExposure };
61
- }
62
- // Same sign: trade reduces pool exposure (pool takes opposite side)
63
- var absPool = Math.abs(poolNetExposure);
64
- var absTrade = Math.abs(tradeExposure);
65
- if (absTrade <= absPool) {
66
- // Pure rebalancing — trade doesn't cross zero
67
- return { rebalancing: tradeExposure, unbalancing: 0 };
68
- }
69
- // Mixed: rebalance up to pool exposure, then unbalance the rest
70
- var rebalancing = poolNetExposure;
71
- var unbalancing = tradeExposure - rebalancing;
72
- return { rebalancing: rebalancing, unbalancing: unbalancing };
73
- };
74
- exports.splitTradeExposure = splitTradeExposure;
75
- /**
76
- * Computes the new log price multiplier (logF) after a trade, handling both
77
- * rebalancing and unbalancing portions.
78
- *
79
- * Mirrors on-chain logic in PriceMultiplier.sol:computeNewLogPriceMultiplier.
80
- */
81
- var computeNewLogF = function (_a) {
82
- var currentLogF = _a.currentLogF, tradeExposure = _a.tradeExposure, poolNetExposure = _a.poolNetExposure, depthFactor = _a.depthFactor, maxExposure = _a.maxExposure;
83
- if (tradeExposure === 0)
84
- return currentLogF;
85
- var _b = (0, exports.splitTradeExposure)(tradeExposure, poolNetExposure), rebalancing = _b.rebalancing, unbalancing = _b.unbalancing;
86
- // Case 1: Has unbalancing portion (includes mixed trades)
87
- if (unbalancing !== 0) {
88
- // If also rebalancing, it brings logF to 0 by definition (trade crosses zero)
89
- var startLogF = rebalancing === 0 ? currentLogF : 0;
90
- return startLogF + unbalancing / (depthFactor * maxExposure);
91
- }
92
- // Case 2: Only rebalancing
93
- // Both rebalancing and poolNetExposure have the same sign, so ratio is in [0, 1]
94
- if (rebalancing !== 0 && poolNetExposure !== 0) {
95
- var ratio = rebalancing / poolNetExposure;
96
- return currentLogF * (1 - ratio);
97
- }
98
- return currentLogF;
99
- };
100
- exports.computeNewLogF = computeNewLogF;
101
- /**
102
- * Estimates the execution price for a trade using the exponential logPriceMultiplier formula.
103
- *
104
- * Mirrors on-chain logic:
105
- * 1. computeNewLogPriceMultiplier (PriceMultiplier.sol)
106
- * 2. computeAmmPrice: ammPrice = oraclePrice * exp(logF)
107
- * 3. computeSignedSpread: executionPrice = ammPrice * (1 + signedSpread)
108
- *
109
- * @audit spreadDiscount not applied — known limitation, to be addressed later
110
- * @audit priceSpacing rounding not applied
111
- */
112
- var calculateEstimatedExecutionPrice = function (_a) {
113
- var oraclePrice = _a.oraclePrice, currentLogF = _a.currentLogF, tradeExposure = _a.tradeExposure, poolNetExposure = _a.poolNetExposure, depthFactor = _a.depthFactor, maxExposure = _a.maxExposure, priceSpread = _a.priceSpread;
114
- if (tradeExposure === 0) {
115
- return oraclePrice * Math.exp(currentLogF);
116
- }
117
- // 1. Compute new logF after trade impact
118
- var newLogF = (0, exports.computeNewLogF)({
119
- currentLogF: currentLogF,
120
- tradeExposure: tradeExposure,
121
- poolNetExposure: poolNetExposure,
122
- depthFactor: depthFactor,
123
- maxExposure: maxExposure,
124
- });
125
- // 2. Compute AMM price: oraclePrice * exp(newLogF)
126
- var ammPrice = oraclePrice * Math.exp(newLogF);
127
- // 3. Apply signed spread
128
- var signedSpread = tradeExposure > 0 ? priceSpread : -priceSpread;
129
- return Math.max(0, ammPrice * (1 + signedSpread));
130
- };
131
- exports.calculateEstimatedExecutionPrice = calculateEstimatedExecutionPrice;
132
38
  var calculateTradeFee = function (_a) {
133
39
  var feeRate = _a.feeRate, tradeNotional = _a.tradeNotional;
134
40
  return feeRate * Math.abs(tradeNotional);
135
41
  };
136
42
  exports.calculateTradeFee = calculateTradeFee;
137
- var calculateSpread = function (_a) {
138
- var depthFactor = _a.depthFactor, maxExposure = _a.maxExposure, oraclePrice = _a.oraclePrice, poolPrice = _a.poolPrice, tradeNotional = _a.tradeNotional;
139
- return (poolPrice / oraclePrice) *
140
- (1 + tradeNotional / (depthFactor * maxExposure) - 1) *
141
- tradeNotional;
142
- };
143
- exports.calculateSpread = calculateSpread;
144
- var calculateEstimatedLiquidationPrice = function (_a) {
145
- var LMR = _a.LMR, accountBalance = _a.accountBalance, isShort = _a.isShort, notional = _a.notional, oraclePrice = _a.oraclePrice;
146
- return Math.max(0, oraclePrice *
147
- (1 - ((accountBalance - LMR) / notional) * (isShort ? -1 : 1)));
148
- };
149
- exports.calculateEstimatedLiquidationPrice = calculateEstimatedLiquidationPrice;
150
43
  var calculateLeverage = function (_a) {
151
44
  var imrMultiplier = _a.imrMultiplier, riskFactor = _a.riskFactor;
152
45
  return 1 / (imrMultiplier * Math.sqrt(riskFactor));
@@ -159,146 +52,6 @@ var calculateRequiredMargin = function (_a) {
159
52
  leverage;
160
53
  };
161
54
  exports.calculateRequiredMargin = calculateRequiredMargin;
162
- /**
163
- * Calculates the maximum notional trade size (unsigned, always ≥ 0).
164
- *
165
- * Implements the UI quant spec v2 ("Maximum trade") with two cases:
166
- * Case 1 — Extending: trade same direction as existing position.
167
- * Case 2 — Reverting: decompose into (a) close position exactly, then
168
- * (b) extend from zero in the opposite direction.
169
- *
170
- * All quadratics use the unsigned convention (t = |tradeNotional|) so the
171
- * positive root always corresponds to the correct direction.
172
- */
173
- var calculateMaxOrderSize = function (_a) {
174
- var currIMR = _a.currIMR, currNodeBalance = _a.currNodeBalance, currNotional = _a.currNotional, depthFactor = _a.depthFactor, feeRate = _a.feeRate, isShortTrade = _a.isShortTrade, leverage = _a.leverage, maxExposure = _a.maxExposure, oraclePrice = _a.oraclePrice, poolPrice = _a.poolPrice, currentLogF = _a.currentLogF, netExposure = _a.netExposure;
175
- var D = depthFactor * maxExposure;
176
- var rho = poolPrice / oraclePrice;
177
- var tradeSign = isShortTrade ? -1 : 1;
178
- var s0 = currNotional > 0 ? 1 : currNotional < 0 ? -1 : tradeSign;
179
- var absN0 = Math.abs(currNotional);
180
- /**
181
- * Solve the extending quadratic (spec §Case 1) for max trade size.
182
- * a·t² + b·t + c = 0 where a = ρ·γ, b = s₀·(1/lev + fee) + (ρ−1), c = −surplus.
183
- * Root selection: pick the root whose sign matches s₀ (dir).
184
- * For rebalancing (a < 0), caps at |NE| (beyond which γ switches to unbalancing).
185
- */
186
- var solveExtending = function (dir, surplus, // aka, IMRDelta
187
- rho_, gamma_, isRebal, absNE) {
188
- if (surplus <= 0)
189
- return 0;
190
- var a = rho_ * gamma_;
191
- var b = dir * (1 / leverage + feeRate) + (rho_ - 1);
192
- var c = -surplus;
193
- // Degenerate: γ = 0 → linear equation b·t + c = 0 (rebalancing with f = 0)
194
- if (a === 0) {
195
- if (b === 0)
196
- return isRebal ? absNE : 0;
197
- var t_1 = -c / b;
198
- if (t_1 * dir <= 0)
199
- return isRebal ? absNE : 0;
200
- return isRebal ? Math.min(Math.abs(t_1), absNE) : Math.abs(t_1);
201
- }
202
- var disc = b * b - 4 * a * c;
203
- if (isRebal) {
204
- if (disc < 0)
205
- return absNE;
206
- var t_2 = (-b + dir * Math.sqrt(disc)) / (2 * a);
207
- return t_2 * dir <= 0 ? absNE : Math.min(Math.abs(t_2), absNE);
208
- }
209
- if (disc < 0)
210
- throw new Error("calculateMaxOrderSize: negative discriminant (".concat(disc, ")"));
211
- var t = (-b + dir * Math.sqrt(disc)) / (2 * a);
212
- if (t * dir <= 0)
213
- throw new Error("calculateMaxOrderSize: no valid root (".concat(t, ")"));
214
- return Math.abs(t);
215
- };
216
- // Determine γ for a trade of given direction against the current pool state
217
- var getGamma = function (dir, logF, ne) {
218
- var isRebal = ne !== 0 && dir === Math.sign(ne);
219
- var gamma = isRebal ? -logF / ne : 1 / D;
220
- return { gamma: gamma, isRebal: isRebal };
221
- };
222
- /**
223
- * Like solveExtending, but when the rebalancing leg is capped at |NE|
224
- * (pool-flip), continues with the unbalancing leg from NE = 0.
225
- *
226
- * For the exact rebalancing trade to NE = 0:
227
- * execRatio = ρ·exp(γ·dir·|NE|) = exp(f)·exp(−f) = 1
228
- * so only fee and IMR consume margin. Then extend with γ = 1/D and ρ' = 1.
229
- */
230
- var extendWithFlip = function (dir, surplus, rho_, gamma_, isRebal, absNE) {
231
- var result = solveExtending(dir, surplus, rho_, gamma_, isRebal, absNE);
232
- if (!isRebal || result < absNE || absNE === 0)
233
- return result;
234
- // Pool-flip: rebalancing consumed absNE, continue unbalancing from NE = 0
235
- var surplusAfter = surplus - absNE * (1 / leverage + feeRate);
236
- if (surplusAfter <= 0)
237
- return absNE;
238
- return absNE + solveExtending(dir, surplusAfter, 1, 1 / D, false, 0);
239
- };
240
- // ── Case 1: Extending ──────────────────────────────────────────────────
241
- if (tradeSign === s0) {
242
- var _b = getGamma(tradeSign, currentLogF, netExposure), gamma = _b.gamma, isRebal = _b.isRebal;
243
- return extendWithFlip(s0, currNodeBalance - currIMR, rho, gamma, isRebal, Math.abs(netExposure));
244
- }
245
- // ── Case 2: Reverting — close N₀, then re-extend ──────────────────────
246
- // Step 1: Close N₀ entirely (spec §Case 2, Step 1)
247
- var closeTrade = -currNotional;
248
- var closeDir = -s0;
249
- var _c = getGamma(closeDir, currentLogF, netExposure), gammaC = _c.gamma, closeIsRebal = _c.isRebal;
250
- var closeFlipsPool = closeIsRebal && absN0 > Math.abs(netExposure);
251
- // Exec price ratio: ρ·exp(γ_c·closeTrade) for non-flip, dedicated formula for flip
252
- var closeExecRatio = closeFlipsPool
253
- ? Math.exp((closeTrade - netExposure) / D)
254
- : rho * Math.exp(gammaC * closeTrade);
255
- var balClose = currNodeBalance - feeRate * absN0 + closeTrade * (1 - closeExecRatio);
256
- var imrClose = currIMR - absN0 / leverage;
257
- var surplusClose = balClose - imrClose;
258
- // Insolvency: can't fully close without going under margin.
259
- // Solve partial-close quadratic (spec appendix): b has flipped feeRate sign.
260
- // Falls back to full close (|N₀|) when no valid partial-close root exists.
261
- if (surplusClose <= 0) {
262
- var IMRDelta = currNodeBalance - currIMR;
263
- var gammaP = getGamma(closeDir, currentLogF, netExposure).gamma;
264
- var a = rho * gammaP;
265
- var b = s0 * (1 / leverage - feeRate) + (rho - 1);
266
- var c = -IMRDelta;
267
- if (a === 0) {
268
- if (b === 0)
269
- return absN0;
270
- var t_3 = -c / b;
271
- if (t_3 * closeDir <= 0)
272
- return absN0;
273
- return Math.min(Math.abs(t_3), absN0);
274
- }
275
- var disc = b * b - 4 * a * c;
276
- if (disc < 0)
277
- return absN0;
278
- var t = (-b + closeDir * Math.sqrt(disc)) / (2 * a);
279
- if (t * closeDir <= 0)
280
- return absN0;
281
- return Math.min(Math.abs(t), absN0);
282
- }
283
- // Step 2: Extend from zero in -s₀ direction with post-close pool state
284
- var neAfter = netExposure + currNotional;
285
- var fPrime;
286
- if (closeFlipsPool) {
287
- fPrime = (closeTrade - netExposure) / D;
288
- }
289
- else if (closeIsRebal) {
290
- fPrime = currentLogF * (1 + currNotional / netExposure);
291
- }
292
- else {
293
- fPrime = currentLogF + closeTrade / D;
294
- }
295
- var rhoPrime = Math.exp(fPrime);
296
- var extDir = -s0;
297
- var _d = getGamma(extDir, fPrime, neAfter), gammaPrime = _d.gamma, isExtRebal = _d.isRebal;
298
- return (absN0 +
299
- extendWithFlip(extDir, surplusClose, rhoPrime, gammaPrime, isExtRebal, Math.abs(neAfter)));
300
- };
301
- exports.calculateMaxOrderSize = calculateMaxOrderSize;
302
55
  var calculateIMR = function (_a) {
303
56
  var marketLeverages = _a.marketLeverages, marketPrices = _a.marketPrices, positions = _a.positions;
304
57
  return Array.from(positions.entries()).reduce(function (sum, _a) {
@@ -333,21 +86,6 @@ var calculateLMR = function (_a) {
333
86
  }, 0);
334
87
  };
335
88
  exports.calculateLMR = calculateLMR;
336
- // if account balance is below LMR position is liquidable
337
- var calculateMarginRatio = function (_a) {
338
- var LMR = _a.LMR, totalBalance = _a.totalBalance, tradeCost = _a.tradeCost;
339
- if (LMR === 0) {
340
- return 0;
341
- }
342
- if (tradeCost > totalBalance) {
343
- return 1;
344
- }
345
- if (totalBalance === tradeCost) {
346
- return Infinity;
347
- }
348
- return Math.min(1, LMR / (totalBalance - tradeCost));
349
- };
350
- exports.calculateMarginRatio = calculateMarginRatio;
351
89
  var calculateTotalMargin = function (_a) {
352
90
  var _b;
353
91
  var marketsTrackers = _a.marketsTrackers, accountBalances = _a.accountBalances, assetPrices = _a.assetPrices, markPrices = _a.markPrices, marketsTokenInfo = _a.marketsTokenInfo, positions = _a.positions, rUSDAddress = _a.rUSDAddress;
@@ -431,67 +169,6 @@ var calculatePositionAdjustedQty = function (origQty, marketBaseMultiplier, posi
431
169
  return origQty.times(marketBaseMultiplier).div(positionBaseMultiplier);
432
170
  };
433
171
  exports.calculatePositionAdjustedQty = calculatePositionAdjustedQty;
434
- /**
435
- * Linearly interpolate a depth ratio from a (thresholds, ratios) curve.
436
- * The curve implicitly starts at (exposure=0, ratio=1.0).
437
- * - Between thresholds: linear interpolation
438
- * - Above last threshold: last ratio (flat extrapolation)
439
- *
440
- * @param thresholds - Sorted ascending exposure thresholds in notional USD (must be non-empty)
441
- * @param ratios - Depth ratio at each threshold (same length as thresholds, must be non-empty)
442
- * @param exposure - Absolute exposure notional (must be >= 0)
443
- * @throws if thresholds or ratios are empty, or if they have different lengths
444
- */
445
- var interpolateDepthRatio = function (thresholds, ratios, exposure) {
446
- if (exposure < 0) {
447
- throw new Error('interpolateDepthRatio: exposure must be >= 0');
448
- }
449
- if (thresholds.length === 0 || ratios.length === 0) {
450
- throw new Error('interpolateDepthRatio: thresholds and ratios must be non-empty');
451
- }
452
- if (thresholds.length !== ratios.length) {
453
- throw new Error('interpolateDepthRatio: thresholds and ratios must have equal length');
454
- }
455
- var allThresholds = __spreadArray([0], thresholds, true);
456
- var allRatios = __spreadArray([1.0], ratios, true);
457
- if (exposure === 0)
458
- return 1.0;
459
- if (exposure >= allThresholds[allThresholds.length - 1]) {
460
- return allRatios[allRatios.length - 1];
461
- }
462
- for (var i = 0; i < allThresholds.length - 1; i++) {
463
- if (exposure <= allThresholds[i + 1]) {
464
- var t = (exposure - allThresholds[i]) /
465
- (allThresholds[i + 1] - allThresholds[i]);
466
- return allRatios[i] + t * (allRatios[i + 1] - allRatios[i]);
467
- }
468
- }
469
- throw new Error('interpolateDepthRatio: unreachable');
470
- };
471
- exports.interpolateDepthRatio = interpolateDepthRatio;
472
- /**
473
- * Calculate the dynamic depth factor for a trade given pool state and config.
474
- *
475
- * The pool takes the opposite side of the trade, so:
476
- * poolNotionalAfterTrade = currentPoolNotional - signedTradeNotional
477
- *
478
- * The depth ratio is interpolated from the exposure curve, then multiplied
479
- * by baseDepth to produce the final depth factor.
480
- *
481
- * @param baseDepth - Base depth multiplier for this market
482
- * @param thresholds - Sorted ascending exposure thresholds (notional USD)
483
- * @param ratios - Depth ratio at each threshold
484
- * @param currentPoolNotional - Pool's current notional in this market (signed)
485
- * @param signedTradeNotional - Trade notional (positive=buy, negative=sell)
486
- */
487
- var calculateDynamicDepthFactor = function (_a) {
488
- var baseDepth = _a.baseDepth, thresholds = _a.thresholds, ratios = _a.ratios, currentPoolNotional = _a.currentPoolNotional, signedTradeNotional = _a.signedTradeNotional;
489
- var poolNotionalAfterTrade = currentPoolNotional - signedTradeNotional;
490
- var absExposureNotional = Math.abs(poolNotionalAfterTrade);
491
- var depthRatio = (0, exports.interpolateDepthRatio)(thresholds, ratios, absExposureNotional);
492
- return depthRatio * baseDepth;
493
- };
494
- exports.calculateDynamicDepthFactor = calculateDynamicDepthFactor;
495
172
  var calculatePositionAdlPnL = function (_a) {
496
173
  var marketTrackerAdlUnwindPrice = _a.marketTrackerAdlUnwindPrice, marketTrackerBaseMultiplier = _a.marketTrackerBaseMultiplier, positionBase = _a.positionBase, positionAvgEntryPrice = _a.positionAvgEntryPrice, positionTrackerBaseMultiplier = _a.positionTrackerBaseMultiplier, positionTrackerAdlUnwindPrice = _a.positionTrackerAdlUnwindPrice;
497
174
  var currentAdlUnwindPrice = marketTrackerAdlUnwindPrice