Class User

Hierarchy

  • User

Constructors

Properties

Accessors

Methods

accountLeverageAfterSwap accountLeverageRatioAfterTrade calculateEntriesEffectOnFreeCollateral calculateFeeForQuoteAmount calculateFreeCollateralDeltaForPerp calculateFreeCollateralDeltaForSpot calculateLeverageFromComponents calculateSpotPositionFreeCollateralContribution calculateSpotPositionLeverageContribution calculateWeightedPerpPositionLiability canBeLiquidated canBypassWithdrawLimits canMakeIdle cloneAndUpdateSpotPosition exists fetchAccounts forceGetUserAccount getActivePerpPositions getActivePerpPositionsAndSlot getActivePerpPositionsForUserAccount getActiveSpotPositions getActiveSpotPositionsAndSlot getActiveSpotPositionsForUserAccount getClonedPosition getCollateralDepositRequiredForTrade getEmptyPosition getEmptySpotPosition getFreeCollateral getFuelBonus getHealth getHealthComponents getInitialMarginRequirement getLPBidAsks getLeverage getLeverageComponents getMaintenanceMarginRequirement getMarginRatio getMarginRequirement getMarginUSDCRequiredForTrade getMaxLeverageForPerp getMaxLeverageForSpot getMaxSwapAmount getMaxTradeSizeUSDCForPerp getMaxTradeSizeUSDCForSpot getNetSpotMarketValue getNetUsdValue getOpenOrders getOpenOrdersAndSlot getOpenOrdersForUserAccount getOracleDataForPerpMarket getOracleDataForSpotMarket getOrder getOrderAndSlot getOrderByUserIdForUserAccount getOrderByUserOrderId getOrderByUserOrderIdAndSlot getOrderForUserAccount getPerpBidAsks getPerpBuyingPower getPerpBuyingPowerFromFreeCollateralAndBaseAssetAmount getPerpLiabilityValue getPerpMarketLiabilityValue getPerpPosition getPerpPositionAndSlot getPerpPositionForUserAccount getPerpPositionHealth getPerpPositionValue getPerpPositionWithLPSettle getPositionEstimatedExitPriceAndPnl getPositionSide getSafestTiers getSpotAssetValue getSpotLiabilityValue getSpotMarketAccountsWithDustPosition getSpotMarketAssetAndLiabilityValue getSpotMarketAssetValue getSpotMarketLiabilityValue getSpotPosition getSpotPositionAndSlot getSpotPositionForUserAccount getSpotPositionValue getTokenAmount getTotalAllTimePnl getTotalAssetValue getTotalCollateral getTotalLiabilityValue getTotalPerpPositionLiability getTotalPerpPositionValueExcludingMarket getUnrealizedFundingPNL getUnrealizedPNL getUserAccount getUserAccountAndSlot getUserAccountPublicKey getUserFeeTier getWithdrawalLimit hasStatus isBankrupt isBeingLiquidated isDustDepositPosition liquidationPrice liquidationPriceAfterClose needsToSettleFundingPayment spotLiquidationPrice subscribe unsubscribe

Constructors

Properties

_isSubscribed: boolean = false
accountSubscriber: UserAccountSubscriber
driftClient: DriftClient
eventEmitter: StrictEventEmitter<EventEmitter<DefaultEventMap>, UserAccountEvents, UserAccountEvents, "addEventListener" | "removeEventListener", "on" | "addListener" | "removeListener" | "once" | "emit">
userAccountPublicKey: PublicKey

Accessors

