serializableTypes.ts module provides serializable versions of Drift protocol data structures that can be safely transmitted over the network or stored in databases.
Overview
This module uses thecerializr library to provide automatic serialization and deserialization of complex types including:
- BigNum and BN (Big Number) types
- PublicKey types from Solana
- Enum types from the SDK
- Complex nested objects and arrays
Type Variants
Most types come in two variants:- Serializable - Basic serializable version with BN types
- UISerializable - UI-friendly version with BigNum types for display
Core Serialization Functions
The module exports serialization utilities through theCommonSerializationUtils object:
Order Types
SerializableOrder
Represents a single order in the Drift protocol. Properties:status: OrderStatus - Current order statusorderType: OrderType - Type of order (market, limit, etc.)ts: BN - TimestamporderId: number - Unique order IDuserOrderId: number - User-defined order IDmarketIndex: number - Market indexprice: BN - Order pricebaseAssetAmount: BN - Base asset amountbaseAssetAmountFilled: BN - Amount filledquoteAssetAmount: BN - Quote asset amountquoteAssetAmountFilled: BN - Quote amount filleddirection: PositionDirection - Long or shortreduceOnly: boolean - Reduce-only flagtriggerPrice: BN - Trigger price for conditional orderstriggerCondition: OrderTriggerCondition - Trigger conditionpostOnly: boolean - Post-only flagimmediateOrCancel: boolean - IOC flagmarketType: MarketType - Perp or spot market
UISerializableOrder
ExtendsSerializableOrder with BigNum types for UI display.
Usage:
SerializableOrderRecord
Wrapped order record event from transaction history. Properties:eventType: ‘OrderRecord’ - Event type identifiertxSig: string - Transaction signaturetxSigIndex: number - Index within transactionslot: number - Slot numberts: BN - Timestampuser: PublicKey - User accountorder: Order - Order data
SerializableOrderActionRecord
Represents an action taken on an order (fill, cancel, etc.). Properties:eventType: ‘OrderActionRecord’action: OrderAction - Action typeactionExplanation: OrderActionExplanation - Why action occurredmarketIndex: numbermarketType: MarketTypefiller: PublicKey | null - Filler accountfillerReward: BN | null - Filler rewardbaseAssetAmountFilled: BN | null - Amount filledquoteAssetAmountFilled: BN | null - Quote amount filledtakerFee: BN | null - Taker feemakerRebate: BN | null - Maker rebatetaker: PublicKey | null - Taker accounttakerOrderId: number | nullmaker: PublicKey | null - Maker accountmakerOrderId: number | nulloraclePrice: BN - Oracle price at time of action
Deposit/Withdrawal Types
SerializableDepositRecord
Represents a deposit or withdrawal event. Properties:depositRecordId: BN - Record IDuserAuthority: PublicKey - User authorityuser: PublicKey - User accountdirection: Direction enum (deposit or withdraw)marketIndex: number - Spot market indexamount: BN - Amount deposited/withdrawnoraclePrice: BN - Oracle pricemarketDepositBalance: BN - Market deposit balance aftermarketWithdrawBalance: BN - Market withdraw balance afterexplanation: DepositExplanation - Why deposit/withdrawal occurred
Funding Rate Types
SerializableFundingRateRecord
Funding rate record for a perpetual market. Properties:ts: BN - TimestamprecordId: BN - Record IDmarketIndex: number - Perp market indexfundingRate: BN - Funding ratecumulativeFundingRateLong: BN - Cumulative funding rate for longscumulativeFundingRateShort: BN - Cumulative funding rate for shortsoraclePrice: BN - Oracle pricemarkPrice: BN - Mark price
SerializableFundingPaymentRecord
Funding payment charged to a user. Properties:ts: BN - Timestampuser: PublicKey - User accountmarketIndex: number - Perp market indexfundingPayment: BN - Payment amount (positive = paid, negative = received)baseAssetAmount: BN - Position sizeuserLastCumulativeFunding: BN - User’s last cumulative fundingamm: Object containing cumulative funding rates (long and short)
Liquidation Types
SerializableLiquidationRecord
Complete liquidation event record. Properties:ts: BN - TimestampliquidationType: LiquidationType - Type of liquidationuser: PublicKey - Liquidated userliquidator: PublicKey - LiquidatormarginRequirement: BN - Margin requirementtotalCollateral: BN - Total collateralmarginFreed: BN - Margin freedliquidationId: BN - Liquidation IDbankrupt: boolean - Whether user went bankruptcanceledOrderIds: number[] - Orders canceledliquidatePerp: LiquidatePerpRecord - Perp liquidation dataliquidateSpot: LiquidateSpotRecord - Spot liquidation dataliquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecordliquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecordperpBankruptcy: PerpBankruptcyRecordspotBankruptcy: SpotBankruptcyRecord
Settle PnL Types
SerializableSettlePnlRecord
PnL settlement event. Properties:ts: BN - Timestampuser: PublicKey - User accountmarketIndex: number - Market indexpnl: BN - PnL amountbaseAssetAmount: BN - Position sizequoteAssetAmountAfter: BN - Quote asset after settlementquoteEntryAmount: BN - Quote entry amountsettlePrice: BN - Settlement priceexplanation: SettlePnlExplanation - Why PnL was settled
Leaderboard Types
SerializableUserSnapshotRecord
User account snapshot for leaderboards. Properties:user: PublicKey - User accountauthority: PublicKey - User authorityepochTs: number - Epoch timestampperpPositions: UserPerpPositionSnapshot[] - Perp positionsspotPositions: UserSpotPositionSnapshot[] - Spot positions
SerializableLeaderboardResult
Leaderboard results. Properties:lastUpdateTs: number - Last update timestampordering: PnlSnapshotOrderOption - Ordering methodresults: LeaderBoardResultRow[] - Result rows
Candle Types
SerializableCandle
OHLCV candle data. Properties:start: BN - Candle start timeresolution: CandleResolution - Time resolutionmarketType: MarketTypemarketIndex: numberopen: BN - Open pricehigh: BN - High pricelow: BN - Low priceclose: BN - Close pricevolume: BN - Volume
Insurance Fund Types
SerializableInsuranceFundRecord
Insurance fund transaction record. Properties:ts: BN - TimestampspotMarketIndex: numberperpMarketIndex: numberuserIfFactor: number - User IF factortotalIfFactor: number - Total IF factorvaultAmountBefore: BN - Vault amount beforeinsuranceVaultAmountBefore: BN - Insurance vault beforetotalIfSharesBefore: BN - Total shares beforetotalIfSharesAfter: BN - Total shares afteramount: BN - Transaction amount
SerializableInsuranceFundStakeRecord
Insurance fund stake/unstake record. Properties:ts: BN - TimestampuserAuthority: PublicKeyaction: StakeAction - Stake or unstakeamount: BN - Amount staked/unstakedmarketIndex: numberinsuranceVaultAmountBefore: BNifSharesBefore: BNuserIfSharesBefore: BNtotalIfSharesBefore: BNifSharesAfter: BNuserIfSharesAfter: BNtotalIfSharesAfter: BN
LP (Liquidity Provider) Types
SerializableLPRecord
LP action record. Properties:ts: BN - Timestampuser: PublicKeyaction: LPAction - Add or remove liquiditynShares: BN - Number of sharesmarketIndex: numberdeltaBaseAssetAmount: BN - Change in base assetdeltaQuoteAssetAmount: BN - Change in quote assetpnl: BN - PnL from LP action
Swap Types
SerializableSwapRecord
Spot market swap record. Properties:ts: BN - Timestampuser: PublicKeyamountOut: BN - Amount receivedamountIn: BN - Amount sentoutMarketIndex: number - Output marketinMarketIndex: number - Input marketfee: BN - Swap fee
Deserialization Utilities
TheCommonSerializationUtils.deserialize object provides methods for all types:
Configuration Setup
Before using UI serializable types, initialize the Config:Source Location
serializableTypes.ts - /home/daytona/workspace/source/common-ts/src/serializableTypes.ts