Methods

  • Estimates what the user leverage will be after swap

    Parameters

    • __namedParameters: {
          inAmount: BN;
          inMarketIndex: number;
          outAmount: BN;
          outMarketIndex: number;
      }
      • inAmount: BN
      • inMarketIndex: number
      • outAmount: BN
      • outMarketIndex: number

    Returns BN

  • Returns the leverage ratio for the account after adding (or subtracting) the given quote size to the given position

    Returns

    leverageRatio : Precision TEN_THOUSAND

    Parameters

    • targetMarketIndex: number

      @param: targetMarketType

    • targetMarketType: MarketType
    • tradeQuoteAmount: BN
    • tradeSide: PositionDirection
    • includeOpenOrders: boolean = true

    Returns BN

  • Calculates how much perp fee will be taken for a given sized trade

    Returns

    feeForQuote : Precision QUOTE_PRECISION

    Parameters

    • quoteAmount: BN
    • Optional marketIndex: number

    Returns BN

  • Parameters

    • __namedParameters: {
          perpLiabilityValue: BN;
          perpPnl: BN;
          spotAssetValue: BN;
          spotLiabilityValue: BN;
      }
      • perpLiabilityValue: BN
      • perpPnl: BN
      • spotAssetValue: BN
      • spotLiabilityValue: BN

    Returns BN

  • Returns {
        canBeLiquidated: boolean;
        marginRequirement: BN;
        totalCollateral: BN;
    }

    • canBeLiquidated: boolean
    • marginRequirement: BN
    • totalCollateral: BN
  • Parameters

    • marketIndex: number

    Returns {
        canBypass: boolean;
        depositAmount: BN;
        maxDepositAmount: BN;
        netDeposits: BN;
    }

    • canBypass: boolean
    • depositAmount: BN
    • maxDepositAmount: BN
    • netDeposits: BN
  • Forces the accountSubscriber to fetch account updates from rpc

    Returns Promise<void>

  • Parameters

    • targetMarketIndex: number
    • baseSize: BN
    • collateralIndex: number

    Returns BN

  • Parameters

    • now: BN
    • includeSettled: boolean = true
    • includeUnsettled: boolean = true

    Returns {
        borrowFuel: BN;
        depositFuel: BN;
        insuranceFuel: BN;
        makerFuel: BN;
        positionFuel: BN;
        takerFuel: BN;
    }

    • borrowFuel: BN
    • depositFuel: BN
    • insuranceFuel: BN
    • makerFuel: BN
    • positionFuel: BN
    • takerFuel: BN
  • calculates User Health by comparing total collateral and maint. margin requirement

    Returns

    : number (value from [0, 100])

    Returns number

  • Returns

    The initial margin requirement in USDC. : QUOTE_PRECISION

    Returns BN

  • calculates the open bids and asks for an lp optionally pass in lpShares to see what bid/asks a user would take on

    Returns

    : lp open bids

    Returns

    : lp open asks

    Parameters

    • marketIndex: number
    • Optional lpShares: BN

    Returns [BN, BN]

  • calculates current user leverage which is (total liability size) / (net asset value)

    Returns

    : Precision TEN_THOUSAND

    Parameters

    • includeOpenOrders: boolean = true

    Returns BN

  • Parameters

    • includeOpenOrders: boolean = true
    • marginCategory: MarginCategory = undefined

    Returns {
        perpLiabilityValue: BN;
        perpPnl: BN;
        spotAssetValue: BN;
        spotLiabilityValue: BN;
    }

    • perpLiabilityValue: BN
    • perpPnl: BN
    • spotAssetValue: BN
    • spotLiabilityValue: BN
  • Returns

    The maintenance margin requirement in USDC. : QUOTE_PRECISION

    Returns BN

  • calculates margin ratio: 1 / leverage

    Returns

    : Precision TEN_THOUSAND

    Returns BN

  • Returns

    The margin requirement of a certain type (Initial or Maintenance) in USDC. : QUOTE_PRECISION

    Parameters

    • marginCategory: MarginCategory
    • Optional liquidationBuffer: BN
    • strict: boolean = false
    • includeOpenOrders: boolean = true

    Returns BN

  • Parameters

    • targetMarketIndex: number
    • baseSize: BN

    Returns BN

  • calculates max allowable leverage exceeding hitting requirement category for large sizes where imf factor activates, result is a lower bound

    Returns

    : Precision TEN_THOUSAND

    Parameters

    • perpMarketIndex: number
    • marginCategory: MarginCategory = 'Initial'

      {Initial, Maintenance}

    • isLp: boolean = false

      if calculating max leveraging for adding lp, need to add buffer

    Returns BN

  • calculates max allowable leverage exceeding hitting requirement category

    Returns

    : Precision TEN_THOUSAND

    Parameters

    Returns BN

  • Calculates the max amount of token that can be swapped from inMarket to outMarket Assumes swap happens at oracle price

    Parameters

    • __namedParameters: {
          calculateSwap?: ((inAmount: BN) => BN);
          inMarketIndex: number;
          iterationLimit?: number;
          outMarketIndex: number;
      }
      • Optional calculateSwap?: ((inAmount: BN) => BN)
          • (inAmount: BN): BN
          • Parameters

            • inAmount: BN

            Returns BN

      • inMarketIndex: number
      • Optional iterationLimit?: number
      • outMarketIndex: number

    Returns {
        inAmount: BN;
        leverage: BN;
        outAmount: BN;
    }

    • inAmount: BN
    • leverage: BN
    • outAmount: BN
  • Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.

    To Calculate Max Quote Available:

    Case 1: SameSide => Remaining quote to get to maxLeverage

    Case 2: NOT SameSide && currentLeverage <= maxLeverage => Current opposite position x2 + remaining to get to maxLeverage

    Case 3: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition > maxLeverage => strictly reduce current position size

    Case 4: NOT SameSide && currentLeverage > maxLeverage && otherPositions - currentPosition < maxLeverage => current position + remaining to get to maxLeverage

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    Returns {
        oppositeSideTradeSize: BN;
        tradeSize: BN;
    }

    • oppositeSideTradeSize: BN
    • tradeSize: BN
  • Get the maximum trade size for a given market, taking into account the user's current leverage, positions, collateral, etc.

    Returns

    tradeSizeAllowed : Precision QUOTE_PRECISION

    Parameters

    • targetMarketIndex: number
    • direction: PositionDirection
    • Optional currentQuoteAssetValue: BN
    • Optional currentSpotMarketNetValue: BN

    Returns BN

  • calculates the total open bids/asks in a perp market (including lps)

    Returns

    : open bids

    Returns

    : open asks

    Parameters

    • marketIndex: number

    Returns [BN, BN]

  • calculates Buying Power = free collateral / initial margin ratio

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    • marketIndex: number
    • collateralBuffer: BN = ZERO

    Returns BN

  • Parameters

    • marketIndex: number
    • freeCollateral: BN
    • baseAssetAmount: BN

    Returns BN

  • calculates position liabiltiy value in margin system

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    • marketIndex: number
    • oraclePriceData: OraclePriceData
    • includeOpenOrders: boolean = false

    Returns BN

  • calculates position value of a single perp market in margin system

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    • marketIndex: number
    • Optional marginCategory: MarginCategory
    • Optional liquidationBuffer: BN
    • Optional includeOpenOrders: boolean
    • strict: boolean = false

    Returns BN

  • Gets the user's current position for a given perp market. If the user has no position returns undefined

    Returns

    userPerpPosition

    Parameters

    • marketIndex: number

    Returns PerpPosition

  • calculates position value based on oracle

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    • marketIndex: number
    • oraclePriceData: OraclePriceData
    • includeOpenOrders: boolean = false

    Returns BN

  • calculates the market position if the lp position was settled

    Returns

    : the settled userPosition

    Returns

    : the dust base asset amount (ie, < stepsize)

    Returns

    : pnl from settle

    Parameters

    • marketIndex: number
    • Optional originalPosition: PerpPosition
    • burnLpShares: boolean = false
    • includeRemainderInBaseAmount: boolean = false

    Returns [PerpPosition, BN, BN]

  • calculates average exit price (optionally for closing up to 100% of position)

    Returns

    : Precision PRICE_PRECISION

    Parameters

    • position: PerpPosition
    • Optional amountToClose: BN
    • useAMMClose: boolean = false

    Returns [BN, BN]

  • Returns {
        perpTier: number;
        spotTier: number;
    }

    • perpTier: number
    • spotTier: number
  • Parameters

    • Optional marketIndex: number
    • Optional marginCategory: MarginCategory
    • Optional liquidationBuffer: BN
    • Optional includeOpenOrders: boolean
    • strict: boolean = false
    • Optional now: BN

    Returns {
        totalAssetValue: BN;
        totalLiabilityValue: BN;
    }

    • totalAssetValue: BN
    • totalLiabilityValue: BN
  • Parameters

    • Optional marketIndex: number
    • Optional marginCategory: MarginCategory
    • Optional includeOpenOrders: boolean
    • strict: boolean = false
    • Optional now: BN

    Returns BN

  • Parameters

    • Optional marketIndex: number
    • Optional marginCategory: MarginCategory
    • Optional liquidationBuffer: BN
    • Optional includeOpenOrders: boolean
    • strict: boolean = false
    • Optional now: BN

    Returns BN

  • Gets the user's current position for a given spot market. If the user has no position returns undefined

    Returns

    userSpotPosition

    Parameters

    • marketIndex: number

    Returns SpotPosition

  • Parameters

    • marketIndex: number
    • Optional marginCategory: MarginCategory
    • Optional includeOpenOrders: boolean
    • strict: boolean = false
    • Optional now: BN

    Returns BN

  • Returns the token amount for a given market. The spot market precision is based on the token mint decimals. Positive if it is a deposit, negative if it is a borrow.

    Parameters

    • marketIndex: number

    Returns BN

  • Calculates the all time P&L of the user.

    Net withdraws + Net spot market value + Net unrealized P&L -

    Returns BN

  • calculates TotalCollateral: collateral + unrealized pnl

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    Returns BN

  • calculates sum of position value across all positions in margin system

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    • Optional marginCategory: MarginCategory
    • Optional liquidationBuffer: BN
    • Optional includeOpenOrders: boolean
    • strict: boolean = false

    Returns BN

  • Get the total position value, excluding any position coming from the given target market

    Returns

    positionValue : Precision QUOTE_PRECISION

    Parameters

    • marketToIgnore: number
    • Optional marginCategory: MarginCategory
    • Optional liquidationBuffer: BN
    • Optional includeOpenOrders: boolean

    Returns BN

  • calculates unrealized funding payment pnl

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    • Optional marketIndex: number

    Returns BN

  • calculates unrealized position price pnl

    Returns

    : Precision QUOTE_PRECISION

    Parameters

    • Optional withFunding: boolean
    • Optional marketIndex: number
    • Optional withWeightMarginCategory: MarginCategory
    • strict: boolean = false

    Returns BN

  • Calculates a user's max withdrawal amounts for a spot market. If reduceOnly is true, it will return the max withdrawal amount without opening a liability for the user

    Returns

    withdrawalLimit : Precision is the token precision for the chosen SpotMarket

    Parameters

    • marketIndex: number
    • Optional reduceOnly: boolean

    Returns BN

  • Calculate the liquidation price of a perp position, with optional parameter to calculate the liquidation price after a trade

    Returns

    Precision : PRICE_PRECISION

    Parameters

    • marketIndex: number
    • positionBaseSizeChange: BN = ZERO

      // change in position size to calculate liquidation price for : Precision 10^9

    • estimatedEntryPrice: BN = ZERO
    • marginCategory: MarginCategory = 'Maintenance'

      // allow Initial to be passed in if we are trying to calculate price for DLP de-risking

    • includeOpenOrders: boolean = false
    • offsetCollateral: BN = ZERO

      // allows calculating the liquidation price after this offset collateral is added to the user's account (e.g. : what will the liquidation price be for this position AFTER I deposit $x worth of collateral)

    Returns BN

  • Calculates the estimated liquidation price for a position after closing a quote amount of the position.

    Returns

    : Precision PRICE_PRECISION

    Parameters

    • positionMarketIndex: number
    • closeQuoteAmount: BN
    • estimatedEntryPrice: BN = ZERO

    Returns BN

  • Checks if any user position cumulative funding differs from respective market cumulative funding

    Returns

    Returns boolean

  • Calculate the liquidation price of a spot position

    Returns

    Precision : PRICE_PRECISION

    Parameters

    • marketIndex: number
    • positionBaseSizeChange: BN = ZERO

    Returns BN

  • Subscribe to User state accounts

    Returns

    SusbcriptionSuccess result

    Parameters

    Returns Promise<boolean>

Generated using TypeDoc