repo_id
stringclasses 563
values | file_path
stringlengths 40
166
| content
stringlengths 1
2.94M
| __index_level_0__
int64 0
0
|
|---|---|---|---|
solana_public_repos/drift-labs/protocol-v2/programs
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/Xargo.toml
|
[target.bpfel-unknown-unknown.dependencies.std]
features = []
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/error.rs
|
use anchor_lang::prelude::*;
pub type DriftResult<T = ()> = std::result::Result<T, ErrorCode>;
#[error_code]
#[derive(PartialEq, Eq)]
pub enum ErrorCode {
#[msg("Invalid Spot Market Authority")]
InvalidSpotMarketAuthority,
#[msg("Clearing house not insurance fund authority")]
InvalidInsuranceFundAuthority,
#[msg("Insufficient deposit")]
InsufficientDeposit,
#[msg("Insufficient collateral")]
InsufficientCollateral,
#[msg("Sufficient collateral")]
SufficientCollateral,
#[msg("Max number of positions taken")]
MaxNumberOfPositions,
#[msg("Admin Controls Prices Disabled")]
AdminControlsPricesDisabled,
#[msg("Market Delisted")]
MarketDelisted,
#[msg("Market Index Already Initialized")]
MarketIndexAlreadyInitialized,
#[msg("User Account And User Positions Account Mismatch")]
UserAccountAndUserPositionsAccountMismatch,
#[msg("User Has No Position In Market")]
UserHasNoPositionInMarket,
#[msg("Invalid Initial Peg")]
InvalidInitialPeg,
#[msg("AMM repeg already configured with amt given")]
InvalidRepegRedundant,
#[msg("AMM repeg incorrect repeg direction")]
InvalidRepegDirection,
#[msg("AMM repeg out of bounds pnl")]
InvalidRepegProfitability,
#[msg("Slippage Outside Limit Price")]
SlippageOutsideLimit,
#[msg("Order Size Too Small")]
OrderSizeTooSmall,
#[msg("Price change too large when updating K")]
InvalidUpdateK,
#[msg("Admin tried to withdraw amount larger than fees collected")]
AdminWithdrawTooLarge,
#[msg("Math Error")]
MathError,
#[msg("Conversion to u128/u64 failed with an overflow or underflow")]
BnConversionError,
#[msg("Clock unavailable")]
ClockUnavailable,
#[msg("Unable To Load Oracles")]
UnableToLoadOracle,
#[msg("Price Bands Breached")]
PriceBandsBreached,
#[msg("Exchange is paused")]
ExchangePaused,
#[msg("Invalid whitelist token")]
InvalidWhitelistToken,
#[msg("Whitelist token not found")]
WhitelistTokenNotFound,
#[msg("Invalid discount token")]
InvalidDiscountToken,
#[msg("Discount token not found")]
DiscountTokenNotFound,
#[msg("Referrer not found")]
ReferrerNotFound,
#[msg("ReferrerNotFound")]
ReferrerStatsNotFound,
#[msg("ReferrerMustBeWritable")]
ReferrerMustBeWritable,
#[msg("ReferrerMustBeWritable")]
ReferrerStatsMustBeWritable,
#[msg("ReferrerAndReferrerStatsAuthorityUnequal")]
ReferrerAndReferrerStatsAuthorityUnequal,
#[msg("InvalidReferrer")]
InvalidReferrer,
#[msg("InvalidOracle")]
InvalidOracle,
#[msg("OracleNotFound")]
OracleNotFound,
#[msg("Liquidations Blocked By Oracle")]
LiquidationsBlockedByOracle,
#[msg("Can not deposit more than max deposit")]
MaxDeposit,
#[msg("Can not delete user that still has collateral")]
CantDeleteUserWithCollateral,
#[msg("AMM funding out of bounds pnl")]
InvalidFundingProfitability,
#[msg("Casting Failure")]
CastingFailure,
#[msg("InvalidOrder")]
InvalidOrder,
#[msg("InvalidOrderMaxTs")]
InvalidOrderMaxTs,
#[msg("InvalidOrderMarketType")]
InvalidOrderMarketType,
#[msg("InvalidOrderForInitialMarginReq")]
InvalidOrderForInitialMarginReq,
#[msg("InvalidOrderNotRiskReducing")]
InvalidOrderNotRiskReducing,
#[msg("InvalidOrderSizeTooSmall")]
InvalidOrderSizeTooSmall,
#[msg("InvalidOrderNotStepSizeMultiple")]
InvalidOrderNotStepSizeMultiple,
#[msg("InvalidOrderBaseQuoteAsset")]
InvalidOrderBaseQuoteAsset,
#[msg("InvalidOrderIOC")]
InvalidOrderIOC,
#[msg("InvalidOrderPostOnly")]
InvalidOrderPostOnly,
#[msg("InvalidOrderIOCPostOnly")]
InvalidOrderIOCPostOnly,
#[msg("InvalidOrderTrigger")]
InvalidOrderTrigger,
#[msg("InvalidOrderAuction")]
InvalidOrderAuction,
#[msg("InvalidOrderOracleOffset")]
InvalidOrderOracleOffset,
#[msg("InvalidOrderMinOrderSize")]
InvalidOrderMinOrderSize,
#[msg("Failed to Place Post-Only Limit Order")]
PlacePostOnlyLimitFailure,
#[msg("User has no order")]
UserHasNoOrder,
#[msg("Order Amount Too Small")]
OrderAmountTooSmall,
#[msg("Max number of orders taken")]
MaxNumberOfOrders,
#[msg("Order does not exist")]
OrderDoesNotExist,
#[msg("Order not open")]
OrderNotOpen,
#[msg("FillOrderDidNotUpdateState")]
FillOrderDidNotUpdateState,
#[msg("Reduce only order increased risk")]
ReduceOnlyOrderIncreasedRisk,
#[msg("Unable to load AccountLoader")]
UnableToLoadAccountLoader,
#[msg("Trade Size Too Large")]
TradeSizeTooLarge,
#[msg("User cant refer themselves")]
UserCantReferThemselves,
#[msg("Did not receive expected referrer")]
DidNotReceiveExpectedReferrer,
#[msg("Could not deserialize referrer")]
CouldNotDeserializeReferrer,
#[msg("Could not deserialize referrer stats")]
CouldNotDeserializeReferrerStats,
#[msg("User Order Id Already In Use")]
UserOrderIdAlreadyInUse,
#[msg("No positions liquidatable")]
NoPositionsLiquidatable,
#[msg("Invalid Margin Ratio")]
InvalidMarginRatio,
#[msg("Cant Cancel Post Only Order")]
CantCancelPostOnlyOrder,
#[msg("InvalidOracleOffset")]
InvalidOracleOffset,
#[msg("CantExpireOrders")]
CantExpireOrders,
#[msg("CouldNotLoadMarketData")]
CouldNotLoadMarketData,
#[msg("PerpMarketNotFound")]
PerpMarketNotFound,
#[msg("InvalidMarketAccount")]
InvalidMarketAccount,
#[msg("UnableToLoadMarketAccount")]
UnableToLoadPerpMarketAccount,
#[msg("MarketWrongMutability")]
MarketWrongMutability,
#[msg("UnableToCastUnixTime")]
UnableToCastUnixTime,
#[msg("CouldNotFindSpotPosition")]
CouldNotFindSpotPosition,
#[msg("NoSpotPositionAvailable")]
NoSpotPositionAvailable,
#[msg("InvalidSpotMarketInitialization")]
InvalidSpotMarketInitialization,
#[msg("CouldNotLoadSpotMarketData")]
CouldNotLoadSpotMarketData,
#[msg("SpotMarketNotFound")]
SpotMarketNotFound,
#[msg("InvalidSpotMarketAccount")]
InvalidSpotMarketAccount,
#[msg("UnableToLoadSpotMarketAccount")]
UnableToLoadSpotMarketAccount,
#[msg("SpotMarketWrongMutability")]
SpotMarketWrongMutability,
#[msg("SpotInterestNotUpToDate")]
SpotMarketInterestNotUpToDate,
#[msg("SpotMarketInsufficientDeposits")]
SpotMarketInsufficientDeposits,
#[msg("UserMustSettleTheirOwnPositiveUnsettledPNL")]
UserMustSettleTheirOwnPositiveUnsettledPNL,
#[msg("CantUpdatePoolBalanceType")]
CantUpdatePoolBalanceType,
#[msg("InsufficientCollateralForSettlingPNL")]
InsufficientCollateralForSettlingPNL,
#[msg("AMMNotUpdatedInSameSlot")]
AMMNotUpdatedInSameSlot,
#[msg("AuctionNotComplete")]
AuctionNotComplete,
#[msg("MakerNotFound")]
MakerNotFound,
#[msg("MakerNotFound")]
MakerStatsNotFound,
#[msg("MakerMustBeWritable")]
MakerMustBeWritable,
#[msg("MakerMustBeWritable")]
MakerStatsMustBeWritable,
#[msg("MakerOrderNotFound")]
MakerOrderNotFound,
#[msg("CouldNotDeserializeMaker")]
CouldNotDeserializeMaker,
#[msg("CouldNotDeserializeMaker")]
CouldNotDeserializeMakerStats,
#[msg("AuctionPriceDoesNotSatisfyMaker")]
AuctionPriceDoesNotSatisfyMaker,
#[msg("MakerCantFulfillOwnOrder")]
MakerCantFulfillOwnOrder,
#[msg("MakerOrderMustBePostOnly")]
MakerOrderMustBePostOnly,
#[msg("CantMatchTwoPostOnlys")]
CantMatchTwoPostOnlys,
#[msg("OrderBreachesOraclePriceLimits")]
OrderBreachesOraclePriceLimits,
#[msg("OrderMustBeTriggeredFirst")]
OrderMustBeTriggeredFirst,
#[msg("OrderNotTriggerable")]
OrderNotTriggerable,
#[msg("OrderDidNotSatisfyTriggerCondition")]
OrderDidNotSatisfyTriggerCondition,
#[msg("PositionAlreadyBeingLiquidated")]
PositionAlreadyBeingLiquidated,
#[msg("PositionDoesntHaveOpenPositionOrOrders")]
PositionDoesntHaveOpenPositionOrOrders,
#[msg("AllOrdersAreAlreadyLiquidations")]
AllOrdersAreAlreadyLiquidations,
#[msg("CantCancelLiquidationOrder")]
CantCancelLiquidationOrder,
#[msg("UserIsBeingLiquidated")]
UserIsBeingLiquidated,
#[msg("LiquidationsOngoing")]
LiquidationsOngoing,
#[msg("WrongSpotBalanceType")]
WrongSpotBalanceType,
#[msg("UserCantLiquidateThemself")]
UserCantLiquidateThemself,
#[msg("InvalidPerpPositionToLiquidate")]
InvalidPerpPositionToLiquidate,
#[msg("InvalidBaseAssetAmountForLiquidatePerp")]
InvalidBaseAssetAmountForLiquidatePerp,
#[msg("InvalidPositionLastFundingRate")]
InvalidPositionLastFundingRate,
#[msg("InvalidPositionDelta")]
InvalidPositionDelta,
#[msg("UserBankrupt")]
UserBankrupt,
#[msg("UserNotBankrupt")]
UserNotBankrupt,
#[msg("UserHasInvalidBorrow")]
UserHasInvalidBorrow,
#[msg("DailyWithdrawLimit")]
DailyWithdrawLimit,
#[msg("DefaultError")]
DefaultError,
#[msg("Insufficient LP tokens")]
InsufficientLPTokens,
#[msg("Cant LP with a market position")]
CantLPWithPerpPosition,
#[msg("Unable to burn LP tokens")]
UnableToBurnLPTokens,
#[msg("Trying to remove liqudity too fast after adding it")]
TryingToRemoveLiquidityTooFast,
#[msg("Invalid Spot Market Vault")]
InvalidSpotMarketVault,
#[msg("Invalid Spot Market State")]
InvalidSpotMarketState,
#[msg("InvalidSerumProgram")]
InvalidSerumProgram,
#[msg("InvalidSerumMarket")]
InvalidSerumMarket,
#[msg("InvalidSerumBids")]
InvalidSerumBids,
#[msg("InvalidSerumAsks")]
InvalidSerumAsks,
#[msg("InvalidSerumOpenOrders")]
InvalidSerumOpenOrders,
#[msg("FailedSerumCPI")]
FailedSerumCPI,
#[msg("FailedToFillOnExternalMarket")]
FailedToFillOnExternalMarket,
#[msg("InvalidFulfillmentConfig")]
InvalidFulfillmentConfig,
#[msg("InvalidFeeStructure")]
InvalidFeeStructure,
#[msg("Insufficient IF shares")]
InsufficientIFShares,
#[msg("the Market has paused this action")]
MarketActionPaused,
#[msg("the Market status doesnt allow placing orders")]
MarketPlaceOrderPaused,
#[msg("the Market status doesnt allow filling orders")]
MarketFillOrderPaused,
#[msg("the Market status doesnt allow withdraws")]
MarketWithdrawPaused,
#[msg("Action violates the Protected Asset Tier rules")]
ProtectedAssetTierViolation,
#[msg("Action violates the Isolated Asset Tier rules")]
IsolatedAssetTierViolation,
#[msg("User Cant Be Deleted")]
UserCantBeDeleted,
#[msg("Reduce Only Withdraw Increased Risk")]
ReduceOnlyWithdrawIncreasedRisk,
#[msg("Max Open Interest")]
MaxOpenInterest,
#[msg("Cant Resolve Perp Bankruptcy")]
CantResolvePerpBankruptcy,
#[msg("Liquidation Doesnt Satisfy Limit Price")]
LiquidationDoesntSatisfyLimitPrice,
#[msg("Margin Trading Disabled")]
MarginTradingDisabled,
#[msg("Invalid Market Status to Settle Perp Pnl")]
InvalidMarketStatusToSettlePnl,
#[msg("PerpMarketNotInSettlement")]
PerpMarketNotInSettlement,
#[msg("PerpMarketNotInReduceOnly")]
PerpMarketNotInReduceOnly,
#[msg("PerpMarketSettlementBufferNotReached")]
PerpMarketSettlementBufferNotReached,
#[msg("PerpMarketSettlementUserHasOpenOrders")]
PerpMarketSettlementUserHasOpenOrders,
#[msg("PerpMarketSettlementUserHasActiveLP")]
PerpMarketSettlementUserHasActiveLP,
#[msg("UnableToSettleExpiredUserPosition")]
UnableToSettleExpiredUserPosition,
#[msg("UnequalMarketIndexForSpotTransfer")]
UnequalMarketIndexForSpotTransfer,
#[msg("InvalidPerpPositionDetected")]
InvalidPerpPositionDetected,
#[msg("InvalidSpotPositionDetected")]
InvalidSpotPositionDetected,
#[msg("InvalidAmmDetected")]
InvalidAmmDetected,
#[msg("InvalidAmmForFillDetected")]
InvalidAmmForFillDetected,
#[msg("InvalidAmmLimitPriceOverride")]
InvalidAmmLimitPriceOverride,
#[msg("InvalidOrderFillPrice")]
InvalidOrderFillPrice,
#[msg("SpotMarketBalanceInvariantViolated")]
SpotMarketBalanceInvariantViolated,
#[msg("SpotMarketVaultInvariantViolated")]
SpotMarketVaultInvariantViolated,
#[msg("InvalidPDA")]
InvalidPDA,
#[msg("InvalidPDASigner")]
InvalidPDASigner,
#[msg("RevenueSettingsCannotSettleToIF")]
RevenueSettingsCannotSettleToIF,
#[msg("NoRevenueToSettleToIF")]
NoRevenueToSettleToIF,
#[msg("NoAmmPerpPnlDeficit")]
NoAmmPerpPnlDeficit,
#[msg("SufficientPerpPnlPool")]
SufficientPerpPnlPool,
#[msg("InsufficientPerpPnlPool")]
InsufficientPerpPnlPool,
#[msg("PerpPnlDeficitBelowThreshold")]
PerpPnlDeficitBelowThreshold,
#[msg("MaxRevenueWithdrawPerPeriodReached")]
MaxRevenueWithdrawPerPeriodReached,
#[msg("InvalidSpotPositionDetected")]
MaxIFWithdrawReached,
#[msg("NoIFWithdrawAvailable")]
NoIFWithdrawAvailable,
#[msg("InvalidIFUnstake")]
InvalidIFUnstake,
#[msg("InvalidIFUnstakeSize")]
InvalidIFUnstakeSize,
#[msg("InvalidIFUnstakeCancel")]
InvalidIFUnstakeCancel,
#[msg("InvalidIFForNewStakes")]
InvalidIFForNewStakes,
#[msg("InvalidIFRebase")]
InvalidIFRebase,
#[msg("InvalidInsuranceUnstakeSize")]
InvalidInsuranceUnstakeSize,
#[msg("InvalidOrderLimitPrice")]
InvalidOrderLimitPrice,
#[msg("InvalidIFDetected")]
InvalidIFDetected,
#[msg("InvalidAmmMaxSpreadDetected")]
InvalidAmmMaxSpreadDetected,
#[msg("InvalidConcentrationCoef")]
InvalidConcentrationCoef,
#[msg("InvalidSrmVault")]
InvalidSrmVault,
#[msg("InvalidVaultOwner")]
InvalidVaultOwner,
#[msg("InvalidMarketStatusForFills")]
InvalidMarketStatusForFills,
#[msg("IFWithdrawRequestInProgress")]
IFWithdrawRequestInProgress,
#[msg("NoIFWithdrawRequestInProgress")]
NoIFWithdrawRequestInProgress,
#[msg("IFWithdrawRequestTooSmall")]
IFWithdrawRequestTooSmall,
#[msg("IncorrectSpotMarketAccountPassed")]
IncorrectSpotMarketAccountPassed,
#[msg("BlockchainClockInconsistency")]
BlockchainClockInconsistency,
#[msg("InvalidIFSharesDetected")]
InvalidIFSharesDetected,
#[msg("NewLPSizeTooSmall")]
NewLPSizeTooSmall,
#[msg("MarketStatusInvalidForNewLP")]
MarketStatusInvalidForNewLP,
#[msg("InvalidMarkTwapUpdateDetected")]
InvalidMarkTwapUpdateDetected,
#[msg("MarketSettlementAttemptOnActiveMarket")]
MarketSettlementAttemptOnActiveMarket,
#[msg("MarketSettlementRequiresSettledLP")]
MarketSettlementRequiresSettledLP,
#[msg("MarketSettlementAttemptTooEarly")]
MarketSettlementAttemptTooEarly,
#[msg("MarketSettlementTargetPriceInvalid")]
MarketSettlementTargetPriceInvalid,
#[msg("UnsupportedSpotMarket")]
UnsupportedSpotMarket,
#[msg("SpotOrdersDisabled")]
SpotOrdersDisabled,
#[msg("Market Being Initialized")]
MarketBeingInitialized,
#[msg("Invalid Sub Account Id")]
InvalidUserSubAccountId,
#[msg("Invalid Trigger Order Condition")]
InvalidTriggerOrderCondition,
#[msg("Invalid Spot Position")]
InvalidSpotPosition,
#[msg("Cant transfer between same user account")]
CantTransferBetweenSameUserAccount,
#[msg("Invalid Perp Position")]
InvalidPerpPosition,
#[msg("Unable To Get Limit Price")]
UnableToGetLimitPrice,
#[msg("Invalid Liquidation")]
InvalidLiquidation,
#[msg("Spot Fulfillment Config Disabled")]
SpotFulfillmentConfigDisabled,
#[msg("Invalid Maker")]
InvalidMaker,
#[msg("Failed Unwrap")]
FailedUnwrap,
#[msg("Max Number Of Users")]
MaxNumberOfUsers,
#[msg("InvalidOracleForSettlePnl")]
InvalidOracleForSettlePnl,
#[msg("MarginOrdersOpen")]
MarginOrdersOpen,
#[msg("TierViolationLiquidatingPerpPnl")]
TierViolationLiquidatingPerpPnl,
#[msg("CouldNotLoadUserData")]
CouldNotLoadUserData,
#[msg("UserWrongMutability")]
UserWrongMutability,
#[msg("InvalidUserAccount")]
InvalidUserAccount,
#[msg("CouldNotLoadUserData")]
CouldNotLoadUserStatsData,
#[msg("UserWrongMutability")]
UserStatsWrongMutability,
#[msg("InvalidUserAccount")]
InvalidUserStatsAccount,
#[msg("UserNotFound")]
UserNotFound,
#[msg("UnableToLoadUserAccount")]
UnableToLoadUserAccount,
#[msg("UserStatsNotFound")]
UserStatsNotFound,
#[msg("UnableToLoadUserStatsAccount")]
UnableToLoadUserStatsAccount,
#[msg("User Not Inactive")]
UserNotInactive,
#[msg("RevertFill")]
RevertFill,
#[msg("Invalid MarketAccount for Deletion")]
InvalidMarketAccountforDeletion,
#[msg("Invalid Spot Fulfillment Params")]
InvalidSpotFulfillmentParams,
#[msg("Failed to Get Mint")]
FailedToGetMint,
#[msg("FailedPhoenixCPI")]
FailedPhoenixCPI,
#[msg("FailedToDeserializePhoenixMarket")]
FailedToDeserializePhoenixMarket,
#[msg("InvalidPricePrecision")]
InvalidPricePrecision,
#[msg("InvalidPhoenixProgram")]
InvalidPhoenixProgram,
#[msg("InvalidPhoenixMarket")]
InvalidPhoenixMarket,
#[msg("InvalidSwap")]
InvalidSwap,
#[msg("SwapLimitPriceBreached")]
SwapLimitPriceBreached,
#[msg("SpotMarketReduceOnly")]
SpotMarketReduceOnly,
#[msg("FundingWasNotUpdated")]
FundingWasNotUpdated,
#[msg("ImpossibleFill")]
ImpossibleFill,
#[msg("CantUpdatePerpBidAskTwap")]
CantUpdatePerpBidAskTwap,
#[msg("UserReduceOnly")]
UserReduceOnly,
#[msg("InvalidMarginCalculation")]
InvalidMarginCalculation,
#[msg("CantPayUserInitFee")]
CantPayUserInitFee,
#[msg("CantReclaimRent")]
CantReclaimRent,
#[msg("InsuranceFundOperationPaused")]
InsuranceFundOperationPaused,
#[msg("NoUnsettledPnl")]
NoUnsettledPnl,
#[msg("PnlPoolCantSettleUser")]
PnlPoolCantSettleUser,
#[msg("OracleInvalid")]
OracleNonPositive,
#[msg("OracleTooVolatile")]
OracleTooVolatile,
#[msg("OracleTooUncertain")]
OracleTooUncertain,
#[msg("OracleStaleForMargin")]
OracleStaleForMargin,
#[msg("OracleInsufficientDataPoints")]
OracleInsufficientDataPoints,
#[msg("OracleStaleForAMM")]
OracleStaleForAMM,
#[msg("Unable to parse pull oracle message")]
UnableToParsePullOracleMessage,
#[msg("Can not borow more than max borrows")]
MaxBorrows,
#[msg("Updates must be monotonically increasing")]
OracleUpdatesNotMonotonic,
#[msg("Trying to update price feed with the wrong feed id")]
OraclePriceFeedMessageMismatch,
#[msg("The message in the update must be a PriceFeedMessage")]
OracleUnsupportedMessageType,
#[msg("Could not deserialize the message in the update")]
OracleDeserializeMessageFailed,
#[msg("Wrong guardian set owner in update price atomic")]
OracleWrongGuardianSetOwner,
#[msg("Oracle post update atomic price feed account must be drift program")]
OracleWrongWriteAuthority,
#[msg("Oracle vaa owner must be wormhole program")]
OracleWrongVaaOwner,
#[msg("Multi updates must have 2 or fewer accounts passed in remaining accounts")]
OracleTooManyPriceAccountUpdates,
#[msg("Don't have the same remaining accounts number and pyth updates left")]
OracleMismatchedVaaAndPriceUpdates,
#[msg("Remaining account passed does not match oracle update derived pda")]
OracleBadRemainingAccountPublicKey,
#[msg("FailedOpenbookV2CPI")]
FailedOpenbookV2CPI,
#[msg("InvalidOpenbookV2Program")]
InvalidOpenbookV2Program,
#[msg("InvalidOpenbookV2Market")]
InvalidOpenbookV2Market,
#[msg("Non zero transfer fee")]
NonZeroTransferFee,
#[msg("Liquidation order failed to fill")]
LiquidationOrderFailedToFill,
#[msg("Invalid prediction market order")]
InvalidPredictionMarketOrder,
#[msg("Ed25519 Ix must be before place and make swift order ix")]
InvalidVerificationIxIndex,
#[msg("Swift message verificaiton failed")]
SigVerificationFailed,
#[msg("Market index mismatched b/w taker and maker swift order params")]
MismatchedSwiftOrderParamsMarketIndex,
#[msg("Swift only available for market/oracle perp orders")]
InvalidSwiftOrderParam,
#[msg("Place and take order success condition failed")]
PlaceAndTakeOrderSuccessConditionFailed,
#[msg("Invalid High Leverage Mode Config")]
InvalidHighLeverageModeConfig,
#[msg("Invalid RFQ User Account")]
InvalidRFQUserAccount,
#[msg("RFQUserAccount should be mutable")]
RFQUserAccountWrongMutability,
#[msg("RFQUserAccount has too many active RFQs")]
RFQUserAccountFull,
#[msg("RFQ order not filled as expected")]
RFQOrderNotFilled,
#[msg("RFQ orders must be jit makers")]
InvalidRFQOrder,
#[msg("RFQ matches must be valid")]
InvalidRFQMatch,
#[msg("Invalid swift user account")]
InvalidSwiftUserAccount,
#[msg("Swift account wrong mutability")]
SwiftUserAccountWrongMutability,
#[msg("SwiftUserAccount has too many active orders")]
SwiftUserOrdersAccountFull,
#[msg("Order with swift uuid does not exist")]
SwiftOrderDoesNotExist,
#[msg("Swift order id cannot be 0s")]
InvalidSwiftOrderId,
#[msg("Invalid pool id")]
InvalidPoolId,
#[msg("Invalid Protected Maker Mode Config")]
InvalidProtectedMakerModeConfig,
#[msg("Invalid pyth lazer storage owner")]
InvalidPythLazerStorageOwner,
#[msg("Verification of pyth lazer message failed")]
UnverifiedPythLazerMessage,
#[msg("Invalid pyth lazer message")]
InvalidPythLazerMessage,
#[msg("Pyth lazer message does not correspond to correct fed id")]
PythLazerMessagePriceFeedMismatch,
}
#[macro_export]
macro_rules! print_error {
($err:expr) => {{
|| {
let error_code: ErrorCode = $err;
msg!("{:?} thrown at {}:{}", error_code, file!(), line!());
$err
}
}};
}
#[macro_export]
macro_rules! math_error {
() => {{
|| {
let error_code = $crate::error::ErrorCode::MathError;
msg!("Error {} thrown at {}:{}", error_code, file!(), line!());
error_code
}
}};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/lib.rs
|
#![allow(clippy::too_many_arguments)]
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::comparison_chain)]
use anchor_lang::prelude::*;
use instructions::*;
#[cfg(test)]
use math::amm;
use math::{bn, constants::*};
use state::oracle::OracleSource;
use crate::controller::position::PositionDirection;
use crate::state::oracle::PrelaunchOracleParams;
use crate::state::order_params::{ModifyOrderParams, OrderParams, RFQMatch};
use crate::state::perp_market::{ContractTier, MarketStatus};
use crate::state::settle_pnl_mode::SettlePnlMode;
use crate::state::spot_market::AssetTier;
use crate::state::spot_market::SpotFulfillmentConfigStatus;
use crate::state::state::FeeStructure;
use crate::state::state::*;
use crate::state::user::MarketType;
pub mod controller;
pub mod error;
pub mod ids;
pub mod instructions;
pub mod macros;
pub mod math;
mod signer;
pub mod state;
#[cfg(test)]
mod test_utils;
mod validation;
#[cfg(feature = "mainnet-beta")]
declare_id!("dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH");
#[cfg(not(feature = "mainnet-beta"))]
declare_id!("dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH");
#[program]
pub mod drift {
use super::*;
use crate::state::spot_market::SpotFulfillmentConfigStatus;
// User Instructions
pub fn initialize_user<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeUser<'info>>,
sub_account_id: u16,
name: [u8; 32],
) -> Result<()> {
handle_initialize_user(ctx, sub_account_id, name)
}
pub fn initialize_user_stats<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeUserStats>,
) -> Result<()> {
handle_initialize_user_stats(ctx)
}
pub fn initialize_rfq_user<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeRFQUser<'info>>,
) -> Result<()> {
handle_initialize_rfq_user(ctx)
}
pub fn initialize_swift_user_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeSwiftUserOrders<'info>>,
num_orders: u16,
) -> Result<()> {
handle_initialize_swift_user_orders(ctx, num_orders)
}
pub fn resize_swift_user_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResizeSwiftUserOrders<'info>>,
num_orders: u16,
) -> Result<()> {
handle_resize_swift_user_orders(ctx, num_orders)
}
pub fn initialize_referrer_name(
ctx: Context<InitializeReferrerName>,
name: [u8; 32],
) -> Result<()> {
handle_initialize_referrer_name(ctx, name)
}
pub fn deposit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Deposit<'info>>,
market_index: u16,
amount: u64,
reduce_only: bool,
) -> Result<()> {
handle_deposit(ctx, market_index, amount, reduce_only)
}
pub fn withdraw<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Withdraw<'info>>,
market_index: u16,
amount: u64,
reduce_only: bool,
) -> anchor_lang::Result<()> {
handle_withdraw(ctx, market_index, amount, reduce_only)
}
pub fn transfer_deposit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, TransferDeposit<'info>>,
market_index: u16,
amount: u64,
) -> anchor_lang::Result<()> {
handle_transfer_deposit(ctx, market_index, amount)
}
pub fn place_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
params: OrderParams,
) -> Result<()> {
handle_place_perp_order(ctx, params)
}
pub fn cancel_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder>,
order_id: Option<u32>,
) -> Result<()> {
handle_cancel_order(ctx, order_id)
}
pub fn cancel_order_by_user_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder>,
user_order_id: u8,
) -> Result<()> {
handle_cancel_order_by_user_id(ctx, user_order_id)
}
pub fn cancel_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder<'info>>,
market_type: Option<MarketType>,
market_index: Option<u16>,
direction: Option<PositionDirection>,
) -> Result<()> {
handle_cancel_orders(ctx, market_type, market_index, direction)
}
pub fn cancel_orders_by_ids<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder>,
order_ids: Vec<u32>,
) -> Result<()> {
handle_cancel_orders_by_ids(ctx, order_ids)
}
pub fn modify_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder<'info>>,
order_id: Option<u32>,
modify_order_params: ModifyOrderParams,
) -> Result<()> {
handle_modify_order(ctx, order_id, modify_order_params)
}
pub fn modify_order_by_user_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder<'info>>,
user_order_id: u8,
modify_order_params: ModifyOrderParams,
) -> Result<()> {
handle_modify_order_by_user_order_id(ctx, user_order_id, modify_order_params)
}
pub fn place_and_take_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndTake<'info>>,
params: OrderParams,
success_condition: Option<u32>,
) -> Result<()> {
handle_place_and_take_perp_order(ctx, params, success_condition)
}
pub fn place_and_make_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMake<'info>>,
params: OrderParams,
taker_order_id: u32,
) -> Result<()> {
handle_place_and_make_perp_order(ctx, params, taker_order_id)
}
pub fn place_and_make_swift_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMakeSwift<'info>>,
params: OrderParams,
swift_order_uuid: [u8; 8],
) -> Result<()> {
handle_place_and_make_swift_perp_order(ctx, params, swift_order_uuid)
}
pub fn place_swift_taker_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceSwiftTakerOrder<'info>>,
swift_message_bytes: Vec<u8>,
swift_order_params_message_bytes: Vec<u8>,
) -> Result<()> {
handle_place_swift_taker_order(ctx, swift_message_bytes, swift_order_params_message_bytes)
}
pub fn place_and_match_rfq_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMatchRFQOrders<'info>>,
rfq_matches: Vec<RFQMatch>,
) -> Result<()> {
handle_place_and_match_rfq_orders(ctx, rfq_matches)
}
pub fn place_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
params: OrderParams,
) -> Result<()> {
handle_place_spot_order(ctx, params)
}
pub fn place_and_take_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndTake<'info>>,
params: OrderParams,
fulfillment_type: Option<SpotFulfillmentType>,
maker_order_id: Option<u32>,
) -> Result<()> {
handle_place_and_take_spot_order(
ctx,
params,
fulfillment_type.unwrap_or(SpotFulfillmentType::Match),
maker_order_id,
)
}
pub fn place_and_make_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMake<'info>>,
params: OrderParams,
taker_order_id: u32,
fulfillment_type: Option<SpotFulfillmentType>,
) -> Result<()> {
handle_place_and_make_spot_order(
ctx,
params,
taker_order_id,
fulfillment_type.unwrap_or(SpotFulfillmentType::Match),
)
}
pub fn place_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
params: Vec<OrderParams>,
) -> Result<()> {
handle_place_orders(ctx, params)
}
pub fn begin_swap<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Swap<'info>>,
in_market_index: u16,
out_market_index: u16,
amount_in: u64,
) -> Result<()> {
handle_begin_swap(ctx, in_market_index, out_market_index, amount_in)
}
pub fn end_swap<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Swap<'info>>,
in_market_index: u16,
out_market_index: u16,
limit_price: Option<u64>,
reduce_only: Option<SwapReduceOnly>,
) -> Result<()> {
handle_end_swap(
ctx,
in_market_index,
out_market_index,
limit_price,
reduce_only,
)
}
pub fn add_perp_lp_shares<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AddRemoveLiquidity<'info>>,
n_shares: u64,
market_index: u16,
) -> Result<()> {
handle_add_perp_lp_shares(ctx, n_shares, market_index)
}
pub fn remove_perp_lp_shares<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AddRemoveLiquidity<'info>>,
shares_to_burn: u64,
market_index: u16,
) -> Result<()> {
handle_remove_perp_lp_shares(ctx, shares_to_burn, market_index)
}
pub fn remove_perp_lp_shares_in_expiring_market<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, RemoveLiquidityInExpiredMarket<'info>>,
shares_to_burn: u64,
market_index: u16,
) -> Result<()> {
handle_remove_perp_lp_shares_in_expiring_market(ctx, shares_to_burn, market_index)
}
pub fn update_user_name(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
name: [u8; 32],
) -> Result<()> {
handle_update_user_name(ctx, _sub_account_id, name)
}
pub fn update_user_custom_margin_ratio(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
margin_ratio: u32,
) -> Result<()> {
handle_update_user_custom_margin_ratio(ctx, _sub_account_id, margin_ratio)
}
pub fn update_user_margin_trading_enabled<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUser<'info>>,
_sub_account_id: u16,
margin_trading_enabled: bool,
) -> Result<()> {
handle_update_user_margin_trading_enabled(ctx, _sub_account_id, margin_trading_enabled)
}
pub fn update_user_pool_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUser<'info>>,
_sub_account_id: u16,
pool_id: u8,
) -> Result<()> {
handle_update_user_pool_id(ctx, _sub_account_id, pool_id)
}
pub fn update_user_delegate(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
delegate: Pubkey,
) -> Result<()> {
handle_update_user_delegate(ctx, _sub_account_id, delegate)
}
pub fn update_user_reduce_only(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
reduce_only: bool,
) -> Result<()> {
handle_update_user_reduce_only(ctx, _sub_account_id, reduce_only)
}
pub fn update_user_advanced_lp(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
advanced_lp: bool,
) -> Result<()> {
handle_update_user_advanced_lp(ctx, _sub_account_id, advanced_lp)
}
pub fn update_user_protected_maker_orders(
ctx: Context<UpdateUserProtectedMakerMode>,
_sub_account_id: u16,
protected_maker_orders: bool,
) -> Result<()> {
handle_update_user_protected_maker_orders(ctx, _sub_account_id, protected_maker_orders)
}
pub fn delete_user<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DeleteUser>,
) -> Result<()> {
handle_delete_user(ctx)
}
pub fn force_delete_user<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ForceDeleteUser<'info>>,
) -> Result<()> {
handle_force_delete_user(ctx)
}
pub fn delete_swift_user_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DeleteSwiftUserOrders>,
) -> Result<()> {
handle_delete_swift_user_orders(ctx)
}
pub fn reclaim_rent(ctx: Context<ReclaimRent>) -> Result<()> {
handle_reclaim_rent(ctx)
}
pub fn enable_user_high_leverage_mode<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, EnableUserHighLeverageMode>,
sub_account_id: u16,
) -> Result<()> {
handle_enable_user_high_leverage_mode(ctx, sub_account_id)
}
// Keeper Instructions
pub fn fill_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, FillOrder<'info>>,
order_id: Option<u32>,
_maker_order_id: Option<u32>,
) -> Result<()> {
handle_fill_perp_order(ctx, order_id)
}
pub fn revert_fill(ctx: Context<RevertFill>) -> Result<()> {
handle_revert_fill(ctx)
}
pub fn fill_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, FillOrder<'info>>,
order_id: Option<u32>,
fulfillment_type: Option<SpotFulfillmentType>,
maker_order_id: Option<u32>,
) -> Result<()> {
handle_fill_spot_order(ctx, order_id, fulfillment_type, maker_order_id)
}
pub fn trigger_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, TriggerOrder<'info>>,
order_id: u32,
) -> Result<()> {
handle_trigger_order(ctx, order_id)
}
pub fn force_cancel_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ForceCancelOrder<'info>>,
) -> Result<()> {
handle_force_cancel_orders(ctx)
}
pub fn update_user_idle<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUserIdle<'info>>,
) -> Result<()> {
handle_update_user_idle(ctx)
}
pub fn log_user_balances<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LogUserBalances<'info>>,
) -> Result<()> {
handle_log_user_balances(ctx)
}
pub fn disable_user_high_leverage_mode<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DisableUserHighLeverageMode<'info>>,
) -> Result<()> {
handle_disable_user_high_leverage_mode(ctx)
}
pub fn update_user_fuel_bonus<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUserFuelBonus<'info>>,
) -> Result<()> {
handle_update_user_fuel_bonus(ctx)
}
pub fn update_user_stats_referrer_status<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUserStatsReferrerInfo<'info>>,
) -> Result<()> {
handle_update_user_stats_referrer_info(ctx)
}
pub fn update_user_open_orders_count(ctx: Context<UpdateUserIdle>) -> Result<()> {
handle_update_user_open_orders_count(ctx)
}
pub fn admin_disable_update_perp_bid_ask_twap(
ctx: Context<AdminDisableBidAskTwapUpdate>,
disable: bool,
) -> Result<()> {
handle_admin_disable_update_perp_bid_ask_twap(ctx, disable)
}
pub fn settle_pnl<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettlePNL>,
market_index: u16,
) -> Result<()> {
handle_settle_pnl(ctx, market_index)
}
pub fn settle_multiple_pnls<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettlePNL>,
market_indexes: Vec<u16>,
mode: SettlePnlMode,
) -> Result<()> {
handle_settle_multiple_pnls(ctx, market_indexes, mode)
}
pub fn settle_funding_payment<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettleFunding>,
) -> Result<()> {
handle_settle_funding_payment(ctx)
}
pub fn settle_lp<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettleLP>,
market_index: u16,
) -> Result<()> {
handle_settle_lp(ctx, market_index)
}
pub fn settle_expired_market<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AdminUpdatePerpMarket<'info>>,
market_index: u16,
) -> Result<()> {
handle_settle_expired_market(ctx, market_index)
}
pub fn liquidate_perp<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidatePerp<'info>>,
market_index: u16,
liquidator_max_base_asset_amount: u64,
limit_price: Option<u64>,
) -> Result<()> {
handle_liquidate_perp(
ctx,
market_index,
liquidator_max_base_asset_amount,
limit_price,
)
}
pub fn liquidate_perp_with_fill<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidatePerp<'info>>,
market_index: u16,
) -> Result<()> {
handle_liquidate_perp_with_fill(ctx, market_index)
}
pub fn liquidate_spot<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidateSpot<'info>>,
asset_market_index: u16,
liability_market_index: u16,
liquidator_max_liability_transfer: u128,
limit_price: Option<u64>, // asset/liaiblity
) -> Result<()> {
handle_liquidate_spot(
ctx,
asset_market_index,
liability_market_index,
liquidator_max_liability_transfer,
limit_price,
)
}
pub fn liquidate_borrow_for_perp_pnl<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidateBorrowForPerpPnl<'info>>,
perp_market_index: u16,
spot_market_index: u16,
liquidator_max_liability_transfer: u128,
limit_price: Option<u64>,
) -> Result<()> {
handle_liquidate_borrow_for_perp_pnl(
ctx,
perp_market_index,
spot_market_index,
liquidator_max_liability_transfer,
limit_price,
)
}
pub fn liquidate_perp_pnl_for_deposit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidatePerpPnlForDeposit<'info>>,
perp_market_index: u16,
spot_market_index: u16,
liquidator_max_pnl_transfer: u128,
limit_price: Option<u64>,
) -> Result<()> {
handle_liquidate_perp_pnl_for_deposit(
ctx,
perp_market_index,
spot_market_index,
liquidator_max_pnl_transfer,
limit_price,
)
}
pub fn set_user_status_to_being_liquidated<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SetUserStatusToBeingLiquidated<'info>>,
) -> Result<()> {
handle_set_user_status_to_being_liquidated(ctx)
}
pub fn resolve_perp_pnl_deficit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResolvePerpPnlDeficit<'info>>,
spot_market_index: u16,
perp_market_index: u16,
) -> Result<()> {
handle_resolve_perp_pnl_deficit(ctx, spot_market_index, perp_market_index)
}
pub fn resolve_perp_bankruptcy<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResolveBankruptcy<'info>>,
quote_spot_market_index: u16,
market_index: u16,
) -> Result<()> {
handle_resolve_perp_bankruptcy(ctx, quote_spot_market_index, market_index)
}
pub fn resolve_spot_bankruptcy<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResolveBankruptcy<'info>>,
market_index: u16,
) -> Result<()> {
handle_resolve_spot_bankruptcy(ctx, market_index)
}
pub fn settle_revenue_to_insurance_fund<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettleRevenueToInsuranceFund<'info>>,
spot_market_index: u16,
) -> Result<()> {
handle_settle_revenue_to_insurance_fund(ctx, spot_market_index)
}
pub fn update_funding_rate(ctx: Context<UpdateFundingRate>, market_index: u16) -> Result<()> {
handle_update_funding_rate(ctx, market_index)
}
pub fn update_prelaunch_oracle(ctx: Context<UpdatePrelaunchOracle>) -> Result<()> {
handle_update_prelaunch_oracle(ctx)
}
pub fn update_perp_bid_ask_twap<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdatePerpBidAskTwap<'info>>,
) -> Result<()> {
handle_update_perp_bid_ask_twap(ctx)
}
pub fn update_spot_market_cumulative_interest(
ctx: Context<UpdateSpotMarketCumulativeInterest>,
) -> Result<()> {
handle_update_spot_market_cumulative_interest(ctx)
}
pub fn update_amms<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateAMM<'info>>,
market_indexes: [u16; 5],
) -> Result<()> {
handle_update_amms(ctx, market_indexes)
}
pub fn update_spot_market_expiry(
ctx: Context<AdminUpdateSpotMarket>,
expiry_ts: i64,
) -> Result<()> {
handle_update_spot_market_expiry(ctx, expiry_ts)
}
pub fn update_user_quote_asset_insurance_stake(
ctx: Context<UpdateUserQuoteAssetInsuranceStake>,
) -> Result<()> {
handle_update_user_quote_asset_insurance_stake(ctx)
}
pub fn update_user_gov_token_insurance_stake(
ctx: Context<UpdateUserGovTokenInsuranceStake>,
) -> Result<()> {
handle_update_user_gov_token_insurance_stake(ctx)
}
pub fn update_user_gov_token_insurance_stake_devnet(
ctx: Context<UpdateUserGovTokenInsuranceStakeDevnet>,
gov_stake_amount: u64,
) -> Result<()> {
handle_update_user_gov_token_insurance_stake_devnet(ctx, gov_stake_amount)
}
// IF stakers
pub fn initialize_insurance_fund_stake(
ctx: Context<InitializeInsuranceFundStake>,
market_index: u16,
) -> Result<()> {
handle_initialize_insurance_fund_stake(ctx, market_index)
}
pub fn add_insurance_fund_stake<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AddInsuranceFundStake<'info>>,
market_index: u16,
amount: u64,
) -> Result<()> {
handle_add_insurance_fund_stake(ctx, market_index, amount)
}
pub fn request_remove_insurance_fund_stake(
ctx: Context<RequestRemoveInsuranceFundStake>,
market_index: u16,
amount: u64,
) -> Result<()> {
handle_request_remove_insurance_fund_stake(ctx, market_index, amount)
}
pub fn cancel_request_remove_insurance_fund_stake(
ctx: Context<RequestRemoveInsuranceFundStake>,
market_index: u16,
) -> Result<()> {
handle_cancel_request_remove_insurance_fund_stake(ctx, market_index)
}
pub fn remove_insurance_fund_stake<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, RemoveInsuranceFundStake<'info>>,
market_index: u16,
) -> Result<()> {
handle_remove_insurance_fund_stake(ctx, market_index)
}
pub fn transfer_protocol_if_shares(
ctx: Context<TransferProtocolIfShares>,
market_index: u16,
shares: u128,
) -> Result<()> {
handle_transfer_protocol_if_shares(ctx, market_index, shares)
}
pub fn update_pyth_pull_oracle(
ctx: Context<UpdatePythPullOraclePriceFeed>,
feed_id: [u8; 32],
params: Vec<u8>,
) -> Result<()> {
handle_update_pyth_pull_oracle(ctx, feed_id, params)
}
pub fn post_pyth_pull_oracle_update_atomic(
ctx: Context<PostPythPullOracleUpdateAtomic>,
feed_id: [u8; 32],
params: Vec<u8>,
) -> Result<()> {
handle_post_pyth_pull_oracle_update_atomic(ctx, feed_id, params)
}
pub fn post_multi_pyth_pull_oracle_updates_atomic<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PostPythPullMultiOracleUpdatesAtomic<'info>>,
params: Vec<u8>,
) -> Result<()> {
handle_post_multi_pyth_pull_oracle_updates_atomic(ctx, params)
}
// Admin Instructions
pub fn initialize(ctx: Context<Initialize>) -> Result<()> {
handle_initialize(ctx)
}
pub fn initialize_spot_market(
ctx: Context<InitializeSpotMarket>,
optimal_utilization: u32,
optimal_borrow_rate: u32,
max_borrow_rate: u32,
oracle_source: OracleSource,
initial_asset_weight: u32,
maintenance_asset_weight: u32,
initial_liability_weight: u32,
maintenance_liability_weight: u32,
imf_factor: u32,
liquidator_fee: u32,
if_liquidation_fee: u32,
active_status: bool,
asset_tier: AssetTier,
scale_initial_asset_weight_start: u64,
withdraw_guard_threshold: u64,
order_tick_size: u64,
order_step_size: u64,
if_total_factor: u32,
name: [u8; 32],
) -> Result<()> {
handle_initialize_spot_market(
ctx,
optimal_utilization,
optimal_borrow_rate,
max_borrow_rate,
oracle_source,
initial_asset_weight,
maintenance_asset_weight,
initial_liability_weight,
maintenance_liability_weight,
imf_factor,
liquidator_fee,
if_liquidation_fee,
active_status,
asset_tier,
scale_initial_asset_weight_start,
withdraw_guard_threshold,
order_tick_size,
order_step_size,
if_total_factor,
name,
)
}
pub fn delete_initialized_spot_market(
ctx: Context<DeleteInitializedSpotMarket>,
market_index: u16,
) -> Result<()> {
handle_delete_initialized_spot_market(ctx, market_index)
}
pub fn initialize_serum_fulfillment_config(
ctx: Context<InitializeSerumFulfillmentConfig>,
market_index: u16,
) -> Result<()> {
handle_initialize_serum_fulfillment_config(ctx, market_index)
}
pub fn update_serum_fulfillment_config_status(
ctx: Context<UpdateSerumFulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
handle_update_serum_fulfillment_config_status(ctx, status)
}
pub fn initialize_openbook_v2_fulfillment_config(
ctx: Context<InitializeOpenbookV2FulfillmentConfig>,
market_index: u16,
) -> Result<()> {
handle_initialize_openbook_v2_fulfillment_config(ctx, market_index)
}
pub fn openbook_v2_fulfillment_config_status(
ctx: Context<UpdateOpenbookV2FulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
handle_update_openbook_v2_fulfillment_config_status(ctx, status)
}
pub fn initialize_phoenix_fulfillment_config(
ctx: Context<InitializePhoenixFulfillmentConfig>,
market_index: u16,
) -> Result<()> {
handle_initialize_phoenix_fulfillment_config(ctx, market_index)
}
pub fn phoenix_fulfillment_config_status(
ctx: Context<UpdatePhoenixFulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
handle_update_phoenix_fulfillment_config_status(ctx, status)
}
pub fn update_serum_vault(ctx: Context<UpdateSerumVault>) -> Result<()> {
handle_update_serum_vault(ctx)
}
pub fn initialize_perp_market<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializePerpMarket<'info>>,
market_index: u16,
amm_base_asset_reserve: u128,
amm_quote_asset_reserve: u128,
amm_periodicity: i64,
amm_peg_multiplier: u128,
oracle_source: OracleSource,
contract_tier: ContractTier,
margin_ratio_initial: u32,
margin_ratio_maintenance: u32,
liquidator_fee: u32,
if_liquidation_fee: u32,
imf_factor: u32,
active_status: bool,
base_spread: u32,
max_spread: u32,
max_open_interest: u128,
max_revenue_withdraw_per_period: u64,
quote_max_insurance: u64,
order_step_size: u64,
order_tick_size: u64,
min_order_size: u64,
concentration_coef_scale: u128,
curve_update_intensity: u8,
amm_jit_intensity: u8,
name: [u8; 32],
) -> Result<()> {
handle_initialize_perp_market(
ctx,
market_index,
amm_base_asset_reserve,
amm_quote_asset_reserve,
amm_periodicity,
amm_peg_multiplier,
oracle_source,
contract_tier,
margin_ratio_initial,
margin_ratio_maintenance,
liquidator_fee,
if_liquidation_fee,
imf_factor,
active_status,
base_spread,
max_spread,
max_open_interest,
max_revenue_withdraw_per_period,
quote_max_insurance,
order_step_size,
order_tick_size,
min_order_size,
concentration_coef_scale,
curve_update_intensity,
amm_jit_intensity,
name,
)
}
pub fn initialize_prediction_market<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AdminUpdatePerpMarket<'info>>,
) -> Result<()> {
handle_initialize_prediction_market(ctx)
}
pub fn delete_initialized_perp_market(
ctx: Context<DeleteInitializedPerpMarket>,
market_index: u16,
) -> Result<()> {
handle_delete_initialized_perp_market(ctx, market_index)
}
pub fn move_amm_price(
ctx: Context<AdminUpdatePerpMarket>,
base_asset_reserve: u128,
quote_asset_reserve: u128,
sqrt_k: u128,
) -> Result<()> {
handle_move_amm_price(ctx, base_asset_reserve, quote_asset_reserve, sqrt_k)
}
pub fn recenter_perp_market_amm(
ctx: Context<AdminUpdatePerpMarket>,
peg_multiplier: u128,
sqrt_k: u128,
) -> Result<()> {
handle_recenter_perp_market_amm(ctx, peg_multiplier, sqrt_k)
}
pub fn update_perp_market_amm_summary_stats(
ctx: Context<AdminUpdatePerpMarketAmmSummaryStats>,
params: UpdatePerpMarketSummaryStatsParams,
) -> Result<()> {
handle_update_perp_market_amm_summary_stats(ctx, params)
}
pub fn update_perp_market_expiry(
ctx: Context<AdminUpdatePerpMarket>,
expiry_ts: i64,
) -> Result<()> {
handle_update_perp_market_expiry(ctx, expiry_ts)
}
pub fn settle_expired_market_pools_to_revenue_pool(
ctx: Context<SettleExpiredMarketPoolsToRevenuePool>,
) -> Result<()> {
handle_settle_expired_market_pools_to_revenue_pool(ctx)
}
pub fn deposit_into_perp_market_fee_pool<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DepositIntoMarketFeePool<'info>>,
amount: u64,
) -> Result<()> {
handle_deposit_into_perp_market_fee_pool(ctx, amount)
}
pub fn deposit_into_spot_market_vault<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DepositIntoSpotMarketVault<'info>>,
amount: u64,
) -> Result<()> {
handle_deposit_into_spot_market_vault(ctx, amount)
}
pub fn deposit_into_spot_market_revenue_pool<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, RevenuePoolDeposit<'info>>,
amount: u64,
) -> Result<()> {
handle_deposit_into_spot_market_revenue_pool(ctx, amount)
}
pub fn repeg_amm_curve(ctx: Context<RepegCurve>, new_peg_candidate: u128) -> Result<()> {
handle_repeg_amm_curve(ctx, new_peg_candidate)
}
pub fn update_perp_market_amm_oracle_twap(ctx: Context<RepegCurve>) -> Result<()> {
handle_update_amm_oracle_twap(ctx)
}
pub fn reset_perp_market_amm_oracle_twap(ctx: Context<RepegCurve>) -> Result<()> {
handle_reset_amm_oracle_twap(ctx)
}
pub fn update_k(ctx: Context<AdminUpdateK>, sqrt_k: u128) -> Result<()> {
handle_update_k(ctx, sqrt_k)
}
pub fn update_perp_market_margin_ratio(
ctx: Context<AdminUpdatePerpMarket>,
margin_ratio_initial: u32,
margin_ratio_maintenance: u32,
) -> Result<()> {
handle_update_perp_market_margin_ratio(ctx, margin_ratio_initial, margin_ratio_maintenance)
}
pub fn update_perp_market_high_leverage_margin_ratio(
ctx: Context<AdminUpdatePerpMarket>,
margin_ratio_initial: u16,
margin_ratio_maintenance: u16,
) -> Result<()> {
handle_update_perp_market_high_leverage_margin_ratio(
ctx,
margin_ratio_initial,
margin_ratio_maintenance,
)
}
pub fn update_perp_market_funding_period(
ctx: Context<AdminUpdatePerpMarket>,
funding_period: i64,
) -> Result<()> {
handle_update_perp_market_funding_period(ctx, funding_period)
}
pub fn update_perp_market_max_imbalances(
ctx: Context<AdminUpdatePerpMarket>,
unrealized_max_imbalance: u64,
max_revenue_withdraw_per_period: u64,
quote_max_insurance: u64,
) -> Result<()> {
handle_update_perp_market_max_imbalances(
ctx,
unrealized_max_imbalance,
max_revenue_withdraw_per_period,
quote_max_insurance,
)
}
pub fn update_perp_market_liquidation_fee(
ctx: Context<AdminUpdatePerpMarket>,
liquidator_fee: u32,
if_liquidation_fee: u32,
) -> Result<()> {
handle_update_perp_liquidation_fee(ctx, liquidator_fee, if_liquidation_fee)
}
pub fn update_insurance_fund_unstaking_period(
ctx: Context<AdminUpdateSpotMarket>,
insurance_fund_unstaking_period: i64,
) -> Result<()> {
handle_update_insurance_fund_unstaking_period(ctx, insurance_fund_unstaking_period)
}
pub fn update_spot_market_pool_id(
ctx: Context<AdminUpdateSpotMarket>,
pool_id: u8,
) -> Result<()> {
handle_update_spot_market_pool_id(ctx, pool_id)
}
pub fn update_spot_market_liquidation_fee(
ctx: Context<AdminUpdateSpotMarket>,
liquidator_fee: u32,
if_liquidation_fee: u32,
) -> Result<()> {
handle_update_spot_market_liquidation_fee(ctx, liquidator_fee, if_liquidation_fee)
}
pub fn update_withdraw_guard_threshold(
ctx: Context<AdminUpdateSpotMarket>,
withdraw_guard_threshold: u64,
) -> Result<()> {
handle_update_withdraw_guard_threshold(ctx, withdraw_guard_threshold)
}
pub fn update_spot_market_if_factor(
ctx: Context<AdminUpdateSpotMarket>,
spot_market_index: u16,
user_if_factor: u32,
total_if_factor: u32,
) -> Result<()> {
handle_update_spot_market_if_factor(ctx, spot_market_index, user_if_factor, total_if_factor)
}
pub fn update_spot_market_revenue_settle_period(
ctx: Context<AdminUpdateSpotMarket>,
revenue_settle_period: i64,
) -> Result<()> {
handle_update_spot_market_revenue_settle_period(ctx, revenue_settle_period)
}
pub fn update_spot_market_status(
ctx: Context<AdminUpdateSpotMarket>,
status: MarketStatus,
) -> Result<()> {
handle_update_spot_market_status(ctx, status)
}
pub fn update_spot_market_paused_operations(
ctx: Context<AdminUpdateSpotMarket>,
paused_operations: u8,
) -> Result<()> {
handle_update_spot_market_paused_operations(ctx, paused_operations)
}
pub fn update_spot_market_asset_tier(
ctx: Context<AdminUpdateSpotMarket>,
asset_tier: AssetTier,
) -> Result<()> {
handle_update_spot_market_asset_tier(ctx, asset_tier)
}
pub fn update_spot_market_margin_weights(
ctx: Context<AdminUpdateSpotMarket>,
initial_asset_weight: u32,
maintenance_asset_weight: u32,
initial_liability_weight: u32,
maintenance_liability_weight: u32,
imf_factor: u32,
) -> Result<()> {
handle_update_spot_market_margin_weights(
ctx,
initial_asset_weight,
maintenance_asset_weight,
initial_liability_weight,
maintenance_liability_weight,
imf_factor,
)
}
pub fn update_spot_market_borrow_rate(
ctx: Context<AdminUpdateSpotMarket>,
optimal_utilization: u32,
optimal_borrow_rate: u32,
max_borrow_rate: u32,
min_borrow_rate: Option<u8>,
) -> Result<()> {
handle_update_spot_market_borrow_rate(
ctx,
optimal_utilization,
optimal_borrow_rate,
max_borrow_rate,
min_borrow_rate,
)
}
pub fn update_spot_market_max_token_deposits(
ctx: Context<AdminUpdateSpotMarket>,
max_token_deposits: u64,
) -> Result<()> {
handle_update_spot_market_max_token_deposits(ctx, max_token_deposits)
}
pub fn update_spot_market_max_token_borrows(
ctx: Context<AdminUpdateSpotMarket>,
max_token_borrows_fraction: u16,
) -> Result<()> {
handle_update_spot_market_max_token_borrows(ctx, max_token_borrows_fraction)
}
pub fn update_spot_market_scale_initial_asset_weight_start(
ctx: Context<AdminUpdateSpotMarket>,
scale_initial_asset_weight_start: u64,
) -> Result<()> {
handle_update_spot_market_scale_initial_asset_weight_start(
ctx,
scale_initial_asset_weight_start,
)
}
pub fn update_spot_market_oracle(
ctx: Context<AdminUpdateSpotMarketOracle>,
oracle: Pubkey,
oracle_source: OracleSource,
) -> Result<()> {
handle_update_spot_market_oracle(ctx, oracle, oracle_source)
}
pub fn update_spot_market_step_size_and_tick_size(
ctx: Context<AdminUpdateSpotMarket>,
step_size: u64,
tick_size: u64,
) -> Result<()> {
handle_update_spot_market_step_size_and_tick_size(ctx, step_size, tick_size)
}
pub fn update_spot_market_min_order_size(
ctx: Context<AdminUpdateSpotMarket>,
order_size: u64,
) -> Result<()> {
handle_update_spot_market_min_order_size(ctx, order_size)
}
pub fn update_spot_market_orders_enabled(
ctx: Context<AdminUpdateSpotMarket>,
orders_enabled: bool,
) -> Result<()> {
handle_update_spot_market_orders_enabled(ctx, orders_enabled)
}
pub fn update_spot_market_if_paused_operations(
ctx: Context<AdminUpdateSpotMarket>,
paused_operations: u8,
) -> Result<()> {
handle_update_spot_market_if_paused_operations(ctx, paused_operations)
}
pub fn update_spot_market_name(
ctx: Context<AdminUpdateSpotMarket>,
name: [u8; 32],
) -> Result<()> {
handle_update_spot_market_name(ctx, name)
}
pub fn update_perp_market_status(
ctx: Context<AdminUpdatePerpMarket>,
status: MarketStatus,
) -> Result<()> {
handle_update_perp_market_status(ctx, status)
}
pub fn update_perp_market_paused_operations(
ctx: Context<AdminUpdatePerpMarket>,
paused_operations: u8,
) -> Result<()> {
handle_update_perp_market_paused_operations(ctx, paused_operations)
}
pub fn update_perp_market_contract_tier(
ctx: Context<AdminUpdatePerpMarket>,
contract_tier: ContractTier,
) -> Result<()> {
handle_update_perp_market_contract_tier(ctx, contract_tier)
}
pub fn update_perp_market_imf_factor(
ctx: Context<AdminUpdatePerpMarket>,
imf_factor: u32,
unrealized_pnl_imf_factor: u32,
) -> Result<()> {
handle_update_perp_market_imf_factor(ctx, imf_factor, unrealized_pnl_imf_factor)
}
pub fn update_perp_market_unrealized_asset_weight(
ctx: Context<AdminUpdatePerpMarket>,
unrealized_initial_asset_weight: u32,
unrealized_maintenance_asset_weight: u32,
) -> Result<()> {
handle_update_perp_market_unrealized_asset_weight(
ctx,
unrealized_initial_asset_weight,
unrealized_maintenance_asset_weight,
)
}
pub fn update_perp_market_concentration_coef(
ctx: Context<AdminUpdatePerpMarket>,
concentration_scale: u128,
) -> Result<()> {
handle_update_perp_market_concentration_coef(ctx, concentration_scale)
}
pub fn update_perp_market_curve_update_intensity(
ctx: Context<AdminUpdatePerpMarket>,
curve_update_intensity: u8,
) -> Result<()> {
handle_update_perp_market_curve_update_intensity(ctx, curve_update_intensity)
}
pub fn update_perp_market_target_base_asset_amount_per_lp(
ctx: Context<AdminUpdatePerpMarket>,
target_base_asset_amount_per_lp: i32,
) -> Result<()> {
handle_update_perp_market_target_base_asset_amount_per_lp(
ctx,
target_base_asset_amount_per_lp,
)
}
pub fn update_perp_market_per_lp_base(
ctx: Context<AdminUpdatePerpMarket>,
per_lp_base: i8,
) -> Result<()> {
handle_update_perp_market_per_lp_base(ctx, per_lp_base)
}
pub fn update_lp_cooldown_time(
ctx: Context<AdminUpdateState>,
lp_cooldown_time: u64,
) -> Result<()> {
handle_update_lp_cooldown_time(ctx, lp_cooldown_time)
}
pub fn update_perp_fee_structure(
ctx: Context<AdminUpdateState>,
fee_structure: FeeStructure,
) -> Result<()> {
handle_update_perp_fee_structure(ctx, fee_structure)
}
pub fn update_spot_fee_structure(
ctx: Context<AdminUpdateState>,
fee_structure: FeeStructure,
) -> Result<()> {
handle_update_spot_fee_structure(ctx, fee_structure)
}
pub fn update_initial_pct_to_liquidate(
ctx: Context<AdminUpdateState>,
initial_pct_to_liquidate: u16,
) -> Result<()> {
handle_update_initial_pct_to_liquidate(ctx, initial_pct_to_liquidate)
}
pub fn update_liquidation_duration(
ctx: Context<AdminUpdateState>,
liquidation_duration: u8,
) -> Result<()> {
handle_update_liquidation_duration(ctx, liquidation_duration)
}
pub fn update_liquidation_margin_buffer_ratio(
ctx: Context<AdminUpdateState>,
liquidation_margin_buffer_ratio: u32,
) -> Result<()> {
handle_update_liquidation_margin_buffer_ratio(ctx, liquidation_margin_buffer_ratio)
}
pub fn update_oracle_guard_rails(
ctx: Context<AdminUpdateState>,
oracle_guard_rails: OracleGuardRails,
) -> Result<()> {
handle_update_oracle_guard_rails(ctx, oracle_guard_rails)
}
pub fn update_state_settlement_duration(
ctx: Context<AdminUpdateState>,
settlement_duration: u16,
) -> Result<()> {
handle_update_state_settlement_duration(ctx, settlement_duration)
}
pub fn update_state_max_number_of_sub_accounts(
ctx: Context<AdminUpdateState>,
max_number_of_sub_accounts: u16,
) -> Result<()> {
handle_update_state_max_number_of_sub_accounts(ctx, max_number_of_sub_accounts)
}
pub fn update_state_max_initialize_user_fee(
ctx: Context<AdminUpdateState>,
max_initialize_user_fee: u16,
) -> Result<()> {
handle_update_state_max_initialize_user_fee(ctx, max_initialize_user_fee)
}
pub fn update_perp_market_oracle(
ctx: Context<RepegCurve>,
oracle: Pubkey,
oracle_source: OracleSource,
) -> Result<()> {
handle_update_perp_market_oracle(ctx, oracle, oracle_source)
}
pub fn update_perp_market_base_spread(
ctx: Context<AdminUpdatePerpMarket>,
base_spread: u32,
) -> Result<()> {
handle_update_perp_market_base_spread(ctx, base_spread)
}
pub fn update_amm_jit_intensity(
ctx: Context<AdminUpdatePerpMarket>,
amm_jit_intensity: u8,
) -> Result<()> {
handle_update_amm_jit_intensity(ctx, amm_jit_intensity)
}
pub fn update_perp_market_max_spread(
ctx: Context<AdminUpdatePerpMarket>,
max_spread: u32,
) -> Result<()> {
handle_update_perp_market_max_spread(ctx, max_spread)
}
pub fn update_perp_market_step_size_and_tick_size(
ctx: Context<AdminUpdatePerpMarket>,
step_size: u64,
tick_size: u64,
) -> Result<()> {
handle_update_perp_market_step_size_and_tick_size(ctx, step_size, tick_size)
}
pub fn update_perp_market_name(
ctx: Context<AdminUpdatePerpMarket>,
name: [u8; 32],
) -> Result<()> {
handle_update_perp_market_name(ctx, name)
}
pub fn update_perp_market_min_order_size(
ctx: Context<AdminUpdatePerpMarket>,
order_size: u64,
) -> Result<()> {
handle_update_perp_market_min_order_size(ctx, order_size)
}
pub fn update_perp_market_max_slippage_ratio(
ctx: Context<AdminUpdatePerpMarket>,
max_slippage_ratio: u16,
) -> Result<()> {
handle_update_perp_market_max_slippage_ratio(ctx, max_slippage_ratio)
}
pub fn update_perp_market_max_fill_reserve_fraction(
ctx: Context<AdminUpdatePerpMarket>,
max_fill_reserve_fraction: u16,
) -> Result<()> {
handle_update_perp_market_max_fill_reserve_fraction(ctx, max_fill_reserve_fraction)
}
pub fn update_perp_market_max_open_interest(
ctx: Context<AdminUpdatePerpMarket>,
max_open_interest: u128,
) -> Result<()> {
handle_update_perp_market_max_open_interest(ctx, max_open_interest)
}
pub fn update_perp_market_number_of_users(
ctx: Context<AdminUpdatePerpMarket>,
number_of_users: Option<u32>,
number_of_users_with_base: Option<u32>,
) -> Result<()> {
handle_update_perp_market_number_of_users(ctx, number_of_users, number_of_users_with_base)
}
pub fn update_perp_market_fee_adjustment(
ctx: Context<AdminUpdatePerpMarket>,
fee_adjustment: i16,
) -> Result<()> {
handle_update_perp_market_fee_adjustment(ctx, fee_adjustment)
}
pub fn update_spot_market_fee_adjustment(
ctx: Context<AdminUpdateSpotMarket>,
fee_adjustment: i16,
) -> Result<()> {
handle_update_spot_market_fee_adjustment(ctx, fee_adjustment)
}
pub fn update_perp_market_fuel(
ctx: Context<AdminUpdatePerpMarket>,
fuel_boost_taker: Option<u8>,
fuel_boost_maker: Option<u8>,
fuel_boost_position: Option<u8>,
) -> Result<()> {
handle_update_perp_market_fuel(ctx, fuel_boost_taker, fuel_boost_maker, fuel_boost_position)
}
pub fn update_spot_market_fuel(
ctx: Context<AdminUpdateSpotMarket>,
fuel_boost_deposits: Option<u8>,
fuel_boost_borrows: Option<u8>,
fuel_boost_taker: Option<u8>,
fuel_boost_maker: Option<u8>,
fuel_boost_insurance: Option<u8>,
) -> Result<()> {
handle_update_spot_market_fuel(
ctx,
fuel_boost_deposits,
fuel_boost_borrows,
fuel_boost_taker,
fuel_boost_maker,
fuel_boost_insurance,
)
}
pub fn init_user_fuel(
ctx: Context<InitUserFuel>,
fuel_boost_deposits: Option<u32>,
fuel_boost_borrows: Option<u32>,
fuel_boost_taker: Option<u32>,
fuel_boost_maker: Option<u32>,
fuel_boost_insurance: Option<u32>,
) -> Result<()> {
handle_init_user_fuel(
ctx,
fuel_boost_deposits,
fuel_boost_borrows,
fuel_boost_taker,
fuel_boost_maker,
fuel_boost_insurance,
)
}
pub fn update_admin(ctx: Context<AdminUpdateState>, admin: Pubkey) -> Result<()> {
handle_update_admin(ctx, admin)
}
pub fn update_whitelist_mint(
ctx: Context<AdminUpdateState>,
whitelist_mint: Pubkey,
) -> Result<()> {
handle_update_whitelist_mint(ctx, whitelist_mint)
}
pub fn update_discount_mint(
ctx: Context<AdminUpdateState>,
discount_mint: Pubkey,
) -> Result<()> {
handle_update_discount_mint(ctx, discount_mint)
}
pub fn update_exchange_status(
ctx: Context<AdminUpdateState>,
exchange_status: u8,
) -> Result<()> {
handle_update_exchange_status(ctx, exchange_status)
}
pub fn update_perp_auction_duration(
ctx: Context<AdminUpdateState>,
min_perp_auction_duration: u8,
) -> Result<()> {
handle_update_perp_auction_duration(ctx, min_perp_auction_duration)
}
pub fn update_spot_auction_duration(
ctx: Context<AdminUpdateState>,
default_spot_auction_duration: u8,
) -> Result<()> {
handle_update_spot_auction_duration(ctx, default_spot_auction_duration)
}
pub fn initialize_protocol_if_shares_transfer_config(
ctx: Context<InitializeProtocolIfSharesTransferConfig>,
) -> Result<()> {
handle_initialize_protocol_if_shares_transfer_config(ctx)
}
pub fn update_protocol_if_shares_transfer_config(
ctx: Context<UpdateProtocolIfSharesTransferConfig>,
whitelisted_signers: Option<[Pubkey; 4]>,
max_transfer_per_epoch: Option<u128>,
) -> Result<()> {
handle_update_protocol_if_shares_transfer_config(
ctx,
whitelisted_signers,
max_transfer_per_epoch,
)
}
pub fn initialize_prelaunch_oracle(
ctx: Context<InitializePrelaunchOracle>,
params: PrelaunchOracleParams,
) -> Result<()> {
handle_initialize_prelaunch_oracle(ctx, params)
}
pub fn update_prelaunch_oracle_params(
ctx: Context<UpdatePrelaunchOracleParams>,
params: PrelaunchOracleParams,
) -> Result<()> {
handle_update_prelaunch_oracle_params(ctx, params)
}
pub fn delete_prelaunch_oracle(
ctx: Context<DeletePrelaunchOracle>,
perp_market_index: u16,
) -> Result<()> {
handle_delete_prelaunch_oracle(ctx, perp_market_index)
}
pub fn initialize_pyth_pull_oracle(
ctx: Context<InitPythPullPriceFeed>,
feed_id: [u8; 32],
) -> Result<()> {
handle_initialize_pyth_pull_oracle(ctx, feed_id)
}
pub fn initialize_pyth_lazer_oracle(
ctx: Context<InitPythLazerOracle>,
feed_id: u32,
) -> Result<()> {
handle_initialize_pyth_lazer_oracle(ctx, feed_id)
}
pub fn post_pyth_lazer_oracle_update<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdatePythLazerOracle>,
pyth_message: Vec<u8>,
) -> Result<()> {
handle_update_pyth_lazer_oracle(ctx, pyth_message)
}
pub fn initialize_high_leverage_mode_config(
ctx: Context<InitializeHighLeverageModeConfig>,
max_users: u32,
) -> Result<()> {
handle_initialize_high_leverage_mode_config(ctx, max_users)
}
pub fn update_high_leverage_mode_config(
ctx: Context<UpdateHighLeverageModeConfig>,
max_users: u32,
reduce_only: bool,
) -> Result<()> {
handle_update_high_leverage_mode_config(ctx, max_users, reduce_only)
}
pub fn initialize_protected_maker_mode_config(
ctx: Context<InitializeProtectedMakerModeConfig>,
max_users: u32,
) -> Result<()> {
handle_initialize_protected_maker_mode_config(ctx, max_users)
}
pub fn update_protected_maker_mode_config(
ctx: Context<UpdateProtectedMakerModeConfig>,
max_users: u32,
reduce_only: bool,
) -> Result<()> {
handle_update_protected_maker_mode_config(ctx, max_users, reduce_only)
}
}
#[cfg(not(feature = "no-entrypoint"))]
use solana_security_txt::security_txt;
#[cfg(not(feature = "no-entrypoint"))]
security_txt! {
name: "Drift v2",
project_url: "https://drift.trade",
contacts: "link:https://docs.drift.trade/security/bug-bounty",
policy: "https://github.com/drift-labs/protocol-v2/blob/main/SECURITY.md",
preferred_languages: "en",
source_code: "https://github.com/drift-labs/protocol-v2"
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/test_utils.rs
|
use anchor_lang::prelude::{AccountInfo, Pubkey};
use anchor_lang::{Owner, ZeroCopy};
use bytes::BytesMut;
use pyth::pc::Price;
use crate::state::user::{Order, PerpPosition, SpotPosition};
pub fn get_positions(position: PerpPosition) -> [PerpPosition; 8] {
let mut positions = [PerpPosition::default(); 8];
positions[0] = position;
positions
}
pub fn get_orders(order: Order) -> [Order; 32] {
let mut orders = [Order::default(); 32];
orders[0] = order;
orders
}
#[macro_export]
macro_rules! get_orders {
($($order: expr),+) => {
{
let mut orders = [Order::default(); 32];
let mut index = 0;
$(
index += 1;
orders[index - 1] = $order;
)+
orders
}
};
}
pub fn get_spot_positions(spot_position: SpotPosition) -> [SpotPosition; 8] {
let mut spot_positions = [SpotPosition::default(); 8];
if spot_position.market_index == 0 {
spot_positions[0] = spot_position;
} else {
spot_positions[1] = spot_position;
}
spot_positions
}
pub fn get_account_bytes<T: bytemuck::Pod>(account: &mut T) -> BytesMut {
let mut bytes = BytesMut::new();
let data = bytemuck::bytes_of_mut(account);
bytes.extend_from_slice(data);
bytes
}
pub fn get_anchor_account_bytes<T: ZeroCopy + Owner>(account: &mut T) -> BytesMut {
let mut bytes = BytesMut::new();
bytes.extend_from_slice(&T::discriminator());
let data = bytemuck::bytes_of_mut(account);
bytes.extend_from_slice(data);
bytes
}
pub fn create_account_info<'a>(
key: &'a Pubkey,
is_writable: bool,
lamports: &'a mut u64,
bytes: &'a mut [u8],
owner: &'a Pubkey,
) -> AccountInfo<'a> {
AccountInfo::new(key, false, is_writable, lamports, bytes, owner, false, 0)
}
pub fn get_pyth_price(price: i64, expo: i32) -> Price {
let mut pyth_price = Price::default();
let price = price * 10_i64.pow(expo as u32);
pyth_price.agg.price = price;
pyth_price.twap = price;
pyth_price.expo = expo;
pyth_price
}
pub fn get_hardcoded_pyth_price(price: i64, expo: i32) -> Price {
let mut pyth_price = Price::default();
pyth_price.agg.price = price;
pyth_price.twap = price;
pyth_price.expo = expo;
pyth_price
}
#[macro_export]
macro_rules! create_anchor_account_info {
($account:expr, $type:ident, $name: ident) => {
let key = Pubkey::default();
let mut lamports = 0;
let mut data = get_anchor_account_bytes(&mut $account);
let owner = $type::owner();
let $name = create_account_info(&key, true, &mut lamports, &mut data[..], &owner);
};
($account:expr, $pubkey:expr, $type:ident, $name: ident) => {
let mut lamports = 0;
let mut data = get_anchor_account_bytes(&mut $account);
let owner = $type::owner();
let $name = create_account_info($pubkey, true, &mut lamports, &mut data[..], &owner);
};
}
#[macro_export]
macro_rules! create_account_info {
($account:expr, $owner:expr, $name: ident) => {
let key = Pubkey::default();
let mut lamports = 0;
let mut data = get_account_bytes(&mut $account);
let owner = $type::owner();
let $name = create_account_info(&key, true, &mut lamports, &mut data[..], $owner);
};
($account:expr, $pubkey:expr, $owner:expr, $name: ident) => {
let mut lamports = 0;
let mut data = get_account_bytes(&mut $account);
let $name = create_account_info($pubkey, true, &mut lamports, &mut data[..], $owner);
};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/ids.rs
|
pub mod pyth_program {
use solana_program::declare_id;
#[cfg(feature = "mainnet-beta")]
declare_id!("FsJ3A3u2vn5cTVofAjvy6y5kwABJAqYWpe4975bi2epH");
#[cfg(not(feature = "mainnet-beta"))]
declare_id!("gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s");
}
pub mod wormhole_program {
use solana_program::declare_id;
declare_id!("HDwcJBJXjL9FpJ7UBsYBtaDjsBUhuLCUYoz3zr8SWWaQ");
}
pub mod drift_oracle_receiver_program {
use solana_program::declare_id;
declare_id!("G6EoTTTgpkNBtVXo96EQp2m6uwwVh2Kt6YidjkmQqoha");
}
pub mod pyth_lazer_program {
use solana_program::declare_id;
declare_id!("pytd2yyk641x7ak7mkaasSJVXh6YYZnC7wTmtgAyxPt");
}
pub mod switchboard_program {
use solana_program::declare_id;
declare_id!("SW1TCH7qEPTdLsDHRgPuMQjbQxKdH2aBStViMFnt64f");
}
pub mod switchboard_on_demand {
use solana_program::declare_id;
#[cfg(feature = "mainnet-beta")]
declare_id!("SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv");
#[cfg(not(feature = "mainnet-beta"))]
declare_id!("Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2");
}
pub mod serum_program {
use solana_program::declare_id;
#[cfg(feature = "mainnet-beta")]
declare_id!("srmqPvymJeFKQ4zGQed1GFppgkRHL9kaELCbyksJtPX");
#[cfg(not(feature = "mainnet-beta"))]
declare_id!("DESVgJVGajEgKGXhb6XmqDHGz3VjdgP7rEVESBgxmroY");
}
pub mod srm_mint {
use solana_program::declare_id;
declare_id!("SRMuApVNdxXokk5GT7XD5cUUgXMBCoAz2LHeuAoKWRt");
}
pub mod msrm_mint {
use solana_program::declare_id;
declare_id!("MSRMcoVyrFxnSgo5uXwone5SKcGhT1KEJMFEkMEWf9L");
}
pub mod jupiter_mainnet_6 {
use solana_program::declare_id;
declare_id!("JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4");
}
pub mod jupiter_mainnet_4 {
use solana_program::declare_id;
declare_id!("JUP4Fb2cqiRUcaTHdrPC8h2gNsA2ETXiPDD33WcGuJB");
}
pub mod jupiter_mainnet_3 {
use solana_program::declare_id;
declare_id!("JUP3c2Uh3WA4Ng34tw6kPd2G4C5BB21Xo36Je1s32Ph");
}
pub mod marinade_mainnet {
use solana_program::declare_id;
declare_id!("MarBmsSgKXdrN1egZf5sqe1TMai9K1rChYNDJgjq7aD");
}
pub mod admin_hot_wallet {
use solana_program::declare_id;
declare_id!("5hMjmxexWu954pX9gB9jkHxMqdjpxArQS2XdvkaevRax");
}
pub mod swift_server {
use solana_program::declare_id;
#[cfg(not(feature = "anchor-test"))]
declare_id!("SW1fThqrxLzVprnCMpiybiqYQfoNCdduC5uWsSUKChS");
#[cfg(feature = "anchor-test")]
declare_id!("DpaEdAPW3ZX67fnczT14AoX12Lx9VMkxvtT81nCHy3Nv");
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/signer.rs
|
pub fn get_signer_seeds(nonce: &u8) -> [&[u8]; 2] {
[b"drift_signer".as_ref(), bytemuck::bytes_of(nonce)]
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/macros.rs
|
#[macro_export]
macro_rules! get_struct_values {
($struct:expr, $($property: ident),+) => {{
($(
$struct.$property,
)+)
}};
}
#[macro_export]
macro_rules! get_then_update_id {
($struct:expr, $property: ident) => {{
let current_id = $struct.$property;
$struct.$property = current_id.checked_add(1).or(Some(1)).unwrap();
current_id
}};
}
#[macro_export]
macro_rules! validate {
($assert:expr, $err:expr) => {{
if ($assert) {
Ok(())
} else {
let error_code: ErrorCode = $err;
msg!("Error {} thrown at {}:{}", error_code, file!(), line!());
Err(error_code)
}
}};
($assert:expr, $err:expr, $($arg:tt)+) => {{
if ($assert) {
Ok(())
} else {
let error_code: ErrorCode = $err;
msg!("Error {} thrown at {}:{}", error_code, file!(), line!());
msg!($($arg)*);
Err(error_code)
}
}};
}
#[macro_export]
macro_rules! dlog {
($($variable: expr),+) => {{
$(
msg!("{}: {}", stringify!($variable), $variable);
)+
}};
($($arg:tt)+) => {{
#[cfg(not(feature = "mainnet-beta"))]
msg!($($arg)+);
}};
}
#[macro_export]
macro_rules! load_mut {
($account_loader:expr) => {{
$account_loader.load_mut().map_err(|e| {
msg!("e {:?}", e);
let error_code = ErrorCode::UnableToLoadAccountLoader;
msg!("Error {} thrown at {}:{}", error_code, file!(), line!());
error_code
})
}};
}
#[macro_export]
macro_rules! load {
($account_loader:expr) => {{
$account_loader.load().map_err(|_| {
let error_code = ErrorCode::UnableToLoadAccountLoader;
msg!("Error {} thrown at {}:{}", error_code, file!(), line!());
error_code
})
}};
}
#[macro_export]
macro_rules! safe_increment {
($struct:expr, $value:expr) => {{
$struct = $struct.checked_add($value).ok_or_else(math_error!())?
}};
}
#[macro_export]
macro_rules! safe_decrement {
($struct:expr, $value:expr) => {{
$struct = $struct.checked_sub($value).ok_or_else(math_error!())?
}};
}
/// Calculate the sha256 digest of anchor encoded `struct`
#[macro_export]
macro_rules! digest_struct {
($struct:expr) => {
solana_program::hash::hash(&$struct.try_to_vec().unwrap()).to_bytes()
};
}
/// Calculate the hexified sha256 digest of anchor encoded `struct`
#[macro_export]
macro_rules! digest_struct_hex {
($struct:expr) => {{
hex::encode(digest_struct!($struct)).into_bytes()
}};
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/keeper.rs
|
use std::cell::RefMut;
use std::convert::{TryFrom, TryInto};
use anchor_lang::prelude::*;
use anchor_spl::associated_token::{
get_associated_token_address, get_associated_token_address_with_program_id,
};
use anchor_spl::token::spl_token;
use anchor_spl::token_2022::spl_token_2022;
use anchor_spl::token_interface::{TokenAccount, TokenInterface};
use solana_program::instruction::Instruction;
use solana_program::sysvar::instructions::{
load_current_index_checked, load_instruction_at_checked, ID as IX_ID,
};
use crate::controller::insurance::update_user_stats_if_stake_amount;
use crate::controller::orders::cancel_orders;
use crate::controller::position::PositionDirection;
use crate::controller::spot_balance::update_spot_balances;
use crate::controller::token::{receive, send_from_program_vault};
use crate::error::ErrorCode;
use crate::ids::{admin_hot_wallet, swift_server};
use crate::instructions::constraints::*;
use crate::instructions::optional_accounts::{load_maps, AccountMaps};
use crate::math::casting::Cast;
use crate::math::constants::QUOTE_SPOT_MARKET_INDEX;
use crate::math::margin::{calculate_user_equity, meets_settle_pnl_maintenance_margin_requirement};
use crate::math::orders::{estimate_price_from_side, find_bids_and_asks_from_users};
use crate::math::position::calculate_base_asset_value_and_pnl_with_oracle_price;
use crate::math::safe_math::SafeMath;
use crate::math::spot_withdraw::validate_spot_market_vault_amount;
use crate::math_error;
use crate::optional_accounts::{get_token_mint, update_prelaunch_oracle};
use crate::state::events::{DeleteUserRecord, OrderActionExplanation, SwiftOrderRecord};
use crate::state::fill_mode::FillMode;
use crate::state::fulfillment_params::drift::MatchFulfillmentParams;
use crate::state::fulfillment_params::openbook_v2::OpenbookV2FulfillmentParams;
use crate::state::fulfillment_params::phoenix::PhoenixFulfillmentParams;
use crate::state::fulfillment_params::serum::SerumFulfillmentParams;
use crate::state::high_leverage_mode_config::HighLeverageModeConfig;
use crate::state::insurance_fund_stake::InsuranceFundStake;
use crate::state::oracle_map::OracleMap;
use crate::state::order_params::{
OrderParams, PlaceOrderOptions, SwiftOrderParamsMessage, SwiftServerMessage,
};
use crate::state::paused_operations::PerpOperation;
use crate::state::perp_market::{ContractType, MarketStatus, PerpMarket};
use crate::state::perp_market_map::{
get_market_set_for_spot_positions, get_market_set_for_user_positions, get_market_set_from_list,
get_writable_perp_market_set, get_writable_perp_market_set_from_vec, MarketSet, PerpMarketMap,
};
use crate::state::settle_pnl_mode::SettlePnlMode;
use crate::state::spot_fulfillment_params::SpotFulfillmentParams;
use crate::state::spot_market::{SpotBalanceType, SpotMarket};
use crate::state::spot_market_map::{
get_writable_spot_market_set, get_writable_spot_market_set_from_many, SpotMarketMap,
};
use crate::state::state::State;
use crate::state::swift_user::{
SwiftOrderId, SwiftUserOrdersLoader, SwiftUserOrdersZeroCopyMut, SWIFT_PDA_SEED,
};
use crate::state::user::{
MarginMode, MarketType, OrderStatus, OrderTriggerCondition, OrderType, User, UserStats,
};
use crate::state::user_map::{load_user_map, load_user_maps, UserMap, UserStatsMap};
use crate::validation::sig_verification::{extract_ed25519_ix_signature, verify_ed25519_msg};
use crate::validation::user::{validate_user_deletion, validate_user_is_idle};
use crate::{
controller, digest_struct, digest_struct_hex, load, math, print_error, safe_decrement,
OracleSource, GOV_SPOT_MARKET_INDEX, MARGIN_PRECISION,
};
use crate::{load_mut, QUOTE_PRECISION_U64};
use crate::{validate, QUOTE_PRECISION_I128};
use crate::math::margin::calculate_margin_requirement_and_total_collateral_and_liability_info;
use crate::math::margin::MarginRequirementType;
use crate::state::margin_calculation::MarginContext;
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_fill_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, FillOrder<'info>>,
order_id: Option<u32>,
) -> Result<()> {
let (order_id, market_index) = {
let user = &load!(ctx.accounts.user)?;
// if there is no order id, use the users last order id
let order_id = order_id.unwrap_or_else(|| user.get_last_order_id());
let market_index = match user.get_order(order_id) {
Some(order) => order.market_index,
None => {
msg!("Order does not exist {}", order_id);
return Ok(());
}
};
(order_id, market_index)
};
let user_key = &ctx.accounts.user.key();
fill_order(ctx, order_id, market_index).map_err(|e| {
msg!(
"Err filling order id {} for user {} for market index {}",
order_id,
user_key,
market_index
);
e
})?;
Ok(())
}
fn fill_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, FillOrder<'info>>,
order_id: u32,
market_index: u16,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&get_writable_perp_market_set(market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let (makers_and_referrer, makers_and_referrer_stats) =
load_user_maps(remaining_accounts_iter, true)?;
controller::repeg::update_amm(
market_index,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.state,
clock,
)?;
controller::orders::fill_perp_order(
order_id,
&ctx.accounts.state,
&ctx.accounts.user,
&ctx.accounts.user_stats,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.filler,
&ctx.accounts.filler_stats,
&makers_and_referrer,
&makers_and_referrer_stats,
None,
clock,
FillMode::Fill,
)?;
Ok(())
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_revert_fill<'info>(ctx: Context<RevertFill>) -> Result<()> {
let filler = load_mut!(ctx.accounts.filler)?;
let clock = Clock::get()?;
validate!(
filler.last_active_slot == clock.slot,
ErrorCode::RevertFill,
"filler last active slot ({}) != current slot ({})",
filler.last_active_slot,
clock.slot
)?;
Ok(())
}
#[derive(Clone, Copy, AnchorSerialize, AnchorDeserialize, PartialEq, Debug, Eq, Default)]
pub enum SpotFulfillmentType {
#[default]
SerumV3,
Match,
PhoenixV1,
OpenbookV2,
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_fill_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, FillOrder<'info>>,
order_id: Option<u32>,
fulfillment_type: Option<SpotFulfillmentType>,
_maker_order_id: Option<u32>,
) -> Result<()> {
let (order_id, market_index) = {
let user = &load!(ctx.accounts.user)?;
// if there is no order id, use the users last order id
let order_id = order_id.unwrap_or_else(|| user.get_last_order_id());
let market_index = user
.get_order(order_id)
.map(|order| order.market_index)
.ok_or(ErrorCode::OrderDoesNotExist)?;
(order_id, market_index)
};
let user_key = &ctx.accounts.user.key();
fill_spot_order(
ctx,
order_id,
market_index,
fulfillment_type.unwrap_or(SpotFulfillmentType::Match),
)
.map_err(|e| {
msg!("Err filling order id {} for user {}", order_id, user_key);
e
})?;
Ok(())
}
fn fill_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, FillOrder<'info>>,
order_id: u32,
market_index: u16,
fulfillment_type: SpotFulfillmentType,
) -> Result<()> {
let clock = Clock::get()?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&get_writable_spot_market_set_from_many(vec![QUOTE_SPOT_MARKET_INDEX, market_index]),
Clock::get()?.slot,
None,
)?;
let (makers_and_referrer, makers_and_referrer_stats) = match fulfillment_type {
SpotFulfillmentType::Match => load_user_maps(remaining_accounts_iter, true)?,
_ => (UserMap::empty(), UserStatsMap::empty()),
};
let mut fulfillment_params: Box<dyn SpotFulfillmentParams> = match fulfillment_type {
SpotFulfillmentType::SerumV3 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(SerumFulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::PhoenixV1 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(PhoenixFulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
)?)
}
SpotFulfillmentType::OpenbookV2 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(OpenbookV2FulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::Match => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(MatchFulfillmentParams::new(
remaining_accounts_iter,
&base_market,
"e_market,
)?)
}
};
controller::orders::fill_spot_order(
order_id,
&ctx.accounts.state,
&ctx.accounts.user,
&ctx.accounts.user_stats,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.filler,
&ctx.accounts.filler_stats,
&makers_and_referrer,
&makers_and_referrer_stats,
None,
&clock,
fulfillment_params.as_mut(),
)?;
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
fulfillment_params.validate_vault_amounts(&base_market, "e_market)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_trigger_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, TriggerOrder<'info>>,
order_id: u32,
) -> Result<()> {
let (market_type, market_index) = match load!(ctx.accounts.user)?.get_order(order_id) {
Some(order) => (order.market_type, order.market_index),
None => {
msg!("order_id not found {}", order_id);
return Ok(());
}
};
let (writeable_perp_markets, writeable_spot_markets) = match market_type {
MarketType::Spot => (
MarketSet::new(),
get_writable_spot_market_set_from_many(vec![QUOTE_SPOT_MARKET_INDEX, market_index]),
),
MarketType::Perp => (MarketSet::new(), MarketSet::new()),
};
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&writeable_perp_markets,
&writeable_spot_markets,
Clock::get()?.slot,
None,
)?;
match market_type {
MarketType::Perp => controller::orders::trigger_order(
order_id,
&ctx.accounts.state,
&ctx.accounts.user,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.filler,
&Clock::get()?,
)?,
MarketType::Spot => controller::orders::trigger_spot_order(
order_id,
&ctx.accounts.state,
&ctx.accounts.user,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.filler,
&Clock::get()?,
)?,
}
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_force_cancel_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ForceCancelOrder>,
) -> Result<()> {
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&get_writable_spot_market_set(QUOTE_SPOT_MARKET_INDEX),
Clock::get()?.slot,
None,
)?;
controller::orders::force_cancel_orders(
&ctx.accounts.state,
&ctx.accounts.user,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.filler,
&Clock::get()?,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_update_user_idle<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUserIdle<'info>>,
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
let clock = Clock::get()?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
None,
)?;
let (equity, _) =
calculate_user_equity(&user, &perp_market_map, &spot_market_map, &mut oracle_map)?;
// user flipped to idle faster if equity is less than 1000
let accelerated = equity < QUOTE_PRECISION_I128 * 1000;
validate_user_is_idle(&user, clock.slot, accelerated)?;
user.idle = true;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_log_user_balances<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LogUserBalances<'info>>,
) -> Result<()> {
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
let clock = Clock::get()?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
None,
)?;
let (equity, _) =
calculate_user_equity(&user, &perp_market_map, &spot_market_map, &mut oracle_map)?;
msg!(
"Authority key {} subaccount id {} user key {}",
user.authority,
user.sub_account_id,
user_key
);
msg!("Equity {}", equity);
for spot_position in user.spot_positions.iter() {
if spot_position.scaled_balance == 0 {
continue;
}
let spot_market = spot_market_map.get_ref(&spot_position.market_index)?;
let token_amount = spot_position.get_signed_token_amount(&spot_market)?;
msg!(
"Spot position {} balance {}",
spot_position.market_index,
token_amount
);
}
for perp_position in user.perp_positions.iter() {
if perp_position.is_available() {
continue;
}
let perp_market = perp_market_map.get_ref(&perp_position.market_index)?;
let oracle_price = oracle_map.get_price_data(&perp_market.oracle_id())?.price;
let (_, unrealized_pnl) =
calculate_base_asset_value_and_pnl_with_oracle_price(&perp_position, oracle_price)?;
if unrealized_pnl == 0 {
continue;
}
msg!(
"Perp position {} unrealized pnl {}",
perp_position.market_index,
unrealized_pnl
);
}
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_update_user_fuel_bonus<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUserFuelBonus<'info>>,
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
None,
)?;
let user_margin_calculation =
calculate_margin_requirement_and_total_collateral_and_liability_info(
&user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
MarginContext::standard(MarginRequirementType::Initial).fuel_numerator(&user, now),
)?;
user_stats.update_fuel_bonus(
&mut user,
user_margin_calculation.fuel_deposits,
user_margin_calculation.fuel_borrows,
user_margin_calculation.fuel_positions,
now,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_update_user_stats_referrer_info<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUserStatsReferrerInfo<'info>>,
) -> Result<()> {
let mut user_stats = load_mut!(ctx.accounts.user_stats)?;
user_stats.update_referrer_status();
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_update_user_open_orders_count<'info>(ctx: Context<UpdateUserIdle>) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
let mut open_orders = 0_u8;
let mut open_auctions = 0_u8;
for order in user.orders.iter() {
if order.status == OrderStatus::Open {
open_orders += 1;
}
if order.has_auction() {
open_auctions += 1;
}
}
user.open_orders = open_orders;
user.has_open_order = open_orders > 0;
user.open_auctions = open_auctions;
user.has_open_auction = open_auctions > 0;
Ok(())
}
pub fn handle_place_swift_taker_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceSwiftTakerOrder<'info>>,
swift_message_bytes: Vec<u8>,
swift_order_params_message_bytes: Vec<u8>,
) -> Result<()> {
let swift_message: SwiftServerMessage =
SwiftServerMessage::deserialize(&mut &swift_message_bytes[..]).unwrap();
let taker_order_params_message: SwiftOrderParamsMessage =
SwiftOrderParamsMessage::deserialize(&mut &swift_order_params_message_bytes[..]).unwrap();
let state = &ctx.accounts.state;
// TODO: generalize to support multiple market types
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
Some(state.oracle_guard_rails),
)?;
let taker_key = ctx.accounts.user.key();
let mut taker = load_mut!(ctx.accounts.user)?;
let mut swift_taker = ctx.accounts.swift_user_orders.load_mut()?;
place_swift_taker_order(
taker_key,
&mut taker,
&mut swift_taker,
swift_message,
taker_order_params_message,
&ctx.accounts.ix_sysvar.to_account_info(),
&perp_market_map,
&spot_market_map,
&mut oracle_map,
state,
)?;
Ok(())
}
pub fn place_swift_taker_order<'c: 'info, 'info>(
taker_key: Pubkey,
taker: &mut RefMut<User>,
swift_account: &mut SwiftUserOrdersZeroCopyMut,
swift_message: SwiftServerMessage,
taker_order_params_message: SwiftOrderParamsMessage,
ix_sysvar: &AccountInfo<'info>,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
state: &State,
) -> Result<()> {
#[cfg(all(feature = "mainnet-beta", not(feature = "anchor-test")))]
{
panic!("Swift orders are disabled on mainnet-beta");
}
// Authenticate the swift param message
let ix_idx = load_current_index_checked(ix_sysvar)?;
validate!(
ix_idx > 1,
ErrorCode::InvalidVerificationIxIndex,
"instruction index must be greater than 1 for two sig verifies"
)?;
// Verify data from first verify ix
let ix: Instruction = load_instruction_at_checked(ix_idx as usize - 2, ix_sysvar)?;
verify_ed25519_msg(
&ix,
&swift_server::id().to_bytes(),
&digest_struct!(swift_message),
)?;
// Verify data from second verify ix
let digest_hex = digest_struct_hex!(taker_order_params_message);
let ix: Instruction = load_instruction_at_checked(ix_idx as usize - 1, ix_sysvar)?;
verify_ed25519_msg(
&ix,
&taker.authority.to_bytes(),
arrayref::array_ref!(digest_hex, 0, 64),
)?;
// Verify that sig from swift server corresponds to order message
if swift_message.swift_order_signature != extract_ed25519_ix_signature(&ix.data)? {
msg!("Swift order signature does not match the order signature");
return Err(ErrorCode::SigVerificationFailed.into());
}
let clock = &Clock::get()?;
// First order must be a taker order
let matching_taker_order_params = &taker_order_params_message.swift_order_params;
if (matching_taker_order_params.order_type != OrderType::Market
&& matching_taker_order_params.order_type != OrderType::Oracle)
|| matching_taker_order_params.market_type != MarketType::Perp
{
msg!("First order must be a market or oracle perp taker order");
return Err(print_error!(ErrorCode::InvalidSwiftOrderParam)().into());
}
// Make sure that them auction parameters are set
if matching_taker_order_params.auction_duration.is_none()
|| matching_taker_order_params.auction_start_price.is_none()
|| matching_taker_order_params.auction_end_price.is_none()
{
msg!("Auction params must be set for swift orders");
return Err(print_error!(ErrorCode::InvalidSwiftOrderParam)().into());
}
// Set max slot for the order early so we set correct swift order id
let order_slot = swift_message.slot;
let market_index = matching_taker_order_params.market_index;
let max_slot = order_slot.safe_add(
matching_taker_order_params
.auction_duration
.unwrap()
.cast::<u64>()?,
)?;
// Dont place order if max slot already passed
if max_slot < clock.slot {
msg!(
"Swift order max_slot {} < current slot {}",
max_slot,
clock.slot
);
return Ok(());
}
// Dont place order if swift order already exists
let swift_order_id = SwiftOrderId::new(swift_message.uuid, max_slot, taker.next_order_id);
if swift_account.check_exists_and_prune_stale_swift_order_ids(swift_order_id, clock.slot) {
msg!("Swift order already exists for taker {}");
return Ok(());
}
swift_account.add_swift_order_id(swift_order_id)?;
controller::orders::place_perp_order(
state,
taker,
taker_key,
perp_market_map,
spot_market_map,
oracle_map,
clock,
*matching_taker_order_params,
PlaceOrderOptions {
swift_taker_order_slot: Some(order_slot),
..PlaceOrderOptions::default()
},
)?;
let order_params_hash = base64::encode(
solana_program::hash::hash(&swift_message.swift_order_signature.try_to_vec().unwrap())
.as_ref(),
);
emit!(SwiftOrderRecord {
user: taker_key,
swift_order_max_slot: swift_order_id.max_slot,
swift_order_uuid: swift_order_id.uuid,
user_order_id: swift_order_id.order_id,
matching_order_params: matching_taker_order_params.clone(),
hash: order_params_hash,
ts: clock.unix_timestamp,
});
if let Some(stop_loss_order_params) = taker_order_params_message.stop_loss_order_params {
let stop_loss_order = OrderParams {
order_type: OrderType::TriggerMarket,
direction: matching_taker_order_params.direction.opposite(),
trigger_price: Some(stop_loss_order_params.trigger_price),
base_asset_amount: stop_loss_order_params.base_asset_amount,
trigger_condition: if matching_taker_order_params.direction == PositionDirection::Long {
OrderTriggerCondition::Below
} else {
OrderTriggerCondition::Above
},
market_index,
market_type: MarketType::Perp,
reduce_only: true,
..OrderParams::default()
};
controller::orders::place_perp_order(
state,
taker,
taker_key,
perp_market_map,
spot_market_map,
oracle_map,
clock,
stop_loss_order,
PlaceOrderOptions {
..PlaceOrderOptions::default()
},
)?;
}
if let Some(take_profit_order_params) = taker_order_params_message.take_profit_order_params {
let take_profit_order = OrderParams {
order_type: OrderType::TriggerMarket,
direction: matching_taker_order_params.direction.opposite(),
trigger_price: Some(take_profit_order_params.trigger_price),
base_asset_amount: take_profit_order_params.base_asset_amount,
trigger_condition: if matching_taker_order_params.direction == PositionDirection::Long {
OrderTriggerCondition::Above
} else {
OrderTriggerCondition::Below
},
market_index,
market_type: MarketType::Perp,
reduce_only: true,
..OrderParams::default()
};
controller::orders::place_perp_order(
state,
taker,
taker_key,
perp_market_map,
spot_market_map,
oracle_map,
clock,
take_profit_order,
PlaceOrderOptions {
swift_taker_order_slot: Some(order_slot),
..PlaceOrderOptions::default()
},
)?;
}
Ok(())
}
#[access_control(
settle_pnl_not_paused(&ctx.accounts.state)
)]
pub fn handle_settle_pnl<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettlePNL>,
market_index: u16,
) -> Result<()> {
let clock = Clock::get()?;
let state = &ctx.accounts.state;
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set(market_index),
&get_writable_spot_market_set(QUOTE_SPOT_MARKET_INDEX),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let market_in_settlement =
perp_market_map.get_ref(&market_index)?.status == MarketStatus::Settlement;
if market_in_settlement {
amm_not_paused(state)?;
controller::pnl::settle_expired_position(
market_index,
user,
&user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
state,
)?;
user.update_last_active_slot(clock.slot);
} else {
controller::repeg::update_amm(
market_index,
&perp_market_map,
&mut oracle_map,
state,
&clock,
)
.map(|_| ErrorCode::InvalidOracleForSettlePnl)?;
controller::pnl::settle_pnl(
market_index,
user,
ctx.accounts.authority.key,
&user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
state,
None,
SettlePnlMode::MustSettle,
)
.map(|_| ErrorCode::InvalidOracleForSettlePnl)?;
user.update_last_active_slot(clock.slot);
}
let spot_market = spot_market_map.get_quote_spot_market()?;
validate_spot_market_vault_amount(&spot_market, ctx.accounts.spot_market_vault.amount)?;
Ok(())
}
#[access_control(
settle_pnl_not_paused(&ctx.accounts.state)
)]
pub fn handle_settle_multiple_pnls<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettlePNL>,
market_indexes: Vec<u16>,
mode: SettlePnlMode,
) -> Result<()> {
let clock = Clock::get()?;
let state = &ctx.accounts.state;
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set_from_vec(&market_indexes),
&get_writable_spot_market_set(QUOTE_SPOT_MARKET_INDEX),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let meets_margin_requirement = meets_settle_pnl_maintenance_margin_requirement(
user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
)?;
for market_index in market_indexes.iter() {
let market_in_settlement =
perp_market_map.get_ref(market_index)?.status == MarketStatus::Settlement;
if market_in_settlement {
amm_not_paused(state)?;
controller::pnl::settle_expired_position(
*market_index,
user,
&user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
state,
)?;
user.update_last_active_slot(clock.slot);
} else {
controller::repeg::update_amm(
*market_index,
&perp_market_map,
&mut oracle_map,
state,
&clock,
)
.map(|_| ErrorCode::InvalidOracleForSettlePnl)?;
controller::pnl::settle_pnl(
*market_index,
user,
ctx.accounts.authority.key,
&user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
state,
Some(meets_margin_requirement),
mode,
)
.map(|_| ErrorCode::InvalidOracleForSettlePnl)?;
user.update_last_active_slot(clock.slot);
}
}
let spot_market = spot_market_map.get_quote_spot_market()?;
validate_spot_market_vault_amount(&spot_market, ctx.accounts.spot_market_vault.amount)?;
Ok(())
}
#[access_control(
funding_not_paused(&ctx.accounts.state)
)]
pub fn handle_settle_funding_payment<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettleFunding>,
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let AccountMaps {
perp_market_map, ..
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_market_set_for_user_positions(&user.perp_positions),
&MarketSet::new(),
clock.slot,
None,
)?;
controller::funding::settle_funding_payments(user, &user_key, &perp_market_map, now)?;
user.update_last_active_slot(clock.slot);
Ok(())
}
#[access_control(
amm_not_paused(&ctx.accounts.state)
)]
pub fn handle_settle_lp<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettleLP>,
market_index: u16,
) -> Result<()> {
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let AccountMaps {
perp_market_map, ..
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set(market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let market = &mut perp_market_map.get_ref_mut(&market_index)?;
controller::lp::settle_funding_payment_then_lp(user, &user_key, market, now)?;
user.update_last_active_slot(clock.slot);
Ok(())
}
#[access_control(
liq_not_paused(&ctx.accounts.state)
)]
pub fn handle_liquidate_perp<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidatePerp<'info>>,
market_index: u16,
liquidator_max_base_asset_amount: u64,
limit_price: Option<u64>,
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let slot = clock.slot;
let state = &ctx.accounts.state;
let user_key = ctx.accounts.user.key();
let liquidator_key = ctx.accounts.liquidator.key();
validate!(
user_key != liquidator_key,
ErrorCode::UserCantLiquidateThemself
)?;
let user = &mut load_mut!(ctx.accounts.user)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let liquidator = &mut load_mut!(ctx.accounts.liquidator)?;
let liquidator_stats = &mut load_mut!(ctx.accounts.liquidator_stats)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set(market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::liquidation::liquidate_perp(
market_index,
liquidator_max_base_asset_amount,
limit_price,
user,
&user_key,
user_stats,
liquidator,
&liquidator_key,
liquidator_stats,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
slot,
now,
state,
)?;
Ok(())
}
#[access_control(
liq_not_paused(&ctx.accounts.state)
)]
pub fn handle_liquidate_perp_with_fill<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidatePerp<'info>>,
market_index: u16,
) -> Result<()> {
let clock = Clock::get()?;
let state = &ctx.accounts.state;
let user_key = ctx.accounts.user.key();
let liquidator_key = ctx.accounts.liquidator.key();
validate!(
user_key != liquidator_key,
ErrorCode::UserCantLiquidateThemself
)?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&get_writable_perp_market_set(market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let (makers_and_referrer, makers_and_referrer_stats) =
load_user_maps(remaining_accounts_iter, true)?;
controller::liquidation::liquidate_perp_with_fill(
market_index,
&ctx.accounts.user,
&user_key,
&ctx.accounts.user_stats,
&ctx.accounts.liquidator,
&liquidator_key,
&ctx.accounts.liquidator_stats,
&makers_and_referrer,
&makers_and_referrer_stats,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
state,
)?;
Ok(())
}
#[access_control(
liq_not_paused(&ctx.accounts.state)
)]
pub fn handle_liquidate_spot<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidateSpot<'info>>,
asset_market_index: u16,
liability_market_index: u16,
liquidator_max_liability_transfer: u128,
limit_price: Option<u64>,
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let state = &ctx.accounts.state;
let user_key = ctx.accounts.user.key();
let liquidator_key = ctx.accounts.liquidator.key();
validate!(
user_key != liquidator_key,
ErrorCode::UserCantLiquidateThemself
)?;
let user = &mut load_mut!(ctx.accounts.user)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let liquidator = &mut load_mut!(ctx.accounts.liquidator)?;
let liquidator_stats = &mut load_mut!(ctx.accounts.liquidator_stats)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&get_writable_spot_market_set_from_many(vec![asset_market_index, liability_market_index]),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::liquidation::liquidate_spot(
asset_market_index,
liability_market_index,
liquidator_max_liability_transfer,
limit_price,
user,
&user_key,
user_stats,
liquidator,
&liquidator_key,
liquidator_stats,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
now,
clock.slot,
state,
)?;
Ok(())
}
#[access_control(
liq_not_paused(&ctx.accounts.state)
)]
pub fn handle_liquidate_borrow_for_perp_pnl<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidateBorrowForPerpPnl<'info>>,
perp_market_index: u16,
spot_market_index: u16,
liquidator_max_liability_transfer: u128,
limit_price: Option<u64>, // currently unimplemented
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let state = &ctx.accounts.state;
let user_key = ctx.accounts.user.key();
let liquidator_key = ctx.accounts.liquidator.key();
validate!(
user_key != liquidator_key,
ErrorCode::UserCantLiquidateThemself
)?;
let user = &mut load_mut!(ctx.accounts.user)?;
let liquidator = &mut load_mut!(ctx.accounts.liquidator)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&get_writable_spot_market_set(spot_market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::liquidation::liquidate_borrow_for_perp_pnl(
perp_market_index,
spot_market_index,
liquidator_max_liability_transfer,
limit_price,
user,
&user_key,
liquidator,
&liquidator_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
now,
clock.slot,
state.liquidation_margin_buffer_ratio,
state.initial_pct_to_liquidate as u128,
state.liquidation_duration as u128,
)?;
Ok(())
}
#[access_control(
liq_not_paused(&ctx.accounts.state)
)]
pub fn handle_liquidate_perp_pnl_for_deposit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, LiquidatePerpPnlForDeposit<'info>>,
perp_market_index: u16,
spot_market_index: u16,
liquidator_max_pnl_transfer: u128,
limit_price: Option<u64>, // currently unimplemented
) -> Result<()> {
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let user_key = ctx.accounts.user.key();
let liquidator_key = ctx.accounts.liquidator.key();
validate!(
user_key != liquidator_key,
ErrorCode::UserCantLiquidateThemself
)?;
let user = &mut load_mut!(ctx.accounts.user)?;
let liquidator = &mut load_mut!(ctx.accounts.liquidator)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&get_writable_spot_market_set(spot_market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::liquidation::liquidate_perp_pnl_for_deposit(
perp_market_index,
spot_market_index,
liquidator_max_pnl_transfer,
limit_price,
user,
&user_key,
liquidator,
&liquidator_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
now,
clock.slot,
state.liquidation_margin_buffer_ratio,
state.initial_pct_to_liquidate as u128,
state.liquidation_duration as u128,
)?;
Ok(())
}
#[access_control(
liq_not_paused(&ctx.accounts.state)
)]
pub fn handle_set_user_status_to_being_liquidated<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SetUserStatusToBeingLiquidated<'info>>,
) -> Result<()> {
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let user = &mut load_mut!(ctx.accounts.user)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::liquidation::set_user_status_to_being_liquidated(
user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock.slot,
&state,
)?;
Ok(())
}
#[access_control(
withdraw_not_paused(&ctx.accounts.state)
)]
pub fn handle_resolve_perp_pnl_deficit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResolvePerpPnlDeficit<'info>>,
spot_market_index: u16,
perp_market_index: u16,
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
validate!(spot_market_index == 0, ErrorCode::InvalidSpotMarketAccount)?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&get_writable_perp_market_set(perp_market_index),
&get_writable_spot_market_set(spot_market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let mint = get_token_mint(remaining_accounts_iter)?;
controller::repeg::update_amm(
perp_market_index,
&perp_market_map,
&mut oracle_map,
state,
&clock,
)?;
{
let spot_market = &mut spot_market_map.get_ref_mut(&spot_market_index)?;
controller::insurance::attempt_settle_revenue_to_insurance_fund(
&ctx.accounts.spot_market_vault,
&ctx.accounts.insurance_fund_vault,
spot_market,
now,
&ctx.accounts.token_program,
&ctx.accounts.drift_signer,
state,
&mint,
)?;
// reload the spot market vault balance so it's up-to-date
ctx.accounts.spot_market_vault.reload()?;
ctx.accounts.insurance_fund_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
}
let insurance_vault_amount = ctx.accounts.insurance_fund_vault.amount;
let spot_market_vault_amount = ctx.accounts.spot_market_vault.amount;
let pay_from_insurance = {
let spot_market = &mut spot_market_map.get_ref_mut(&spot_market_index)?;
let perp_market = &mut perp_market_map.get_ref_mut(&perp_market_index)?;
if perp_market.amm.curve_update_intensity > 0 {
validate!(
perp_market.amm.last_oracle_valid,
ErrorCode::InvalidOracle,
"Oracle Price detected as invalid"
)?;
validate!(
oracle_map.slot == perp_market.amm.last_update_slot,
ErrorCode::AMMNotUpdatedInSameSlot,
"AMM must be updated in a prior instruction within same slot"
)?;
}
validate!(
!perp_market.is_in_settlement(now),
ErrorCode::MarketActionPaused,
"Market is in settlement mode",
)?;
let oracle_price = oracle_map.get_price_data(&perp_market.oracle_id())?.price;
controller::orders::validate_market_within_price_band(perp_market, state, oracle_price)?;
controller::insurance::resolve_perp_pnl_deficit(
spot_market_vault_amount,
insurance_vault_amount,
spot_market,
perp_market,
clock.unix_timestamp,
)?
};
if pay_from_insurance > 0 {
validate!(
pay_from_insurance < ctx.accounts.insurance_fund_vault.amount,
ErrorCode::InsufficientCollateral,
"Insurance Fund balance InsufficientCollateral for payment: !{} < {}",
pay_from_insurance,
ctx.accounts.insurance_fund_vault.amount
)?;
controller::token::send_from_program_vault(
&ctx.accounts.token_program,
&ctx.accounts.insurance_fund_vault,
&ctx.accounts.spot_market_vault,
&ctx.accounts.drift_signer,
state.signer_nonce,
pay_from_insurance,
&mint,
)?;
validate!(
ctx.accounts.insurance_fund_vault.amount > 0,
ErrorCode::InvalidIFDetected,
"insurance_fund_vault.amount must remain > 0"
)?;
}
// todo: validate amounts transfered and spot_market before and after are zero-sum
Ok(())
}
#[access_control(
withdraw_not_paused(&ctx.accounts.state)
)]
pub fn handle_resolve_perp_bankruptcy<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResolveBankruptcy<'info>>,
quote_spot_market_index: u16,
market_index: u16,
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let user_key = ctx.accounts.user.key();
let liquidator_key = ctx.accounts.liquidator.key();
validate!(
user_key != liquidator_key,
ErrorCode::UserCantLiquidateThemself
)?;
validate!(
quote_spot_market_index == QUOTE_SPOT_MARKET_INDEX,
ErrorCode::InvalidSpotMarketAccount
)?;
let user = &mut load_mut!(ctx.accounts.user)?;
let liquidator = &mut load_mut!(ctx.accounts.liquidator)?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&get_writable_perp_market_set(market_index),
&get_writable_spot_market_set(quote_spot_market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let mint = get_token_mint(remaining_accounts_iter)?;
{
let spot_market = &mut spot_market_map.get_ref_mut("e_spot_market_index)?;
controller::insurance::attempt_settle_revenue_to_insurance_fund(
&ctx.accounts.spot_market_vault,
&ctx.accounts.insurance_fund_vault,
spot_market,
now,
&ctx.accounts.token_program,
&ctx.accounts.drift_signer,
state,
&mint,
)?;
// reload the spot market vault balance so it's up-to-date
ctx.accounts.spot_market_vault.reload()?;
ctx.accounts.insurance_fund_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
}
let pay_from_insurance = controller::liquidation::resolve_perp_bankruptcy(
market_index,
user,
&user_key,
liquidator,
&liquidator_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
now,
ctx.accounts.insurance_fund_vault.amount,
)?;
if pay_from_insurance > 0 {
validate!(
pay_from_insurance < ctx.accounts.insurance_fund_vault.amount,
ErrorCode::InsufficientCollateral,
"Insurance Fund balance InsufficientCollateral for payment: !{} < {}",
pay_from_insurance,
ctx.accounts.insurance_fund_vault.amount
)?;
controller::token::send_from_program_vault(
&ctx.accounts.token_program,
&ctx.accounts.insurance_fund_vault,
&ctx.accounts.spot_market_vault,
&ctx.accounts.drift_signer,
state.signer_nonce,
pay_from_insurance,
&mint,
)?;
validate!(
ctx.accounts.insurance_fund_vault.amount > 0,
ErrorCode::InvalidIFDetected,
"insurance_fund_vault.amount must remain > 0"
)?;
}
{
let spot_market = &mut spot_market_map.get_ref_mut("e_spot_market_index)?;
// reload the spot market vault balance so it's up-to-date
ctx.accounts.spot_market_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
}
Ok(())
}
#[access_control(
withdraw_not_paused(&ctx.accounts.state)
)]
pub fn handle_resolve_spot_bankruptcy<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResolveBankruptcy<'info>>,
market_index: u16,
) -> Result<()> {
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let user_key = ctx.accounts.user.key();
let liquidator_key = ctx.accounts.liquidator.key();
validate!(
user_key != liquidator_key,
ErrorCode::UserCantLiquidateThemself
)?;
let user = &mut load_mut!(ctx.accounts.user)?;
let liquidator = &mut load_mut!(ctx.accounts.liquidator)?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&get_writable_spot_market_set(market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let mint = get_token_mint(remaining_accounts_iter)?;
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
controller::insurance::attempt_settle_revenue_to_insurance_fund(
&ctx.accounts.spot_market_vault,
&ctx.accounts.insurance_fund_vault,
spot_market,
now,
&ctx.accounts.token_program,
&ctx.accounts.drift_signer,
state,
&mint,
)?;
// reload the spot market vault balance so it's up-to-date
ctx.accounts.spot_market_vault.reload()?;
ctx.accounts.insurance_fund_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
}
let pay_from_insurance = controller::liquidation::resolve_spot_bankruptcy(
market_index,
user,
&user_key,
liquidator,
&liquidator_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
now,
ctx.accounts.insurance_fund_vault.amount,
)?;
if pay_from_insurance > 0 {
controller::token::send_from_program_vault(
&ctx.accounts.token_program,
&ctx.accounts.insurance_fund_vault,
&ctx.accounts.spot_market_vault,
&ctx.accounts.drift_signer,
ctx.accounts.state.signer_nonce,
pay_from_insurance,
&mint,
)?;
validate!(
ctx.accounts.insurance_fund_vault.amount > 0,
ErrorCode::InvalidIFDetected,
"insurance_fund_vault.amount must remain > 0"
)?;
}
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
// reload the spot market vault balance so it's up-to-date
ctx.accounts.spot_market_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
}
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
funding_not_paused(&ctx.accounts.state)
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_update_funding_rate(
ctx: Context<UpdateFundingRate>,
perp_market_index: u16,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let clock_slot = clock.slot;
let state = &ctx.accounts.state;
let mut oracle_map = OracleMap::load_one(
&ctx.accounts.oracle,
clock_slot,
Some(state.oracle_guard_rails),
)?;
let oracle_price_data = &oracle_map.get_price_data(&perp_market.oracle_id())?;
controller::repeg::_update_amm(perp_market, oracle_price_data, state, now, clock_slot)?;
validate!(
matches!(
perp_market.status,
MarketStatus::Active | MarketStatus::ReduceOnly
),
ErrorCode::MarketActionPaused,
"Market funding is paused",
)?;
let funding_paused =
state.funding_paused()? || perp_market.is_operation_paused(PerpOperation::UpdateFunding);
let is_updated = controller::funding::update_funding_rate(
perp_market_index,
perp_market,
&mut oracle_map,
now,
clock_slot,
&state.oracle_guard_rails,
funding_paused,
None,
)?;
if !is_updated {
let time_until_next_update = crate::math::helpers::on_the_hour_update(
now,
perp_market.amm.last_funding_rate_ts,
perp_market.amm.funding_period,
)?;
msg!(
"time_until_next_update = {:?} seconds",
time_until_next_update
);
return Err(ErrorCode::FundingWasNotUpdated.into());
}
Ok(())
}
#[access_control(
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_update_prelaunch_oracle(ctx: Context<UpdatePrelaunchOracle>) -> Result<()> {
let clock = Clock::get()?;
let clock_slot = clock.slot;
let oracle_map = OracleMap::load_one(&ctx.accounts.oracle, clock_slot, None)?;
let perp_market = &load!(ctx.accounts.perp_market)?;
validate!(
perp_market.amm.oracle_source == OracleSource::Prelaunch,
ErrorCode::DefaultError,
"wrong oracle source"
)?;
update_prelaunch_oracle(perp_market, &oracle_map, clock_slot)?;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
funding_not_paused(&ctx.accounts.state)
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_update_perp_bid_ask_twap<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdatePerpBidAskTwap<'info>>,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let slot = clock.slot;
let state = &ctx.accounts.state;
let mut oracle_map =
OracleMap::load_one(&ctx.accounts.oracle, slot, Some(state.oracle_guard_rails))?;
let keeper_stats = load!(ctx.accounts.keeper_stats)?;
validate!(
!keeper_stats.disable_update_perp_bid_ask_twap,
ErrorCode::CantUpdatePerpBidAskTwap,
"Keeper stats disable_update_perp_bid_ask_twap is true"
)?;
let min_if_stake = 1000 * QUOTE_PRECISION_U64;
validate!(
keeper_stats.if_staked_quote_asset_amount >= min_if_stake,
ErrorCode::CantUpdatePerpBidAskTwap,
"Keeper doesnt have min if stake. stake = {} min if stake = {}",
keeper_stats.if_staked_quote_asset_amount,
min_if_stake
)?;
let oracle_price_data = oracle_map.get_price_data(&perp_market.oracle_id())?;
controller::repeg::_update_amm(perp_market, oracle_price_data, state, now, slot)?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let makers = load_user_map(remaining_accounts_iter, false)?;
let depth = perp_market.get_market_depth_for_funding_rate()?;
let (bids, asks) =
find_bids_and_asks_from_users(perp_market, oracle_price_data, &makers, slot, now)?;
let estimated_bid = estimate_price_from_side(&bids, depth)?;
let estimated_ask = estimate_price_from_side(&asks, depth)?;
msg!(
"estimated_bid = {:?} estimated_ask = {:?}",
estimated_bid,
estimated_ask
);
if perp_market.contract_type == ContractType::Prediction
&& perp_market.is_operation_paused(PerpOperation::AmmFill)
&& (estimated_bid.is_none() || estimated_ask.is_none())
{
msg!("skipping mark twap update for disabled amm prediction market");
return Ok(());
}
msg!(
"before amm bid twap = {} ask twap = {} ts = {}",
perp_market.amm.last_bid_price_twap,
perp_market.amm.last_ask_price_twap,
perp_market.amm.last_mark_price_twap_ts
);
let sanitize_clamp_denominator = perp_market.get_sanitize_clamp_denominator()?;
math::amm::update_mark_twap_crank(
&mut perp_market.amm,
now,
oracle_price_data,
estimated_bid,
estimated_ask,
sanitize_clamp_denominator,
)?;
msg!(
"after amm bid twap = {} ask twap = {} ts = {}",
perp_market.amm.last_bid_price_twap,
perp_market.amm.last_ask_price_twap,
perp_market.amm.last_mark_price_twap_ts
);
let funding_paused =
state.funding_paused()? || perp_market.is_operation_paused(PerpOperation::UpdateFunding);
controller::funding::update_funding_rate(
perp_market.market_index,
perp_market,
&mut oracle_map,
now,
slot,
&state.oracle_guard_rails,
funding_paused,
None,
)?;
Ok(())
}
#[access_control(
withdraw_not_paused(&ctx.accounts.state)
)]
pub fn handle_settle_revenue_to_insurance_fund<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, SettleRevenueToInsuranceFund<'info>>,
spot_market_index: u16,
) -> Result<()> {
let state = &ctx.accounts.state;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let mint = get_token_mint(remaining_accounts_iter)?;
validate!(
spot_market_index == spot_market.market_index,
ErrorCode::InvalidSpotMarketAccount,
"invalid spot_market passed"
)?;
validate!(
spot_market.insurance_fund.revenue_settle_period > 0,
ErrorCode::RevenueSettingsCannotSettleToIF,
"invalid revenue_settle_period settings on spot market"
)?;
let spot_vault_amount = ctx.accounts.spot_market_vault.amount;
let insurance_vault_amount = ctx.accounts.insurance_fund_vault.amount;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let time_until_next_update = math::helpers::on_the_hour_update(
now,
spot_market.insurance_fund.last_revenue_settle_ts,
spot_market.insurance_fund.revenue_settle_period,
)?;
validate!(
time_until_next_update == 0,
ErrorCode::RevenueSettingsCannotSettleToIF,
"Must wait {} seconds until next available settlement time",
time_until_next_update
)?;
// uses proportion of revenue pool allocated to insurance fund
let token_amount = controller::insurance::settle_revenue_to_insurance_fund(
spot_vault_amount,
insurance_vault_amount,
spot_market,
now,
true,
)?;
spot_market.insurance_fund.last_revenue_settle_ts = now;
controller::token::send_from_program_vault(
&ctx.accounts.token_program,
&ctx.accounts.spot_market_vault,
&ctx.accounts.insurance_fund_vault,
&ctx.accounts.drift_signer,
state.signer_nonce,
token_amount,
&mint,
)?;
// reload the spot market vault balance so it's up-to-date
ctx.accounts.spot_market_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
exchange_not_paused(&ctx.accounts.state)
valid_oracle_for_spot_market(&ctx.accounts.oracle, &ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_cumulative_interest(
ctx: Context<UpdateSpotMarketCumulativeInterest>,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let clock_slot = clock.slot;
let mut oracle_map = OracleMap::load_one(
&ctx.accounts.oracle,
clock_slot,
Some(state.oracle_guard_rails),
)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
if !state.funding_paused()? {
controller::spot_balance::update_spot_market_cumulative_interest(
spot_market,
Some(oracle_price_data),
now,
)?;
} else {
// even if funding is paused still update twap stats
controller::spot_balance::update_spot_market_twap_stats(
spot_market,
Some(oracle_price_data),
now,
)?;
}
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_update_amms<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateAMM<'info>>,
market_indexes: [u16; 5],
) -> Result<()> {
// up to ~60k compute units (per amm) worst case
let clock = Clock::get()?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let oracle_map = &mut OracleMap::load(remaining_accounts_iter, clock.slot, None)?;
let market_map = &mut PerpMarketMap::load(
&get_market_set_from_list(market_indexes),
remaining_accounts_iter,
)?;
controller::repeg::update_amms(market_map, oracle_map, state, &clock)?;
Ok(())
}
pub fn handle_update_user_quote_asset_insurance_stake(
ctx: Context<UpdateUserQuoteAssetInsuranceStake>,
) -> Result<()> {
let insurance_fund_stake = &mut load_mut!(ctx.accounts.insurance_fund_stake)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
validate!(
insurance_fund_stake.market_index == 0,
ErrorCode::IncorrectSpotMarketAccountPassed,
"insurance_fund_stake is not for quote market"
)?;
if insurance_fund_stake.market_index == 0 && spot_market.market_index == 0 {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
update_user_stats_if_stake_amount(
0,
ctx.accounts.insurance_fund_vault.amount,
insurance_fund_stake,
user_stats,
spot_market,
now,
)?;
}
Ok(())
}
pub fn handle_update_user_gov_token_insurance_stake(
ctx: Context<UpdateUserGovTokenInsuranceStake>,
) -> Result<()> {
let insurance_fund_stake = &mut load_mut!(ctx.accounts.insurance_fund_stake)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
validate!(
insurance_fund_stake.market_index == GOV_SPOT_MARKET_INDEX,
ErrorCode::IncorrectSpotMarketAccountPassed,
"insurance_fund_stake is not for governance market index = {}",
GOV_SPOT_MARKET_INDEX
)?;
if insurance_fund_stake.market_index == GOV_SPOT_MARKET_INDEX
&& spot_market.market_index == GOV_SPOT_MARKET_INDEX
{
let clock = Clock::get()?;
let now = clock.unix_timestamp;
update_user_stats_if_stake_amount(
0,
ctx.accounts.insurance_fund_vault.amount,
insurance_fund_stake,
user_stats,
spot_market,
now,
)?;
}
Ok(())
}
pub fn handle_update_user_gov_token_insurance_stake_devnet(
ctx: Context<UpdateUserGovTokenInsuranceStakeDevnet>,
gov_stake_amount: u64,
) -> Result<()> {
#[cfg(all(feature = "mainnet-beta", not(feature = "anchor-test")))]
{
panic!("Devnet function is disabled on mainnet-beta");
}
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
user_stats.if_staked_gov_token_amount = gov_stake_amount;
Ok(())
}
pub fn handle_disable_user_high_leverage_mode<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DisableUserHighLeverageMode<'info>>,
) -> Result<()> {
let state = &ctx.accounts.state;
let mut user = load_mut!(ctx.accounts.user)?;
let slot = Clock::get()?.slot;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
slot,
Some(state.oracle_guard_rails),
)?;
validate!(
user.margin_mode == MarginMode::HighLeverage,
ErrorCode::DefaultError,
"user must be in high leverage mode"
)?;
user.margin_mode = MarginMode::Default;
let meets_margin_requirement_with_buffer =
calculate_margin_requirement_and_total_collateral_and_liability_info(
&user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
MarginContext::standard(MarginRequirementType::Initial)
.margin_buffer(MARGIN_PRECISION / 100), // 1% buffer
)
.map(|calc| calc.meets_margin_requirement_with_buffer())?;
validate!(
meets_margin_requirement_with_buffer,
ErrorCode::DefaultError,
"user does not meet margin requirement with buffer"
)?;
// only check if signer is not user authority
if user.authority != *ctx.accounts.authority.key {
let slots_since_last_active = slot.safe_sub(user.last_active_slot)?;
validate!(
slots_since_last_active >= 9000, // 60 * 60 / .4
ErrorCode::DefaultError,
"user not inactive for long enough: {}",
slots_since_last_active
)?;
}
let mut config = load_mut!(ctx.accounts.high_leverage_mode_config)?;
config.current_users = config.current_users.safe_sub(1)?;
config.validate()?;
Ok(())
}
pub fn handle_force_delete_user<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ForceDeleteUser<'info>>,
) -> Result<()> {
#[cfg(not(feature = "anchor-test"))]
{
validate!(
*ctx.accounts.keeper.key == admin_hot_wallet::id(),
ErrorCode::DefaultError,
"only admin hot wallet can force delete user"
)?;
}
let state = &ctx.accounts.state;
let keeper_key = *ctx.accounts.keeper.key;
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let slot = Clock::get()?.slot;
let now = Clock::get()?.unix_timestamp;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&get_market_set_for_spot_positions(&user.spot_positions),
slot,
Some(state.oracle_guard_rails),
)?;
// check the user equity
let (user_equity, _) =
calculate_user_equity(user, &perp_market_map, &spot_market_map, &mut oracle_map)?;
let max_equity = QUOTE_PRECISION_I128 / 20;
validate!(
user_equity <= max_equity,
ErrorCode::DefaultError,
"user equity must be less than {}",
max_equity
)?;
#[cfg(not(feature = "anchor-test"))]
{
let slots_since_last_active = slot.safe_sub(user.last_active_slot)?;
validate!(
slots_since_last_active >= 18144000, // 60 * 60 * 24 * 7 * 4 * 3 / .4 (~3 months)
ErrorCode::DefaultError,
"user not inactive for long enough: {}",
slots_since_last_active
)?;
}
// cancel all open orders
let canceled_order_ids = cancel_orders(
user,
&user_key,
Some(&keeper_key),
&perp_market_map,
&spot_market_map,
&mut oracle_map,
now,
slot,
OrderActionExplanation::None,
None,
None,
None,
)?;
for spot_position in user.spot_positions.iter_mut() {
if spot_position.is_available() {
continue;
}
let spot_market = &mut spot_market_map.get_ref_mut(&spot_position.market_index)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
controller::spot_balance::update_spot_market_cumulative_interest(
spot_market,
Some(oracle_price_data),
now,
)?;
let token_amount = spot_position.get_token_amount(spot_market)?;
let balance_type = spot_position.balance_type;
let token_program_pubkey = if spot_market.token_program == 1 {
spl_token_2022::ID
} else {
spl_token::ID
};
let token_program = &ctx
.remaining_accounts
.iter()
.find(|acc| acc.key() == token_program_pubkey)
.map(|acc| Interface::try_from(acc))
.unwrap()
.unwrap();
let spot_market_mint = &spot_market.mint;
let mint_account_info = ctx
.remaining_accounts
.iter()
.find(|acc| acc.key() == spot_market_mint.key())
.map(|acc| InterfaceAccount::try_from(acc).unwrap());
let keeper_vault = get_associated_token_address_with_program_id(
&keeper_key,
spot_market_mint,
&token_program_pubkey,
);
let keeper_vault_account_info = ctx
.remaining_accounts
.iter()
.find(|acc| acc.key() == keeper_vault.key())
.map(|acc| InterfaceAccount::try_from(acc))
.unwrap()
.unwrap();
let spot_market_vault = spot_market.vault;
let mut spot_market_vault_account_info = ctx
.remaining_accounts
.iter()
.find(|acc| acc.key() == spot_market_vault.key())
.map(|acc| InterfaceAccount::try_from(acc))
.unwrap()
.unwrap();
if balance_type == SpotBalanceType::Deposit {
update_spot_balances(
token_amount,
&SpotBalanceType::Borrow,
spot_market,
spot_position,
true,
)?;
send_from_program_vault(
&token_program,
&spot_market_vault_account_info,
&keeper_vault_account_info,
&ctx.accounts.drift_signer,
state.signer_nonce,
token_amount.cast()?,
&mint_account_info,
)?;
} else {
update_spot_balances(
token_amount,
&SpotBalanceType::Deposit,
spot_market,
spot_position,
false,
)?;
receive(
token_program,
&keeper_vault_account_info,
&spot_market_vault_account_info,
&ctx.accounts.keeper.to_account_info(),
token_amount.cast()?,
&mint_account_info,
)?;
}
spot_market_vault_account_info.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
spot_market_vault_account_info.amount,
)?;
}
validate_user_deletion(
user,
user_stats,
&ctx.accounts.state,
Clock::get()?.unix_timestamp,
)?;
safe_decrement!(user_stats.number_of_sub_accounts, 1);
let state = &mut ctx.accounts.state;
safe_decrement!(state.number_of_sub_accounts, 1);
emit!(DeleteUserRecord {
ts: now,
user_authority: *ctx.accounts.authority.key,
user: user_key,
sub_account_id: user.sub_account_id,
keeper: Some(*ctx.accounts.keeper.key),
});
Ok(())
}
#[derive(Accounts)]
pub struct FillOrder<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&filler, &authority)?
)]
pub filler: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&filler, &filler_stats)?
)]
pub filler_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct RevertFill<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&filler, &authority)?
)]
pub filler: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&filler, &filler_stats)?
)]
pub filler_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct TriggerOrder<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&filler, &authority)?
)]
pub filler: AccountLoader<'info, User>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
}
#[derive(Accounts)]
pub struct ForceCancelOrder<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&filler, &authority)?
)]
pub filler: AccountLoader<'info, User>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
}
#[derive(Accounts)]
pub struct UpdateUserIdle<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&filler, &authority)?
)]
pub filler: AccountLoader<'info, User>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
}
#[derive(Accounts)]
pub struct LogUserBalances<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
}
#[derive(Accounts)]
pub struct UpdateUserFuelBonus<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct UpdateUserStatsReferrerInfo<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(mut)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct SettlePNL<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
#[account(
seeds = [b"spot_market_vault".as_ref(), 0_u16.to_le_bytes().as_ref()],
bump
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
#[derive(Accounts)]
pub struct PlaceSwiftTakerOrder<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(
mut,
seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()],
bump,
)]
/// CHECK: checked in SwiftUserOrdersZeroCopy checks
pub swift_user_orders: AccountInfo<'info>,
pub authority: Signer<'info>,
/// CHECK: The address check is needed because otherwise
/// the supplied Sysvar could be anything else.
/// The Instruction Sysvar has not been implemented
/// in the Anchor framework yet, so this is the safe approach.
#[account(address = IX_ID)]
pub ix_sysvar: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct SettleFunding<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
}
#[derive(Accounts)]
pub struct SettleLP<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
}
#[derive(Accounts)]
pub struct LiquidatePerp<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&liquidator, &authority)?
)]
pub liquidator: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&liquidator, &liquidator_stats)?
)]
pub liquidator_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct LiquidateSpot<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&liquidator, &authority)?
)]
pub liquidator: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&liquidator, &liquidator_stats)?
)]
pub liquidator_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct LiquidateBorrowForPerpPnl<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&liquidator, &authority)?
)]
pub liquidator: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&liquidator, &liquidator_stats)?
)]
pub liquidator_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct LiquidatePerpPnlForDeposit<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&liquidator, &authority)?
)]
pub liquidator: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&liquidator, &liquidator_stats)?
)]
pub liquidator_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct SetUserStatusToBeingLiquidated<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
#[instruction(spot_market_index: u16,)]
pub struct ResolveBankruptcy<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&liquidator, &authority)?
)]
pub liquidator: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&liquidator, &liquidator_stats)?
)]
pub liquidator_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), spot_market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), spot_market_index.to_le_bytes().as_ref()], // todo: market_index=0 hardcode for perps?
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(spot_market_index: u16,)]
pub struct ResolvePerpPnlDeficit<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), spot_market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), spot_market_index.to_le_bytes().as_ref()], // todo: market_index=0 hardcode for perps?
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(market_index: u16,)]
pub struct SettleRevenueToInsuranceFund<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
pub struct UpdateSpotMarketCumulativeInterest<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub spot_market: AccountLoader<'info, SpotMarket>,
/// CHECK: checked in `update_spot_market_cumulative_interest` ix constraint
pub oracle: AccountInfo<'info>,
#[account(
seeds = [b"spot_market_vault".as_ref(), spot_market.load()?.market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
#[derive(Accounts)]
pub struct UpdateAMM<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct UpdateFundingRate<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
/// CHECK: checked in `update_funding_rate` ix constraint
pub oracle: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct UpdatePerpBidAskTwap<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
/// CHECK: checked in `update_funding_rate` ix constraint
pub oracle: AccountInfo<'info>,
pub keeper_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct UpdateUserQuoteAssetInsuranceStake<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
constraint = is_stats_for_if_stake(&insurance_fund_stake, &user_stats)?
)]
pub insurance_fund_stake: AccountLoader<'info, InsuranceFundStake>,
#[account(mut)]
pub user_stats: AccountLoader<'info, UserStats>,
pub signer: Signer<'info>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), 0_u16.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
#[derive(Accounts)]
pub struct UpdateUserGovTokenInsuranceStake<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [b"spot_market", 15_u16.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
constraint = is_stats_for_if_stake(&insurance_fund_stake, &user_stats)?
)]
pub insurance_fund_stake: AccountLoader<'info, InsuranceFundStake>,
#[account(mut)]
pub user_stats: AccountLoader<'info, UserStats>,
pub signer: Signer<'info>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), 15_u16.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
#[derive(Accounts)]
pub struct UpdateUserGovTokenInsuranceStakeDevnet<'info> {
#[account(mut)]
pub user_stats: AccountLoader<'info, UserStats>,
pub signer: Signer<'info>,
}
#[derive(Accounts)]
pub struct UpdatePrelaunchOracle<'info> {
pub state: Box<Account<'info, State>>,
pub perp_market: AccountLoader<'info, PerpMarket>,
#[account(mut)]
/// CHECK: checked in ix
pub oracle: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct DisableUserHighLeverageMode<'info> {
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(mut)]
pub high_leverage_mode_config: AccountLoader<'info, HighLeverageModeConfig>,
}
#[derive(Accounts)]
pub struct ForceDeleteUser<'info> {
#[account(
mut,
has_one = authority,
close = authority
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
has_one = authority
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub state: Box<Account<'info, State>>,
/// CHECK: authority
#[account(mut)]
pub authority: AccountInfo<'info>,
#[account(mut)]
pub keeper: Signer<'info>,
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/optional_accounts.rs
|
use crate::error::{DriftResult, ErrorCode};
use std::cell::RefMut;
use std::convert::TryFrom;
use crate::error::ErrorCode::UnableToLoadOracle;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::load_ref::load_ref_mut;
use crate::state::oracle::PrelaunchOracle;
use crate::state::oracle_map::OracleMap;
use crate::state::perp_market::PerpMarket;
use crate::state::perp_market_map::{MarketSet, PerpMarketMap};
use crate::state::spot_market_map::SpotMarketMap;
use crate::state::state::OracleGuardRails;
use crate::state::traits::Size;
use crate::state::user::{User, UserStats};
use crate::{validate, OracleSource};
use anchor_lang::accounts::account::Account;
use anchor_lang::prelude::{AccountInfo, Interface};
use anchor_lang::prelude::{AccountLoader, InterfaceAccount};
use anchor_lang::Discriminator;
use anchor_spl::token::TokenAccount;
use anchor_spl::token_interface::{Mint, TokenInterface};
use arrayref::array_ref;
use solana_program::account_info::next_account_info;
use solana_program::msg;
use std::iter::Peekable;
use std::ops::Deref;
use std::slice::Iter;
pub struct AccountMaps<'a> {
pub perp_market_map: PerpMarketMap<'a>,
pub spot_market_map: SpotMarketMap<'a>,
pub oracle_map: OracleMap<'a>,
}
pub fn load_maps<'a, 'b>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'a>>>,
writable_perp_markets: &'b MarketSet,
writable_spot_markets: &'b MarketSet,
slot: u64,
oracle_guard_rails: Option<OracleGuardRails>,
) -> DriftResult<AccountMaps<'a>> {
let oracle_map = OracleMap::load(account_info_iter, slot, oracle_guard_rails)?;
let spot_market_map = SpotMarketMap::load(writable_spot_markets, account_info_iter)?;
let perp_market_map = PerpMarketMap::load(writable_perp_markets, account_info_iter)?;
for perp_market_index in writable_perp_markets.iter() {
update_prelaunch_oracle(
perp_market_map.get_ref(perp_market_index)?.deref(),
&oracle_map,
slot,
)?;
}
Ok(AccountMaps {
perp_market_map,
spot_market_map,
oracle_map,
})
}
pub fn update_prelaunch_oracle(
perp_market: &PerpMarket,
oracle_map: &OracleMap,
slot: u64,
) -> DriftResult {
if perp_market.amm.oracle_source != OracleSource::Prelaunch {
return Ok(());
}
let oracle_account_info = oracle_map.get_account_info(&perp_market.amm.oracle)?;
let mut oracle: RefMut<PrelaunchOracle> =
load_ref_mut(&oracle_account_info).or(Err(UnableToLoadOracle))?;
oracle.update(perp_market, slot)?;
Ok(())
}
pub fn get_maker_and_maker_stats<'a>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'a>>>,
) -> DriftResult<(AccountLoader<'a, User>, AccountLoader<'a, UserStats>)> {
let maker_account_info =
next_account_info(account_info_iter).or(Err(ErrorCode::MakerNotFound))?;
validate!(
maker_account_info.is_writable,
ErrorCode::MakerMustBeWritable
)?;
let maker: AccountLoader<User> =
AccountLoader::try_from(maker_account_info).or(Err(ErrorCode::CouldNotDeserializeMaker))?;
let maker_stats_account_info =
next_account_info(account_info_iter).or(Err(ErrorCode::MakerStatsNotFound))?;
validate!(
maker_stats_account_info.is_writable,
ErrorCode::MakerStatsMustBeWritable
)?;
let maker_stats: AccountLoader<UserStats> =
AccountLoader::try_from(maker_stats_account_info)
.or(Err(ErrorCode::CouldNotDeserializeMakerStats))?;
Ok((maker, maker_stats))
}
#[allow(clippy::type_complexity)]
pub fn get_referrer_and_referrer_stats<'a>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'a>>>,
) -> DriftResult<(
Option<AccountLoader<'a, User>>,
Option<AccountLoader<'a, UserStats>>,
)> {
let referrer_account_info = account_info_iter.peek();
if referrer_account_info.is_none() {
return Ok((None, None));
}
let referrer_account_info = referrer_account_info.safe_unwrap()?;
let data = referrer_account_info.try_borrow_data().map_err(|e| {
msg!("{:?}", e);
ErrorCode::CouldNotDeserializeReferrer
})?;
if data.len() < User::SIZE {
return Ok((None, None));
}
let user_discriminator: [u8; 8] = User::discriminator();
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &user_discriminator {
return Ok((None, None));
}
let referrer_account_info = next_account_info(account_info_iter).safe_unwrap()?;
validate!(
referrer_account_info.is_writable,
ErrorCode::ReferrerMustBeWritable
)?;
let referrer: AccountLoader<User> = AccountLoader::try_from(referrer_account_info)
.or(Err(ErrorCode::CouldNotDeserializeReferrer))?;
let referrer_stats_account_info = account_info_iter.peek();
if referrer_stats_account_info.is_none() {
return Ok((None, None));
}
let referrer_stats_account_info = referrer_stats_account_info.safe_unwrap()?;
let data = referrer_stats_account_info.try_borrow_data().map_err(|e| {
msg!("{:?}", e);
ErrorCode::CouldNotDeserializeReferrerStats
})?;
if data.len() < UserStats::SIZE {
return Ok((None, None));
}
let user_stats_discriminator: [u8; 8] = UserStats::discriminator();
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &user_stats_discriminator {
return Ok((None, None));
}
let referrer_stats_account_info = next_account_info(account_info_iter).safe_unwrap()?;
validate!(
referrer_stats_account_info.is_writable,
ErrorCode::ReferrerMustBeWritable
)?;
let referrer_stats: AccountLoader<UserStats> =
AccountLoader::try_from(referrer_stats_account_info)
.or(Err(ErrorCode::CouldNotDeserializeReferrerStats))?;
Ok((Some(referrer), Some(referrer_stats)))
}
pub fn get_whitelist_token<'a>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'a>>>,
) -> DriftResult<Account<'a, TokenAccount>> {
let token_account_info = account_info_iter.peek();
if token_account_info.is_none() {
msg!("Could not find whitelist token");
return Err(ErrorCode::InvalidWhitelistToken);
}
let token_account_info = token_account_info.safe_unwrap()?;
let whitelist_token: Account<TokenAccount> =
Account::try_from(token_account_info).map_err(|e| {
msg!("Unable to deserialize whitelist token");
msg!("{:?}", e);
ErrorCode::InvalidWhitelistToken
})?;
Ok(whitelist_token)
}
pub fn get_token_interface<'a>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'a>>>,
) -> DriftResult<Option<Interface<'a, TokenInterface>>> {
let token_interface_account_info = account_info_iter.peek();
if token_interface_account_info.is_none() {
return Ok(None);
}
let token_interface_account_info = account_info_iter.next().safe_unwrap()?;
let token_interface: Interface<TokenInterface> =
Interface::try_from(token_interface_account_info).map_err(|e| {
msg!("Unable to deserialize token interface");
msg!("{:?}", e);
ErrorCode::DefaultError
})?;
Ok(Some(token_interface))
}
pub fn get_token_mint<'a>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'a>>>,
) -> DriftResult<Option<InterfaceAccount<'a, Mint>>> {
let mint_account_info = account_info_iter.peek();
if mint_account_info.is_none() {
return Ok(None);
}
let mint_account_info = account_info_iter.next().safe_unwrap()?;
match InterfaceAccount::try_from(mint_account_info) {
Ok(mint) => Ok(Some(mint)),
Err(_) => Ok(None),
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/pyth_pull_oracle.rs
|
use crate::error::ErrorCode;
use crate::ids::{drift_oracle_receiver_program, wormhole_program};
use crate::validate;
use anchor_lang::prelude::*;
use pyth_solana_receiver_sdk::{
cpi::accounts::{PostUpdate, PostUpdateAtomic},
price_update::PriceUpdateV2,
program::PythSolanaReceiver,
PostMultiUpdatesAtomicParams, PostUpdateAtomicParams, PostUpdateParams,
};
use pythnet_sdk::{
messages::Message,
wire::{from_slice, PrefixedVec},
};
pub const PTYH_PRICE_FEED_SEED_PREFIX: &[u8] = b"pyth_pull";
pub fn handle_update_pyth_pull_oracle(
ctx: Context<UpdatePythPullOraclePriceFeed>,
feed_id: [u8; 32],
params: Vec<u8>,
) -> Result<()> {
let cpi_program = ctx.accounts.pyth_solana_receiver.to_account_info();
let cpi_accounts = PostUpdate {
payer: ctx.accounts.keeper.to_account_info(),
encoded_vaa: ctx.accounts.encoded_vaa.to_account_info(),
price_update_account: ctx.accounts.price_feed.to_account_info(),
write_authority: ctx.accounts.price_feed.to_account_info(),
};
let seeds = &[
PTYH_PRICE_FEED_SEED_PREFIX,
feed_id.as_ref(),
&[ctx.bumps.price_feed],
];
let signer_seeds = &[&seeds[..]];
let cpi_context = CpiContext::new_with_signer(cpi_program, cpi_accounts, signer_seeds);
let params = PostUpdateParams::deserialize(&mut ¶ms[..]).unwrap();
// Get the timestamp of the price currently stored in the price feed account.
let current_timestamp = get_timestamp_from_price_feed_account(&ctx.accounts.price_feed)?;
let next_timestamp =
get_timestamp_from_price_update_message(¶ms.merkle_price_update.message)?;
// Only update the price feed if the message contains a newer price. Pushing a stale price
// suceeds without changing the on-chain state.
if next_timestamp > current_timestamp {
pyth_solana_receiver_sdk::cpi::post_update(cpi_context, params)?;
{
let price_feed_account_data = ctx.accounts.price_feed.try_borrow_data()?;
let price_feed_account =
PriceUpdateV2::try_deserialize(&mut &price_feed_account_data[..])?;
validate!(
price_feed_account.price_message.feed_id == feed_id,
ErrorCode::OraclePriceFeedMessageMismatch
)?;
}
}
Ok(())
}
pub fn handle_post_pyth_pull_oracle_update_atomic(
ctx: Context<PostPythPullOracleUpdateAtomic>,
feed_id: [u8; 32],
params: Vec<u8>,
) -> Result<()> {
let cpi_program = ctx.accounts.pyth_solana_receiver.to_account_info();
let cpi_accounts = PostUpdateAtomic {
payer: ctx.accounts.keeper.to_account_info(),
guardian_set: ctx.accounts.guardian_set.to_account_info(),
price_update_account: ctx.accounts.price_feed.to_account_info(),
write_authority: ctx.accounts.price_feed.to_account_info(),
};
let seeds = &[
PTYH_PRICE_FEED_SEED_PREFIX,
feed_id.as_ref(),
&[ctx.bumps.price_feed],
];
let signer_seeds = &[&seeds[..]];
let cpi_context = CpiContext::new_with_signer(cpi_program, cpi_accounts, signer_seeds);
let params = PostUpdateAtomicParams::deserialize(&mut ¶ms[..]).unwrap();
// Get the timestamp of the price currently stored in the price feed account.
let current_timestamp = get_timestamp_from_price_feed_account(&ctx.accounts.price_feed)?;
let next_timestamp =
get_timestamp_from_price_update_message(¶ms.merkle_price_update.message)?;
if next_timestamp > current_timestamp {
pyth_solana_receiver_sdk::cpi::post_update_atomic(cpi_context, params)?;
{
let price_feed_account_data = ctx.accounts.price_feed.try_borrow_data()?;
let price_feed_account =
PriceUpdateV2::try_deserialize(&mut &price_feed_account_data[..])?;
validate!(
price_feed_account.price_message.feed_id == feed_id,
ErrorCode::OraclePriceFeedMessageMismatch
)?;
}
msg!(
"Posting new update. current ts {} < next ts {}",
current_timestamp,
next_timestamp
);
} else {
msg!(
"Skipping new update. current ts {} >= next ts {}",
current_timestamp,
next_timestamp
);
}
Ok(())
}
pub fn handle_post_multi_pyth_pull_oracle_updates_atomic<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PostPythPullMultiOracleUpdatesAtomic<'info>>,
params: Vec<u8>,
) -> Result<()> {
let remaining_accounts = ctx.remaining_accounts;
validate!(
remaining_accounts.len() <= 2,
ErrorCode::OracleTooManyPriceAccountUpdates
)?;
let update_param = PostMultiUpdatesAtomicParams::deserialize(&mut ¶ms[..]).unwrap();
let vaa = update_param.vaa;
let merkle_price_updates = update_param.merkle_price_updates;
validate!(
remaining_accounts.len() == merkle_price_updates.len(),
ErrorCode::OracleMismatchedVaaAndPriceUpdates
)?;
for (account, merkle_price_update) in remaining_accounts.iter().zip(merkle_price_updates.iter())
{
let cpi_program = ctx.accounts.pyth_solana_receiver.to_account_info();
let cpi_accounts = PostUpdateAtomic {
payer: ctx.accounts.keeper.to_account_info(),
guardian_set: ctx.accounts.guardian_set.to_account_info(),
price_update_account: account.clone(),
write_authority: account.clone(),
};
let price_feed_account_data = account.try_borrow_data()?;
let price_feed_account = PriceUpdateV2::try_deserialize(&mut &price_feed_account_data[..])?;
let feed_id = price_feed_account.price_message.feed_id;
// Verify the pda
let (pda, bump) = Pubkey::find_program_address(
&[PTYH_PRICE_FEED_SEED_PREFIX, feed_id.as_ref()],
&crate::ID,
);
require_keys_eq!(
*account.key,
pda,
ErrorCode::OracleBadRemainingAccountPublicKey
);
let seeds = &[PTYH_PRICE_FEED_SEED_PREFIX, feed_id.as_ref(), &[bump]];
let signer_seeds = &[&seeds[..]];
let cpi_context = CpiContext::new_with_signer(cpi_program, cpi_accounts, signer_seeds);
// Get the timestamp of the price currently stored in the price feed account.
let current_timestamp = get_timestamp_from_price_feed_account(account)?;
let next_timestamp = get_timestamp_from_price_update_message(&merkle_price_update.message)?;
drop(price_feed_account_data);
if next_timestamp > current_timestamp {
pyth_solana_receiver_sdk::cpi::post_update_atomic(
cpi_context,
PostUpdateAtomicParams {
merkle_price_update: merkle_price_update.clone(),
vaa: vaa.clone(),
},
)?;
msg!(
"Posting new update. current ts {} < next ts {}",
current_timestamp,
next_timestamp
);
} else {
msg!(
"Skipping new update. current ts {} >= next ts {}",
current_timestamp,
next_timestamp
);
}
}
Ok(())
}
pub fn get_timestamp_from_price_feed_account(price_feed_account: &AccountInfo) -> Result<i64> {
if price_feed_account.data_is_empty() {
Ok(0)
} else {
let price_feed_account_data = price_feed_account.try_borrow_data()?;
let price_feed_account = PriceUpdateV2::try_deserialize(&mut &price_feed_account_data[..])?;
Ok(price_feed_account.price_message.publish_time)
}
}
pub fn get_timestamp_from_price_update_message(
update_message: &PrefixedVec<u16, u8>,
) -> Result<i64> {
let message = from_slice::<byteorder::BE, Message>(update_message.as_ref())
.map_err(|_| ErrorCode::OracleDeserializeMessageFailed)?;
let next_timestamp = match message {
Message::PriceFeedMessage(price_feed_message) => price_feed_message.publish_time,
Message::TwapMessage(_) => {
return Err(ErrorCode::OracleUnsupportedMessageType.into());
}
};
Ok(next_timestamp)
}
#[derive(Accounts)]
#[instruction(feed_id : [u8; 32])]
pub struct UpdatePythPullOraclePriceFeed<'info> {
#[account(mut)]
pub keeper: Signer<'info>,
pub pyth_solana_receiver: Program<'info, PythSolanaReceiver>,
/// CHECK: Checked by CPI into the Pyth Solana Receiver
#[account(owner = wormhole_program::id() @ ErrorCode::OracleWrongVaaOwner)]
pub encoded_vaa: AccountInfo<'info>,
/// CHECK: This account's seeds are checked
#[account(mut, seeds = [PTYH_PRICE_FEED_SEED_PREFIX, &feed_id], bump, owner = drift_oracle_receiver_program::id())]
pub price_feed: AccountInfo<'info>,
}
#[derive(Accounts)]
#[instruction(feed_id : [u8; 32])]
pub struct PostPythPullOracleUpdateAtomic<'info> {
#[account(mut)]
pub keeper: Signer<'info>,
pub pyth_solana_receiver: Program<'info, PythSolanaReceiver>,
/// CHECK: We can't use AccountVariant::<GuardianSet> here because its owner is hardcoded as the "official" Wormhole program
#[account(
owner = wormhole_program::id() @ ErrorCode::OracleWrongGuardianSetOwner)]
pub guardian_set: AccountInfo<'info>,
/// CHECK: This account's seeds are checked
#[account(mut, owner = drift_oracle_receiver_program::id(), seeds = [PTYH_PRICE_FEED_SEED_PREFIX, &feed_id], bump)]
pub price_feed: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct PostPythPullMultiOracleUpdatesAtomic<'info> {
#[account(mut)]
pub keeper: Signer<'info>,
pub pyth_solana_receiver: Program<'info, PythSolanaReceiver>,
/// CHECK: We can't use AccountVariant::<GuardianSet> here because its owner is hardcoded as the "official" Wormhole program
#[account(
owner = wormhole_program::id() @ ErrorCode::OracleWrongGuardianSetOwner)]
pub guardian_set: AccountInfo<'info>,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/user.rs
|
use anchor_lang::prelude::*;
use anchor_lang::Discriminator;
use anchor_spl::{
token::Token,
token_2022::Token2022,
token_interface::{TokenAccount, TokenInterface},
};
use solana_program::instruction::Instruction;
use solana_program::program::invoke;
use solana_program::system_instruction::transfer;
use crate::controller::orders::place_and_match_rfq_orders;
use crate::controller::orders::{cancel_orders, ModifyOrderId};
use crate::controller::position::PositionDirection;
use crate::controller::spot_balance::update_revenue_pool_balances;
use crate::controller::spot_position::{
update_spot_balances_and_cumulative_deposits,
update_spot_balances_and_cumulative_deposits_with_limits,
};
use crate::error::ErrorCode;
use crate::ids::{
jupiter_mainnet_3, jupiter_mainnet_4, jupiter_mainnet_6, marinade_mainnet, serum_program,
};
use crate::instructions::constraints::*;
use crate::instructions::optional_accounts::{
get_referrer_and_referrer_stats, get_whitelist_token, load_maps, AccountMaps,
};
use crate::instructions::SpotFulfillmentType;
use crate::math::casting::Cast;
use crate::math::liquidation::is_user_being_liquidated;
use crate::math::margin::meets_initial_margin_requirement;
use crate::math::margin::{
calculate_max_withdrawable_amount, meets_maintenance_margin_requirement,
meets_place_order_margin_requirement, meets_withdraw_margin_requirement,
validate_spot_margin_trading, MarginRequirementType,
};
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::get_token_value;
use crate::math::spot_swap;
use crate::math::spot_swap::{calculate_swap_price, validate_price_bands_for_swap};
use crate::math_error;
use crate::optional_accounts::{get_token_interface, get_token_mint};
use crate::print_error;
use crate::safe_decrement;
use crate::safe_increment;
use crate::state::events::{
DepositDirection, DepositExplanation, DepositRecord, LPAction, LPRecord, NewUserRecord,
OrderActionExplanation, SwapRecord,
};
use crate::state::fill_mode::FillMode;
use crate::state::fulfillment_params::drift::MatchFulfillmentParams;
use crate::state::fulfillment_params::openbook_v2::OpenbookV2FulfillmentParams;
use crate::state::fulfillment_params::phoenix::PhoenixFulfillmentParams;
use crate::state::fulfillment_params::serum::SerumFulfillmentParams;
use crate::state::high_leverage_mode_config::HighLeverageModeConfig;
use crate::state::oracle::StrictOraclePrice;
use crate::state::order_params::RFQMatch;
use crate::state::order_params::{
parse_optional_params, ModifyOrderParams, OrderParams, PlaceAndTakeOrderSuccessCondition,
PlaceOrderOptions, PostOnlyParam,
};
use crate::state::paused_operations::{PerpOperation, SpotOperation};
use crate::state::perp_market::ContractType;
use crate::state::perp_market::MarketStatus;
use crate::state::perp_market_map::{get_writable_perp_market_set, MarketSet};
use crate::state::protected_maker_mode_config::ProtectedMakerModeConfig;
use crate::state::rfq_user::{load_rfq_user_account_map, RFQUser, RFQ_PDA_SEED};
use crate::state::spot_fulfillment_params::SpotFulfillmentParams;
use crate::state::spot_market::SpotBalanceType;
use crate::state::spot_market::SpotMarket;
use crate::state::spot_market_map::{
get_writable_spot_market_set, get_writable_spot_market_set_from_many,
};
use crate::state::state::State;
use crate::state::swift_user::SwiftOrderId;
use crate::state::swift_user::SwiftUserOrdersLoader;
use crate::state::swift_user::{SwiftUserOrders, SWIFT_PDA_SEED};
use crate::state::traits::Size;
use crate::state::user::ReferrerStatus;
use crate::state::user::{MarginMode, MarketType, OrderType, ReferrerName, User, UserStats};
use crate::state::user_map::{load_user_maps, UserMap, UserStatsMap};
use crate::validate;
use crate::validation::sig_verification::verify_ed25519_ix;
use crate::validation::user::validate_user_deletion;
use crate::validation::whitelist::validate_whitelist_token;
use crate::{controller, math};
use crate::{get_then_update_id, QUOTE_SPOT_MARKET_INDEX};
use crate::{load, THIRTEEN_DAY};
use crate::{load_mut, ExchangeStatus};
use anchor_lang::solana_program::sysvar::instructions;
use anchor_spl::associated_token::AssociatedToken;
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::sysvar::instructions::{
load_current_index_checked, load_instruction_at_checked, ID as IX_ID,
};
pub fn handle_initialize_user<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeUser<'info>>,
sub_account_id: u16,
name: [u8; 32],
) -> Result<()> {
let user_key = ctx.accounts.user.key();
let mut user = ctx
.accounts
.user
.load_init()
.or(Err(ErrorCode::UnableToLoadAccountLoader))?;
user.authority = ctx.accounts.authority.key();
user.sub_account_id = sub_account_id;
user.name = name;
user.next_order_id = 1;
user.next_liquidation_id = 1;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let mut user_stats = load_mut!(ctx.accounts.user_stats)?;
user_stats.number_of_sub_accounts = user_stats.number_of_sub_accounts.safe_add(1)?;
// Only try to add referrer if it is the first user
if user_stats.number_of_sub_accounts_created == 0 {
let (referrer, referrer_stats) = get_referrer_and_referrer_stats(remaining_accounts_iter)?;
let referrer = if let (Some(referrer), Some(referrer_stats)) = (referrer, referrer_stats) {
let referrer = load!(referrer)?;
let mut referrer_stats = load_mut!(referrer_stats)?;
validate!(referrer.sub_account_id == 0, ErrorCode::InvalidReferrer)?;
validate!(
referrer.authority == referrer_stats.authority,
ErrorCode::ReferrerAndReferrerStatsAuthorityUnequal
)?;
referrer_stats.referrer_status |= ReferrerStatus::IsReferrer as u8;
user_stats.referrer_status |= ReferrerStatus::IsReferred as u8;
referrer.authority
} else {
Pubkey::default()
};
user_stats.referrer = referrer;
}
let whitelist_mint = &ctx.accounts.state.whitelist_mint;
if !whitelist_mint.eq(&Pubkey::default()) {
validate_whitelist_token(
get_whitelist_token(remaining_accounts_iter)?,
whitelist_mint,
&ctx.accounts.authority.key(),
)?;
}
validate!(
sub_account_id == user_stats.number_of_sub_accounts_created,
ErrorCode::InvalidUserSubAccountId,
"Invalid sub account id {}, must be {}",
sub_account_id,
user_stats.number_of_sub_accounts_created
)?;
user_stats.number_of_sub_accounts_created =
user_stats.number_of_sub_accounts_created.safe_add(1)?;
let state = &mut ctx.accounts.state;
safe_increment!(state.number_of_sub_accounts, 1);
let max_number_of_sub_accounts = state.max_number_of_sub_accounts();
validate!(
max_number_of_sub_accounts == 0
|| state.number_of_sub_accounts <= max_number_of_sub_accounts,
ErrorCode::MaxNumberOfUsers
)?;
let now_ts = Clock::get()?.unix_timestamp;
user.last_fuel_bonus_update_ts = now_ts.cast()?;
emit!(NewUserRecord {
ts: now_ts,
user_authority: ctx.accounts.authority.key(),
user: user_key,
sub_account_id,
name,
referrer: user_stats.referrer
});
drop(user);
let init_fee = state.get_init_user_fee()?;
if init_fee > 0 {
let payer_lamports = ctx.accounts.payer.to_account_info().try_lamports()?;
if payer_lamports < init_fee {
msg!("payer lamports {} init fee {}", payer_lamports, init_fee);
return Err(ErrorCode::CantPayUserInitFee.into());
}
invoke(
&transfer(
&ctx.accounts.payer.key(),
&ctx.accounts.user.key(),
init_fee,
),
&[
ctx.accounts.payer.to_account_info(),
ctx.accounts.user.to_account_info(),
ctx.accounts.system_program.to_account_info(),
],
)?;
}
Ok(())
}
pub fn handle_initialize_user_stats<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeUserStats>,
) -> Result<()> {
let clock = Clock::get()?;
let mut user_stats = ctx
.accounts
.user_stats
.load_init()
.or(Err(ErrorCode::UnableToLoadAccountLoader))?;
*user_stats = UserStats {
authority: ctx.accounts.authority.key(),
number_of_sub_accounts: 0,
last_taker_volume_30d_ts: clock.unix_timestamp,
last_maker_volume_30d_ts: clock.unix_timestamp,
last_filler_volume_30d_ts: clock.unix_timestamp,
last_fuel_if_bonus_update_ts: clock.unix_timestamp.cast()?,
..UserStats::default()
};
let state = &mut ctx.accounts.state;
safe_increment!(state.number_of_authorities, 1);
let max_number_of_sub_accounts = state.max_number_of_sub_accounts();
validate!(
max_number_of_sub_accounts == 0
|| state.number_of_authorities <= max_number_of_sub_accounts,
ErrorCode::MaxNumberOfUsers
)?;
Ok(())
}
pub fn handle_initialize_referrer_name(
ctx: Context<InitializeReferrerName>,
name: [u8; 32],
) -> Result<()> {
let authority_key = ctx.accounts.authority.key();
let user_stats_key = ctx.accounts.user_stats.key();
let user_key = ctx.accounts.user.key();
let mut referrer_name = ctx
.accounts
.referrer_name
.load_init()
.or(Err(ErrorCode::UnableToLoadAccountLoader))?;
let user = load!(ctx.accounts.user)?;
validate!(
user.sub_account_id == 0,
ErrorCode::InvalidReferrer,
"must be subaccount 0"
)?;
referrer_name.authority = authority_key;
referrer_name.user = user_key;
referrer_name.user_stats = user_stats_key;
referrer_name.name = name;
Ok(())
}
pub fn handle_initialize_rfq_user<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeRFQUser<'info>>,
) -> Result<()> {
let mut rfq_user = ctx
.accounts
.rfq_user
.load_init()
.or(Err(ErrorCode::UnableToLoadAccountLoader))?;
rfq_user.user_pubkey = ctx.accounts.user.key();
Ok(())
}
pub fn handle_initialize_swift_user_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, InitializeSwiftUserOrders<'info>>,
num_orders: u16,
) -> Result<()> {
#[cfg(all(feature = "mainnet-beta", not(feature = "anchor-test")))]
{
panic!("Swift orders are disabled on mainnet-beta");
}
let swift_user_orders = &mut ctx.accounts.swift_user_orders;
swift_user_orders.user_pubkey = ctx.accounts.user.key();
swift_user_orders
.swift_order_data
.resize_with(num_orders as usize, SwiftOrderId::default);
swift_user_orders.validate()?;
Ok(())
}
pub fn handle_resize_swift_user_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, ResizeSwiftUserOrders<'info>>,
num_orders: u16,
) -> Result<()> {
let swift_user_orders = &mut ctx.accounts.swift_user_orders;
swift_user_orders
.swift_order_data
.resize_with(num_orders as usize, SwiftOrderId::default);
swift_user_orders.validate()?;
Ok(())
}
#[access_control(
deposit_not_paused(&ctx.accounts.state)
)]
pub fn handle_deposit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Deposit<'info>>,
market_index: u16,
amount: u64,
reduce_only: bool,
) -> Result<()> {
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let slot = clock.slot;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&get_writable_spot_market_set(market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let mint = get_token_mint(remaining_accounts_iter)?;
if amount == 0 {
return Err(ErrorCode::InsufficientDeposit.into());
}
validate!(!user.is_bankrupt(), ErrorCode::UserBankrupt)?;
let mut spot_market = spot_market_map.get_ref_mut(&market_index)?;
let oracle_price_data = *oracle_map.get_price_data(&spot_market.oracle_id())?;
validate!(
user.pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) != market pool id ({})",
user.pool_id,
spot_market.pool_id
)?;
validate!(
!matches!(spot_market.status, MarketStatus::Initialized),
ErrorCode::MarketBeingInitialized,
"Market is being initialized"
)?;
controller::spot_balance::update_spot_market_cumulative_interest(
&mut spot_market,
Some(&oracle_price_data),
now,
)?;
let position_index = user.force_get_spot_position_index(spot_market.market_index)?;
let is_borrow_before = user.spot_positions[position_index].is_borrow();
let force_reduce_only = spot_market.is_reduce_only();
// if reduce only, have to compare ix amount to current borrow amount
let amount = if (force_reduce_only || reduce_only)
&& user.spot_positions[position_index].balance_type == SpotBalanceType::Borrow
{
user.spot_positions[position_index]
.get_token_amount(&spot_market)?
.cast::<u64>()?
.min(amount)
} else {
amount
};
user.increment_total_deposits(
amount,
oracle_price_data.price,
spot_market.get_precision().cast()?,
)?;
let total_deposits_after = user.total_deposits;
let total_withdraws_after = user.total_withdraws;
let spot_position = &mut user.spot_positions[position_index];
controller::spot_position::update_spot_balances_and_cumulative_deposits(
amount as u128,
&SpotBalanceType::Deposit,
&mut spot_market,
spot_position,
false,
None,
)?;
let token_amount = spot_position.get_token_amount(&spot_market)?;
if token_amount == 0 {
validate!(
spot_position.scaled_balance == 0,
ErrorCode::InvalidSpotPosition,
"deposit left user with invalid position. scaled balance = {} token amount = {}",
spot_position.scaled_balance,
token_amount
)?;
}
if spot_position.balance_type == SpotBalanceType::Deposit && spot_position.scaled_balance > 0 {
validate!(
matches!(spot_market.status, MarketStatus::Active),
ErrorCode::MarketActionPaused,
"spot_market not active",
)?;
}
drop(spot_market);
if user.is_being_liquidated() {
// try to update liquidation status if user is was already being liq'd
let is_being_liquidated = is_user_being_liquidated(
user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
state.liquidation_margin_buffer_ratio,
)?;
if !is_being_liquidated {
user.exit_liquidation();
}
}
user.update_last_active_slot(slot);
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
controller::token::receive(
&ctx.accounts.token_program,
&ctx.accounts.user_token_account,
&ctx.accounts.spot_market_vault,
&ctx.accounts.authority,
amount,
&mint,
)?;
ctx.accounts.spot_market_vault.reload()?;
let deposit_record_id = get_then_update_id!(spot_market, next_deposit_record_id);
let oracle_price = oracle_price_data.price;
let explanation = if is_borrow_before {
DepositExplanation::RepayBorrow
} else {
DepositExplanation::None
};
let deposit_record = DepositRecord {
ts: now,
deposit_record_id,
user_authority: user.authority,
user: user_key,
direction: DepositDirection::Deposit,
amount,
oracle_price,
market_deposit_balance: spot_market.deposit_balance,
market_withdraw_balance: spot_market.borrow_balance,
market_cumulative_deposit_interest: spot_market.cumulative_deposit_interest,
market_cumulative_borrow_interest: spot_market.cumulative_borrow_interest,
total_deposits_after,
total_withdraws_after,
market_index,
explanation,
transfer_user: None,
};
emit!(deposit_record);
spot_market.validate_max_token_deposits_and_borrows(false)?;
Ok(())
}
#[access_control(
withdraw_not_paused(&ctx.accounts.state)
)]
pub fn handle_withdraw<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Withdraw<'info>>,
market_index: u16,
amount: u64,
reduce_only: bool,
) -> anchor_lang::Result<()> {
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let mut user_stats = load_mut!(ctx.accounts.user_stats)?;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let slot = clock.slot;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&get_writable_spot_market_set(market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let mint = get_token_mint(remaining_accounts_iter)?;
validate!(!user.is_bankrupt(), ErrorCode::UserBankrupt)?;
let spot_market_is_reduce_only = {
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
controller::spot_balance::update_spot_market_cumulative_interest(
spot_market,
Some(oracle_price_data),
now,
)?;
spot_market.is_reduce_only()
};
let amount = {
let reduce_only = reduce_only || spot_market_is_reduce_only;
let position_index = user.force_get_spot_position_index(market_index)?;
let mut amount = if reduce_only {
validate!(
user.spot_positions[position_index].balance_type == SpotBalanceType::Deposit,
ErrorCode::ReduceOnlyWithdrawIncreasedRisk
)?;
let max_withdrawable_amount = calculate_max_withdrawable_amount(
market_index,
user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
)?;
let spot_market = &spot_market_map.get_ref(&market_index)?;
let existing_deposit_amount = user.spot_positions[position_index]
.get_token_amount(spot_market)?
.cast::<u64>()?;
amount
.min(max_withdrawable_amount)
.min(existing_deposit_amount)
} else {
amount
};
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
user.increment_total_withdraws(
amount,
oracle_price_data.price,
spot_market.get_precision().cast()?,
)?;
// prevents withdraw when limits hit
controller::spot_position::update_spot_balances_and_cumulative_deposits_with_limits(
amount as u128,
&SpotBalanceType::Borrow,
spot_market,
user,
)?;
amount
};
user.meets_withdraw_margin_requirement_and_increment_fuel_bonus(
&perp_market_map,
&spot_market_map,
&mut oracle_map,
MarginRequirementType::Initial,
market_index,
amount as u128,
&mut user_stats,
now,
)?;
validate_spot_margin_trading(user, &perp_market_map, &spot_market_map, &mut oracle_map)?;
if user.is_being_liquidated() {
user.exit_liquidation();
}
user.update_last_active_slot(slot);
let mut spot_market = spot_market_map.get_ref_mut(&market_index)?;
let oracle_price = oracle_map.get_price_data(&spot_market.oracle_id())?.price;
let is_borrow = user
.get_spot_position(market_index)
.map_or(false, |pos| pos.is_borrow());
let deposit_explanation = if is_borrow {
DepositExplanation::Borrow
} else {
DepositExplanation::None
};
let deposit_record_id = get_then_update_id!(spot_market, next_deposit_record_id);
let deposit_record = DepositRecord {
ts: now,
deposit_record_id,
user_authority: user.authority,
user: user_key,
direction: DepositDirection::Withdraw,
oracle_price,
amount,
market_index,
market_deposit_balance: spot_market.deposit_balance,
market_withdraw_balance: spot_market.borrow_balance,
market_cumulative_deposit_interest: spot_market.cumulative_deposit_interest,
market_cumulative_borrow_interest: spot_market.cumulative_borrow_interest,
total_deposits_after: user.total_deposits,
total_withdraws_after: user.total_withdraws,
explanation: deposit_explanation,
transfer_user: None,
};
emit!(deposit_record);
controller::token::send_from_program_vault(
&ctx.accounts.token_program,
&ctx.accounts.spot_market_vault,
&ctx.accounts.user_token_account,
&ctx.accounts.drift_signer,
state.signer_nonce,
amount,
&mint,
)?;
// reload the spot market vault balance so it's up-to-date
ctx.accounts.spot_market_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
&spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
spot_market.validate_max_token_deposits_and_borrows(is_borrow)?;
Ok(())
}
#[access_control(
deposit_not_paused(&ctx.accounts.state)
withdraw_not_paused(&ctx.accounts.state)
)]
pub fn handle_transfer_deposit<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, TransferDeposit<'info>>,
market_index: u16,
amount: u64,
) -> anchor_lang::Result<()> {
let authority_key = ctx.accounts.authority.key;
let to_user_key = ctx.accounts.to_user.key();
let from_user_key = ctx.accounts.from_user.key();
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let slot = clock.slot;
let to_user = &mut load_mut!(ctx.accounts.to_user)?;
let from_user = &mut load_mut!(ctx.accounts.from_user)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
validate!(
!to_user.is_bankrupt(),
ErrorCode::UserBankrupt,
"to_user bankrupt"
)?;
validate!(
!from_user.is_bankrupt(),
ErrorCode::UserBankrupt,
"from_user bankrupt"
)?;
validate!(
from_user_key != to_user_key,
ErrorCode::CantTransferBetweenSameUserAccount,
"cant transfer between the same user account"
)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&get_writable_spot_market_set(market_index),
clock.slot,
Some(state.oracle_guard_rails),
)?;
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
controller::spot_balance::update_spot_market_cumulative_interest(
spot_market,
Some(oracle_price_data),
clock.unix_timestamp,
)?;
}
let oracle_price = {
let spot_market = &spot_market_map.get_ref(&market_index)?;
oracle_map.get_price_data(&spot_market.oracle_id())?.price
};
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
validate!(
from_user.pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) != market pool id ({})",
from_user.pool_id,
spot_market.pool_id
)?;
from_user.increment_total_withdraws(
amount,
oracle_price,
spot_market.get_precision().cast()?,
)?;
// prevents withdraw when limits hit
controller::spot_position::update_spot_balances_and_cumulative_deposits_with_limits(
amount as u128,
&SpotBalanceType::Borrow,
spot_market,
from_user,
)?;
}
from_user.meets_withdraw_margin_requirement_and_increment_fuel_bonus(
&perp_market_map,
&spot_market_map,
&mut oracle_map,
MarginRequirementType::Initial,
market_index,
amount as u128,
user_stats,
now,
)?;
validate_spot_margin_trading(
from_user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
)?;
if from_user.is_being_liquidated() {
from_user.exit_liquidation();
}
from_user.update_last_active_slot(slot);
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
let deposit_record_id = get_then_update_id!(spot_market, next_deposit_record_id);
let deposit_record = DepositRecord {
ts: clock.unix_timestamp,
deposit_record_id,
user_authority: *authority_key,
user: from_user_key,
direction: DepositDirection::Withdraw,
amount,
oracle_price,
market_index,
market_deposit_balance: spot_market.deposit_balance,
market_withdraw_balance: spot_market.borrow_balance,
market_cumulative_deposit_interest: spot_market.cumulative_deposit_interest,
market_cumulative_borrow_interest: spot_market.cumulative_borrow_interest,
total_deposits_after: from_user.total_deposits,
total_withdraws_after: from_user.total_withdraws,
explanation: DepositExplanation::Transfer,
transfer_user: Some(to_user_key),
};
emit!(deposit_record);
}
{
let spot_market = &mut spot_market_map.get_ref_mut(&market_index)?;
validate!(
to_user.pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) != market pool id ({})",
to_user.pool_id,
spot_market.pool_id
)?;
to_user.increment_total_deposits(
amount,
oracle_price,
spot_market.get_precision().cast()?,
)?;
let total_deposits_after = to_user.total_deposits;
let total_withdraws_after = to_user.total_withdraws;
let to_spot_position = to_user.force_get_spot_position_mut(spot_market.market_index)?;
controller::spot_position::update_spot_balances_and_cumulative_deposits(
amount as u128,
&SpotBalanceType::Deposit,
spot_market,
to_spot_position,
false,
None,
)?;
let token_amount = to_spot_position.get_token_amount(spot_market)?;
if token_amount == 0 {
validate!(
to_spot_position.scaled_balance == 0,
ErrorCode::InvalidSpotPosition,
"deposit left to_user with invalid position. scaled balance = {} token amount = {}",
to_spot_position.scaled_balance,
token_amount
)?;
}
let deposit_record_id = get_then_update_id!(spot_market, next_deposit_record_id);
let deposit_record = DepositRecord {
ts: clock.unix_timestamp,
deposit_record_id,
user_authority: *authority_key,
user: to_user_key,
direction: DepositDirection::Deposit,
amount,
oracle_price,
market_index,
market_deposit_balance: spot_market.deposit_balance,
market_withdraw_balance: spot_market.borrow_balance,
market_cumulative_deposit_interest: spot_market.cumulative_deposit_interest,
market_cumulative_borrow_interest: spot_market.cumulative_borrow_interest,
total_deposits_after,
total_withdraws_after,
explanation: DepositExplanation::Transfer,
transfer_user: Some(from_user_key),
};
emit!(deposit_record);
}
to_user.update_last_active_slot(slot);
let spot_market = spot_market_map.get_ref(&market_index)?;
math::spot_withdraw::validate_spot_market_vault_amount(
&spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_place_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
params: OrderParams,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
if params.immediate_or_cancel {
msg!("immediate_or_cancel order must be in place_and_make or place_and_take");
return Err(print_error!(ErrorCode::InvalidOrderIOC)().into());
}
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
controller::orders::place_perp_order(
&ctx.accounts.state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
params,
PlaceOrderOptions::default(),
)?;
Ok(())
}
pub fn handle_place_and_match_rfq_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMatchRFQOrders<'info>>,
rfq_matches: Vec<RFQMatch>,
) -> Result<()> {
// Verify everything before proceeding to match the rfq orders
let ix_sysvar = &ctx.accounts.ix_sysvar.to_account_info();
let number_of_verify_ixs_needed = rfq_matches.len();
let ix_idx = load_current_index_checked(ix_sysvar)?;
for i in 0..rfq_matches.len() {
// First verify that the message is legitimate
let maker_order_params = &rfq_matches[i].maker_order_params;
if rfq_matches[i].base_asset_amount > maker_order_params.base_asset_amount {
msg!(
"RFQ match amount exceeds maker order amount: {} > {}",
rfq_matches[i].base_asset_amount,
maker_order_params.base_asset_amount
);
return Err(ErrorCode::InvalidRFQMatch.into());
}
let ix: Instruction = load_instruction_at_checked(
ix_idx as usize - number_of_verify_ixs_needed + i,
ix_sysvar,
)?;
verify_ed25519_ix(
&ix,
&maker_order_params.authority.to_bytes(),
&maker_order_params.clone().try_to_vec()?,
&rfq_matches[i].maker_signature,
)?;
}
// TODO: generalize to support multiple market types
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
Some(state.oracle_guard_rails),
)?;
let (makers_and_referrer, makers_and_referrer_stats) =
load_user_maps(remaining_accounts_iter, true)?;
let maker_rfq_account_map = load_rfq_user_account_map(remaining_accounts_iter)?;
place_and_match_rfq_orders(
&ctx.accounts.user,
&ctx.accounts.user_stats,
rfq_matches,
maker_rfq_account_map,
&makers_and_referrer,
&makers_and_referrer_stats,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
state,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_cancel_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder>,
order_id: Option<u32>,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let order_id = match order_id {
Some(order_id) => order_id,
None => load!(ctx.accounts.user)?.get_last_order_id(),
};
controller::orders::cancel_order_by_order_id(
order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_cancel_order_by_user_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder>,
user_order_id: u8,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::orders::cancel_order_by_user_order_id(
user_order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_cancel_orders_by_ids<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder>,
order_ids: Vec<u32>,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
for order_id in order_ids {
controller::orders::cancel_order_by_order_id(
order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
}
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_cancel_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder<'info>>,
market_type: Option<MarketType>,
market_index: Option<u16>,
direction: Option<PositionDirection>,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
cancel_orders(
&mut user,
&user_key,
None,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock.unix_timestamp,
clock.slot,
OrderActionExplanation::None,
market_type,
market_index,
direction,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_modify_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder<'info>>,
order_id: Option<u32>,
modify_order_params: ModifyOrderParams,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let order_id = match order_id {
Some(order_id) => order_id,
None => load!(ctx.accounts.user)?.get_last_order_id(),
};
controller::orders::modify_order(
ModifyOrderId::OrderId(order_id),
modify_order_params,
&ctx.accounts.user,
state,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_modify_order_by_user_order_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, CancelOrder<'info>>,
user_order_id: u8,
modify_order_params: ModifyOrderParams,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::orders::modify_order(
ModifyOrderId::UserOrderId(user_order_id),
modify_order_params,
&ctx.accounts.user,
state,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
Ok(())
}
#[access_control(
exchange_not_paused(&ctx.accounts.state)
)]
pub fn handle_place_orders<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
params: Vec<OrderParams>,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
validate!(
params.len() <= 32,
ErrorCode::DefaultError,
"max 32 order params"
)?;
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
let num_orders = params.len();
for (i, params) in params.iter().enumerate() {
validate!(
!params.immediate_or_cancel,
ErrorCode::InvalidOrderIOC,
"immediate_or_cancel order must be in place_and_make or place_and_take"
)?;
// only enforce margin on last order and only try to expire on first order
let options = PlaceOrderOptions {
swift_taker_order_slot: None,
enforce_margin_check: i == num_orders - 1,
try_expire_orders: i == 0,
risk_increasing: false,
explanation: OrderActionExplanation::None,
is_rfq_order: false,
};
if params.market_type == MarketType::Perp {
controller::orders::place_perp_order(
&ctx.accounts.state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
*params,
options,
)?;
} else {
controller::orders::place_spot_order(
&ctx.accounts.state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
*params,
options,
)?;
}
}
Ok(())
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_place_and_take_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndTake<'info>>,
params: OrderParams,
optional_params: Option<u32>, // u32 for backwards compatibility
) -> Result<()> {
let clock = Clock::get()?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&get_writable_perp_market_set(params.market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
if params.post_only != PostOnlyParam::None {
msg!("post_only cant be used in place_and_take");
return Err(print_error!(ErrorCode::InvalidOrderPostOnly)().into());
}
let (makers_and_referrer, makers_and_referrer_stats) =
load_user_maps(remaining_accounts_iter, true)?;
let is_immediate_or_cancel = params.immediate_or_cancel;
controller::repeg::update_amm(
params.market_index,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.state,
&Clock::get()?,
)?;
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
let clock = Clock::get()?;
let (success_condition, auction_duration_percentage) = parse_optional_params(optional_params);
controller::orders::place_perp_order(
&ctx.accounts.state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
params,
PlaceOrderOptions::default(),
)?;
drop(user);
let user = &mut ctx.accounts.user;
let order_id = load!(user)?.get_last_order_id();
let (base_asset_amount_filled, _) = controller::orders::fill_perp_order(
order_id,
&ctx.accounts.state,
user,
&ctx.accounts.user_stats,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&user.clone(),
&ctx.accounts.user_stats.clone(),
&makers_and_referrer,
&makers_and_referrer_stats,
None,
&Clock::get()?,
FillMode::PlaceAndTake(
is_immediate_or_cancel || optional_params.is_some(),
auction_duration_percentage,
),
)?;
let order_exists = load!(ctx.accounts.user)?
.orders
.iter()
.any(|order| order.order_id == order_id);
if is_immediate_or_cancel && order_exists {
controller::orders::cancel_order_by_order_id(
order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&Clock::get()?,
)?;
}
if success_condition == PlaceAndTakeOrderSuccessCondition::PartialFill as u8 {
validate!(
base_asset_amount_filled > 0,
ErrorCode::PlaceAndTakeOrderSuccessConditionFailed,
"no partial fill"
)?;
} else if success_condition == PlaceAndTakeOrderSuccessCondition::FullFill as u8 {
validate!(
base_asset_amount_filled > 0 && !order_exists,
ErrorCode::PlaceAndTakeOrderSuccessConditionFailed,
"no full fill"
)?;
}
Ok(())
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_place_and_make_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMake<'info>>,
params: OrderParams,
taker_order_id: u32,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&get_writable_perp_market_set(params.market_index),
&MarketSet::new(),
Clock::get()?.slot,
Some(state.oracle_guard_rails),
)?;
if !params.immediate_or_cancel
|| params.post_only == PostOnlyParam::None
|| params.order_type != OrderType::Limit
{
msg!("place_and_make must use IOC post only limit order");
return Err(print_error!(ErrorCode::InvalidOrderIOCPostOnly)().into());
}
controller::repeg::update_amm(
params.market_index,
&perp_market_map,
&mut oracle_map,
state,
clock,
)?;
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
controller::orders::place_perp_order(
state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
params,
PlaceOrderOptions::default(),
)?;
let (order_id, authority) = (user.get_last_order_id(), user.authority);
drop(user);
let (mut makers_and_referrer, mut makers_and_referrer_stats) =
load_user_maps(remaining_accounts_iter, true)?;
makers_and_referrer.insert(ctx.accounts.user.key(), ctx.accounts.user.clone())?;
makers_and_referrer_stats.insert(authority, ctx.accounts.user_stats.clone())?;
controller::orders::fill_perp_order(
taker_order_id,
state,
&ctx.accounts.taker,
&ctx.accounts.taker_stats,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.user.clone(),
&ctx.accounts.user_stats.clone(),
&makers_and_referrer,
&makers_and_referrer_stats,
Some(order_id),
clock,
FillMode::PlaceAndMake,
)?;
let order_exists = load!(ctx.accounts.user)?
.orders
.iter()
.any(|order| order.order_id == order_id);
if order_exists {
controller::orders::cancel_order_by_order_id(
order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
}
Ok(())
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_place_and_make_swift_perp_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMakeSwift<'info>>,
params: OrderParams,
swift_order_uuid: [u8; 8],
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&get_writable_perp_market_set(params.market_index),
&MarketSet::new(),
Clock::get()?.slot,
Some(state.oracle_guard_rails),
)?;
if !params.immediate_or_cancel
|| params.post_only == PostOnlyParam::None
|| params.order_type != OrderType::Limit
{
msg!("place_and_make must use IOC post only limit order");
return Err(print_error!(ErrorCode::InvalidOrderIOCPostOnly)().into());
}
controller::repeg::update_amm(
params.market_index,
&perp_market_map,
&mut oracle_map,
state,
clock,
)?;
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
controller::orders::place_perp_order(
state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
params,
PlaceOrderOptions::default(),
)?;
let (order_id, authority) = (user.get_last_order_id(), user.authority);
drop(user);
let (mut makers_and_referrer, mut makers_and_referrer_stats) =
load_user_maps(remaining_accounts_iter, true)?;
makers_and_referrer.insert(ctx.accounts.user.key(), ctx.accounts.user.clone())?;
makers_and_referrer_stats.insert(authority, ctx.accounts.user_stats.clone())?;
let taker_swift_account = ctx.accounts.taker_swift_user_orders.load()?;
let taker_order_id = taker_swift_account
.iter()
.find(|swift_order_id| swift_order_id.uuid == swift_order_uuid)
.ok_or(ErrorCode::SwiftOrderDoesNotExist)?
.order_id;
controller::orders::fill_perp_order(
taker_order_id,
state,
&ctx.accounts.taker,
&ctx.accounts.taker_stats,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.user.clone(),
&ctx.accounts.user_stats.clone(),
&makers_and_referrer,
&makers_and_referrer_stats,
Some(order_id),
clock,
FillMode::PlaceAndMake,
)?;
let order_exists = load!(ctx.accounts.user)?
.orders
.iter()
.any(|order| order.order_id == order_id);
if order_exists {
controller::orders::cancel_order_by_order_id(
order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
}
Ok(())
}
pub fn handle_place_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceOrder>,
params: OrderParams,
) -> Result<()> {
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
None,
)?;
if params.immediate_or_cancel {
msg!("immediate_or_cancel order must be in place_and_make or place_and_take");
return Err(print_error!(ErrorCode::InvalidOrderIOC)().into());
}
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
controller::orders::place_spot_order(
&ctx.accounts.state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&Clock::get()?,
params,
PlaceOrderOptions::default(),
)?;
Ok(())
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_place_and_take_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndTake<'info>>,
params: OrderParams,
fulfillment_type: SpotFulfillmentType,
_maker_order_id: Option<u32>,
) -> Result<()> {
let clock = Clock::get()?;
let market_index = params.market_index;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&get_writable_spot_market_set_from_many(vec![QUOTE_SPOT_MARKET_INDEX, market_index]),
clock.slot,
None,
)?;
if params.post_only != PostOnlyParam::None {
msg!("post_only cant be used in place_and_take");
return Err(print_error!(ErrorCode::InvalidOrderPostOnly)().into());
}
let (makers_and_referrer, makers_and_referrer_stats) = match fulfillment_type {
SpotFulfillmentType::Match => load_user_maps(remaining_accounts_iter, true)?,
_ => (UserMap::empty(), UserStatsMap::empty()),
};
let is_immediate_or_cancel = params.immediate_or_cancel;
let mut fulfillment_params: Box<dyn SpotFulfillmentParams> = match fulfillment_type {
SpotFulfillmentType::SerumV3 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(SerumFulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::PhoenixV1 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(PhoenixFulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
)?)
}
SpotFulfillmentType::OpenbookV2 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(OpenbookV2FulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::Match => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(MatchFulfillmentParams::new(
remaining_accounts_iter,
&base_market,
"e_market,
)?)
}
};
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
let order_id_before = user.get_last_order_id();
controller::orders::place_spot_order(
&ctx.accounts.state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
params,
PlaceOrderOptions::default(),
)?;
drop(user);
let user = &mut ctx.accounts.user;
let order_id = load!(user)?.get_last_order_id();
if order_id == order_id_before {
msg!("new order failed to be placed");
return Err(print_error!(ErrorCode::InvalidOrder)().into());
}
controller::orders::fill_spot_order(
order_id,
&ctx.accounts.state,
user,
&ctx.accounts.user_stats,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&user.clone(),
&ctx.accounts.user_stats.clone(),
&makers_and_referrer,
&makers_and_referrer_stats,
None,
&clock,
fulfillment_params.as_mut(),
)?;
let order_exists = load!(ctx.accounts.user)?
.orders
.iter()
.any(|order| order.order_id == order_id);
if is_immediate_or_cancel && order_exists {
controller::orders::cancel_order_by_order_id(
order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
&clock,
)?;
}
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
fulfillment_params.validate_vault_amounts(&base_market, "e_market)?;
Ok(())
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_place_and_make_spot_order<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, PlaceAndMake<'info>>,
params: OrderParams,
taker_order_id: u32,
fulfillment_type: SpotFulfillmentType,
) -> Result<()> {
let clock = &Clock::get()?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&get_writable_spot_market_set_from_many(vec![QUOTE_SPOT_MARKET_INDEX, params.market_index]),
Clock::get()?.slot,
None,
)?;
let (_referrer, _referrer_stats) = get_referrer_and_referrer_stats(remaining_accounts_iter)?;
if !params.immediate_or_cancel
|| params.post_only == PostOnlyParam::None
|| params.order_type != OrderType::Limit
{
msg!("place_and_make must use IOC post only limit order");
return Err(print_error!(ErrorCode::InvalidOrderIOCPostOnly)().into());
}
let market_index = params.market_index;
let mut fulfillment_params: Box<dyn SpotFulfillmentParams> = match fulfillment_type {
SpotFulfillmentType::SerumV3 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(SerumFulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::PhoenixV1 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(PhoenixFulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
)?)
}
SpotFulfillmentType::OpenbookV2 => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(OpenbookV2FulfillmentParams::new(
remaining_accounts_iter,
&ctx.accounts.state,
&base_market,
"e_market,
clock.unix_timestamp,
)?)
}
SpotFulfillmentType::Match => {
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
Box::new(MatchFulfillmentParams::new(
remaining_accounts_iter,
&base_market,
"e_market,
)?)
}
};
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(ctx.accounts.user)?;
let authority = user.authority;
controller::orders::place_spot_order(
state,
&mut user,
user_key,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
params,
PlaceOrderOptions::default(),
)?;
drop(user);
let order_id = load!(ctx.accounts.user)?.get_last_order_id();
let mut makers_and_referrer = UserMap::empty();
let mut makers_and_referrer_stats = UserStatsMap::empty();
makers_and_referrer.insert(ctx.accounts.user.key(), ctx.accounts.user.clone())?;
makers_and_referrer_stats.insert(authority, ctx.accounts.user_stats.clone())?;
controller::orders::fill_spot_order(
taker_order_id,
state,
&ctx.accounts.taker,
&ctx.accounts.taker_stats,
&spot_market_map,
&perp_market_map,
&mut oracle_map,
&ctx.accounts.user.clone(),
&ctx.accounts.user_stats.clone(),
&makers_and_referrer,
&makers_and_referrer_stats,
Some(order_id),
clock,
fulfillment_params.as_mut(),
)?;
let order_exists = load!(ctx.accounts.user)?
.orders
.iter()
.any(|order| order.order_id == order_id);
if order_exists {
controller::orders::cancel_order_by_order_id(
order_id,
&ctx.accounts.user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
clock,
)?;
}
let base_market = spot_market_map.get_ref(&market_index)?;
let quote_market = spot_market_map.get_quote_spot_market()?;
fulfillment_params.validate_vault_amounts(&base_market, "e_market)?;
Ok(())
}
#[access_control(
amm_not_paused(&ctx.accounts.state)
)]
pub fn handle_add_perp_lp_shares<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AddRemoveLiquidity<'info>>,
n_shares: u64,
market_index: u16,
) -> Result<()> {
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set(market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
validate!(!user.is_bankrupt(), ErrorCode::UserBankrupt)?;
math::liquidation::validate_user_not_being_liquidated(
user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
state.liquidation_margin_buffer_ratio,
)?;
{
let mut market = perp_market_map.get_ref_mut(&market_index)?;
validate!(
matches!(market.status, MarketStatus::Active),
ErrorCode::MarketStatusInvalidForNewLP,
"Market Status doesn't allow for new LP liquidity"
)?;
validate!(
!matches!(market.contract_type, ContractType::Prediction),
ErrorCode::MarketStatusInvalidForNewLP,
"Contract Type doesn't allow for LP liquidity"
)?;
validate!(
!market.is_operation_paused(PerpOperation::AmmFill),
ErrorCode::MarketStatusInvalidForNewLP,
"Market amm fills paused"
)?;
validate!(
n_shares >= market.amm.order_step_size,
ErrorCode::NewLPSizeTooSmall,
"minting {} shares is less than step size {}",
n_shares,
market.amm.order_step_size,
)?;
controller::funding::settle_funding_payment(user, &user_key, &mut market, now)?;
// standardize n shares to mint
let n_shares = crate::math::orders::standardize_base_asset_amount(
n_shares.cast()?,
market.amm.order_step_size,
)?
.cast::<u64>()?;
controller::lp::mint_lp_shares(
user.force_get_perp_position_mut(market_index)?,
&mut market,
n_shares,
)?;
user.last_add_perp_lp_shares_ts = now;
}
// check margin requirements
meets_place_order_margin_requirement(
user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
true,
)?;
user.update_last_active_slot(clock.slot);
emit!(LPRecord {
ts: now,
action: LPAction::AddLiquidity,
user: user_key,
n_shares,
market_index,
..LPRecord::default()
});
Ok(())
}
pub fn handle_remove_perp_lp_shares_in_expiring_market<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, RemoveLiquidityInExpiredMarket<'info>>,
shares_to_burn: u64,
market_index: u16,
) -> Result<()> {
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let AccountMaps {
perp_market_map,
mut oracle_map,
..
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set(market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
// additional validate
{
let market = perp_market_map.get_ref(&market_index)?;
validate!(
market.is_reduce_only()?,
ErrorCode::PerpMarketNotInReduceOnly,
"Can only permissionless burn when market is in reduce only"
)?;
}
controller::lp::remove_perp_lp_shares(
perp_market_map,
&mut oracle_map,
state,
user,
user_key,
shares_to_burn,
market_index,
now,
)?;
user.update_last_active_slot(clock.slot);
Ok(())
}
#[access_control(
amm_not_paused(&ctx.accounts.state)
)]
pub fn handle_remove_perp_lp_shares<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AddRemoveLiquidity<'info>>,
shares_to_burn: u64,
market_index: u16,
) -> Result<()> {
let user_key = ctx.accounts.user.key();
let user = &mut load_mut!(ctx.accounts.user)?;
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let AccountMaps {
perp_market_map,
mut oracle_map,
..
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set(market_index),
&MarketSet::new(),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::lp::remove_perp_lp_shares(
perp_market_map,
&mut oracle_map,
state,
user,
user_key,
shares_to_burn,
market_index,
now,
)?;
user.update_last_active_slot(clock.slot);
Ok(())
}
pub fn handle_update_user_name(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
name: [u8; 32],
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
user.name = name;
Ok(())
}
pub fn handle_update_user_custom_margin_ratio(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
margin_ratio: u32,
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
user.max_margin_ratio = margin_ratio;
Ok(())
}
pub fn handle_update_user_margin_trading_enabled<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUser<'info>>,
_sub_account_id: u16,
margin_trading_enabled: bool,
) -> Result<()> {
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
..
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
None,
)?;
let mut user = load_mut!(ctx.accounts.user)?;
user.is_margin_trading_enabled = margin_trading_enabled;
validate_spot_margin_trading(&user, &perp_market_map, &spot_market_map, &mut oracle_map)
.map_err(|_| ErrorCode::MarginOrdersOpen)?;
Ok(())
}
pub fn handle_update_user_pool_id<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdateUser<'info>>,
_sub_account_id: u16,
pool_id: u8,
) -> Result<()> {
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
..
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
None,
)?;
let mut user = load_mut!(ctx.accounts.user)?;
user.pool_id = pool_id;
// will throw if user has deposits/positions in other pools
meets_initial_margin_requirement(&user, &perp_market_map, &spot_market_map, &mut oracle_map)?;
Ok(())
}
pub fn handle_update_user_delegate(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
delegate: Pubkey,
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
user.delegate = delegate;
Ok(())
}
pub fn handle_update_user_reduce_only(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
reduce_only: bool,
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
validate!(!user.is_being_liquidated(), ErrorCode::LiquidationsOngoing)?;
user.update_reduce_only_status(reduce_only)?;
Ok(())
}
pub fn handle_update_user_advanced_lp(
ctx: Context<UpdateUser>,
_sub_account_id: u16,
advanced_lp: bool,
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
validate!(!user.is_being_liquidated(), ErrorCode::LiquidationsOngoing)?;
user.update_advanced_lp_status(advanced_lp)?;
Ok(())
}
pub fn handle_update_user_protected_maker_orders(
ctx: Context<UpdateUserProtectedMakerMode>,
_sub_account_id: u16,
protected_maker_orders: bool,
) -> Result<()> {
let mut user = load_mut!(ctx.accounts.user)?;
validate!(!user.is_being_liquidated(), ErrorCode::LiquidationsOngoing)?;
user.update_protected_maker_orders_status(protected_maker_orders)?;
let mut config = load_mut!(ctx.accounts.protected_maker_mode_config)?;
if protected_maker_orders {
validate!(
!config.is_reduce_only(),
ErrorCode::DefaultError,
"protected maker mode config reduce only"
)?;
config.current_users = config.current_users.safe_add(1)?;
} else {
config.current_users = config.current_users.safe_sub(1)?;
}
config.validate()?;
Ok(())
}
pub fn handle_delete_user(ctx: Context<DeleteUser>) -> Result<()> {
let user = &load!(ctx.accounts.user)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
validate_user_deletion(
user,
user_stats,
&ctx.accounts.state,
Clock::get()?.unix_timestamp,
)?;
safe_decrement!(user_stats.number_of_sub_accounts, 1);
let state = &mut ctx.accounts.state;
safe_decrement!(state.number_of_sub_accounts, 1);
Ok(())
}
pub fn handle_delete_swift_user_orders(_ctx: Context<DeleteSwiftUserOrders>) -> Result<()> {
Ok(())
}
pub fn handle_reclaim_rent(ctx: Context<ReclaimRent>) -> Result<()> {
let user_size = ctx.accounts.user.to_account_info().data_len();
let minimum_lamports = ctx.accounts.rent.minimum_balance(user_size);
let current_lamports = ctx.accounts.user.to_account_info().try_lamports()?;
let reclaim_amount = current_lamports.saturating_sub(minimum_lamports);
validate!(
reclaim_amount > 0,
ErrorCode::CantReclaimRent,
"user account has no excess lamports to reclaim"
)?;
**ctx
.accounts
.user
.to_account_info()
.try_borrow_mut_lamports()? = minimum_lamports;
**ctx
.accounts
.authority
.to_account_info()
.try_borrow_mut_lamports()? += reclaim_amount;
let user_stats = &mut load!(ctx.accounts.user_stats)?;
// Skip age check if is no max sub accounts
let max_sub_accounts = ctx.accounts.state.max_number_of_sub_accounts();
let estimated_user_stats_age = user_stats.get_age_ts(Clock::get()?.unix_timestamp);
validate!(
max_sub_accounts == 0 || estimated_user_stats_age >= THIRTEEN_DAY,
ErrorCode::CantReclaimRent,
"user stats too young to reclaim rent. age ={} minimum = {}",
estimated_user_stats_age,
THIRTEEN_DAY
)?;
Ok(())
}
#[access_control(
deposit_not_paused(&ctx.accounts.state)
)]
pub fn handle_deposit_into_spot_market_revenue_pool<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, RevenuePoolDeposit<'info>>,
amount: u64,
) -> Result<()> {
if amount == 0 {
return Err(ErrorCode::InsufficientDeposit.into());
}
let mut spot_market = load_mut!(ctx.accounts.spot_market)?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let mint = get_token_mint(remaining_accounts_iter)?;
validate!(
!spot_market.is_in_settlement(Clock::get()?.unix_timestamp),
ErrorCode::DefaultError,
"spot market {} not active",
spot_market.market_index
)?;
controller::spot_balance::update_revenue_pool_balances(
amount.cast::<u128>()?,
&SpotBalanceType::Deposit,
&mut spot_market,
)?;
controller::token::receive(
&ctx.accounts.token_program,
&ctx.accounts.user_token_account,
&ctx.accounts.spot_market_vault,
&ctx.accounts.authority,
amount,
&mint,
)?;
spot_market.validate_max_token_deposits_and_borrows(false)?;
ctx.accounts.spot_market_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
&spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
Ok(())
}
pub fn handle_enable_user_high_leverage_mode<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, EnableUserHighLeverageMode>,
_sub_account_id: u16,
) -> Result<()> {
let state = &ctx.accounts.state;
let mut user = load_mut!(ctx.accounts.user)?;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&MarketSet::new(),
&MarketSet::new(),
Clock::get()?.slot,
Some(state.oracle_guard_rails),
)?;
validate!(
user.margin_mode != MarginMode::HighLeverage,
ErrorCode::DefaultError,
"user already in high leverage mode"
)?;
meets_maintenance_margin_requirement(
&user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
)?;
user.margin_mode = MarginMode::HighLeverage;
let mut config = load_mut!(ctx.accounts.high_leverage_mode_config)?;
validate!(
!config.is_reduce_only(),
ErrorCode::DefaultError,
"high leverage mode config reduce only"
)?;
config.current_users = config.current_users.safe_add(1)?;
config.validate()?;
Ok(())
}
#[derive(Accounts)]
#[instruction(
sub_account_id: u16,
)]
pub struct InitializeUser<'info> {
#[account(
init,
seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()],
space = User::SIZE,
bump,
payer = payer
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
has_one = authority
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(mut)]
pub payer: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct InitializeUserStats<'info> {
#[account(
init,
seeds = [b"user_stats", authority.key.as_ref()],
space = UserStats::SIZE,
bump,
payer = payer
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(mut)]
pub payer: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct InitializeRFQUser<'info> {
#[account(
init,
seeds = [RFQ_PDA_SEED.as_ref(), user.key().as_ref()],
space = RFQUser::SIZE,
bump,
payer = payer
)]
pub rfq_user: AccountLoader<'info, RFQUser>,
pub authority: Signer<'info>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(mut)]
pub payer: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(num_orders: u16)]
pub struct InitializeSwiftUserOrders<'info> {
#[account(
init,
seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()],
space = SwiftUserOrders::space(num_orders as usize),
bump,
payer = payer
)]
pub swift_user_orders: Box<Account<'info, SwiftUserOrders>>,
pub authority: Signer<'info>,
#[account(
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(mut)]
pub payer: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(num_orders: u16)]
pub struct ResizeSwiftUserOrders<'info> {
#[account(
mut,
seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()],
bump,
realloc = SwiftUserOrders::space(num_orders as usize),
realloc::payer = authority,
realloc::zero = false,
)]
pub swift_user_orders: Box<Account<'info, SwiftUserOrders>>,
#[account(mut)]
pub authority: Signer<'info>,
#[account(
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(
name: [u8; 32],
)]
pub struct InitializeReferrerName<'info> {
#[account(
init,
seeds = [b"referrer_name", name.as_ref()],
space = ReferrerName::SIZE,
bump,
payer = payer
)]
pub referrer_name: AccountLoader<'info, ReferrerName>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(mut)]
pub payer: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(market_index: u16,)]
pub struct Deposit<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
constraint = &spot_market_vault.mint.eq(&user_token_account.mint),
token::authority = authority
)]
pub user_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
pub struct RevenuePoolDeposit<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(mut)]
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), spot_market.load()?.market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
constraint = &spot_market_vault.mint.eq(&user_token_account.mint),
token::authority = authority
)]
pub user_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(market_index: u16,)]
pub struct Withdraw<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
has_one = authority,
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
has_one = authority
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
#[account(
mut,
constraint = &spot_market_vault.mint.eq(&user_token_account.mint)
)]
pub user_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(market_index: u16,)]
pub struct TransferDeposit<'info> {
#[account(
mut,
has_one = authority,
)]
pub from_user: AccountLoader<'info, User>,
#[account(
mut,
has_one = authority,
)]
pub to_user: AccountLoader<'info, User>,
#[account(
mut,
has_one = authority
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
pub state: Box<Account<'info, State>>,
#[account(
seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
#[derive(Accounts)]
pub struct PlaceOrder<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct CancelOrder<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct PlaceAndTake<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct PlaceAndMake<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub taker: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&taker, &taker_stats)?
)]
pub taker_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct PlaceAndMakeSwift<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub taker: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&taker, &taker_stats)?
)]
pub taker_stats: AccountLoader<'info, UserStats>,
#[account(
seeds = [SWIFT_PDA_SEED.as_ref(), taker.key().as_ref()],
bump,
)]
/// CHECK: checked in SwiftUserOrdersZeroCopy checks
pub taker_swift_user_orders: AccountInfo<'info>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct PlaceAndMatchRFQOrders<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
/// CHECK: The address check is needed because otherwise
/// the supplied Sysvar could be anything else.
/// The Instruction Sysvar has not been implemented
/// in the Anchor framework yet, so this is the safe approach.
#[account(address = IX_ID)]
pub ix_sysvar: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct AddRemoveLiquidity<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?,
)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct RemoveLiquidityInExpiredMarket<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
}
#[derive(Accounts)]
#[instruction(
sub_account_id: u16,
)]
pub struct UpdateUser<'info> {
#[account(
mut,
seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()],
bump,
)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct DeleteUser<'info> {
#[account(
mut,
has_one = authority,
close = authority
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
has_one = authority
)]
pub user_stats: AccountLoader<'info, UserStats>,
#[account(mut)]
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct DeleteSwiftUserOrders<'info> {
#[account(
mut,
has_one = authority,
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
close = user,
seeds = [SWIFT_PDA_SEED.as_ref(), user.key().as_ref()],
bump,
)]
pub swift_user_orders: Box<Account<'info, SwiftUserOrders>>,
#[account(mut)]
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
}
#[derive(Accounts)]
pub struct ReclaimRent<'info> {
#[account(
mut,
has_one = authority,
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
has_one = authority
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
}
#[derive(Accounts)]
#[instruction(in_market_index: u16, out_market_index: u16, )]
pub struct Swap<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
#[account(
mut,
constraint = is_stats_for_user(&user, &user_stats)?
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), out_market_index.to_le_bytes().as_ref()],
bump,
)]
pub out_spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), in_market_index.to_le_bytes().as_ref()],
bump,
)]
pub in_spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
constraint = &out_spot_market_vault.mint.eq(&out_token_account.mint),
token::authority = authority
)]
pub out_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
constraint = &in_spot_market_vault.mint.eq(&in_token_account.mint),
token::authority = authority
)]
pub in_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
/// Instructions Sysvar for instruction introspection
/// CHECK: fixed instructions sysvar account
#[account(address = instructions::ID)]
pub instructions: UncheckedAccount<'info>,
}
#[derive(Accounts)]
#[instruction(
sub_account_id: u16,
)]
pub struct EnableUserHighLeverageMode<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
constraint = can_sign_for_user(&user, &authority)?
)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
#[account(mut)]
pub high_leverage_mode_config: AccountLoader<'info, HighLeverageModeConfig>,
}
#[derive(Accounts)]
#[instruction(
sub_account_id: u16,
)]
pub struct UpdateUserProtectedMakerMode<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [b"user", authority.key.as_ref(), sub_account_id.to_le_bytes().as_ref()],
bump,
)]
pub user: AccountLoader<'info, User>,
pub authority: Signer<'info>,
#[account(mut)]
pub protected_maker_mode_config: AccountLoader<'info, ProtectedMakerModeConfig>,
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_begin_swap<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Swap<'info>>,
in_market_index: u16,
out_market_index: u16,
amount_in: u64,
) -> Result<()> {
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts_iter,
&MarketSet::new(),
&get_writable_spot_market_set_from_many(vec![in_market_index, out_market_index]),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let _token_interface = get_token_interface(remaining_accounts_iter)?;
let mint = get_token_mint(remaining_accounts_iter)?;
let mut user = load_mut!(&ctx.accounts.user)?;
let delegate_is_signer = user.delegate == ctx.accounts.authority.key();
validate!(!user.is_bankrupt(), ErrorCode::UserBankrupt)?;
math::liquidation::validate_user_not_being_liquidated(
&mut user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
ctx.accounts.state.liquidation_margin_buffer_ratio,
)?;
let mut in_spot_market = spot_market_map.get_ref_mut(&in_market_index)?;
validate!(
in_spot_market.fills_enabled(),
ErrorCode::MarketFillOrderPaused,
"Swaps disabled for {}",
in_market_index
)?;
validate!(
in_spot_market.flash_loan_initial_token_amount == 0
&& in_spot_market.flash_loan_amount == 0,
ErrorCode::InvalidSwap,
"begin_swap ended in invalid state"
)?;
let in_oracle_data = oracle_map.get_price_data(&in_spot_market.oracle_id())?;
controller::spot_balance::update_spot_market_cumulative_interest(
&mut in_spot_market,
Some(in_oracle_data),
now,
)?;
let mut out_spot_market = spot_market_map.get_ref_mut(&out_market_index)?;
validate!(
out_spot_market.fills_enabled(),
ErrorCode::MarketFillOrderPaused,
"Swaps disabled for {}",
out_market_index
)?;
validate!(
out_spot_market.flash_loan_initial_token_amount == 0
&& out_spot_market.flash_loan_amount == 0,
ErrorCode::InvalidSwap,
"begin_swap ended in invalid state"
)?;
let out_oracle_data = oracle_map.get_price_data(&out_spot_market.oracle_id())?;
controller::spot_balance::update_spot_market_cumulative_interest(
&mut out_spot_market,
Some(out_oracle_data),
now,
)?;
validate!(
in_market_index != out_market_index,
ErrorCode::InvalidSwap,
"in and out market the same"
)?;
validate!(
amount_in != 0,
ErrorCode::InvalidSwap,
"amount_out cannot be zero"
)?;
let in_vault = &ctx.accounts.in_spot_market_vault;
let in_token_account = &ctx.accounts.in_token_account;
in_spot_market.flash_loan_amount = amount_in;
in_spot_market.flash_loan_initial_token_amount = in_token_account.amount;
let out_token_account = &ctx.accounts.out_token_account;
out_spot_market.flash_loan_initial_token_amount = out_token_account.amount;
controller::token::send_from_program_vault(
&ctx.accounts.token_program,
in_vault,
&ctx.accounts.in_token_account,
&ctx.accounts.drift_signer,
state.signer_nonce,
amount_in,
&mint,
)?;
let ixs = ctx.accounts.instructions.as_ref();
let current_index = instructions::load_current_index_checked(ixs)? as usize;
let current_ix = instructions::load_instruction_at_checked(current_index, ixs)?;
validate!(
current_ix.program_id == *ctx.program_id,
ErrorCode::InvalidSwap,
"SwapBegin must be a top-level instruction (cant be cpi)"
)?;
// The only other drift program allowed is SwapEnd
let mut index = current_index + 1;
let mut found_end = false;
loop {
let ix = match instructions::load_instruction_at_checked(index, ixs) {
Ok(ix) => ix,
Err(ProgramError::InvalidArgument) => break,
Err(e) => return Err(e.into()),
};
// Check that the drift program key is not used
if ix.program_id == crate::id() {
// must be the last ix -- this could possibly be relaxed
validate!(
!found_end,
ErrorCode::InvalidSwap,
"the transaction must not contain a Drift instruction after FlashLoanEnd"
)?;
found_end = true;
// must be the SwapEnd instruction
let discriminator = crate::instruction::EndSwap::discriminator();
validate!(
ix.data[0..8] == discriminator,
ErrorCode::InvalidSwap,
"last drift ix must be end of swap"
)?;
validate!(
ctx.accounts.user.key() == ix.accounts[1].pubkey,
ErrorCode::InvalidSwap,
"the user passed to SwapBegin and End must match"
)?;
validate!(
ctx.accounts.authority.key() == ix.accounts[3].pubkey,
ErrorCode::InvalidSwap,
"the authority passed to SwapBegin and End must match"
)?;
validate!(
ctx.accounts.out_spot_market_vault.key() == ix.accounts[4].pubkey,
ErrorCode::InvalidSwap,
"the out_spot_market_vault passed to SwapBegin and End must match"
)?;
validate!(
ctx.accounts.in_spot_market_vault.key() == ix.accounts[5].pubkey,
ErrorCode::InvalidSwap,
"the in_spot_market_vault passed to SwapBegin and End must match"
)?;
validate!(
ctx.accounts.out_token_account.key() == ix.accounts[6].pubkey,
ErrorCode::InvalidSwap,
"the out_token_account passed to SwapBegin and End must match"
)?;
validate!(
ctx.accounts.in_token_account.key() == ix.accounts[7].pubkey,
ErrorCode::InvalidSwap,
"the in_token_account passed to SwapBegin and End must match"
)?;
validate!(
ctx.remaining_accounts.len() == ix.accounts.len() - 11,
ErrorCode::InvalidSwap,
"begin and end ix must have the same number of accounts"
)?;
for i in 11..ix.accounts.len() {
validate!(
*ctx.remaining_accounts[i - 11].key == ix.accounts[i].pubkey,
ErrorCode::InvalidSwap,
"begin and end ix must have the same accounts. {}th account mismatch. begin: {}, end: {}",
i,
ctx.remaining_accounts[i - 11].key,
ix.accounts[i].pubkey
)?;
}
} else {
if found_end {
for meta in ix.accounts.iter() {
validate!(
meta.is_writable == false,
ErrorCode::InvalidSwap,
"instructions after swap end must not have writable accounts"
)?;
}
} else {
let mut whitelisted_programs = vec![
serum_program::id(),
AssociatedToken::id(),
jupiter_mainnet_3::ID,
jupiter_mainnet_4::ID,
jupiter_mainnet_6::ID,
];
if !delegate_is_signer {
whitelisted_programs.push(Token::id());
whitelisted_programs.push(Token2022::id());
whitelisted_programs.push(marinade_mainnet::ID);
}
validate!(
whitelisted_programs.contains(&ix.program_id),
ErrorCode::InvalidSwap,
"only allowed to pass in ixs to token, openbook, and Jupiter v3/v4/v6 programs"
)?;
for meta in ix.accounts.iter() {
validate!(
meta.pubkey != crate::id(),
ErrorCode::InvalidSwap,
"instructions between begin and end must not be drift instructions"
)?;
}
}
}
index += 1;
}
validate!(
found_end,
ErrorCode::InvalidSwap,
"found no SwapEnd instruction in transaction"
)?;
Ok(())
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq)]
pub enum SwapReduceOnly {
In,
Out,
}
#[access_control(
fill_not_paused(&ctx.accounts.state)
)]
pub fn handle_end_swap<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, Swap<'info>>,
in_market_index: u16,
out_market_index: u16,
limit_price: Option<u64>,
reduce_only: Option<SwapReduceOnly>,
) -> Result<()> {
let state = &ctx.accounts.state;
let clock = Clock::get()?;
let slot = clock.slot;
let now = clock.unix_timestamp;
let remaining_accounts = &mut ctx.remaining_accounts.iter().peekable();
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
remaining_accounts,
&MarketSet::new(),
&get_writable_spot_market_set_from_many(vec![in_market_index, out_market_index]),
clock.slot,
Some(state.oracle_guard_rails),
)?;
let out_token_program = get_token_interface(remaining_accounts)?;
let in_mint = get_token_mint(remaining_accounts)?;
let out_mint = get_token_mint(remaining_accounts)?;
let user_key = ctx.accounts.user.key();
let mut user = load_mut!(&ctx.accounts.user)?;
let mut user_stats = load_mut!(&ctx.accounts.user_stats)?;
let exchange_status = state.get_exchange_status()?;
validate!(
!exchange_status.contains(ExchangeStatus::DepositPaused | ExchangeStatus::WithdrawPaused),
ErrorCode::ExchangePaused
)?;
let mut in_spot_market = spot_market_map.get_ref_mut(&in_market_index)?;
validate!(
!in_spot_market.is_operation_paused(SpotOperation::Withdraw),
ErrorCode::MarketFillOrderPaused,
"withdraw from market {} paused",
in_market_index
)?;
validate!(
in_spot_market.flash_loan_amount != 0,
ErrorCode::InvalidSwap,
"the in_spot_market must have a flash loan amount set"
)?;
let in_oracle_data = oracle_map.get_price_data(&in_spot_market.oracle_id())?;
let in_oracle_price = in_oracle_data.price;
let mut out_spot_market = spot_market_map.get_ref_mut(&out_market_index)?;
validate!(
!out_spot_market.is_operation_paused(SpotOperation::Deposit),
ErrorCode::MarketFillOrderPaused,
"deposit to market {} paused",
out_market_index
)?;
let out_oracle_data = oracle_map.get_price_data(&out_spot_market.oracle_id())?;
let out_oracle_price = out_oracle_data.price;
let in_vault = &mut ctx.accounts.in_spot_market_vault;
let in_token_account = &mut ctx.accounts.in_token_account;
let mut amount_in = in_spot_market.flash_loan_amount;
if in_token_account.amount > in_spot_market.flash_loan_initial_token_amount {
let residual = in_token_account
.amount
.safe_sub(in_spot_market.flash_loan_initial_token_amount)?;
controller::token::receive(
&ctx.accounts.token_program,
in_token_account,
in_vault,
&ctx.accounts.authority,
residual,
&in_mint,
)?;
in_token_account.reload()?;
in_vault.reload()?;
amount_in = amount_in.safe_sub(residual)?;
}
let in_token_amount_before = user
.force_get_spot_position_mut(in_market_index)?
.get_signed_token_amount(&in_spot_market)?;
// checks deposit/borrow limits
update_spot_balances_and_cumulative_deposits_with_limits(
amount_in.cast()?,
&SpotBalanceType::Borrow,
&mut in_spot_market,
&mut user,
)?;
let in_token_amount_after = user
.force_get_spot_position_mut(in_market_index)?
.get_signed_token_amount(&in_spot_market)?;
let in_position_is_reduced =
in_token_amount_before > 0 && in_token_amount_before.unsigned_abs() >= amount_in.cast()?;
if !in_position_is_reduced {
validate!(
!in_spot_market.is_reduce_only(),
ErrorCode::SpotMarketReduceOnly,
"in spot market is reduce only but token amount before ({}) < amount in ({})",
in_token_amount_before,
amount_in
)?;
validate!(
reduce_only != Some(SwapReduceOnly::In),
ErrorCode::InvalidSwap,
"reduce only violated. In position before ({}) < amount in ({})",
in_token_amount_before,
amount_in
)?;
validate!(
user.is_margin_trading_enabled,
ErrorCode::MarginTradingDisabled,
"swap lead to increase in liability for in market {}",
in_market_index
)?;
validate!(
!user.is_reduce_only(),
ErrorCode::UserReduceOnly,
"swap lead to increase in liability for in market {}",
in_market_index
)?;
}
math::spot_withdraw::validate_spot_market_vault_amount(&in_spot_market, in_vault.amount)?;
in_spot_market.flash_loan_initial_token_amount = 0;
in_spot_market.flash_loan_amount = 0;
let out_vault = &mut ctx.accounts.out_spot_market_vault;
let out_token_account = &mut ctx.accounts.out_token_account;
let mut amount_out = 0_u64;
if out_token_account.amount > out_spot_market.flash_loan_initial_token_amount {
amount_out = out_token_account
.amount
.safe_sub(out_spot_market.flash_loan_initial_token_amount)?;
if let Some(token_interface) = out_token_program {
controller::token::receive(
&token_interface,
out_token_account,
out_vault,
&ctx.accounts.authority,
amount_out,
&out_mint,
)?;
} else {
controller::token::receive(
&ctx.accounts.token_program,
out_token_account,
out_vault,
&ctx.accounts.authority,
amount_out,
&out_mint,
)?;
}
out_vault.reload()?;
}
if let Some(limit_price) = limit_price {
let swap_price = calculate_swap_price(
amount_out.cast()?,
amount_in.cast()?,
out_spot_market.decimals,
in_spot_market.decimals,
)?;
validate!(
swap_price >= limit_price.cast()?,
ErrorCode::SwapLimitPriceBreached,
"swap_price ({}) < limit price ({})",
swap_price,
limit_price
)?;
}
let fee = 0_u64; // no fee
let amount_out_after_fee = amount_out.safe_sub(fee)?;
out_spot_market.total_swap_fee = out_spot_market.total_swap_fee.saturating_add(fee);
let fee_value = get_token_value(fee.cast()?, out_spot_market.decimals, out_oracle_price)?;
// update fees
user.update_cumulative_spot_fees(-fee_value.cast()?)?;
user_stats.increment_total_fees(fee_value.cast()?)?;
if fee != 0 {
// update taker volume
let amount_out_value = get_token_value(
amount_out.cast()?,
out_spot_market.decimals,
out_oracle_price,
)?;
user_stats.update_taker_volume_30d(
out_spot_market.fuel_boost_taker,
amount_out_value.cast()?,
now,
)?;
}
validate!(
amount_out != 0,
ErrorCode::InvalidSwap,
"amount_out must be greater than 0"
)?;
let out_token_amount_before = user
.force_get_spot_position_mut(out_market_index)?
.get_signed_token_amount(&out_spot_market)?;
update_spot_balances_and_cumulative_deposits(
amount_out_after_fee.cast()?,
&SpotBalanceType::Deposit,
&mut out_spot_market,
user.force_get_spot_position_mut(out_market_index)?,
false,
Some(amount_out.cast()?),
)?;
let out_token_amount_after = user
.force_get_spot_position_mut(out_market_index)?
.get_signed_token_amount(&out_spot_market)?;
// update fees
update_revenue_pool_balances(fee.cast()?, &SpotBalanceType::Deposit, &mut out_spot_market)?;
let out_position_is_reduced = out_token_amount_before < 0
&& out_token_amount_before.unsigned_abs() >= amount_out_after_fee.cast()?;
if !out_position_is_reduced {
validate!(
!out_spot_market.is_reduce_only(),
ErrorCode::SpotMarketReduceOnly,
"out spot market is reduce only but token amount before ({}) < amount out ({})",
out_token_amount_before,
amount_out
)?;
validate!(
reduce_only != Some(SwapReduceOnly::Out),
ErrorCode::InvalidSwap,
"reduce only violated. Out position before ({}) < amount out ({})",
out_token_amount_before,
amount_out
)?;
validate!(
!user.is_reduce_only(),
ErrorCode::UserReduceOnly,
"swap lead to increase in deposit for in market {}, can only pay off borrow",
out_market_index
)?;
}
math::spot_withdraw::validate_spot_market_vault_amount(&out_spot_market, out_vault.amount)?;
out_spot_market.flash_loan_initial_token_amount = 0;
out_spot_market.flash_loan_amount = 0;
out_spot_market.validate_max_token_deposits_and_borrows(false)?;
let in_strict_price = StrictOraclePrice::new(
in_oracle_price,
in_spot_market
.historical_oracle_data
.last_oracle_price_twap_5min,
true,
);
let out_strict_price = StrictOraclePrice::new(
out_oracle_price,
out_spot_market
.historical_oracle_data
.last_oracle_price_twap_5min,
true,
);
let margin_type = spot_swap::select_margin_type_for_swap(
&in_spot_market,
&out_spot_market,
&in_strict_price,
&out_strict_price,
in_token_amount_before,
out_token_amount_before,
in_token_amount_after,
out_token_amount_after,
MarginRequirementType::Initial,
)?;
drop(out_spot_market);
drop(in_spot_market);
meets_withdraw_margin_requirement(
&user,
&perp_market_map,
&spot_market_map,
&mut oracle_map,
margin_type,
)?;
user.update_last_active_slot(slot);
let swap_record = SwapRecord {
ts: now,
amount_in,
amount_out,
out_market_index,
in_market_index,
in_oracle_price,
out_oracle_price,
user: user_key,
fee,
};
emit!(swap_record);
let out_spot_market = spot_market_map.get_ref_mut(&out_market_index)?;
validate!(
out_spot_market.flash_loan_initial_token_amount == 0
&& out_spot_market.flash_loan_amount == 0,
ErrorCode::InvalidSwap,
"end_swap ended in invalid state"
)?;
let in_spot_market = spot_market_map.get_ref_mut(&in_market_index)?;
validate!(
in_spot_market.flash_loan_initial_token_amount == 0
&& in_spot_market.flash_loan_amount == 0,
ErrorCode::InvalidSwap,
"end_swap ended in invalid state"
)?;
validate_price_bands_for_swap(
&in_spot_market,
&out_spot_market,
amount_in,
amount_out,
in_oracle_price,
out_oracle_price,
state
.oracle_guard_rails
.max_oracle_twap_5min_percent_divergence(),
)?;
Ok(())
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/mod.rs
|
pub use admin::*;
pub use constraints::*;
pub use if_staker::*;
pub use keeper::*;
pub use pyth_lazer_oracle::*;
pub use pyth_pull_oracle::*;
pub use user::*;
mod admin;
mod constraints;
mod if_staker;
mod keeper;
pub mod optional_accounts;
mod pyth_lazer_oracle;
mod pyth_pull_oracle;
mod user;
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/constraints.rs
|
use anchor_lang::accounts::account::Account;
use anchor_lang::accounts::account_loader::AccountLoader;
use anchor_lang::accounts::signer::Signer;
use anchor_lang::prelude::{AccountInfo, Pubkey};
use crate::error::ErrorCode;
use crate::state::insurance_fund_stake::InsuranceFundStake;
use crate::state::perp_market::{MarketStatus, PerpMarket};
use crate::state::spot_market::SpotMarket;
use crate::state::state::{ExchangeStatus, State};
use crate::state::user::{User, UserStats};
use crate::validate;
use solana_program::msg;
pub fn can_sign_for_user(user: &AccountLoader<User>, signer: &Signer) -> anchor_lang::Result<bool> {
user.load().map(|user| {
user.authority.eq(signer.key)
|| (user.delegate.eq(signer.key) && !user.delegate.eq(&Pubkey::default()))
})
}
pub fn is_stats_for_user(
user: &AccountLoader<User>,
user_stats: &AccountLoader<UserStats>,
) -> anchor_lang::Result<bool> {
let user = user.load()?;
let user_stats = user_stats.load()?;
Ok(user_stats.authority.eq(&user.authority))
}
pub fn is_stats_for_if_stake(
if_stake: &AccountLoader<InsuranceFundStake>,
user_stats: &AccountLoader<UserStats>,
) -> anchor_lang::Result<bool> {
let if_stake = if_stake.load()?;
let user_stats = user_stats.load()?;
Ok(user_stats.authority.eq(&if_stake.authority))
}
pub fn perp_market_valid(market: &AccountLoader<PerpMarket>) -> anchor_lang::Result<()> {
if market.load()?.status == MarketStatus::Delisted {
return Err(ErrorCode::MarketDelisted.into());
}
Ok(())
}
pub fn spot_market_valid(market: &AccountLoader<SpotMarket>) -> anchor_lang::Result<()> {
if market.load()?.status == MarketStatus::Delisted {
return Err(ErrorCode::MarketDelisted.into());
}
Ok(())
}
pub fn valid_oracle_for_spot_market(
oracle: &AccountInfo,
market: &AccountLoader<SpotMarket>,
) -> anchor_lang::Result<()> {
validate!(
market.load()?.oracle.eq(oracle.key),
ErrorCode::InvalidOracle,
"not valid_oracle_for_spot_market"
)?;
Ok(())
}
pub fn valid_oracle_for_perp_market(
oracle: &AccountInfo,
market: &AccountLoader<PerpMarket>,
) -> anchor_lang::Result<()> {
validate!(
market.load()?.amm.oracle.eq(oracle.key),
ErrorCode::InvalidOracle,
"not valid_oracle_for_perp_market"
)?;
Ok(())
}
pub fn liq_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state
.get_exchange_status()?
.contains(ExchangeStatus::LiqPaused)
{
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
pub fn funding_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state.funding_paused()? {
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
pub fn amm_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state.amm_paused()? {
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
pub fn fill_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state
.get_exchange_status()?
.contains(ExchangeStatus::FillPaused)
{
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
pub fn deposit_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state
.get_exchange_status()?
.contains(ExchangeStatus::DepositPaused)
{
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
pub fn withdraw_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state
.get_exchange_status()?
.contains(ExchangeStatus::WithdrawPaused)
{
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
pub fn settle_pnl_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state
.get_exchange_status()?
.contains(ExchangeStatus::SettlePnlPaused)
{
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
pub fn exchange_not_paused(state: &Account<State>) -> anchor_lang::Result<()> {
if state.get_exchange_status()?.is_all() {
return Err(ErrorCode::ExchangePaused.into());
}
Ok(())
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/if_staker.rs
|
use anchor_lang::prelude::*;
use anchor_spl::token_interface::{TokenAccount, TokenInterface};
use crate::controller::insurance::transfer_protocol_insurance_fund_stake;
use crate::error::ErrorCode;
use crate::instructions::constraints::*;
use crate::optional_accounts::get_token_mint;
use crate::state::insurance_fund_stake::{InsuranceFundStake, ProtocolIfSharesTransferConfig};
use crate::state::paused_operations::InsuranceFundOperation;
use crate::state::perp_market::MarketStatus;
use crate::state::spot_market::SpotMarket;
use crate::state::state::State;
use crate::state::traits::Size;
use crate::state::user::UserStats;
use crate::validate;
use crate::{controller, math};
use crate::{load_mut, QUOTE_SPOT_MARKET_INDEX};
pub fn handle_initialize_insurance_fund_stake(
ctx: Context<InitializeInsuranceFundStake>,
market_index: u16,
) -> Result<()> {
let mut if_stake = ctx
.accounts
.insurance_fund_stake
.load_init()
.or(Err(ErrorCode::UnableToLoadAccountLoader))?;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
*if_stake = InsuranceFundStake::new(*ctx.accounts.authority.key, market_index, now);
let spot_market = ctx.accounts.spot_market.load()?;
validate!(
!spot_market.is_insurance_fund_operation_paused(InsuranceFundOperation::Init),
ErrorCode::InsuranceFundOperationPaused,
"if staking init disabled",
)?;
Ok(())
}
pub fn handle_add_insurance_fund_stake<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AddInsuranceFundStake<'info>>,
market_index: u16,
amount: u64,
) -> Result<()> {
if amount == 0 {
return Err(ErrorCode::InsufficientDeposit.into());
}
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let insurance_fund_stake = &mut load_mut!(ctx.accounts.insurance_fund_stake)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let mint = get_token_mint(remaining_accounts_iter)?;
validate!(
!spot_market.is_insurance_fund_operation_paused(InsuranceFundOperation::Add),
ErrorCode::InsuranceFundOperationPaused,
"if staking add disabled",
)?;
validate!(
insurance_fund_stake.market_index == market_index,
ErrorCode::IncorrectSpotMarketAccountPassed,
"insurance_fund_stake does not match market_index"
)?;
validate!(
spot_market.status != MarketStatus::Initialized,
ErrorCode::InvalidSpotMarketState,
"spot market = {} not active for insurance_fund_stake",
spot_market.market_index
)?;
validate!(
insurance_fund_stake.last_withdraw_request_shares == 0
&& insurance_fund_stake.last_withdraw_request_value == 0,
ErrorCode::IFWithdrawRequestInProgress,
"withdraw request in progress"
)?;
{
controller::insurance::attempt_settle_revenue_to_insurance_fund(
&ctx.accounts.spot_market_vault,
&ctx.accounts.insurance_fund_vault,
spot_market,
now,
&ctx.accounts.token_program,
&ctx.accounts.drift_signer,
state,
&mint,
)?;
// reload the vault balances so they're up-to-date
ctx.accounts.spot_market_vault.reload()?;
ctx.accounts.insurance_fund_vault.reload()?;
math::spot_withdraw::validate_spot_market_vault_amount(
spot_market,
ctx.accounts.spot_market_vault.amount,
)?;
}
controller::insurance::add_insurance_fund_stake(
amount,
ctx.accounts.insurance_fund_vault.amount,
insurance_fund_stake,
user_stats,
spot_market,
clock.unix_timestamp,
)?;
controller::token::receive(
&ctx.accounts.token_program,
&ctx.accounts.user_token_account,
&ctx.accounts.insurance_fund_vault,
&ctx.accounts.authority,
amount,
&mint,
)?;
Ok(())
}
pub fn handle_request_remove_insurance_fund_stake(
ctx: Context<RequestRemoveInsuranceFundStake>,
market_index: u16,
amount: u64,
) -> Result<()> {
let clock = Clock::get()?;
let insurance_fund_stake = &mut load_mut!(ctx.accounts.insurance_fund_stake)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
validate!(
!spot_market.is_insurance_fund_operation_paused(InsuranceFundOperation::RequestRemove),
ErrorCode::InsuranceFundOperationPaused,
"if staking request remove disabled",
)?;
validate!(
insurance_fund_stake.market_index == market_index,
ErrorCode::IncorrectSpotMarketAccountPassed,
"insurance_fund_stake does not match market_index"
)?;
validate!(
insurance_fund_stake.last_withdraw_request_shares == 0,
ErrorCode::IFWithdrawRequestInProgress,
"Withdraw request is already in progress"
)?;
let n_shares = math::insurance::vault_amount_to_if_shares(
amount,
spot_market.insurance_fund.total_shares,
ctx.accounts.insurance_fund_vault.amount,
)?;
validate!(
n_shares > 0,
ErrorCode::IFWithdrawRequestTooSmall,
"Requested lp_shares = 0"
)?;
let user_if_shares = insurance_fund_stake.checked_if_shares(spot_market)?;
validate!(user_if_shares >= n_shares, ErrorCode::InsufficientIFShares)?;
controller::insurance::request_remove_insurance_fund_stake(
n_shares,
ctx.accounts.insurance_fund_vault.amount,
insurance_fund_stake,
user_stats,
spot_market,
clock.unix_timestamp,
)?;
Ok(())
}
pub fn handle_cancel_request_remove_insurance_fund_stake(
ctx: Context<RequestRemoveInsuranceFundStake>,
market_index: u16,
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let insurance_fund_stake = &mut load_mut!(ctx.accounts.insurance_fund_stake)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
validate!(
insurance_fund_stake.market_index == market_index,
ErrorCode::IncorrectSpotMarketAccountPassed,
"insurance_fund_stake does not match market_index"
)?;
validate!(
insurance_fund_stake.last_withdraw_request_shares != 0,
ErrorCode::NoIFWithdrawRequestInProgress,
"No withdraw request in progress"
)?;
controller::insurance::cancel_request_remove_insurance_fund_stake(
ctx.accounts.insurance_fund_vault.amount,
insurance_fund_stake,
user_stats,
spot_market,
now,
)?;
Ok(())
}
#[access_control(
withdraw_not_paused(&ctx.accounts.state)
)]
pub fn handle_remove_insurance_fund_stake<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, RemoveInsuranceFundStake<'info>>,
market_index: u16,
) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let insurance_fund_stake = &mut load_mut!(ctx.accounts.insurance_fund_stake)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
let state = &ctx.accounts.state;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let mint = get_token_mint(remaining_accounts_iter)?;
validate!(
!spot_market.is_insurance_fund_operation_paused(InsuranceFundOperation::Remove),
ErrorCode::InsuranceFundOperationPaused,
"if staking remove disabled",
)?;
validate!(
insurance_fund_stake.market_index == market_index,
ErrorCode::IncorrectSpotMarketAccountPassed,
"insurance_fund_stake does not match market_index"
)?;
// check if spot market is healthy
validate!(
spot_market.is_healthy_utilization()?,
ErrorCode::SpotMarketInsufficientDeposits,
"spot market utilization above health threshold"
)?;
let amount = controller::insurance::remove_insurance_fund_stake(
ctx.accounts.insurance_fund_vault.amount,
insurance_fund_stake,
user_stats,
spot_market,
now,
)?;
controller::token::send_from_program_vault(
&ctx.accounts.token_program,
&ctx.accounts.insurance_fund_vault,
&ctx.accounts.user_token_account,
&ctx.accounts.drift_signer,
state.signer_nonce,
amount,
&mint,
)?;
ctx.accounts.insurance_fund_vault.reload()?;
validate!(
ctx.accounts.insurance_fund_vault.amount > 0,
ErrorCode::InvalidIFDetected,
"insurance_fund_vault.amount must remain > 0"
)?;
// validate relevant spot market balances before unstake
math::spot_withdraw::validate_spot_balances(spot_market)?;
Ok(())
}
pub fn handle_transfer_protocol_if_shares(
ctx: Context<TransferProtocolIfShares>,
market_index: u16,
shares: u128,
) -> Result<()> {
let now = Clock::get()?.unix_timestamp;
validate!(
market_index == QUOTE_SPOT_MARKET_INDEX,
ErrorCode::DefaultError,
"must be if for quote spot market"
)?;
let mut transfer_config = ctx.accounts.transfer_config.load_mut()?;
transfer_config.validate_signer(ctx.accounts.signer.key)?;
transfer_config.update_epoch(now)?;
transfer_config.validate_transfer(shares)?;
transfer_config.current_epoch_transfer += shares;
let mut if_stake = ctx.accounts.insurance_fund_stake.load_mut()?;
let mut user_stats = ctx.accounts.user_stats.load_mut()?;
let mut spot_market = ctx.accounts.spot_market.load_mut()?;
transfer_protocol_insurance_fund_stake(
ctx.accounts.insurance_fund_vault.amount,
shares,
&mut if_stake,
&mut user_stats,
&mut spot_market,
Clock::get()?.unix_timestamp,
ctx.accounts.state.signer,
)?;
Ok(())
}
#[derive(Accounts)]
#[instruction(
market_index: u16,
)]
pub struct InitializeInsuranceFundStake<'info> {
#[account(
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
init,
seeds = [b"insurance_fund_stake", authority.key.as_ref(), market_index.to_le_bytes().as_ref()],
space = InsuranceFundStake::SIZE,
bump,
payer = payer
)]
pub insurance_fund_stake: AccountLoader<'info, InsuranceFundStake>,
#[account(
mut,
has_one = authority
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub state: Box<Account<'info, State>>,
pub authority: Signer<'info>,
#[account(mut)]
pub payer: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(market_index: u16)]
pub struct AddInsuranceFundStake<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
has_one = authority,
)]
pub insurance_fund_stake: AccountLoader<'info, InsuranceFundStake>,
#[account(
mut,
has_one = authority,
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
#[account(
mut,
token::mint = insurance_fund_vault.mint,
token::authority = authority
)]
pub user_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(market_index: u16,)]
pub struct RequestRemoveInsuranceFundStake<'info> {
#[account(
mut,
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
has_one = authority,
)]
pub insurance_fund_stake: AccountLoader<'info, InsuranceFundStake>,
#[account(
mut,
has_one = authority,
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
#[derive(Accounts)]
#[instruction(market_index: u16,)]
pub struct RemoveInsuranceFundStake<'info> {
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
has_one = authority,
)]
pub insurance_fund_stake: AccountLoader<'info, InsuranceFundStake>,
#[account(
mut,
has_one = authority,
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: forced drift_signer
pub drift_signer: AccountInfo<'info>,
#[account(
mut,
token::mint = insurance_fund_vault.mint,
token::authority = authority
)]
pub user_token_account: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(market_index: u16,)]
pub struct TransferProtocolIfShares<'info> {
pub signer: Signer<'info>,
#[account(mut)]
pub transfer_config: AccountLoader<'info, ProtocolIfSharesTransferConfig>,
pub state: Box<Account<'info, State>>,
#[account(
mut,
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
seeds = [b"insurance_fund_stake", authority.key.as_ref(), market_index.to_le_bytes().as_ref()],
bump,
has_one = authority,
)]
pub insurance_fund_stake: AccountLoader<'info, InsuranceFundStake>,
#[account(
mut,
has_one = authority,
)]
pub user_stats: AccountLoader<'info, UserStats>,
pub authority: Signer<'info>,
#[account(
seeds = [b"insurance_fund_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/admin.rs
|
use std::convert::identity;
use std::mem::size_of;
use anchor_lang::prelude::*;
use anchor_spl::token::Token;
use anchor_spl::token_2022::Token2022;
use anchor_spl::token_interface::{Mint, TokenAccount, TokenInterface};
use phoenix::quantities::WrapperU64;
use pyth_solana_receiver_sdk::cpi::accounts::InitPriceUpdate;
use pyth_solana_receiver_sdk::program::PythSolanaReceiver;
use serum_dex::state::ToAlignedBytes;
use solana_program::msg;
use crate::controller::token::close_vault;
use crate::error::ErrorCode;
use crate::ids::admin_hot_wallet;
use crate::instructions::constraints::*;
use crate::instructions::optional_accounts::{load_maps, AccountMaps};
use crate::math::casting::Cast;
use crate::math::constants::{
DEFAULT_LIQUIDATION_MARGIN_BUFFER_RATIO, FEE_POOL_TO_REVENUE_POOL_THRESHOLD, FUEL_START_TS,
IF_FACTOR_PRECISION, INSURANCE_A_MAX, INSURANCE_B_MAX, INSURANCE_C_MAX,
INSURANCE_SPECULATIVE_MAX, LIQUIDATION_FEE_PRECISION, MAX_CONCENTRATION_COEFFICIENT,
MAX_SQRT_K, MAX_UPDATE_K_PRICE_CHANGE, PERCENTAGE_PRECISION, QUOTE_SPOT_MARKET_INDEX,
SPOT_CUMULATIVE_INTEREST_PRECISION, SPOT_IMF_PRECISION, SPOT_WEIGHT_PRECISION, THIRTEEN_DAY,
TWENTY_FOUR_HOUR,
};
use crate::math::cp_curve::get_update_k_result;
use crate::math::orders::is_multiple_of_step_size;
use crate::math::repeg::get_total_fee_lower_bound;
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::get_token_amount;
use crate::math::spot_withdraw::validate_spot_market_vault_amount;
use crate::math::{amm, bn};
use crate::optional_accounts::get_token_mint;
use crate::state::events::{CurveRecord, SpotMarketVaultDepositRecord};
use crate::state::fulfillment_params::openbook_v2::{
OpenbookV2Context, OpenbookV2FulfillmentConfig,
};
use crate::state::fulfillment_params::phoenix::PhoenixMarketContext;
use crate::state::fulfillment_params::phoenix::PhoenixV1FulfillmentConfig;
use crate::state::fulfillment_params::serum::SerumContext;
use crate::state::fulfillment_params::serum::SerumV3FulfillmentConfig;
use crate::state::high_leverage_mode_config::HighLeverageModeConfig;
use crate::state::insurance_fund_stake::ProtocolIfSharesTransferConfig;
use crate::state::oracle::get_sb_on_demand_price;
use crate::state::oracle::{
get_oracle_price, get_prelaunch_price, get_pyth_price, get_switchboard_price,
HistoricalIndexData, HistoricalOracleData, OraclePriceData, OracleSource, PrelaunchOracle,
PrelaunchOracleParams,
};
use crate::state::oracle_map::OracleMap;
use crate::state::paused_operations::{InsuranceFundOperation, PerpOperation, SpotOperation};
use crate::state::perp_market::{
ContractTier, ContractType, InsuranceClaim, MarketStatus, PerpMarket, PoolBalance, AMM,
};
use crate::state::perp_market_map::get_writable_perp_market_set;
use crate::state::protected_maker_mode_config::ProtectedMakerModeConfig;
use crate::state::pyth_lazer_oracle::{PythLazerOracle, PYTH_LAZER_ORACLE_SEED};
use crate::state::spot_market::{
AssetTier, InsuranceFund, SpotBalanceType, SpotFulfillmentConfigStatus, SpotMarket,
};
use crate::state::spot_market_map::get_writable_spot_market_set;
use crate::state::state::{ExchangeStatus, FeeStructure, OracleGuardRails, State};
use crate::state::traits::Size;
use crate::state::user::{User, UserStats};
use crate::validate;
use crate::validation::fee_structure::validate_fee_structure;
use crate::validation::margin::{validate_margin, validate_margin_weights};
use crate::validation::perp_market::validate_perp_market;
use crate::validation::spot_market::validate_borrow_rate;
use crate::{controller, QUOTE_PRECISION_I64};
use crate::{get_then_update_id, EPOCH_DURATION};
use crate::{load, FEE_ADJUSTMENT_MAX};
use crate::{load_mut, PTYH_PRICE_FEED_SEED_PREFIX};
use crate::{math, safe_decrement, safe_increment};
use crate::{math_error, SPOT_BALANCE_PRECISION};
pub fn handle_initialize(ctx: Context<Initialize>) -> Result<()> {
let (drift_signer, drift_signer_nonce) =
Pubkey::find_program_address(&[b"drift_signer".as_ref()], ctx.program_id);
**ctx.accounts.state = State {
admin: *ctx.accounts.admin.key,
exchange_status: ExchangeStatus::active(),
whitelist_mint: Pubkey::default(),
discount_mint: Pubkey::default(),
oracle_guard_rails: OracleGuardRails::default(),
number_of_authorities: 0,
number_of_sub_accounts: 0,
number_of_markets: 0,
number_of_spot_markets: 0,
min_perp_auction_duration: 10,
default_market_order_time_in_force: 60,
default_spot_auction_duration: 10,
liquidation_margin_buffer_ratio: DEFAULT_LIQUIDATION_MARGIN_BUFFER_RATIO,
settlement_duration: 0, // extra duration after market expiry to allow settlement
signer: drift_signer,
signer_nonce: drift_signer_nonce,
srm_vault: Pubkey::default(),
perp_fee_structure: FeeStructure::perps_default(),
spot_fee_structure: FeeStructure::spot_default(),
lp_cooldown_time: 0,
liquidation_duration: 0,
initial_pct_to_liquidate: 0,
max_number_of_sub_accounts: 0,
max_initialize_user_fee: 0,
padding: [0; 10],
};
Ok(())
}
pub fn handle_initialize_spot_market(
ctx: Context<InitializeSpotMarket>,
optimal_utilization: u32,
optimal_borrow_rate: u32,
max_borrow_rate: u32,
oracle_source: OracleSource,
initial_asset_weight: u32,
maintenance_asset_weight: u32,
initial_liability_weight: u32,
maintenance_liability_weight: u32,
imf_factor: u32,
liquidator_fee: u32,
if_liquidation_fee: u32,
active_status: bool,
asset_tier: AssetTier,
scale_initial_asset_weight_start: u64,
withdraw_guard_threshold: u64,
order_tick_size: u64,
order_step_size: u64,
if_total_factor: u32,
name: [u8; 32],
) -> Result<()> {
let state = &mut ctx.accounts.state;
let spot_market_pubkey = ctx.accounts.spot_market.key();
// protocol must be authority of collateral vault
if ctx.accounts.spot_market_vault.owner != state.signer {
return Err(ErrorCode::InvalidSpotMarketAuthority.into());
}
// protocol must be authority of collateral vault
if ctx.accounts.insurance_fund_vault.owner != state.signer {
return Err(ErrorCode::InvalidInsuranceFundAuthority.into());
}
validate_borrow_rate(optimal_utilization, optimal_borrow_rate, max_borrow_rate, 0)?;
let spot_market_index = get_then_update_id!(state, number_of_spot_markets);
msg!("initializing spot market {}", spot_market_index);
if oracle_source == OracleSource::QuoteAsset {
// catches inconsistent parameters
validate!(
ctx.accounts.oracle.key == &Pubkey::default(),
ErrorCode::InvalidSpotMarketInitialization,
"For OracleSource::QuoteAsset, oracle must be default public key"
)?;
} else {
OracleMap::validate_oracle_account_info(&ctx.accounts.oracle)?;
}
let oracle_price_data = get_oracle_price(
&oracle_source,
&ctx.accounts.oracle,
Clock::get()?.unix_timestamp.cast()?,
);
let (historical_oracle_data_default, historical_index_data_default) =
if spot_market_index == QUOTE_SPOT_MARKET_INDEX {
validate!(
ctx.accounts.oracle.key == &Pubkey::default(),
ErrorCode::InvalidSpotMarketInitialization,
"For quote asset spot market, oracle must be default public key"
)?;
validate!(
oracle_source == OracleSource::QuoteAsset,
ErrorCode::InvalidSpotMarketInitialization,
"For quote asset spot market, oracle source must be QuoteAsset"
)?;
validate!(
ctx.accounts.spot_market_mint.decimals == 6,
ErrorCode::InvalidSpotMarketInitialization,
"For quote asset spot market, mint decimals must be 6"
)?;
(
HistoricalOracleData::default_quote_oracle(),
HistoricalIndexData::default_quote_oracle(),
)
} else {
validate!(
ctx.accounts.spot_market_mint.decimals >= 5,
ErrorCode::InvalidSpotMarketInitialization,
"Mint decimals must be greater than or equal to 5"
)?;
validate!(
oracle_price_data.is_ok(),
ErrorCode::InvalidSpotMarketInitialization,
"Unable to read oracle price for {}",
ctx.accounts.oracle.key,
)?;
(
HistoricalOracleData::default_with_current_oracle(oracle_price_data?),
HistoricalIndexData::default_with_current_oracle(oracle_price_data?)?,
)
};
validate_margin_weights(
spot_market_index,
initial_asset_weight,
maintenance_asset_weight,
initial_liability_weight,
maintenance_liability_weight,
imf_factor,
)?;
let spot_market = &mut ctx.accounts.spot_market.load_init()?;
let clock = Clock::get()?;
let now = clock
.unix_timestamp
.cast()
.or(Err(ErrorCode::UnableToCastUnixTime))?;
let decimals = ctx.accounts.spot_market_mint.decimals.cast::<u32>()?;
let token_program = if ctx.accounts.token_program.key() == Token2022::id() {
1_u8
} else if ctx.accounts.token_program.key() == Token::id() {
0_u8
} else {
msg!("unexpected program {:?}", ctx.accounts.token_program.key());
return Err(ErrorCode::DefaultError.into());
};
**spot_market = SpotMarket {
market_index: spot_market_index,
pubkey: spot_market_pubkey,
status: if active_status {
MarketStatus::Active
} else {
MarketStatus::Initialized
},
name,
asset_tier,
expiry_ts: 0,
oracle: ctx.accounts.oracle.key(),
oracle_source,
historical_oracle_data: historical_oracle_data_default,
historical_index_data: historical_index_data_default,
mint: ctx.accounts.spot_market_mint.key(),
vault: *ctx.accounts.spot_market_vault.to_account_info().key,
revenue_pool: PoolBalance {
scaled_balance: 0,
market_index: spot_market_index,
..PoolBalance::default()
}, // in base asset
decimals,
optimal_utilization,
optimal_borrow_rate,
max_borrow_rate,
deposit_balance: 0,
borrow_balance: 0,
max_token_deposits: 0,
deposit_token_twap: 0,
borrow_token_twap: 0,
utilization_twap: 0,
cumulative_deposit_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
cumulative_borrow_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
total_social_loss: 0,
total_quote_social_loss: 0,
last_interest_ts: now,
last_twap_ts: now,
initial_asset_weight,
maintenance_asset_weight,
initial_liability_weight,
maintenance_liability_weight,
imf_factor,
liquidator_fee,
if_liquidation_fee, // 1%
withdraw_guard_threshold,
order_step_size,
order_tick_size,
min_order_size: order_step_size,
max_position_size: 0,
next_fill_record_id: 1,
next_deposit_record_id: 1,
spot_fee_pool: PoolBalance::default(), // in quote asset
total_spot_fee: 0,
orders_enabled: spot_market_index != 0,
paused_operations: 0,
if_paused_operations: 0,
fee_adjustment: 0,
max_token_borrows_fraction: 0,
flash_loan_amount: 0,
flash_loan_initial_token_amount: 0,
total_swap_fee: 0,
scale_initial_asset_weight_start,
min_borrow_rate: 0,
fuel_boost_deposits: 0,
fuel_boost_borrows: 0,
fuel_boost_taker: 0,
fuel_boost_maker: 0,
fuel_boost_insurance: 0,
token_program,
pool_id: 0,
padding: [0; 40],
insurance_fund: InsuranceFund {
vault: *ctx.accounts.insurance_fund_vault.to_account_info().key,
unstaking_period: THIRTEEN_DAY,
total_factor: if_total_factor,
user_factor: if_total_factor / 2,
..InsuranceFund::default()
},
};
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_pool_id(
ctx: Context<AdminUpdateSpotMarket>,
pool_id: u8,
) -> Result<()> {
#[cfg(all(feature = "mainnet-beta", not(feature = "anchor-test")))]
{
panic!("pools disabled on mainnet-beta");
}
let mut spot_market = load_mut!(ctx.accounts.spot_market)?;
msg!(
"updating spot market {} pool id to {}",
spot_market.market_index,
pool_id
);
validate!(
spot_market.status == MarketStatus::Initialized,
ErrorCode::DefaultError,
"Market must be just initialized to update pool"
)?;
spot_market.pool_id = pool_id;
Ok(())
}
pub fn handle_initialize_serum_fulfillment_config(
ctx: Context<InitializeSerumFulfillmentConfig>,
market_index: u16,
) -> Result<()> {
validate!(
market_index != QUOTE_SPOT_MARKET_INDEX,
ErrorCode::InvalidSpotMarketAccount,
"Cant add serum market to quote asset"
)?;
let base_spot_market = load!(&ctx.accounts.base_spot_market)?;
let quote_spot_market = load!(&ctx.accounts.quote_spot_market)?;
let serum_program_id = crate::ids::serum_program::id();
validate!(
ctx.accounts.serum_program.key() == serum_program_id,
ErrorCode::InvalidSerumProgram
)?;
let serum_market_key = ctx.accounts.serum_market.key();
let serum_context = SerumContext {
serum_program: &ctx.accounts.serum_program,
serum_market: &ctx.accounts.serum_market,
serum_open_orders: &ctx.accounts.serum_open_orders,
};
let market_state = serum_context.load_serum_market()?;
validate!(
identity(market_state.coin_mint) == base_spot_market.mint.to_aligned_bytes(),
ErrorCode::InvalidSerumMarket,
"Invalid base mint"
)?;
validate!(
identity(market_state.pc_mint) == quote_spot_market.mint.to_aligned_bytes(),
ErrorCode::InvalidSerumMarket,
"Invalid quote mint"
)?;
let market_step_size = market_state.coin_lot_size;
let valid_step_size = base_spot_market.order_step_size >= market_step_size
&& base_spot_market
.order_step_size
.rem_euclid(market_step_size)
== 0;
validate!(
valid_step_size,
ErrorCode::InvalidSerumMarket,
"base market step size ({}) not a multiple of serum step size ({})",
base_spot_market.order_step_size,
market_step_size
)?;
let market_tick_size = market_state.pc_lot_size;
let valid_tick_size = base_spot_market.order_tick_size >= market_tick_size
&& base_spot_market
.order_tick_size
.rem_euclid(market_tick_size)
== 0;
validate!(
valid_tick_size,
ErrorCode::InvalidSerumMarket,
"base market tick size ({}) not a multiple of serum tick size ({})",
base_spot_market.order_tick_size,
market_tick_size
)?;
drop(market_state);
let open_orders_seeds: &[&[u8]] = &[b"serum_open_orders", serum_market_key.as_ref()];
controller::pda::seed_and_create_pda(
ctx.program_id,
&ctx.accounts.admin.to_account_info(),
&Rent::get()?,
size_of::<serum_dex::state::OpenOrders>() + 12,
&serum_program_id,
&ctx.accounts.system_program.to_account_info(),
&ctx.accounts.serum_open_orders,
open_orders_seeds,
)?;
let open_orders = serum_context.load_open_orders()?;
validate!(
open_orders.account_flags == 0,
ErrorCode::InvalidSerumOpenOrders,
"Serum open orders already initialized"
)?;
drop(open_orders);
serum_context.invoke_init_open_orders(
&ctx.accounts.drift_signer,
&ctx.accounts.rent,
ctx.accounts.state.signer_nonce,
)?;
let serum_fulfillment_config_key = ctx.accounts.serum_fulfillment_config.key();
let mut serum_fulfillment_config = ctx.accounts.serum_fulfillment_config.load_init()?;
*serum_fulfillment_config = serum_context
.to_serum_v3_fulfillment_config(&serum_fulfillment_config_key, market_index)?;
Ok(())
}
pub fn handle_update_serum_fulfillment_config_status(
ctx: Context<UpdateSerumFulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
let mut config = load_mut!(ctx.accounts.serum_fulfillment_config)?;
msg!("config.status {:?} -> {:?}", config.status, status);
config.status = status;
Ok(())
}
pub fn handle_update_serum_vault(ctx: Context<UpdateSerumVault>) -> Result<()> {
let vault = &ctx.accounts.srm_vault;
validate!(
vault.mint == crate::ids::srm_mint::id() || vault.mint == crate::ids::msrm_mint::id(),
ErrorCode::InvalidSrmVault,
"vault did not hav srm or msrm mint"
)?;
validate!(
vault.owner == ctx.accounts.state.signer,
ErrorCode::InvalidVaultOwner,
"vault owner was not program signer"
)?;
let state = &mut ctx.accounts.state;
msg!("state.srm_vault {:?} -> {:?}", state.srm_vault, vault.key());
state.srm_vault = vault.key();
Ok(())
}
pub fn handle_initialize_openbook_v2_fulfillment_config(
ctx: Context<InitializeOpenbookV2FulfillmentConfig>,
market_index: u16,
) -> Result<()> {
validate!(
market_index != QUOTE_SPOT_MARKET_INDEX,
ErrorCode::InvalidSpotMarketAccount,
"Cannot add openbook v2 market to quote asset"
)?;
let base_spot_market = load!(&ctx.accounts.base_spot_market)?;
let quote_spot_market = load!(&ctx.accounts.quote_spot_market)?;
let openbook_v2_program_id = openbook_v2_light::id();
validate!(
ctx.accounts.openbook_v2_program.key() == openbook_v2_program_id,
ErrorCode::InvalidOpenbookV2Program
)?;
let openbook_v2_market_context = OpenbookV2Context {
openbook_v2_program: &ctx.accounts.openbook_v2_program,
openbook_v2_market: &ctx.accounts.openbook_v2_market,
};
let market = openbook_v2_market_context.load_openbook_v2_market()?;
validate!(
market.base_mint == base_spot_market.mint,
ErrorCode::InvalidOpenbookV2Market,
"Invalid base mint"
)?;
validate!(
market.quote_mint == quote_spot_market.mint,
ErrorCode::InvalidOpenbookV2Market,
"Invalid quote mint"
)?;
validate!(
market.taker_fee == 0,
ErrorCode::InvalidOpenbookV2Market,
"Fee must be 0"
)?;
let market_step_size = market.base_lot_size as u64;
let valid_step_size = base_spot_market.order_step_size >= market_step_size
&& base_spot_market
.order_step_size
.rem_euclid(market_step_size)
== 0;
validate!(
valid_step_size,
ErrorCode::InvalidOpenbookV2Market,
"base market step size ({}) not a multiple of Openbook V2 base lot size ({})",
base_spot_market.order_step_size,
market_step_size
)?;
let openbook_v2_fulfillment_config_key = ctx.accounts.openbook_v2_fulfillment_config.key();
let mut openbook_v2_fulfillment_config =
ctx.accounts.openbook_v2_fulfillment_config.load_init()?;
*openbook_v2_fulfillment_config = openbook_v2_market_context
.to_openbook_v2_fulfillment_config(&openbook_v2_fulfillment_config_key, market_index)?;
Ok(())
}
pub fn handle_update_openbook_v2_fulfillment_config_status(
ctx: Context<UpdateOpenbookV2FulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
let mut config = load_mut!(ctx.accounts.openbook_v2_fulfillment_config)?;
msg!("config.status {:?} -> {:?}", config.status, status);
config.status = status;
Ok(())
}
pub fn handle_initialize_phoenix_fulfillment_config(
ctx: Context<InitializePhoenixFulfillmentConfig>,
market_index: u16,
) -> Result<()> {
validate!(
market_index != QUOTE_SPOT_MARKET_INDEX,
ErrorCode::InvalidSpotMarketAccount,
"Cannot add phoenix market to quote asset"
)?;
let base_spot_market = load!(&ctx.accounts.base_spot_market)?;
let quote_spot_market = load!(&ctx.accounts.quote_spot_market)?;
let phoenix_program_id = phoenix::id();
validate!(
ctx.accounts.phoenix_program.key() == phoenix_program_id,
ErrorCode::InvalidPhoenixProgram
)?;
let phoenix_market_context = PhoenixMarketContext::new(&ctx.accounts.phoenix_market)?;
validate!(
phoenix_market_context.header.base_params.mint_key == base_spot_market.mint,
ErrorCode::InvalidPhoenixMarket,
"Invalid base mint"
)?;
validate!(
phoenix_market_context.header.quote_params.mint_key == quote_spot_market.mint,
ErrorCode::InvalidPhoenixMarket,
"Invalid quote mint"
)?;
let market_step_size = phoenix_market_context.header.get_base_lot_size().as_u64();
let valid_step_size = base_spot_market.order_step_size >= market_step_size
&& base_spot_market
.order_step_size
.rem_euclid(market_step_size)
== 0;
validate!(
valid_step_size,
ErrorCode::InvalidPhoenixMarket,
"base market step size ({}) not a multiple of Phoenix base lot size ({})",
base_spot_market.order_step_size,
market_step_size
)?;
let phoenix_fulfillment_config_key = ctx.accounts.phoenix_fulfillment_config.key();
let mut phoenix_fulfillment_config = ctx.accounts.phoenix_fulfillment_config.load_init()?;
*phoenix_fulfillment_config = phoenix_market_context
.to_phoenix_v1_fulfillment_config(&phoenix_fulfillment_config_key, market_index);
Ok(())
}
pub fn handle_update_phoenix_fulfillment_config_status(
ctx: Context<UpdatePhoenixFulfillmentConfig>,
status: SpotFulfillmentConfigStatus,
) -> Result<()> {
let mut config = load_mut!(ctx.accounts.phoenix_fulfillment_config)?;
msg!("config.status {:?} -> {:?}", config.status, status);
config.status = status;
Ok(())
}
pub fn handle_initialize_perp_market(
ctx: Context<InitializePerpMarket>,
market_index: u16,
amm_base_asset_reserve: u128,
amm_quote_asset_reserve: u128,
amm_periodicity: i64,
amm_peg_multiplier: u128,
oracle_source: OracleSource,
contract_tier: ContractTier,
margin_ratio_initial: u32,
margin_ratio_maintenance: u32,
liquidator_fee: u32,
if_liquidation_fee: u32,
imf_factor: u32,
active_status: bool,
base_spread: u32,
max_spread: u32,
max_open_interest: u128,
max_revenue_withdraw_per_period: u64,
quote_max_insurance: u64,
order_step_size: u64,
order_tick_size: u64,
min_order_size: u64,
concentration_coef_scale: u128,
curve_update_intensity: u8,
amm_jit_intensity: u8,
name: [u8; 32],
) -> Result<()> {
msg!("perp market {}", market_index);
let perp_market_pubkey = ctx.accounts.perp_market.to_account_info().key;
let perp_market = &mut ctx.accounts.perp_market.load_init()?;
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let clock_slot = clock.slot;
if amm_base_asset_reserve != amm_quote_asset_reserve {
return Err(ErrorCode::InvalidInitialPeg.into());
}
validate!(
(0..=200).contains(&curve_update_intensity),
ErrorCode::DefaultError,
"invalid curve_update_intensity",
)?;
validate!(
(0..=200).contains(&amm_jit_intensity),
ErrorCode::DefaultError,
"invalid amm_jit_intensity",
)?;
let init_reserve_price = amm::calculate_price(
amm_quote_asset_reserve,
amm_base_asset_reserve,
amm_peg_multiplier,
)?;
assert_eq!(amm_peg_multiplier, init_reserve_price.cast::<u128>()?);
let concentration_coef = MAX_CONCENTRATION_COEFFICIENT;
// Verify there's no overflow
let _k =
bn::U192::from(amm_base_asset_reserve).safe_mul(bn::U192::from(amm_quote_asset_reserve))?;
let (min_base_asset_reserve, max_base_asset_reserve) =
amm::calculate_bid_ask_bounds(concentration_coef, amm_base_asset_reserve)?;
OracleMap::validate_oracle_account_info(&ctx.accounts.oracle)?;
// Verify oracle is readable
let (oracle_price, oracle_delay, last_oracle_price_twap) = match oracle_source {
OracleSource::Pyth => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(&ctx.accounts.oracle, clock_slot, &OracleSource::Pyth)?;
let last_oracle_price_twap = perp_market
.amm
.get_pyth_twap(&ctx.accounts.oracle, &OracleSource::Pyth)?;
(oracle_price, oracle_delay, last_oracle_price_twap)
}
OracleSource::Pyth1K => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(&ctx.accounts.oracle, clock_slot, &OracleSource::Pyth1K)?;
let last_oracle_price_twap = perp_market
.amm
.get_pyth_twap(&ctx.accounts.oracle, &OracleSource::Pyth1K)?;
(oracle_price, oracle_delay, last_oracle_price_twap)
}
OracleSource::Pyth1M => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(&ctx.accounts.oracle, clock_slot, &OracleSource::Pyth1M)?;
let last_oracle_price_twap = perp_market
.amm
.get_pyth_twap(&ctx.accounts.oracle, &OracleSource::Pyth1M)?;
(oracle_price, oracle_delay, last_oracle_price_twap)
}
OracleSource::PythStableCoin => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(
&ctx.accounts.oracle,
clock_slot,
&OracleSource::PythStableCoin,
)?;
(oracle_price, oracle_delay, QUOTE_PRECISION_I64)
}
OracleSource::Switchboard => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_switchboard_price(&ctx.accounts.oracle, clock_slot)?;
(oracle_price, oracle_delay, oracle_price)
}
OracleSource::QuoteAsset => {
msg!("Quote asset oracle cant be used for perp market");
return Err(ErrorCode::InvalidOracle.into());
}
OracleSource::Prelaunch => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_prelaunch_price(&ctx.accounts.oracle, clock_slot)?;
(oracle_price, oracle_delay, oracle_price)
}
OracleSource::PythPull => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(&ctx.accounts.oracle, clock_slot, &OracleSource::PythPull)?;
let last_oracle_price_twap = perp_market
.amm
.get_pyth_twap(&ctx.accounts.oracle, &OracleSource::PythPull)?;
(oracle_price, oracle_delay, last_oracle_price_twap)
}
OracleSource::Pyth1KPull => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(&ctx.accounts.oracle, clock_slot, &OracleSource::Pyth1KPull)?;
let last_oracle_price_twap = perp_market
.amm
.get_pyth_twap(&ctx.accounts.oracle, &OracleSource::Pyth1KPull)?;
(oracle_price, oracle_delay, last_oracle_price_twap)
}
OracleSource::Pyth1MPull => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(&ctx.accounts.oracle, clock_slot, &OracleSource::Pyth1MPull)?;
let last_oracle_price_twap = perp_market
.amm
.get_pyth_twap(&ctx.accounts.oracle, &OracleSource::Pyth1MPull)?;
(oracle_price, oracle_delay, last_oracle_price_twap)
}
OracleSource::PythStableCoinPull => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(
&ctx.accounts.oracle,
clock_slot,
&OracleSource::PythStableCoinPull,
)?;
(oracle_price, oracle_delay, QUOTE_PRECISION_I64)
}
OracleSource::SwitchboardOnDemand => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_sb_on_demand_price(&ctx.accounts.oracle, clock_slot)?;
(oracle_price, oracle_delay, oracle_price)
}
OracleSource::PythLazer => {
let OraclePriceData {
price: oracle_price,
delay: oracle_delay,
..
} = get_pyth_price(&ctx.accounts.oracle, clock_slot, &OracleSource::PythLazer)?;
let last_oracle_price_twap = perp_market
.amm
.get_pyth_twap(&ctx.accounts.oracle, &OracleSource::PythLazer)?;
(oracle_price, oracle_delay, last_oracle_price_twap)
}
};
validate_margin(
margin_ratio_initial,
margin_ratio_maintenance,
0,
0,
liquidator_fee,
max_spread,
)?;
let state = &mut ctx.accounts.state;
validate!(
market_index == state.number_of_markets,
ErrorCode::MarketIndexAlreadyInitialized,
"market_index={} != state.number_of_markets={}",
market_index,
state.number_of_markets
)?;
**perp_market = PerpMarket {
contract_type: ContractType::Perpetual,
contract_tier,
status: if active_status {
MarketStatus::Active
} else {
MarketStatus::Initialized
},
name,
expiry_price: 0,
expiry_ts: 0,
pubkey: *perp_market_pubkey,
market_index,
number_of_users_with_base: 0,
number_of_users: 0,
margin_ratio_initial, // unit is 20% (+2 decimal places)
margin_ratio_maintenance,
imf_factor,
next_fill_record_id: 1,
next_funding_rate_record_id: 1,
next_curve_record_id: 1,
pnl_pool: PoolBalance::default(),
insurance_claim: InsuranceClaim {
max_revenue_withdraw_per_period,
quote_max_insurance,
..InsuranceClaim::default()
},
unrealized_pnl_initial_asset_weight: 0, // 100%
unrealized_pnl_maintenance_asset_weight: SPOT_WEIGHT_PRECISION.cast()?, // 100%
unrealized_pnl_imf_factor: 0,
unrealized_pnl_max_imbalance: 0,
liquidator_fee,
if_liquidation_fee,
paused_operations: 0,
quote_spot_market_index: QUOTE_SPOT_MARKET_INDEX,
fee_adjustment: 0,
fuel_boost_position: 0,
fuel_boost_taker: 0,
fuel_boost_maker: 0,
pool_id: 0,
high_leverage_margin_ratio_initial: 0,
high_leverage_margin_ratio_maintenance: 0,
padding: [0; 38],
amm: AMM {
oracle: *ctx.accounts.oracle.key,
oracle_source,
base_asset_reserve: amm_base_asset_reserve,
quote_asset_reserve: amm_quote_asset_reserve,
terminal_quote_asset_reserve: amm_quote_asset_reserve,
ask_base_asset_reserve: amm_base_asset_reserve,
ask_quote_asset_reserve: amm_quote_asset_reserve,
bid_base_asset_reserve: amm_base_asset_reserve,
bid_quote_asset_reserve: amm_quote_asset_reserve,
cumulative_funding_rate_long: 0,
cumulative_funding_rate_short: 0,
total_social_loss: 0,
last_funding_rate: 0,
last_funding_rate_long: 0,
last_funding_rate_short: 0,
last_24h_avg_funding_rate: 0,
last_funding_rate_ts: now,
funding_period: amm_periodicity,
last_mark_price_twap: init_reserve_price,
last_mark_price_twap_5min: init_reserve_price,
last_mark_price_twap_ts: now,
sqrt_k: amm_base_asset_reserve,
concentration_coef,
min_base_asset_reserve,
max_base_asset_reserve,
peg_multiplier: amm_peg_multiplier,
total_fee: 0,
total_fee_withdrawn: 0,
total_fee_minus_distributions: 0,
total_mm_fee: 0,
total_exchange_fee: 0,
total_liquidation_fee: 0,
net_revenue_since_last_funding: 0,
historical_oracle_data: HistoricalOracleData {
last_oracle_price: oracle_price,
last_oracle_delay: oracle_delay,
last_oracle_price_twap,
last_oracle_price_twap_5min: oracle_price,
last_oracle_price_twap_ts: now,
..HistoricalOracleData::default()
},
last_oracle_normalised_price: oracle_price,
last_oracle_conf_pct: 0,
last_oracle_reserve_price_spread_pct: 0, // todo
order_step_size,
order_tick_size,
min_order_size,
max_position_size: 0,
max_slippage_ratio: 50, // ~2%
max_fill_reserve_fraction: 100, // moves price ~2%
base_spread,
long_spread: 0,
short_spread: 0,
max_spread,
last_bid_price_twap: init_reserve_price,
last_ask_price_twap: init_reserve_price,
base_asset_amount_with_amm: 0,
base_asset_amount_long: 0,
base_asset_amount_short: 0,
quote_asset_amount: 0,
quote_entry_amount_long: 0,
quote_entry_amount_short: 0,
quote_break_even_amount_long: 0,
quote_break_even_amount_short: 0,
max_open_interest,
mark_std: 0,
oracle_std: 0,
volume_24h: 0,
long_intensity_count: 0,
long_intensity_volume: 0,
short_intensity_count: 0,
short_intensity_volume: 0,
last_trade_ts: now,
curve_update_intensity,
fee_pool: PoolBalance::default(),
base_asset_amount_per_lp: 0,
quote_asset_amount_per_lp: 0,
last_update_slot: clock_slot,
// lp stuff
base_asset_amount_with_unsettled_lp: 0,
user_lp_shares: 0,
amm_jit_intensity,
last_oracle_valid: false,
target_base_asset_amount_per_lp: 0,
per_lp_base: 0,
padding1: 0,
padding2: 0,
total_fee_earned_per_lp: 0,
net_unsettled_funding_pnl: 0,
quote_asset_amount_with_unsettled_lp: 0,
reference_price_offset: 0,
padding: [0; 12],
},
};
safe_increment!(state.number_of_markets, 1);
controller::amm::update_concentration_coef(perp_market, concentration_coef_scale)?;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_initialize_prediction_market(ctx: Context<AdminUpdatePerpMarket>) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("updating perp market {} expiry", perp_market.market_index);
validate!(
perp_market.status == MarketStatus::Initialized,
ErrorCode::DefaultError,
"Market must be just initialized to make prediction market"
)?;
perp_market.contract_type = ContractType::Prediction;
let paused_operations = perp_market.paused_operations | PerpOperation::UpdateFunding as u8;
perp_market.paused_operations = paused_operations;
Ok(())
}
pub fn handle_delete_initialized_perp_market(
ctx: Context<DeleteInitializedPerpMarket>,
market_index: u16,
) -> Result<()> {
let perp_market = &mut ctx.accounts.perp_market.load()?;
msg!("perp market {}", perp_market.market_index);
let state = &mut ctx.accounts.state;
// to preserve all protocol invariants, can only remove the last market if it hasn't been "activated"
validate!(
state.number_of_markets - 1 == market_index,
ErrorCode::InvalidMarketAccountforDeletion,
"state.number_of_markets={} != market_index={}",
state.number_of_markets,
market_index
)?;
validate!(
perp_market.status == MarketStatus::Initialized,
ErrorCode::InvalidMarketAccountforDeletion,
"perp_market.status != Initialized",
)?;
validate!(
perp_market.number_of_users == 0,
ErrorCode::InvalidMarketAccountforDeletion,
"perp_market.number_of_users={} != 0",
perp_market.number_of_users,
)?;
validate!(
perp_market.market_index == market_index,
ErrorCode::InvalidMarketAccountforDeletion,
"market_index={} != perp_market.market_index={}",
market_index,
perp_market.market_index
)?;
safe_decrement!(state.number_of_markets, 1);
Ok(())
}
pub fn handle_delete_initialized_spot_market(
ctx: Context<DeleteInitializedSpotMarket>,
market_index: u16,
) -> Result<()> {
let spot_market = ctx.accounts.spot_market.load()?;
msg!("spot market {}", spot_market.market_index);
let state = &mut ctx.accounts.state;
// to preserve all protocol invariants, can only remove the last market if it hasn't been "activated"
validate!(
state.number_of_spot_markets - 1 == market_index,
ErrorCode::InvalidMarketAccountforDeletion,
"state.number_of_spot_markets={} != market_index={}",
state.number_of_markets,
market_index
)?;
validate!(
spot_market.status == MarketStatus::Initialized,
ErrorCode::InvalidMarketAccountforDeletion,
"spot_market.status != Initialized",
)?;
validate!(
spot_market.deposit_balance == 0,
ErrorCode::InvalidMarketAccountforDeletion,
"spot_market.number_of_users={} != 0",
spot_market.deposit_balance,
)?;
validate!(
spot_market.borrow_balance == 0,
ErrorCode::InvalidMarketAccountforDeletion,
"spot_market.borrow_balance={} != 0",
spot_market.borrow_balance,
)?;
validate!(
spot_market.market_index == market_index,
ErrorCode::InvalidMarketAccountforDeletion,
"market_index={} != spot_market.market_index={}",
market_index,
spot_market.market_index
)?;
safe_decrement!(state.number_of_spot_markets, 1);
drop(spot_market);
validate!(
ctx.accounts.spot_market_vault.amount == 0,
ErrorCode::InvalidMarketAccountforDeletion,
"ctx.accounts.spot_market_vault.amount={}",
ctx.accounts.spot_market_vault.amount
)?;
close_vault(
&ctx.accounts.token_program,
&ctx.accounts.spot_market_vault,
&ctx.accounts.admin.to_account_info(),
&ctx.accounts.drift_signer,
state.signer_nonce,
)?;
validate!(
ctx.accounts.insurance_fund_vault.amount == 0,
ErrorCode::InvalidMarketAccountforDeletion,
"ctx.accounts.insurance_fund_vault.amount={}",
ctx.accounts.insurance_fund_vault.amount
)?;
close_vault(
&ctx.accounts.token_program,
&ctx.accounts.insurance_fund_vault,
&ctx.accounts.admin.to_account_info(),
&ctx.accounts.drift_signer,
state.signer_nonce,
)?;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_oracle(
ctx: Context<AdminUpdateSpotMarketOracle>,
oracle: Pubkey,
oracle_source: OracleSource,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("updating spot market {} oracle", spot_market.market_index);
let clock = Clock::get()?;
OracleMap::validate_oracle_account_info(&ctx.accounts.oracle)?;
validate!(
ctx.accounts.oracle.key == &oracle,
ErrorCode::DefaultError,
"oracle account info ({:?}) and ix data ({:?}) must match",
ctx.accounts.oracle.key,
oracle
)?;
// Verify oracle is readable
let OraclePriceData {
price: _oracle_price,
delay: _oracle_delay,
..
} = get_oracle_price(&oracle_source, &ctx.accounts.oracle, clock.slot)?;
msg!(
"spot_market.oracle {:?} -> {:?}",
spot_market.oracle,
oracle
);
msg!(
"spot_market.oracle_source {:?} -> {:?}",
spot_market.oracle_source,
oracle_source
);
spot_market.oracle = oracle;
spot_market.oracle_source = oracle_source;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_expiry(
ctx: Context<AdminUpdateSpotMarket>,
expiry_ts: i64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("updating spot market {} expiry", spot_market.market_index);
let now = Clock::get()?.unix_timestamp;
validate!(
now < expiry_ts,
ErrorCode::DefaultError,
"Market expiry ts must later than current clock timestamp"
)?;
msg!(
"spot_market.status {:?} -> {:?}",
spot_market.status,
MarketStatus::ReduceOnly
);
msg!(
"spot_market.expiry_ts {} -> {}",
spot_market.expiry_ts,
expiry_ts
);
// automatically enter reduce only
spot_market.status = MarketStatus::ReduceOnly;
spot_market.expiry_ts = expiry_ts;
Ok(())
}
pub fn handle_init_user_fuel(
ctx: Context<InitUserFuel>,
fuel_bonus_deposits: Option<u32>,
fuel_bonus_borrows: Option<u32>,
fuel_bonus_taker: Option<u32>,
fuel_bonus_maker: Option<u32>,
fuel_bonus_insurance: Option<u32>,
) -> Result<()> {
let clock: Clock = Clock::get()?;
let now_u32 = clock.unix_timestamp as u32;
let user = &mut load_mut!(ctx.accounts.user)?;
let user_stats = &mut load_mut!(ctx.accounts.user_stats)?;
validate!(
user.last_fuel_bonus_update_ts < FUEL_START_TS as u32,
ErrorCode::DefaultError,
"User must not have begun earning fuel"
)?;
if let Some(fuel_bonus_deposits) = fuel_bonus_deposits {
msg!(
"user_stats.fuel_deposits {:?} -> {:?}",
user_stats.fuel_deposits,
user_stats.fuel_deposits.saturating_add(fuel_bonus_deposits)
);
user_stats.fuel_deposits = user_stats.fuel_deposits.saturating_add(fuel_bonus_deposits);
}
if let Some(fuel_bonus_borrows) = fuel_bonus_borrows {
msg!(
"user_stats.fuel_borrows {:?} -> {:?}",
user_stats.fuel_borrows,
user_stats.fuel_borrows.saturating_add(fuel_bonus_borrows)
);
user_stats.fuel_borrows = user_stats.fuel_borrows.saturating_add(fuel_bonus_borrows);
}
if let Some(fuel_bonus_taker) = fuel_bonus_taker {
msg!(
"user_stats.fuel_taker {:?} -> {:?}",
user_stats.fuel_taker,
user_stats.fuel_taker.saturating_add(fuel_bonus_taker)
);
user_stats.fuel_taker = user_stats.fuel_taker.saturating_add(fuel_bonus_taker);
}
if let Some(fuel_bonus_maker) = fuel_bonus_maker {
msg!(
"user_stats.fuel_maker {:?} -> {:?}",
user_stats.fuel_maker,
user_stats.fuel_maker.saturating_add(fuel_bonus_maker)
);
user_stats.fuel_maker = user_stats.fuel_maker.saturating_add(fuel_bonus_maker);
}
if let Some(fuel_bonus_insurance) = fuel_bonus_insurance {
msg!(
"user_stats.fuel_insurance {:?} -> {:?}",
user_stats.fuel_insurance,
user_stats
.fuel_insurance
.saturating_add(fuel_bonus_insurance)
);
user_stats.fuel_insurance = user_stats
.fuel_insurance
.saturating_add(fuel_bonus_insurance);
}
user.last_fuel_bonus_update_ts = now_u32;
user_stats.last_fuel_if_bonus_update_ts = now_u32;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_expiry(
ctx: Context<AdminUpdatePerpMarket>,
expiry_ts: i64,
) -> Result<()> {
let clock: Clock = Clock::get()?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("updating perp market {} expiry", perp_market.market_index);
validate!(
clock.unix_timestamp < expiry_ts,
ErrorCode::DefaultError,
"Market expiry ts must later than current clock timestamp"
)?;
msg!(
"perp_market.status {:?} -> {:?}",
perp_market.status,
MarketStatus::ReduceOnly
);
msg!(
"perp_market.expiry_ts {} -> {}",
perp_market.expiry_ts,
expiry_ts
);
// automatically enter reduce only
perp_market.status = MarketStatus::ReduceOnly;
perp_market.expiry_ts = expiry_ts;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_move_amm_price(
ctx: Context<AdminUpdatePerpMarket>,
base_asset_reserve: u128,
quote_asset_reserve: u128,
sqrt_k: u128,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"moving amm price for perp market {}",
perp_market.market_index
);
let base_asset_reserve_before = perp_market.amm.base_asset_reserve;
let quote_asset_reserve_before = perp_market.amm.quote_asset_reserve;
let sqrt_k_before = perp_market.amm.sqrt_k;
let max_base_asset_reserve_before = perp_market.amm.max_base_asset_reserve;
let min_base_asset_reserve_before = perp_market.amm.min_base_asset_reserve;
controller::amm::move_price(perp_market, base_asset_reserve, quote_asset_reserve, sqrt_k)?;
validate_perp_market(perp_market)?;
let base_asset_reserve_after = perp_market.amm.base_asset_reserve;
let quote_asset_reserve_after = perp_market.amm.quote_asset_reserve;
let sqrt_k_after = perp_market.amm.sqrt_k;
let max_base_asset_reserve_after = perp_market.amm.max_base_asset_reserve;
let min_base_asset_reserve_after = perp_market.amm.min_base_asset_reserve;
msg!(
"base_asset_reserve {} -> {}",
base_asset_reserve_before,
base_asset_reserve_after
);
msg!(
"quote_asset_reserve {} -> {}",
quote_asset_reserve_before,
quote_asset_reserve_after
);
msg!("sqrt_k {} -> {}", sqrt_k_before, sqrt_k_after);
msg!(
"max_base_asset_reserve {} -> {}",
max_base_asset_reserve_before,
max_base_asset_reserve_after
);
msg!(
"min_base_asset_reserve {} -> {}",
min_base_asset_reserve_before,
min_base_asset_reserve_after
);
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_recenter_perp_market_amm(
ctx: Context<AdminUpdatePerpMarket>,
peg_multiplier: u128,
sqrt_k: u128,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"recentering amm for perp market {}",
perp_market.market_index
);
let base_asset_reserve_before = perp_market.amm.base_asset_reserve;
let quote_asset_reserve_before = perp_market.amm.quote_asset_reserve;
let sqrt_k_before = perp_market.amm.sqrt_k;
let peg_multiplier_before = perp_market.amm.peg_multiplier;
let max_base_asset_reserve_before = perp_market.amm.max_base_asset_reserve;
let min_base_asset_reserve_before = perp_market.amm.min_base_asset_reserve;
controller::amm::recenter_perp_market_amm(perp_market, peg_multiplier, sqrt_k)?;
validate_perp_market(perp_market)?;
let base_asset_reserve_after = perp_market.amm.base_asset_reserve;
let quote_asset_reserve_after = perp_market.amm.quote_asset_reserve;
let sqrt_k_after = perp_market.amm.sqrt_k;
let peg_multiplier_after = perp_market.amm.peg_multiplier;
let max_base_asset_reserve_after = perp_market.amm.max_base_asset_reserve;
let min_base_asset_reserve_after = perp_market.amm.min_base_asset_reserve;
msg!(
"base_asset_reserve {} -> {}",
base_asset_reserve_before,
base_asset_reserve_after
);
msg!(
"quote_asset_reserve {} -> {}",
quote_asset_reserve_before,
quote_asset_reserve_after
);
msg!("sqrt_k {} -> {}", sqrt_k_before, sqrt_k_after);
msg!(
"peg_multiplier {} -> {}",
peg_multiplier_before,
peg_multiplier_after
);
msg!(
"max_base_asset_reserve {} -> {}",
max_base_asset_reserve_before,
max_base_asset_reserve_after
);
msg!(
"min_base_asset_reserve {} -> {}",
min_base_asset_reserve_before,
min_base_asset_reserve_after
);
Ok(())
}
#[derive(Debug, Clone, Copy, AnchorSerialize, AnchorDeserialize, PartialEq, Eq)]
pub struct UpdatePerpMarketSummaryStatsParams {
// new aggregate unsettled user stats
pub quote_asset_amount_with_unsettled_lp: Option<i64>,
pub net_unsettled_funding_pnl: Option<i64>,
pub update_amm_summary_stats: Option<bool>,
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_amm_summary_stats(
ctx: Context<AdminUpdatePerpMarketAmmSummaryStats>,
params: UpdatePerpMarketSummaryStatsParams,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
let spot_market = &mut load!(ctx.accounts.spot_market)?;
msg!(
"updating amm summary stats for perp market {}",
perp_market.market_index
);
msg!(
"updating amm summary stats for spot market {}",
spot_market.market_index
);
let clock = Clock::get()?;
let price_oracle = &ctx.accounts.oracle;
let OraclePriceData {
price: oracle_price,
..
} = get_oracle_price(&perp_market.amm.oracle_source, price_oracle, clock.slot)?;
if let Some(quote_asset_amount_with_unsettled_lp) = params.quote_asset_amount_with_unsettled_lp
{
msg!(
"quote_asset_amount_with_unsettled_lp {} -> {}",
perp_market.amm.quote_asset_amount_with_unsettled_lp,
quote_asset_amount_with_unsettled_lp
);
perp_market.amm.quote_asset_amount_with_unsettled_lp = quote_asset_amount_with_unsettled_lp;
}
if let Some(net_unsettled_funding_pnl) = params.net_unsettled_funding_pnl {
msg!(
"net_unsettled_funding_pnl {} -> {}",
perp_market.amm.net_unsettled_funding_pnl,
net_unsettled_funding_pnl
);
perp_market.amm.net_unsettled_funding_pnl = net_unsettled_funding_pnl;
}
if params.update_amm_summary_stats == Some(true) {
let new_total_fee_minus_distributions =
controller::amm::calculate_perp_market_amm_summary_stats(
perp_market,
spot_market,
oracle_price,
)?;
msg!(
"updating amm summary stats for market index = {}",
perp_market.market_index,
);
msg!(
"total_fee_minus_distributions: {:?} -> {:?}",
perp_market.amm.total_fee_minus_distributions,
new_total_fee_minus_distributions,
);
let fee_difference = new_total_fee_minus_distributions
.safe_sub(perp_market.amm.total_fee_minus_distributions)?;
msg!(
"perp_market.amm.total_fee: {} -> {}",
perp_market.amm.total_fee,
perp_market.amm.total_fee.saturating_add(fee_difference)
);
msg!(
"perp_market.amm.total_mm_fee: {} -> {}",
perp_market.amm.total_mm_fee,
perp_market.amm.total_mm_fee.saturating_add(fee_difference)
);
perp_market.amm.total_fee = perp_market.amm.total_fee.saturating_add(fee_difference);
perp_market.amm.total_mm_fee = perp_market.amm.total_mm_fee.saturating_add(fee_difference);
perp_market.amm.total_fee_minus_distributions = new_total_fee_minus_distributions;
}
validate_perp_market(perp_market)?;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_settle_expired_market_pools_to_revenue_pool(
ctx: Context<SettleExpiredMarketPoolsToRevenuePool>,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
let spot_market: &mut std::cell::RefMut<'_, SpotMarket> =
&mut load_mut!(ctx.accounts.spot_market)?;
let state = &ctx.accounts.state;
msg!(
"settling expired market pools to revenue pool for perp market {}",
perp_market.market_index
);
msg!(
"settling expired market pools to revenue pool for spot market {}",
spot_market.market_index
);
let clock = Clock::get()?;
let now = clock.unix_timestamp;
controller::spot_balance::update_spot_market_cumulative_interest(spot_market, None, now)?;
validate!(
spot_market.market_index == QUOTE_SPOT_MARKET_INDEX,
ErrorCode::DefaultError,
"spot_market must be perp market's quote asset"
)?;
validate!(
perp_market.status == MarketStatus::Settlement,
ErrorCode::DefaultError,
"Market must in Settlement"
)?;
validate!(
perp_market.amm.base_asset_amount_long == 0
&& perp_market.amm.base_asset_amount_short == 0
&& perp_market.number_of_users_with_base == 0,
ErrorCode::DefaultError,
"outstanding base_asset_amounts must be balanced {} {} {}",
perp_market.amm.base_asset_amount_long,
perp_market.amm.base_asset_amount_short,
perp_market.number_of_users_with_base
)?;
validate!(
math::amm::calculate_net_user_cost_basis(&perp_market.amm)? == 0,
ErrorCode::DefaultError,
"outstanding quote_asset_amounts must be balanced"
)?;
// block when settlement_duration is default/unconfigured
validate!(
state.settlement_duration != 0,
ErrorCode::DefaultError,
"invalid state.settlement_duration (is 0)"
)?;
let escrow_period_before_transfer = if state.settlement_duration > 1 {
// minimum of TWENTY_FOUR_HOUR to examine settlement process
TWENTY_FOUR_HOUR
.safe_add(state.settlement_duration.cast()?)?
.safe_sub(1)?
} else {
// for testing / expediting if settlement_duration not default but 1
state.settlement_duration.cast::<i64>()?
};
validate!(
now > perp_market
.expiry_ts
.safe_add(escrow_period_before_transfer)?,
ErrorCode::DefaultError,
"must be escrow_period_before_transfer={} after market.expiry_ts",
escrow_period_before_transfer
)?;
let fee_pool_token_amount = get_token_amount(
perp_market.amm.fee_pool.scaled_balance,
spot_market,
&SpotBalanceType::Deposit,
)?;
let pnl_pool_token_amount = get_token_amount(
perp_market.pnl_pool.scaled_balance,
spot_market,
&SpotBalanceType::Deposit,
)?;
controller::spot_balance::update_spot_balances(
fee_pool_token_amount,
&SpotBalanceType::Borrow,
spot_market,
&mut perp_market.amm.fee_pool,
false,
)?;
controller::spot_balance::update_spot_balances(
pnl_pool_token_amount,
&SpotBalanceType::Borrow,
spot_market,
&mut perp_market.pnl_pool,
false,
)?;
controller::spot_balance::update_revenue_pool_balances(
pnl_pool_token_amount.safe_add(fee_pool_token_amount)?,
&SpotBalanceType::Deposit,
spot_market,
)?;
math::spot_withdraw::validate_spot_balances(spot_market)?;
perp_market.status = MarketStatus::Delisted;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_deposit_into_perp_market_fee_pool<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DepositIntoMarketFeePool<'info>>,
amount: u64,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let mint = get_token_mint(remaining_accounts_iter)?;
msg!(
"depositing {} into perp market {} fee pool",
amount,
perp_market.market_index
);
msg!(
"perp_market.amm.total_fee_minus_distributions: {:?} -> {:?}",
perp_market.amm.total_fee_minus_distributions,
perp_market
.amm
.total_fee_minus_distributions
.safe_add(amount.cast()?)?,
);
perp_market.amm.total_fee_minus_distributions = perp_market
.amm
.total_fee_minus_distributions
.safe_add(amount.cast()?)?;
let quote_spot_market = &mut load_mut!(ctx.accounts.quote_spot_market)?;
controller::spot_balance::update_spot_balances(
amount.cast::<u128>()?,
&SpotBalanceType::Deposit,
quote_spot_market,
&mut perp_market.amm.fee_pool,
false,
)?;
controller::token::receive(
&ctx.accounts.token_program,
&ctx.accounts.source_vault,
&ctx.accounts.spot_market_vault,
&ctx.accounts.admin.to_account_info(),
amount,
&mint,
)?;
Ok(())
}
#[access_control(
deposit_not_paused(&ctx.accounts.state)
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_deposit_into_spot_market_vault<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, DepositIntoSpotMarketVault<'info>>,
amount: u64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
validate!(
!spot_market.is_operation_paused(SpotOperation::Deposit),
ErrorCode::DefaultError,
"spot market deposits paused"
)?;
let remaining_accounts_iter = &mut ctx.remaining_accounts.iter().peekable();
let mint = get_token_mint(remaining_accounts_iter)?;
msg!(
"depositing {} into spot market {} vault",
amount,
spot_market.market_index
);
let deposit_token_amount_before = spot_market.get_deposits()?;
let deposit_token_amount_after = deposit_token_amount_before.safe_add(amount.cast()?)?;
validate!(
deposit_token_amount_after > deposit_token_amount_before,
ErrorCode::DefaultError,
"new_deposit_token_amount ({}) <= deposit_token_amount ({})",
deposit_token_amount_after,
deposit_token_amount_before
)?;
let token_precision = spot_market.get_precision();
let cumulative_deposit_interest_before = spot_market.cumulative_deposit_interest;
let cumulative_deposit_interest_after = deposit_token_amount_after
.safe_mul(SPOT_CUMULATIVE_INTEREST_PRECISION)?
.safe_div(spot_market.deposit_balance)?
.safe_mul(SPOT_BALANCE_PRECISION)?
.safe_div(token_precision.cast()?)?;
validate!(
cumulative_deposit_interest_after > cumulative_deposit_interest_before,
ErrorCode::DefaultError,
"cumulative_deposit_interest_after ({}) <= cumulative_deposit_interest_before ({})",
cumulative_deposit_interest_after,
cumulative_deposit_interest_before
)?;
spot_market.cumulative_deposit_interest = cumulative_deposit_interest_after;
controller::token::receive(
&ctx.accounts.token_program,
&ctx.accounts.source_vault,
&ctx.accounts.spot_market_vault,
&ctx.accounts.admin.to_account_info(),
amount,
&mint,
)?;
ctx.accounts.spot_market_vault.reload()?;
validate_spot_market_vault_amount(spot_market, ctx.accounts.spot_market_vault.amount)?;
spot_market.validate_max_token_deposits_and_borrows(false)?;
emit!(SpotMarketVaultDepositRecord {
ts: Clock::get()?.unix_timestamp,
market_index: spot_market.market_index,
deposit_balance: spot_market.deposit_balance,
cumulative_deposit_interest_before,
cumulative_deposit_interest_after,
deposit_token_amount_before: deposit_token_amount_before.cast()?,
amount
});
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_repeg_amm_curve(ctx: Context<RepegCurve>, new_peg_candidate: u128) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let clock_slot = clock.slot;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"repegging amm curve for perp market {}",
perp_market.market_index
);
let price_oracle = &ctx.accounts.oracle;
let OraclePriceData {
price: oracle_price,
..
} = get_oracle_price(&perp_market.amm.oracle_source, price_oracle, clock.slot)?;
let peg_multiplier_before = perp_market.amm.peg_multiplier;
let base_asset_reserve_before = perp_market.amm.base_asset_reserve;
let quote_asset_reserve_before = perp_market.amm.quote_asset_reserve;
let sqrt_k_before = perp_market.amm.sqrt_k;
let oracle_validity_rails = &ctx.accounts.state.oracle_guard_rails;
let adjustment_cost = controller::repeg::repeg(
perp_market,
price_oracle,
new_peg_candidate,
clock_slot,
oracle_validity_rails,
)?;
let peg_multiplier_after = perp_market.amm.peg_multiplier;
let base_asset_reserve_after = perp_market.amm.base_asset_reserve;
let quote_asset_reserve_after = perp_market.amm.quote_asset_reserve;
let sqrt_k_after = perp_market.amm.sqrt_k;
msg!(
"perp_market.amm.peg_multiplier {} -> {}",
peg_multiplier_before,
peg_multiplier_after
);
msg!(
"perp_market.amm.base_asset_reserve {} -> {}",
base_asset_reserve_before,
base_asset_reserve_after
);
msg!(
"perp_market.amm.quote_asset_reserve {} -> {}",
quote_asset_reserve_before,
quote_asset_reserve_after
);
msg!(
"perp_market.amm.sqrt_k {} -> {}",
sqrt_k_before,
sqrt_k_after
);
emit!(CurveRecord {
ts: now,
record_id: get_then_update_id!(perp_market, next_curve_record_id),
market_index: perp_market.market_index,
peg_multiplier_before,
base_asset_reserve_before,
quote_asset_reserve_before,
sqrt_k_before,
peg_multiplier_after,
base_asset_reserve_after,
quote_asset_reserve_after,
sqrt_k_after,
base_asset_amount_long: perp_market.amm.base_asset_amount_long.unsigned_abs(),
base_asset_amount_short: perp_market.amm.base_asset_amount_short.unsigned_abs(),
base_asset_amount_with_amm: perp_market.amm.base_asset_amount_with_amm,
number_of_users: perp_market.number_of_users,
total_fee: perp_market.amm.total_fee,
total_fee_minus_distributions: perp_market.amm.total_fee_minus_distributions,
adjustment_cost,
oracle_price,
fill_record: 0,
});
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_update_amm_oracle_twap(ctx: Context<RepegCurve>) -> Result<()> {
// allow update to amm's oracle twap iff price gap is reduced and thus more tame funding
// otherwise if oracle error or funding flip: set oracle twap to mark twap (0 gap)
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"updating amm oracle twap for perp market {}",
perp_market.market_index
);
let price_oracle = &ctx.accounts.oracle;
let oracle_twap = perp_market.amm.get_oracle_twap(price_oracle, clock.slot)?;
if let Some(oracle_twap) = oracle_twap {
let oracle_mark_gap_before = perp_market
.amm
.last_mark_price_twap
.cast::<i64>()?
.safe_sub(
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap,
)?;
let oracle_mark_gap_after = perp_market
.amm
.last_mark_price_twap
.cast::<i64>()?
.safe_sub(oracle_twap)?;
if (oracle_mark_gap_after > 0 && oracle_mark_gap_before < 0)
|| (oracle_mark_gap_after < 0 && oracle_mark_gap_before > 0)
{
msg!(
"perp_market.amm.historical_oracle_data.last_oracle_price_twap {} -> {}",
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap,
perp_market.amm.last_mark_price_twap.cast::<i64>()?
);
msg!(
"perp_market.amm.historical_oracle_data.last_oracle_price_twap_ts {} -> {}",
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_ts,
now
);
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap = perp_market.amm.last_mark_price_twap.cast::<i64>()?;
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_ts = now;
} else if oracle_mark_gap_after.unsigned_abs() <= oracle_mark_gap_before.unsigned_abs() {
msg!(
"perp_market.amm.historical_oracle_data.last_oracle_price_twap {} -> {}",
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap,
oracle_twap
);
msg!(
"perp_market.amm.historical_oracle_data.last_oracle_price_twap_ts {} -> {}",
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_ts,
now
);
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap = oracle_twap;
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_ts = now;
} else {
return Err(ErrorCode::PriceBandsBreached.into());
}
} else {
return Err(ErrorCode::InvalidOracle.into());
}
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_update_k(ctx: Context<AdminUpdateK>, sqrt_k: u128) -> Result<()> {
let clock = Clock::get()?;
let now = clock.unix_timestamp;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("updating k for perp market {}", perp_market.market_index);
let base_asset_amount_long = perp_market.amm.base_asset_amount_long.unsigned_abs();
let base_asset_amount_short = perp_market.amm.base_asset_amount_short.unsigned_abs();
let base_asset_amount_with_amm = perp_market.amm.base_asset_amount_with_amm;
let number_of_users = perp_market.number_of_users_with_base;
let price_before = math::amm::calculate_price(
perp_market.amm.quote_asset_reserve,
perp_market.amm.base_asset_reserve,
perp_market.amm.peg_multiplier,
)?;
let peg_multiplier_before = perp_market.amm.peg_multiplier;
let base_asset_reserve_before = perp_market.amm.base_asset_reserve;
let quote_asset_reserve_before = perp_market.amm.quote_asset_reserve;
let sqrt_k_before = perp_market.amm.sqrt_k;
let k_increasing = sqrt_k > perp_market.amm.sqrt_k;
let new_sqrt_k_u192 = bn::U192::from(sqrt_k);
let update_k_result = get_update_k_result(perp_market, new_sqrt_k_u192, true)?;
let adjustment_cost: i128 = math::cp_curve::adjust_k_cost(perp_market, &update_k_result)?;
math::cp_curve::update_k(perp_market, &update_k_result)?;
if k_increasing {
validate!(
adjustment_cost >= 0,
ErrorCode::InvalidUpdateK,
"adjustment_cost negative when k increased",
)?;
} else {
validate!(
adjustment_cost <= 0,
ErrorCode::InvalidUpdateK,
"adjustment_cost positive when k decreased",
)?;
}
if adjustment_cost > 0 {
let max_cost = perp_market
.amm
.total_fee_minus_distributions
.safe_sub(get_total_fee_lower_bound(perp_market)?.cast()?)?
.safe_sub(perp_market.amm.total_fee_withdrawn.cast()?)?;
validate!(
adjustment_cost <= max_cost,
ErrorCode::InvalidUpdateK,
"adjustment_cost={} > max_cost={} for k change",
adjustment_cost,
max_cost
)?;
}
validate!(
!k_increasing || perp_market.amm.sqrt_k < MAX_SQRT_K,
ErrorCode::InvalidUpdateK,
"cannot increase sqrt_k={} past MAX_SQRT_K",
perp_market.amm.sqrt_k
)?;
validate!(
perp_market.amm.sqrt_k > perp_market.amm.user_lp_shares,
ErrorCode::InvalidUpdateK,
"cannot decrease sqrt_k={} below user_lp_shares={}",
perp_market.amm.sqrt_k,
perp_market.amm.user_lp_shares
)?;
perp_market.amm.total_fee_minus_distributions = perp_market
.amm
.total_fee_minus_distributions
.safe_sub(adjustment_cost)?;
perp_market.amm.net_revenue_since_last_funding = perp_market
.amm
.net_revenue_since_last_funding
.safe_sub(adjustment_cost as i64)?;
let amm = &perp_market.amm;
let price_after = math::amm::calculate_price(
amm.quote_asset_reserve,
amm.base_asset_reserve,
amm.peg_multiplier,
)?;
let price_change_too_large = price_before
.cast::<i128>()?
.safe_sub(price_after.cast::<i128>()?)?
.unsigned_abs()
.gt(&MAX_UPDATE_K_PRICE_CHANGE);
if price_change_too_large {
msg!(
"{:?} -> {:?} (> {:?})",
price_before,
price_after,
MAX_UPDATE_K_PRICE_CHANGE
);
return Err(ErrorCode::InvalidUpdateK.into());
}
let k_sqrt_check = bn::U192::from(amm.base_asset_reserve)
.safe_mul(bn::U192::from(amm.quote_asset_reserve))?
.integer_sqrt()
.try_to_u128()?;
let k_err = k_sqrt_check
.cast::<i128>()?
.safe_sub(amm.sqrt_k.cast::<i128>()?)?;
if k_err.unsigned_abs() > 100 {
msg!("k_err={:?}, {:?} != {:?}", k_err, k_sqrt_check, amm.sqrt_k);
return Err(ErrorCode::InvalidUpdateK.into());
}
let peg_multiplier_after = amm.peg_multiplier;
let base_asset_reserve_after = amm.base_asset_reserve;
let quote_asset_reserve_after = amm.quote_asset_reserve;
let sqrt_k_after = amm.sqrt_k;
msg!(
"perp_market.amm.peg_multiplier {} -> {}",
peg_multiplier_before,
peg_multiplier_after
);
msg!(
"perp_market.amm.base_asset_reserve {} -> {}",
base_asset_reserve_before,
base_asset_reserve_after
);
msg!(
"perp_market.amm.quote_asset_reserve {} -> {}",
quote_asset_reserve_before,
quote_asset_reserve_after
);
msg!(
"perp_market.amm.sqrt_k {} -> {}",
sqrt_k_before,
sqrt_k_after
);
let total_fee = amm.total_fee;
let total_fee_minus_distributions = amm.total_fee_minus_distributions;
let OraclePriceData {
price: oracle_price,
..
} = get_oracle_price(
&perp_market.amm.oracle_source,
&ctx.accounts.oracle,
clock.slot,
)?;
emit!(CurveRecord {
ts: now,
record_id: get_then_update_id!(perp_market, next_curve_record_id),
market_index: perp_market.market_index,
peg_multiplier_before,
base_asset_reserve_before,
quote_asset_reserve_before,
sqrt_k_before,
peg_multiplier_after,
base_asset_reserve_after,
quote_asset_reserve_after,
sqrt_k_after,
base_asset_amount_long,
base_asset_amount_short,
base_asset_amount_with_amm,
number_of_users,
adjustment_cost,
total_fee,
total_fee_minus_distributions,
oracle_price,
fill_record: 0,
});
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
valid_oracle_for_perp_market(&ctx.accounts.oracle, &ctx.accounts.perp_market)
)]
pub fn handle_reset_amm_oracle_twap(ctx: Context<RepegCurve>) -> Result<()> {
// admin failsafe to reset amm oracle_twap to the mark_twap
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"resetting amm oracle twap for perp market {}",
perp_market.market_index
);
msg!(
"perp_market.amm.historical_oracle_data.last_oracle_price_twap: {:?} -> {:?}",
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap,
perp_market.amm.last_mark_price_twap.cast::<i64>()?
);
msg!(
"perp_market.amm.historical_oracle_data.last_oracle_price_twap_ts: {:?} -> {:?}",
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_ts,
perp_market.amm.last_mark_price_twap_ts
);
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap = perp_market.amm.last_mark_price_twap.cast::<i64>()?;
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_ts = perp_market.amm.last_mark_price_twap_ts;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_margin_ratio(
ctx: Context<AdminUpdatePerpMarket>,
margin_ratio_initial: u32,
margin_ratio_maintenance: u32,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"updating perp market {} margin ratio",
perp_market.market_index
);
validate_margin(
margin_ratio_initial,
margin_ratio_maintenance,
perp_market.high_leverage_margin_ratio_initial.cast()?,
perp_market.high_leverage_margin_ratio_maintenance.cast()?,
perp_market.liquidator_fee,
perp_market.amm.max_spread,
)?;
msg!(
"perp_market.margin_ratio_initial: {:?} -> {:?}",
perp_market.margin_ratio_initial,
margin_ratio_initial
);
msg!(
"perp_market.margin_ratio_maintenance: {:?} -> {:?}",
perp_market.margin_ratio_maintenance,
margin_ratio_maintenance
);
perp_market.margin_ratio_initial = margin_ratio_initial;
perp_market.margin_ratio_maintenance = margin_ratio_maintenance;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_high_leverage_margin_ratio(
ctx: Context<AdminUpdatePerpMarket>,
margin_ratio_initial: u16,
margin_ratio_maintenance: u16,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"updating perp market {} margin ratio",
perp_market.market_index
);
validate_margin(
perp_market.margin_ratio_initial,
perp_market.margin_ratio_maintenance,
margin_ratio_initial.cast()?,
margin_ratio_maintenance.cast()?,
perp_market.liquidator_fee,
perp_market.amm.max_spread,
)?;
msg!(
"perp_market.high_leverage_margin_ratio_initial: {:?} -> {:?}",
perp_market.high_leverage_margin_ratio_initial,
margin_ratio_initial
);
msg!(
"perp_market.high_leverage_margin_ratio_maintenance: {:?} -> {:?}",
perp_market.high_leverage_margin_ratio_maintenance,
margin_ratio_maintenance
);
perp_market.high_leverage_margin_ratio_initial = margin_ratio_initial;
perp_market.high_leverage_margin_ratio_maintenance = margin_ratio_maintenance;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_funding_period(
ctx: Context<AdminUpdatePerpMarket>,
funding_period: i64,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"updating funding period for perp market {}",
perp_market.market_index
);
validate!(funding_period >= 0, ErrorCode::DefaultError)?;
msg!(
"perp_market.amm.funding_period: {:?} -> {:?}",
perp_market.amm.funding_period,
funding_period
);
perp_market.amm.funding_period = funding_period;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_max_imbalances(
ctx: Context<AdminUpdatePerpMarket>,
unrealized_max_imbalance: u64,
max_revenue_withdraw_per_period: u64,
quote_max_insurance: u64,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"updating perp market {} max imbalances",
perp_market.market_index
);
let max_insurance_for_tier = match perp_market.contract_tier {
ContractTier::A => INSURANCE_A_MAX,
ContractTier::B => INSURANCE_B_MAX,
ContractTier::C => INSURANCE_C_MAX,
ContractTier::Speculative => INSURANCE_SPECULATIVE_MAX,
ContractTier::HighlySpeculative => INSURANCE_SPECULATIVE_MAX,
ContractTier::Isolated => INSURANCE_SPECULATIVE_MAX,
};
validate!(
max_revenue_withdraw_per_period
<= max_insurance_for_tier.max(FEE_POOL_TO_REVENUE_POOL_THRESHOLD.cast()?)
&& unrealized_max_imbalance <= max_insurance_for_tier + 1
&& quote_max_insurance <= max_insurance_for_tier,
ErrorCode::DefaultError,
"all maxs must be less than max_insurance for ContractTier ={}",
max_insurance_for_tier
)?;
validate!(
perp_market.insurance_claim.quote_settled_insurance <= quote_max_insurance,
ErrorCode::DefaultError,
"quote_max_insurance must be above market.insurance_claim.quote_settled_insurance={}",
perp_market.insurance_claim.quote_settled_insurance
)?;
msg!(
"market.max_revenue_withdraw_per_period: {:?} -> {:?}",
perp_market.insurance_claim.max_revenue_withdraw_per_period,
max_revenue_withdraw_per_period
);
msg!(
"market.unrealized_max_imbalance: {:?} -> {:?}",
perp_market.unrealized_pnl_max_imbalance,
unrealized_max_imbalance
);
msg!(
"market.quote_max_insurance: {:?} -> {:?}",
perp_market.insurance_claim.quote_max_insurance,
quote_max_insurance
);
perp_market.insurance_claim.max_revenue_withdraw_per_period = max_revenue_withdraw_per_period;
perp_market.unrealized_pnl_max_imbalance = unrealized_max_imbalance;
perp_market.insurance_claim.quote_max_insurance = quote_max_insurance;
// ensure altered max_revenue_withdraw_per_period doesn't break invariant check
crate::validation::perp_market::validate_perp_market(perp_market)?;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_name(
ctx: Context<AdminUpdatePerpMarket>,
name: [u8; 32],
) -> Result<()> {
let mut perp_market = load_mut!(ctx.accounts.perp_market)?;
msg!("perp_market.name: {:?} -> {:?}", perp_market.name, name);
perp_market.name = name;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_name(
ctx: Context<AdminUpdateSpotMarket>,
name: [u8; 32],
) -> Result<()> {
let mut spot_market = load_mut!(ctx.accounts.spot_market)?;
msg!("spot_market.name: {:?} -> {:?}", spot_market.name, name);
spot_market.name = name;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_liquidation_fee(
ctx: Context<AdminUpdatePerpMarket>,
liquidator_fee: u32,
if_liquidation_fee: u32,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!(
"updating perp market {} liquidation fee",
perp_market.market_index
);
validate!(
liquidator_fee.safe_add(if_liquidation_fee)? < LIQUIDATION_FEE_PRECISION,
ErrorCode::DefaultError,
"Total liquidation fee must be less than 100%"
)?;
validate!(
if_liquidation_fee < LIQUIDATION_FEE_PRECISION,
ErrorCode::DefaultError,
"If liquidation fee must be less than 100%"
)?;
validate_margin(
perp_market.margin_ratio_initial,
perp_market.margin_ratio_maintenance,
perp_market.high_leverage_margin_ratio_initial.cast()?,
perp_market.high_leverage_margin_ratio_maintenance.cast()?,
liquidator_fee,
perp_market.amm.max_spread,
)?;
msg!(
"perp_market.liquidator_fee: {:?} -> {:?}",
perp_market.liquidator_fee,
liquidator_fee
);
msg!(
"perp_market.if_liquidation_fee: {:?} -> {:?}",
perp_market.if_liquidation_fee,
if_liquidation_fee
);
perp_market.liquidator_fee = liquidator_fee;
perp_market.if_liquidation_fee = if_liquidation_fee;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_insurance_fund_unstaking_period(
ctx: Context<AdminUpdateSpotMarket>,
insurance_fund_unstaking_period: i64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("updating spot market {} IF unstaking period");
msg!(
"spot_market.insurance_fund.unstaking_period: {:?} -> {:?}",
spot_market.insurance_fund.unstaking_period,
insurance_fund_unstaking_period
);
spot_market.insurance_fund.unstaking_period = insurance_fund_unstaking_period;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_liquidation_fee(
ctx: Context<AdminUpdateSpotMarket>,
liquidator_fee: u32,
if_liquidation_fee: u32,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!(
"updating spot market {} liquidation fee",
spot_market.market_index
);
validate!(
liquidator_fee.safe_add(if_liquidation_fee)? < LIQUIDATION_FEE_PRECISION,
ErrorCode::DefaultError,
"Total liquidation fee must be less than 100%"
)?;
validate!(
if_liquidation_fee <= LIQUIDATION_FEE_PRECISION / 10,
ErrorCode::DefaultError,
"if_liquidation_fee must be <= 10%"
)?;
msg!(
"spot_market.liquidator_fee: {:?} -> {:?}",
spot_market.liquidator_fee,
liquidator_fee
);
msg!(
"spot_market.if_liquidation_fee: {:?} -> {:?}",
spot_market.if_liquidation_fee,
if_liquidation_fee
);
spot_market.liquidator_fee = liquidator_fee;
spot_market.if_liquidation_fee = if_liquidation_fee;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_withdraw_guard_threshold(
ctx: Context<AdminUpdateSpotMarket>,
withdraw_guard_threshold: u64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!(
"updating spot market withdraw guard threshold {}",
spot_market.market_index
);
msg!(
"spot_market.withdraw_guard_threshold: {:?} -> {:?}",
spot_market.withdraw_guard_threshold,
withdraw_guard_threshold
);
spot_market.withdraw_guard_threshold = withdraw_guard_threshold;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_if_factor(
ctx: Context<AdminUpdateSpotMarket>,
spot_market_index: u16,
user_if_factor: u32,
total_if_factor: u32,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
validate!(
spot_market.market_index == spot_market_index,
ErrorCode::DefaultError,
"spot_market_index dne spot_market.index"
)?;
validate!(
user_if_factor <= total_if_factor,
ErrorCode::DefaultError,
"user_if_factor must be <= total_if_factor"
)?;
validate!(
total_if_factor <= IF_FACTOR_PRECISION.cast()?,
ErrorCode::DefaultError,
"total_if_factor must be <= 100%"
)?;
msg!(
"spot_market.user_if_factor: {:?} -> {:?}",
spot_market.insurance_fund.user_factor,
user_if_factor
);
msg!(
"spot_market.total_if_factor: {:?} -> {:?}",
spot_market.insurance_fund.total_factor,
total_if_factor
);
spot_market.insurance_fund.user_factor = user_if_factor;
spot_market.insurance_fund.total_factor = total_if_factor;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_revenue_settle_period(
ctx: Context<AdminUpdateSpotMarket>,
revenue_settle_period: i64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
validate!(revenue_settle_period > 0, ErrorCode::DefaultError)?;
msg!(
"spot_market.revenue_settle_period: {:?} -> {:?}",
spot_market.insurance_fund.revenue_settle_period,
revenue_settle_period
);
spot_market.insurance_fund.revenue_settle_period = revenue_settle_period;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_status(
ctx: Context<AdminUpdateSpotMarket>,
status: MarketStatus,
) -> Result<()> {
status.validate_not_deprecated()?;
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
msg!(
"spot_market.status: {:?} -> {:?}",
spot_market.status,
status
);
spot_market.status = status;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_paused_operations(
ctx: Context<AdminUpdateSpotMarket>,
paused_operations: u8,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
spot_market.paused_operations = paused_operations;
SpotOperation::log_all_operations_paused(spot_market.paused_operations);
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_asset_tier(
ctx: Context<AdminUpdateSpotMarket>,
asset_tier: AssetTier,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
if spot_market.initial_asset_weight > 0 {
validate!(
matches!(asset_tier, AssetTier::Collateral | AssetTier::Protected),
ErrorCode::DefaultError,
"initial_asset_weight > 0 so AssetTier must be collateral or protected"
)?;
}
msg!(
"spot_market.asset_tier: {:?} -> {:?}",
spot_market.asset_tier,
asset_tier
);
spot_market.asset_tier = asset_tier;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_margin_weights(
ctx: Context<AdminUpdateSpotMarket>,
initial_asset_weight: u32,
maintenance_asset_weight: u32,
initial_liability_weight: u32,
maintenance_liability_weight: u32,
imf_factor: u32,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
validate_margin_weights(
spot_market.market_index,
initial_asset_weight,
maintenance_asset_weight,
initial_liability_weight,
maintenance_liability_weight,
imf_factor,
)?;
msg!(
"spot_market.initial_asset_weight: {:?} -> {:?}",
spot_market.initial_asset_weight,
initial_asset_weight
);
msg!(
"spot_market.maintenance_asset_weight: {:?} -> {:?}",
spot_market.maintenance_asset_weight,
maintenance_asset_weight
);
msg!(
"spot_market.initial_liability_weight: {:?} -> {:?}",
spot_market.initial_liability_weight,
initial_liability_weight
);
msg!(
"spot_market.maintenance_liability_weight: {:?} -> {:?}",
spot_market.maintenance_liability_weight,
maintenance_liability_weight
);
msg!(
"spot_market.imf_factor: {:?} -> {:?}",
spot_market.imf_factor,
imf_factor
);
spot_market.initial_asset_weight = initial_asset_weight;
spot_market.maintenance_asset_weight = maintenance_asset_weight;
spot_market.initial_liability_weight = initial_liability_weight;
spot_market.maintenance_liability_weight = maintenance_liability_weight;
spot_market.imf_factor = imf_factor;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_borrow_rate(
ctx: Context<AdminUpdateSpotMarket>,
optimal_utilization: u32,
optimal_borrow_rate: u32,
max_borrow_rate: u32,
min_borrow_rate: Option<u8>,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
validate_borrow_rate(
optimal_utilization,
optimal_borrow_rate,
max_borrow_rate,
min_borrow_rate
.unwrap_or(spot_market.min_borrow_rate)
.cast::<u32>()?
* ((PERCENTAGE_PRECISION / 200) as u32),
)?;
msg!(
"spot_market.optimal_utilization: {:?} -> {:?}",
spot_market.optimal_utilization,
optimal_utilization
);
msg!(
"spot_market.optimal_borrow_rate: {:?} -> {:?}",
spot_market.optimal_borrow_rate,
optimal_borrow_rate
);
msg!(
"spot_market.max_borrow_rate: {:?} -> {:?}",
spot_market.max_borrow_rate,
max_borrow_rate
);
spot_market.optimal_utilization = optimal_utilization;
spot_market.optimal_borrow_rate = optimal_borrow_rate;
spot_market.max_borrow_rate = max_borrow_rate;
if let Some(min_borrow_rate) = min_borrow_rate {
msg!(
"spot_market.min_borrow_rate: {:?} -> {:?}",
spot_market.min_borrow_rate,
min_borrow_rate
);
spot_market.min_borrow_rate = min_borrow_rate
}
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_max_token_deposits(
ctx: Context<AdminUpdateSpotMarket>,
max_token_deposits: u64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
msg!(
"spot_market.max_token_deposits: {:?} -> {:?}",
spot_market.max_token_deposits,
max_token_deposits
);
spot_market.max_token_deposits = max_token_deposits;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_max_token_borrows(
ctx: Context<AdminUpdateSpotMarket>,
max_token_borrows_fraction: u16,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
msg!(
"spot_market.max_token_borrows_fraction: {:?} -> {:?}",
spot_market.max_token_borrows_fraction,
max_token_borrows_fraction
);
let current_spot_tokens_borrows: u64 = spot_market.get_borrows()?.cast()?;
let new_max_token_borrows = spot_market
.max_token_deposits
.safe_mul(max_token_borrows_fraction.cast()?)?
.safe_div(10000)?;
validate!(
current_spot_tokens_borrows <= new_max_token_borrows,
ErrorCode::InvalidSpotMarketInitialization,
"spot borrows {} > max_token_borrows {}",
current_spot_tokens_borrows,
max_token_borrows_fraction
)?;
spot_market.max_token_borrows_fraction = max_token_borrows_fraction;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_scale_initial_asset_weight_start(
ctx: Context<AdminUpdateSpotMarket>,
scale_initial_asset_weight_start: u64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
msg!(
"spot_market.scale_initial_asset_weight_start: {:?} -> {:?}",
spot_market.scale_initial_asset_weight_start,
scale_initial_asset_weight_start
);
spot_market.scale_initial_asset_weight_start = scale_initial_asset_weight_start;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_orders_enabled(
ctx: Context<AdminUpdateSpotMarket>,
orders_enabled: bool,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
msg!(
"spot_market.orders_enabled: {:?} -> {:?}",
spot_market.orders_enabled,
orders_enabled
);
spot_market.orders_enabled = orders_enabled;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_if_paused_operations(
ctx: Context<AdminUpdateSpotMarket>,
paused_operations: u8,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
spot_market.if_paused_operations = paused_operations;
msg!("spot market {}", spot_market.market_index);
InsuranceFundOperation::log_all_operations_paused(paused_operations);
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_status(
ctx: Context<AdminUpdatePerpMarket>,
status: MarketStatus,
) -> Result<()> {
validate!(
!matches!(status, MarketStatus::Delisted | MarketStatus::Settlement),
ErrorCode::DefaultError,
"must set settlement/delist through another instruction",
)?;
status.validate_not_deprecated()?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.status: {:?} -> {:?}",
perp_market.status,
status
);
perp_market.status = status;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_paused_operations(
ctx: Context<AdminUpdatePerpMarket>,
paused_operations: u8,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
perp_market.paused_operations = paused_operations;
if perp_market.is_prediction_market() {
validate!(
perp_market.is_operation_paused(PerpOperation::UpdateFunding),
ErrorCode::DefaultError,
"prediction market must have funding paused"
)?;
}
PerpOperation::log_all_operations_paused(perp_market.paused_operations);
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_contract_tier(
ctx: Context<AdminUpdatePerpMarket>,
contract_tier: ContractTier,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.contract_tier: {:?} -> {:?}",
perp_market.contract_tier,
contract_tier
);
perp_market.contract_tier = contract_tier;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_imf_factor(
ctx: Context<AdminUpdatePerpMarket>,
imf_factor: u32,
unrealized_pnl_imf_factor: u32,
) -> Result<()> {
validate!(
imf_factor <= SPOT_IMF_PRECISION,
ErrorCode::DefaultError,
"invalid imf factor",
)?;
validate!(
unrealized_pnl_imf_factor <= SPOT_IMF_PRECISION,
ErrorCode::DefaultError,
"invalid unrealized pnl imf factor",
)?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.imf_factor: {:?} -> {:?}",
perp_market.imf_factor,
imf_factor
);
msg!(
"perp_market.unrealized_pnl_imf_factor: {:?} -> {:?}",
perp_market.unrealized_pnl_imf_factor,
unrealized_pnl_imf_factor
);
perp_market.imf_factor = imf_factor;
perp_market.unrealized_pnl_imf_factor = unrealized_pnl_imf_factor;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_unrealized_asset_weight(
ctx: Context<AdminUpdatePerpMarket>,
unrealized_initial_asset_weight: u32,
unrealized_maintenance_asset_weight: u32,
) -> Result<()> {
validate!(
unrealized_initial_asset_weight <= SPOT_WEIGHT_PRECISION.cast()?,
ErrorCode::DefaultError,
"invalid unrealized_initial_asset_weight",
)?;
validate!(
unrealized_maintenance_asset_weight <= SPOT_WEIGHT_PRECISION.cast()?,
ErrorCode::DefaultError,
"invalid unrealized_maintenance_asset_weight",
)?;
validate!(
unrealized_initial_asset_weight <= unrealized_maintenance_asset_weight,
ErrorCode::DefaultError,
"must enforce unrealized_initial_asset_weight <= unrealized_maintenance_asset_weight",
)?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.unrealized_initial_asset_weight: {:?} -> {:?}",
perp_market.unrealized_pnl_initial_asset_weight,
unrealized_initial_asset_weight
);
msg!(
"perp_market.unrealized_maintenance_asset_weight: {:?} -> {:?}",
perp_market.unrealized_pnl_maintenance_asset_weight,
unrealized_maintenance_asset_weight
);
perp_market.unrealized_pnl_initial_asset_weight = unrealized_initial_asset_weight;
perp_market.unrealized_pnl_maintenance_asset_weight = unrealized_maintenance_asset_weight;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_concentration_coef(
ctx: Context<AdminUpdatePerpMarket>,
concentration_scale: u128,
) -> Result<()> {
validate!(
concentration_scale > 0,
ErrorCode::DefaultError,
"invalid concentration_scale",
)?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
let prev_concentration_coef = perp_market.amm.concentration_coef;
controller::amm::update_concentration_coef(perp_market, concentration_scale)?;
let new_concentration_coef = perp_market.amm.concentration_coef;
msg!(
"perp_market.amm.concentration_coef: {} -> {}",
prev_concentration_coef,
new_concentration_coef
);
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_curve_update_intensity(
ctx: Context<AdminUpdatePerpMarket>,
curve_update_intensity: u8,
) -> Result<()> {
// (0, 100] is for repeg / formulaic k intensity
// (100, 200] is for reference price offset intensity
validate!(
curve_update_intensity <= 200,
ErrorCode::DefaultError,
"invalid curve_update_intensity",
)?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.amm.curve_update_intensity: {} -> {}",
perp_market.amm.curve_update_intensity,
curve_update_intensity
);
perp_market.amm.curve_update_intensity = curve_update_intensity;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_target_base_asset_amount_per_lp(
ctx: Context<AdminUpdatePerpMarket>,
target_base_asset_amount_per_lp: i32,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.amm.target_base_asset_amount_per_lp: {} -> {}",
perp_market.amm.target_base_asset_amount_per_lp,
target_base_asset_amount_per_lp
);
perp_market.amm.target_base_asset_amount_per_lp = target_base_asset_amount_per_lp;
Ok(())
}
pub fn handle_update_perp_market_per_lp_base(
ctx: Context<AdminUpdatePerpMarket>,
per_lp_base: i8,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
let old_per_lp_base = perp_market.amm.per_lp_base;
msg!(
"updated perp_market per_lp_base {} -> {}",
old_per_lp_base,
per_lp_base
);
let expo_diff = per_lp_base.safe_sub(old_per_lp_base)?;
validate!(
expo_diff.abs() == 1,
ErrorCode::DefaultError,
"invalid expo update (must be 1)",
)?;
validate!(
per_lp_base.abs() <= 9,
ErrorCode::DefaultError,
"only consider lp_base within range of AMM_RESERVE_PRECISION",
)?;
controller::lp::apply_lp_rebase_to_perp_market(perp_market, expo_diff)?;
Ok(())
}
pub fn handle_update_lp_cooldown_time(
ctx: Context<AdminUpdateState>,
lp_cooldown_time: u64,
) -> Result<()> {
msg!(
"lp_cooldown_time: {} -> {}",
ctx.accounts.state.lp_cooldown_time,
lp_cooldown_time
);
ctx.accounts.state.lp_cooldown_time = lp_cooldown_time;
Ok(())
}
pub fn handle_update_perp_fee_structure(
ctx: Context<AdminUpdateState>,
fee_structure: FeeStructure,
) -> Result<()> {
validate_fee_structure(&fee_structure)?;
msg!(
"perp_fee_structure: {:?} -> {:?}",
ctx.accounts.state.perp_fee_structure,
fee_structure
);
ctx.accounts.state.perp_fee_structure = fee_structure;
Ok(())
}
pub fn handle_update_spot_fee_structure(
ctx: Context<AdminUpdateState>,
fee_structure: FeeStructure,
) -> Result<()> {
validate_fee_structure(&fee_structure)?;
msg!(
"spot_fee_structure: {:?} -> {:?}",
ctx.accounts.state.spot_fee_structure,
fee_structure
);
ctx.accounts.state.spot_fee_structure = fee_structure;
Ok(())
}
pub fn handle_update_initial_pct_to_liquidate(
ctx: Context<AdminUpdateState>,
initial_pct_to_liquidate: u16,
) -> Result<()> {
msg!(
"initial_pct_to_liquidate: {} -> {}",
ctx.accounts.state.initial_pct_to_liquidate,
initial_pct_to_liquidate
);
ctx.accounts.state.initial_pct_to_liquidate = initial_pct_to_liquidate;
Ok(())
}
pub fn handle_update_liquidation_duration(
ctx: Context<AdminUpdateState>,
liquidation_duration: u8,
) -> Result<()> {
msg!(
"liquidation_duration: {} -> {}",
ctx.accounts.state.liquidation_duration,
liquidation_duration
);
ctx.accounts.state.liquidation_duration = liquidation_duration;
Ok(())
}
pub fn handle_update_liquidation_margin_buffer_ratio(
ctx: Context<AdminUpdateState>,
liquidation_margin_buffer_ratio: u32,
) -> Result<()> {
msg!(
"liquidation_margin_buffer_ratio: {} -> {}",
ctx.accounts.state.liquidation_margin_buffer_ratio,
liquidation_margin_buffer_ratio
);
ctx.accounts.state.liquidation_margin_buffer_ratio = liquidation_margin_buffer_ratio;
Ok(())
}
pub fn handle_update_oracle_guard_rails(
ctx: Context<AdminUpdateState>,
oracle_guard_rails: OracleGuardRails,
) -> Result<()> {
msg!(
"oracle_guard_rails: {:?} -> {:?}",
ctx.accounts.state.oracle_guard_rails,
oracle_guard_rails
);
ctx.accounts.state.oracle_guard_rails = oracle_guard_rails;
Ok(())
}
pub fn handle_update_state_settlement_duration(
ctx: Context<AdminUpdateState>,
settlement_duration: u16,
) -> Result<()> {
msg!(
"settlement_duration: {} -> {}",
ctx.accounts.state.settlement_duration,
settlement_duration
);
ctx.accounts.state.settlement_duration = settlement_duration;
Ok(())
}
pub fn handle_update_state_max_number_of_sub_accounts(
ctx: Context<AdminUpdateState>,
max_number_of_sub_accounts: u16,
) -> Result<()> {
msg!(
"max_number_of_sub_accounts: {} -> {}",
ctx.accounts.state.max_number_of_sub_accounts,
max_number_of_sub_accounts
);
ctx.accounts.state.max_number_of_sub_accounts = max_number_of_sub_accounts;
Ok(())
}
pub fn handle_update_state_max_initialize_user_fee(
ctx: Context<AdminUpdateState>,
max_initialize_user_fee: u16,
) -> Result<()> {
msg!(
"max_initialize_user_fee: {} -> {}",
ctx.accounts.state.max_initialize_user_fee,
max_initialize_user_fee
);
ctx.accounts.state.max_initialize_user_fee = max_initialize_user_fee;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_oracle(
ctx: Context<RepegCurve>,
oracle: Pubkey,
oracle_source: OracleSource,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
let clock = Clock::get()?;
OracleMap::validate_oracle_account_info(&ctx.accounts.oracle)?;
validate!(
ctx.accounts.oracle.key == &oracle,
ErrorCode::DefaultError,
"oracle account info ({:?}) and ix data ({:?}) must match",
ctx.accounts.oracle.key,
oracle
)?;
// Verify oracle is readable
let OraclePriceData {
price: _oracle_price,
delay: _oracle_delay,
..
} = get_oracle_price(&oracle_source, &ctx.accounts.oracle, clock.slot)?;
msg!(
"perp_market.amm.oracle: {:?} -> {:?}",
perp_market.amm.oracle,
oracle
);
msg!(
"perp_market.amm.oracle_source: {:?} -> {:?}",
perp_market.amm.oracle_source,
oracle_source
);
perp_market.amm.oracle = oracle;
perp_market.amm.oracle_source = oracle_source;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_base_spread(
ctx: Context<AdminUpdatePerpMarket>,
base_spread: u32,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.amm.base_spread: {:?} -> {:?}",
perp_market.amm.base_spread,
base_spread
);
msg!(
"perp_market.amm.long_spread: {:?} -> {:?}",
perp_market.amm.long_spread,
base_spread / 2
);
msg!(
"perp_market.amm.short_spread: {:?} -> {:?}",
perp_market.amm.short_spread,
base_spread / 2
);
perp_market.amm.base_spread = base_spread;
perp_market.amm.long_spread = base_spread / 2;
perp_market.amm.short_spread = base_spread / 2;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_amm_jit_intensity(
ctx: Context<AdminUpdatePerpMarket>,
amm_jit_intensity: u8,
) -> Result<()> {
validate!(
(0..=200).contains(&amm_jit_intensity),
ErrorCode::DefaultError,
"invalid amm_jit_intensity",
)?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.amm.amm_jit_intensity: {} -> {}",
perp_market.amm.amm_jit_intensity,
amm_jit_intensity
);
perp_market.amm.amm_jit_intensity = amm_jit_intensity;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_max_spread(
ctx: Context<AdminUpdatePerpMarket>,
max_spread: u32,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
validate!(
max_spread >= perp_market.amm.base_spread,
ErrorCode::DefaultError,
"invalid max_spread < base_spread",
)?;
validate!(
max_spread <= perp_market.margin_ratio_initial * 100,
ErrorCode::DefaultError,
"invalid max_spread > market.margin_ratio_initial * 100",
)?;
msg!(
"perp_market.amm.max_spread: {:?} -> {:?}",
perp_market.amm.max_spread,
max_spread
);
perp_market.amm.max_spread = max_spread;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_step_size_and_tick_size(
ctx: Context<AdminUpdatePerpMarket>,
step_size: u64,
tick_size: u64,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
validate!(step_size > 0 && tick_size > 0, ErrorCode::DefaultError)?;
validate!(step_size <= 2000000000, ErrorCode::DefaultError)?; // below i32 max for lp's remainder_base_asset
msg!(
"perp_market.amm.order_step_size: {:?} -> {:?}",
perp_market.amm.order_step_size,
step_size
);
msg!(
"perp_market.amm.order_tick_size: {:?} -> {:?}",
perp_market.amm.order_tick_size,
tick_size
);
perp_market.amm.order_step_size = step_size;
perp_market.amm.order_tick_size = tick_size;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_min_order_size(
ctx: Context<AdminUpdatePerpMarket>,
order_size: u64,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
validate!(order_size > 0, ErrorCode::DefaultError)?;
msg!(
"perp_market.amm.min_order_size: {:?} -> {:?}",
perp_market.amm.min_order_size,
order_size
);
perp_market.amm.min_order_size = order_size;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_step_size_and_tick_size(
ctx: Context<AdminUpdateSpotMarket>,
step_size: u64,
tick_size: u64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
validate!(
spot_market.market_index == 0 || step_size > 0 && tick_size > 0,
ErrorCode::DefaultError
)?;
msg!(
"spot_market.order_step_size: {:?} -> {:?}",
spot_market.order_step_size,
step_size
);
msg!(
"spot_market.order_tick_size: {:?} -> {:?}",
spot_market.order_tick_size,
tick_size
);
spot_market.order_step_size = step_size;
spot_market.order_tick_size = tick_size;
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_min_order_size(
ctx: Context<AdminUpdateSpotMarket>,
order_size: u64,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
validate!(
spot_market.market_index == 0 || order_size > 0,
ErrorCode::DefaultError
)?;
msg!(
"spot_market.min_order_size: {:?} -> {:?}",
spot_market.min_order_size,
order_size
);
spot_market.min_order_size = order_size;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_max_slippage_ratio(
ctx: Context<AdminUpdatePerpMarket>,
max_slippage_ratio: u16,
) -> Result<()> {
validate!(max_slippage_ratio > 0, ErrorCode::DefaultError)?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.amm.max_slippage_ratio: {:?} -> {:?}",
perp_market.amm.max_slippage_ratio,
max_slippage_ratio
);
perp_market.amm.max_slippage_ratio = max_slippage_ratio;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_max_fill_reserve_fraction(
ctx: Context<AdminUpdatePerpMarket>,
max_fill_reserve_fraction: u16,
) -> Result<()> {
validate!(max_fill_reserve_fraction > 0, ErrorCode::DefaultError)?;
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
msg!(
"perp_market.amm.max_fill_reserve_fraction: {:?} -> {:?}",
perp_market.amm.max_fill_reserve_fraction,
max_fill_reserve_fraction
);
perp_market.amm.max_fill_reserve_fraction = max_fill_reserve_fraction;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_max_open_interest(
ctx: Context<AdminUpdatePerpMarket>,
max_open_interest: u128,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
validate!(
is_multiple_of_step_size(
max_open_interest.cast::<u64>()?,
perp_market.amm.order_step_size
)?,
ErrorCode::DefaultError,
"max oi not a multiple of the step size"
)?;
msg!(
"perp_market.amm.max_open_interest: {:?} -> {:?}",
perp_market.amm.max_open_interest,
max_open_interest
);
perp_market.amm.max_open_interest = max_open_interest;
Ok(())
}
#[access_control(
perp_market_valid(&ctx.accounts.perp_market)
)]
pub fn handle_update_perp_market_fee_adjustment(
ctx: Context<AdminUpdatePerpMarket>,
fee_adjustment: i16,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
validate!(
fee_adjustment.unsigned_abs().cast::<u64>()? <= FEE_ADJUSTMENT_MAX,
ErrorCode::DefaultError,
"fee adjustment {} greater than max {}",
fee_adjustment,
FEE_ADJUSTMENT_MAX
)?;
msg!(
"perp_market.fee_adjustment: {:?} -> {:?}",
perp_market.fee_adjustment,
fee_adjustment
);
perp_market.fee_adjustment = fee_adjustment;
Ok(())
}
pub fn handle_update_perp_market_number_of_users(
ctx: Context<AdminUpdatePerpMarket>,
number_of_users: Option<u32>,
number_of_users_with_base: Option<u32>,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
if let Some(number_of_users) = number_of_users {
msg!(
"perp_market.number_of_users: {:?} -> {:?}",
perp_market.number_of_users,
number_of_users
);
perp_market.number_of_users = number_of_users;
} else {
msg!("perp_market.number_of_users: unchanged");
}
if let Some(number_of_users_with_base) = number_of_users_with_base {
msg!(
"perp_market.number_of_users_with_base: {:?} -> {:?}",
perp_market.number_of_users_with_base,
number_of_users_with_base
);
perp_market.number_of_users_with_base = number_of_users_with_base;
} else {
msg!("perp_market.number_of_users_with_base: unchanged");
}
validate!(
perp_market.number_of_users >= perp_market.number_of_users_with_base,
ErrorCode::DefaultError,
"number_of_users must be >= number_of_users_with_base "
)?;
Ok(())
}
pub fn handle_update_perp_market_fuel(
ctx: Context<AdminUpdatePerpMarket>,
fuel_boost_taker: Option<u8>,
fuel_boost_maker: Option<u8>,
fuel_boost_position: Option<u8>,
) -> Result<()> {
let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
msg!("perp market {}", perp_market.market_index);
if let Some(fuel_boost_taker) = fuel_boost_taker {
msg!(
"perp_market.fuel_boost_taker: {:?} -> {:?}",
perp_market.fuel_boost_taker,
fuel_boost_taker
);
perp_market.fuel_boost_taker = fuel_boost_taker;
} else {
msg!("perp_market.fuel_boost_taker: unchanged");
}
if let Some(fuel_boost_maker) = fuel_boost_maker {
msg!(
"perp_market.fuel_boost_maker: {:?} -> {:?}",
perp_market.fuel_boost_maker,
fuel_boost_maker
);
perp_market.fuel_boost_maker = fuel_boost_maker;
} else {
msg!("perp_market.fuel_boost_maker: unchanged");
}
if let Some(fuel_boost_position) = fuel_boost_position {
msg!(
"perp_market.fuel_boost_position: {:?} -> {:?}",
perp_market.fuel_boost_position,
fuel_boost_position
);
perp_market.fuel_boost_position = fuel_boost_position;
} else {
msg!("perp_market.fuel_boost_position: unchanged");
}
Ok(())
}
#[access_control(
spot_market_valid(&ctx.accounts.spot_market)
)]
pub fn handle_update_spot_market_fee_adjustment(
ctx: Context<AdminUpdateSpotMarket>,
fee_adjustment: i16,
) -> Result<()> {
let spot = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot.market_index);
validate!(
fee_adjustment.unsigned_abs().cast::<u64>()? <= FEE_ADJUSTMENT_MAX,
ErrorCode::DefaultError,
"fee adjustment {} greater than max {}",
fee_adjustment,
FEE_ADJUSTMENT_MAX
)?;
msg!(
"spot_market.fee_adjustment: {:?} -> {:?}",
spot.fee_adjustment,
fee_adjustment
);
spot.fee_adjustment = fee_adjustment;
Ok(())
}
pub fn handle_update_spot_market_fuel(
ctx: Context<AdminUpdateSpotMarket>,
fuel_boost_deposits: Option<u8>,
fuel_boost_borrows: Option<u8>,
fuel_boost_taker: Option<u8>,
fuel_boost_maker: Option<u8>,
fuel_boost_insurance: Option<u8>,
) -> Result<()> {
let spot_market = &mut load_mut!(ctx.accounts.spot_market)?;
msg!("spot market {}", spot_market.market_index);
if let Some(fuel_boost_taker) = fuel_boost_taker {
msg!(
"spot_market.fuel_boost_taker: {:?} -> {:?}",
spot_market.fuel_boost_taker,
fuel_boost_taker
);
spot_market.fuel_boost_taker = fuel_boost_taker;
} else {
msg!("spot_market.fuel_boost_taker: unchanged");
}
if let Some(fuel_boost_maker) = fuel_boost_maker {
msg!(
"spot_market.fuel_boost_maker: {:?} -> {:?}",
spot_market.fuel_boost_maker,
fuel_boost_maker
);
spot_market.fuel_boost_maker = fuel_boost_maker;
} else {
msg!("spot_market.fuel_boost_maker: unchanged");
}
if let Some(fuel_boost_deposits) = fuel_boost_deposits {
msg!(
"spot_market.fuel_boost_deposits: {:?} -> {:?}",
spot_market.fuel_boost_deposits,
fuel_boost_deposits
);
spot_market.fuel_boost_deposits = fuel_boost_deposits;
} else {
msg!("spot_market.fuel_boost_deposits: unchanged");
}
if let Some(fuel_boost_borrows) = fuel_boost_borrows {
msg!(
"spot_market.fuel_boost_borrows: {:?} -> {:?}",
spot_market.fuel_boost_borrows,
fuel_boost_borrows
);
spot_market.fuel_boost_borrows = fuel_boost_borrows;
} else {
msg!("spot_market.fuel_boost_borrows: unchanged");
}
if let Some(fuel_boost_insurance) = fuel_boost_insurance {
msg!(
"spot_market.fuel_boost_insurance: {:?} -> {:?}",
spot_market.fuel_boost_insurance,
fuel_boost_insurance
);
spot_market.fuel_boost_insurance = fuel_boost_insurance;
} else {
msg!("spot_market.fuel_boost_insurance: unchanged");
}
Ok(())
}
pub fn handle_update_admin(ctx: Context<AdminUpdateState>, admin: Pubkey) -> Result<()> {
msg!("admin: {:?} -> {:?}", ctx.accounts.state.admin, admin);
ctx.accounts.state.admin = admin;
Ok(())
}
pub fn handle_update_whitelist_mint(
ctx: Context<AdminUpdateState>,
whitelist_mint: Pubkey,
) -> Result<()> {
msg!(
"whitelist_mint: {:?} -> {:?}",
ctx.accounts.state.whitelist_mint,
whitelist_mint
);
ctx.accounts.state.whitelist_mint = whitelist_mint;
Ok(())
}
pub fn handle_update_discount_mint(
ctx: Context<AdminUpdateState>,
discount_mint: Pubkey,
) -> Result<()> {
msg!(
"discount_mint: {:?} -> {:?}",
ctx.accounts.state.discount_mint,
discount_mint
);
ctx.accounts.state.discount_mint = discount_mint;
Ok(())
}
pub fn handle_update_exchange_status(
ctx: Context<AdminUpdateState>,
exchange_status: u8,
) -> Result<()> {
msg!(
"exchange_status: {:?} -> {:?}",
ctx.accounts.state.exchange_status,
exchange_status
);
ctx.accounts.state.exchange_status = exchange_status;
Ok(())
}
pub fn handle_update_perp_auction_duration(
ctx: Context<AdminUpdateState>,
min_perp_auction_duration: u8,
) -> Result<()> {
msg!(
"min_perp_auction_duration: {:?} -> {:?}",
ctx.accounts.state.min_perp_auction_duration,
min_perp_auction_duration
);
ctx.accounts.state.min_perp_auction_duration = min_perp_auction_duration;
Ok(())
}
pub fn handle_update_spot_auction_duration(
ctx: Context<AdminUpdateState>,
default_spot_auction_duration: u8,
) -> Result<()> {
msg!(
"default_spot_auction_duration: {:?} -> {:?}",
ctx.accounts.state.default_spot_auction_duration,
default_spot_auction_duration
);
ctx.accounts.state.default_spot_auction_duration = default_spot_auction_duration;
Ok(())
}
pub fn handle_admin_disable_update_perp_bid_ask_twap(
ctx: Context<AdminDisableBidAskTwapUpdate>,
disable: bool,
) -> Result<()> {
let mut user_stats = load_mut!(ctx.accounts.user_stats)?;
msg!(
"disable_update_perp_bid_ask_twap: {:?} -> {:?}",
user_stats.disable_update_perp_bid_ask_twap,
disable
);
user_stats.disable_update_perp_bid_ask_twap = disable;
Ok(())
}
pub fn handle_initialize_protocol_if_shares_transfer_config(
ctx: Context<InitializeProtocolIfSharesTransferConfig>,
) -> Result<()> {
let mut config = ctx
.accounts
.protocol_if_shares_transfer_config
.load_init()?;
let now = Clock::get()?.unix_timestamp;
msg!(
"next_epoch_ts: {:?} -> {:?}",
config.next_epoch_ts,
now.safe_add(EPOCH_DURATION)?
);
config.next_epoch_ts = now.safe_add(EPOCH_DURATION)?;
Ok(())
}
pub fn handle_update_protocol_if_shares_transfer_config(
ctx: Context<UpdateProtocolIfSharesTransferConfig>,
whitelisted_signers: Option<[Pubkey; 4]>,
max_transfer_per_epoch: Option<u128>,
) -> Result<()> {
let mut config = ctx.accounts.protocol_if_shares_transfer_config.load_mut()?;
if let Some(whitelisted_signers) = whitelisted_signers {
msg!(
"whitelisted_signers: {:?} -> {:?}",
config.whitelisted_signers,
whitelisted_signers
);
config.whitelisted_signers = whitelisted_signers;
} else {
msg!("whitelisted_signers: unchanged");
}
if let Some(max_transfer_per_epoch) = max_transfer_per_epoch {
msg!(
"max_transfer_per_epoch: {:?} -> {:?}",
config.max_transfer_per_epoch,
max_transfer_per_epoch
);
config.max_transfer_per_epoch = max_transfer_per_epoch;
} else {
msg!("max_transfer_per_epoch: unchanged");
}
Ok(())
}
pub fn handle_initialize_prelaunch_oracle(
ctx: Context<InitializePrelaunchOracle>,
params: PrelaunchOracleParams,
) -> Result<()> {
let mut oracle = ctx.accounts.prelaunch_oracle.load_init()?;
msg!("perp market {}", params.perp_market_index);
oracle.perp_market_index = params.perp_market_index;
if let Some(price) = params.price {
oracle.price = price;
}
if let Some(max_price) = params.max_price {
oracle.max_price = max_price;
}
oracle.validate()?;
Ok(())
}
pub fn handle_update_prelaunch_oracle_params(
ctx: Context<UpdatePrelaunchOracleParams>,
params: PrelaunchOracleParams,
) -> Result<()> {
let mut oracle = ctx.accounts.prelaunch_oracle.load_mut()?;
let mut perp_market = ctx.accounts.perp_market.load_mut()?;
msg!("perp market {}", perp_market.market_index);
let now = Clock::get()?.unix_timestamp;
if let Some(price) = params.price {
oracle.price = price;
msg!("before mark twap ts = {:?} mark twap = {:?} mark twap 5min = {:?} bid twap = {:?} ask twap {:?}", perp_market.amm.last_mark_price_twap_ts, perp_market.amm.last_mark_price_twap, perp_market.amm.last_mark_price_twap_5min, perp_market.amm.last_bid_price_twap, perp_market.amm.last_ask_price_twap);
perp_market.amm.last_mark_price_twap_ts = now;
perp_market.amm.last_mark_price_twap = price.cast()?;
perp_market.amm.last_mark_price_twap_5min = price.cast()?;
perp_market.amm.last_bid_price_twap =
perp_market.amm.last_bid_price_twap.min(price.cast()?);
perp_market.amm.last_ask_price_twap =
perp_market.amm.last_ask_price_twap.max(price.cast()?);
msg!("after mark twap ts = {:?} mark twap = {:?} mark twap 5min = {:?} bid twap = {:?} ask twap {:?}", perp_market.amm.last_mark_price_twap_ts, perp_market.amm.last_mark_price_twap, perp_market.amm.last_mark_price_twap_5min, perp_market.amm.last_bid_price_twap, perp_market.amm.last_ask_price_twap);
} else {
msg!("mark twap ts, mark twap, mark twap 5min, bid twap, ask twap: unchanged");
}
if let Some(max_price) = params.max_price {
msg!("max price: {:?} -> {:?}", oracle.max_price, max_price);
oracle.max_price = max_price;
} else {
msg!("max price: unchanged")
}
oracle.validate()?;
Ok(())
}
pub fn handle_delete_prelaunch_oracle(
ctx: Context<DeletePrelaunchOracle>,
_perp_market_index: u16,
) -> Result<()> {
let perp_market = ctx.accounts.perp_market.load()?;
msg!("perp market {}", perp_market.market_index);
validate!(
perp_market.amm.oracle != ctx.accounts.prelaunch_oracle.key(),
ErrorCode::DefaultError,
"prelaunch oracle currently in use"
)?;
Ok(())
}
pub fn handle_initialize_pyth_pull_oracle(
ctx: Context<InitPythPullPriceFeed>,
feed_id: [u8; 32],
) -> Result<()> {
let cpi_program = ctx.accounts.pyth_solana_receiver.to_account_info();
let cpi_accounts = InitPriceUpdate {
payer: ctx.accounts.admin.to_account_info(),
price_update_account: ctx.accounts.price_feed.to_account_info(),
system_program: ctx.accounts.system_program.to_account_info(),
write_authority: ctx.accounts.price_feed.to_account_info(),
};
let seeds = &[
PTYH_PRICE_FEED_SEED_PREFIX,
feed_id.as_ref(),
&[ctx.bumps.price_feed],
];
let signer_seeds = &[&seeds[..]];
let cpi_context = CpiContext::new_with_signer(cpi_program, cpi_accounts, signer_seeds);
pyth_solana_receiver_sdk::cpi::init_price_update(cpi_context, feed_id)?;
Ok(())
}
pub fn handle_initialize_pyth_lazer_oracle(
ctx: Context<InitPythLazerOracle>,
feed_id: u32,
) -> Result<()> {
let pubkey = ctx.accounts.lazer_oracle.to_account_info().key;
msg!(
"Lazer price feed initted {} with feed_id {}",
pubkey,
feed_id
);
Ok(())
}
pub fn handle_settle_expired_market<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, AdminUpdatePerpMarket<'info>>,
market_index: u16,
) -> Result<()> {
let clock = Clock::get()?;
let _now = clock.unix_timestamp;
let state = &ctx.accounts.state;
let AccountMaps {
perp_market_map,
spot_market_map,
mut oracle_map,
} = load_maps(
&mut ctx.remaining_accounts.iter().peekable(),
&get_writable_perp_market_set(market_index),
&get_writable_spot_market_set(QUOTE_SPOT_MARKET_INDEX),
clock.slot,
Some(state.oracle_guard_rails),
)?;
controller::repeg::update_amm(
market_index,
&perp_market_map,
&mut oracle_map,
state,
&clock,
)?;
controller::repeg::settle_expired_market(
market_index,
&perp_market_map,
&mut oracle_map,
&spot_market_map,
state,
&clock,
)?;
Ok(())
}
pub fn handle_initialize_high_leverage_mode_config(
ctx: Context<InitializeHighLeverageModeConfig>,
max_users: u32,
) -> Result<()> {
let mut config = ctx.accounts.high_leverage_mode_config.load_init()?;
config.max_users = max_users;
config.validate()?;
Ok(())
}
pub fn handle_update_high_leverage_mode_config(
ctx: Context<UpdateHighLeverageModeConfig>,
max_users: u32,
reduce_only: bool,
) -> Result<()> {
let mut config = load_mut!(ctx.accounts.high_leverage_mode_config)?;
config.max_users = max_users;
config.reduce_only = reduce_only as u8;
config.validate()?;
Ok(())
}
pub fn handle_initialize_protected_maker_mode_config(
ctx: Context<InitializeProtectedMakerModeConfig>,
max_users: u32,
) -> Result<()> {
let mut config = ctx.accounts.protected_maker_mode_config.load_init()?;
config.max_users = max_users;
Ok(())
}
pub fn handle_update_protected_maker_mode_config(
ctx: Context<UpdateProtectedMakerModeConfig>,
max_users: u32,
reduce_only: bool,
) -> Result<()> {
let mut config = load_mut!(ctx.accounts.protected_maker_mode_config)?;
config.max_users = max_users;
config.reduce_only = reduce_only as u8;
config.validate()?;
Ok(())
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
init,
seeds = [b"drift_state".as_ref()],
space = State::SIZE,
bump,
payer = admin
)]
pub state: Box<Account<'info, State>>,
pub quote_asset_mint: Box<InterfaceAccount<'info, Mint>>,
/// CHECK: checked in `initialize`
pub drift_signer: AccountInfo<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
pub struct InitializeSpotMarket<'info> {
#[account(
init,
seeds = [b"spot_market", state.number_of_spot_markets.to_le_bytes().as_ref()],
space = SpotMarket::SIZE,
bump,
payer = admin
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
pub spot_market_mint: Box<InterfaceAccount<'info, Mint>>,
#[account(
init,
seeds = [b"spot_market_vault".as_ref(), state.number_of_spot_markets.to_le_bytes().as_ref()],
bump,
payer = admin,
token::mint = spot_market_mint,
token::authority = drift_signer
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
init,
seeds = [b"insurance_fund_vault".as_ref(), state.number_of_spot_markets.to_le_bytes().as_ref()],
bump,
payer = admin,
token::mint = spot_market_mint,
token::authority = drift_signer
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: program signer
pub drift_signer: AccountInfo<'info>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
/// CHECK: checked in `initialize_spot_market`
pub oracle: AccountInfo<'info>,
#[account(mut)]
pub admin: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(market_index: u16)]
pub struct DeleteInitializedSpotMarket<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut, close = admin)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
seeds = [b"insurance_fund_vault".as_ref(), market_index.to_le_bytes().as_ref()],
bump,
)]
pub insurance_fund_vault: Box<InterfaceAccount<'info, TokenAccount>>,
/// CHECK: program signer
pub drift_signer: AccountInfo<'info>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
#[instruction(market_index: u16)]
pub struct InitializeSerumFulfillmentConfig<'info> {
#[account(
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump,
)]
pub base_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
bump,
)]
pub quote_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
/// CHECK: checked in ix
pub serum_program: AccountInfo<'info>,
/// CHECK: checked in ix
pub serum_market: AccountInfo<'info>,
#[account(
mut,
seeds = [b"serum_open_orders".as_ref(), serum_market.key.as_ref()],
bump,
)]
/// CHECK: checked in ix
pub serum_open_orders: AccountInfo<'info>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: program signer
pub drift_signer: AccountInfo<'info>,
#[account(
init,
seeds = [b"serum_fulfillment_config".as_ref(), serum_market.key.as_ref()],
space = SerumV3FulfillmentConfig::SIZE,
bump,
payer = admin,
)]
pub serum_fulfillment_config: AccountLoader<'info, SerumV3FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdateSerumFulfillmentConfig<'info> {
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub serum_fulfillment_config: AccountLoader<'info, SerumV3FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
}
#[derive(Accounts)]
#[instruction(market_index: u16)]
pub struct InitializePhoenixFulfillmentConfig<'info> {
#[account(
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump,
)]
pub base_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
bump,
)]
pub quote_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
/// CHECK: checked in ix
pub phoenix_program: AccountInfo<'info>,
/// CHECK: checked in ix
pub phoenix_market: AccountInfo<'info>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: program signer
pub drift_signer: AccountInfo<'info>,
#[account(
init,
seeds = [b"phoenix_fulfillment_config".as_ref(), phoenix_market.key.as_ref()],
space = PhoenixV1FulfillmentConfig::SIZE,
bump,
payer = admin,
)]
pub phoenix_fulfillment_config: AccountLoader<'info, PhoenixV1FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdatePhoenixFulfillmentConfig<'info> {
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub phoenix_fulfillment_config: AccountLoader<'info, PhoenixV1FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
}
#[derive(Accounts)]
pub struct UpdateSerumVault<'info> {
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub admin: Signer<'info>,
pub srm_vault: Box<InterfaceAccount<'info, TokenAccount>>,
}
#[derive(Accounts)]
pub struct InitializePerpMarket<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(
init,
seeds = [b"perp_market", state.number_of_markets.to_le_bytes().as_ref()],
space = PerpMarket::SIZE,
bump,
payer = admin
)]
pub perp_market: AccountLoader<'info, PerpMarket>,
/// CHECK: checked in `initialize_perp_market`
pub oracle: AccountInfo<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct DeleteInitializedPerpMarket<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut, close = admin)]
pub perp_market: AccountLoader<'info, PerpMarket>,
}
#[derive(Accounts)]
pub struct AdminUpdatePerpMarket<'info> {
pub admin: Signer<'info>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
}
#[derive(Accounts)]
pub struct AdminUpdatePerpMarketAmmSummaryStats<'info> {
#[account(
constraint = admin.key() == admin_hot_wallet::id() || admin.key() == state.admin
)]
pub admin: Signer<'info>,
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
#[account(
seeds = [b"spot_market", perp_market.load()?.quote_spot_market_index.to_le_bytes().as_ref()],
bump,
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
/// CHECK: checked in `admin_update_perp_market_summary_stats` ix constraint
pub oracle: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct SettleExpiredMarketPoolsToRevenuePool<'info> {
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
pub admin: Signer<'info>,
#[account(
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
bump,
mut
)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
}
#[derive(Accounts)]
pub struct DepositIntoMarketFeePool<'info> {
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
pub admin: Signer<'info>,
#[account(
mut,
token::authority = admin
)]
pub source_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: withdraw fails if this isn't vault owner
pub drift_signer: AccountInfo<'info>,
#[account(
mut,
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
bump,
)]
pub quote_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
seeds = [b"spot_market_vault".as_ref(), 0_u16.to_le_bytes().as_ref()],
bump,
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
pub struct DepositIntoSpotMarketVault<'info> {
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub spot_market: AccountLoader<'info, SpotMarket>,
#[account(
constraint = admin.key() == admin_hot_wallet::id() || admin.key() == state.admin
)]
pub admin: Signer<'info>,
#[account(
mut,
token::authority = admin
)]
pub source_vault: Box<InterfaceAccount<'info, TokenAccount>>,
#[account(
mut,
constraint = spot_market.load()?.vault == spot_market_vault.key()
)]
pub spot_market_vault: Box<InterfaceAccount<'info, TokenAccount>>,
pub token_program: Interface<'info, TokenInterface>,
}
#[derive(Accounts)]
pub struct RepegCurve<'info> {
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
/// CHECK: checked in `repeg_curve` ix constraint
pub oracle: AccountInfo<'info>,
pub admin: Signer<'info>,
}
#[derive(Accounts)]
pub struct AdminUpdateState<'info> {
pub admin: Signer<'info>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
}
#[derive(Accounts)]
pub struct AdminUpdateK<'info> {
pub admin: Signer<'info>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub perp_market: AccountLoader<'info, PerpMarket>,
/// CHECK: checked in `admin_update_k` ix constraint
pub oracle: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct AdminUpdateSpotMarket<'info> {
pub admin: Signer<'info>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub spot_market: AccountLoader<'info, SpotMarket>,
}
#[derive(Accounts)]
pub struct AdminUpdateSpotMarketOracle<'info> {
pub admin: Signer<'info>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub spot_market: AccountLoader<'info, SpotMarket>,
/// CHECK: checked in `initialize_spot_market`
pub oracle: AccountInfo<'info>,
}
#[derive(Accounts)]
pub struct AdminDisableBidAskTwapUpdate<'info> {
pub admin: Signer<'info>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct InitUserFuel<'info> {
#[account(
constraint = admin.key() == admin_hot_wallet::id() || admin.key() == state.admin
)]
pub admin: Signer<'info>, // todo
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub user: AccountLoader<'info, User>,
#[account(mut)]
pub user_stats: AccountLoader<'info, UserStats>,
}
#[derive(Accounts)]
pub struct InitializeProtocolIfSharesTransferConfig<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
init,
seeds = [b"if_shares_transfer_config".as_ref()],
space = ProtocolIfSharesTransferConfig::SIZE,
bump,
payer = admin
)]
pub protocol_if_shares_transfer_config: AccountLoader<'info, ProtocolIfSharesTransferConfig>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdateProtocolIfSharesTransferConfig<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
seeds = [b"if_shares_transfer_config".as_ref()],
bump,
)]
pub protocol_if_shares_transfer_config: AccountLoader<'info, ProtocolIfSharesTransferConfig>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
}
#[derive(Accounts)]
#[instruction(params: PrelaunchOracleParams,)]
pub struct InitializePrelaunchOracle<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
init,
seeds = [b"prelaunch_oracle".as_ref(), params.perp_market_index.to_le_bytes().as_ref()],
space = PrelaunchOracle::SIZE,
bump,
payer = admin
)]
pub prelaunch_oracle: AccountLoader<'info, PrelaunchOracle>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
#[instruction(params: PrelaunchOracleParams,)]
pub struct UpdatePrelaunchOracleParams<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
seeds = [b"prelaunch_oracle".as_ref(), params.perp_market_index.to_le_bytes().as_ref()],
bump,
)]
pub prelaunch_oracle: AccountLoader<'info, PrelaunchOracle>,
#[account(
mut,
constraint = perp_market.load()?.market_index == params.perp_market_index
)]
pub perp_market: AccountLoader<'info, PerpMarket>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
}
#[derive(Accounts)]
#[instruction(perp_market_index: u16,)]
pub struct DeletePrelaunchOracle<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
seeds = [b"prelaunch_oracle".as_ref(), perp_market_index.to_le_bytes().as_ref()],
bump,
close = admin
)]
pub prelaunch_oracle: AccountLoader<'info, PrelaunchOracle>,
#[account(
constraint = perp_market.load()?.market_index == perp_market_index
)]
pub perp_market: AccountLoader<'info, PerpMarket>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
}
#[derive(Accounts)]
#[instruction(market_index: u16)]
pub struct InitializeOpenbookV2FulfillmentConfig<'info> {
#[account(
seeds = [b"spot_market", market_index.to_le_bytes().as_ref()],
bump,
)]
pub base_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
seeds = [b"spot_market", 0_u16.to_le_bytes().as_ref()],
bump,
)]
pub quote_spot_market: AccountLoader<'info, SpotMarket>,
#[account(
mut,
has_one = admin
)]
pub state: Box<Account<'info, State>>,
/// CHECK: checked in ix
pub openbook_v2_program: AccountInfo<'info>,
/// CHECK: checked in ix
pub openbook_v2_market: AccountInfo<'info>,
#[account(
constraint = state.signer.eq(&drift_signer.key())
)]
/// CHECK: program signer
pub drift_signer: AccountInfo<'info>,
#[account(
init,
seeds = [b"openbook_v2_fulfillment_config".as_ref(), openbook_v2_market.key.as_ref()],
space = OpenbookV2FulfillmentConfig::SIZE,
bump,
payer = admin,
)]
pub openbook_v2_fulfillment_config: AccountLoader<'info, OpenbookV2FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdateOpenbookV2FulfillmentConfig<'info> {
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
#[account(mut)]
pub openbook_v2_fulfillment_config: AccountLoader<'info, OpenbookV2FulfillmentConfig>,
#[account(mut)]
pub admin: Signer<'info>,
}
#[derive(Accounts)]
#[instruction(feed_id : [u8; 32])]
pub struct InitPythPullPriceFeed<'info> {
#[account(
mut,
constraint = admin.key() == admin_hot_wallet::id() || admin.key() == state.admin
)]
pub admin: Signer<'info>,
pub pyth_solana_receiver: Program<'info, PythSolanaReceiver>,
/// CHECK: This account's seeds are checked
#[account(mut, seeds = [PTYH_PRICE_FEED_SEED_PREFIX, &feed_id], bump)]
pub price_feed: AccountInfo<'info>,
pub system_program: Program<'info, System>,
pub state: Box<Account<'info, State>>,
}
#[derive(Accounts)]
#[instruction(feed_id: u32)]
pub struct InitPythLazerOracle<'info> {
#[account(
mut,
constraint = admin.key() == admin_hot_wallet::id() || admin.key() == state.admin
)]
pub admin: Signer<'info>,
#[account(init, seeds = [PYTH_LAZER_ORACLE_SEED, &feed_id.to_le_bytes()],
space=PythLazerOracle::SIZE,
bump,
payer=admin
)]
pub lazer_oracle: AccountLoader<'info, PythLazerOracle>,
pub state: Box<Account<'info, State>>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct InitializeHighLeverageModeConfig<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
init,
seeds = [b"high_leverage_mode_config".as_ref()],
space = HighLeverageModeConfig::SIZE,
bump,
payer = admin
)]
pub high_leverage_mode_config: AccountLoader<'info, HighLeverageModeConfig>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdateHighLeverageModeConfig<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
seeds = [b"high_leverage_mode_config".as_ref()],
bump,
)]
pub high_leverage_mode_config: AccountLoader<'info, HighLeverageModeConfig>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
}
#[derive(Accounts)]
pub struct InitializeProtectedMakerModeConfig<'info> {
#[account(
mut,
constraint = admin.key() == admin_hot_wallet::id() || admin.key() == state.admin
)]
pub admin: Signer<'info>,
#[account(
init,
seeds = [b"protected_maker_mode_config".as_ref()],
space = ProtectedMakerModeConfig::SIZE,
bump,
payer = admin
)]
pub protected_maker_mode_config: AccountLoader<'info, ProtectedMakerModeConfig>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
pub rent: Sysvar<'info, Rent>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdateProtectedMakerModeConfig<'info> {
#[account(mut)]
pub admin: Signer<'info>,
#[account(
mut,
seeds = [b"protected_maker_mode_config".as_ref()],
bump,
)]
pub protected_maker_mode_config: AccountLoader<'info, ProtectedMakerModeConfig>,
#[account(
has_one = admin
)]
pub state: Box<Account<'info, State>>,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/instructions/pyth_lazer_oracle.rs
|
use crate::error::ErrorCode;
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
use crate::state::pyth_lazer_oracle::{
PythLazerOracle, PYTH_LAZER_ORACLE_SEED, PYTH_LAZER_STORAGE_ID,
};
use crate::validate;
use anchor_lang::prelude::*;
use pyth_lazer_sdk::protocol::payload::{PayloadData, PayloadPropertyValue};
use pyth_lazer_sdk::protocol::router::Price;
use solana_program::sysvar::instructions::load_current_index_checked;
pub fn handle_update_pyth_lazer_oracle<'c: 'info, 'info>(
ctx: Context<'_, '_, 'c, 'info, UpdatePythLazerOracle>,
pyth_message: Vec<u8>,
) -> Result<()> {
// Verify the Pyth lazer message
let ix_idx = load_current_index_checked(&ctx.accounts.ix_sysvar.to_account_info())?;
validate!(
ix_idx > 0,
ErrorCode::InvalidVerificationIxIndex,
"instruction index must be greater than 0 to include the sig verify ix"
)?;
let verified = pyth_lazer_sdk::verify_message(
&ctx.accounts.pyth_lazer_storage,
&ctx.accounts.ix_sysvar.to_account_info(),
&pyth_message,
ix_idx - 1,
0,
0,
);
if verified.is_err() {
msg!("{:?}", verified);
return Err(ErrorCode::UnverifiedPythLazerMessage.into());
}
// Load oracle accounts from remaining accounts
let remaining_accounts = ctx.remaining_accounts;
validate!(
remaining_accounts.len() <= 3,
ErrorCode::OracleTooManyPriceAccountUpdates
)?;
let data = PayloadData::deserialize_slice_le(verified.unwrap().payload)
.map_err(|_| ProgramError::InvalidInstructionData)?;
let next_timestamp = data.timestamp_us.0;
validate!(
remaining_accounts.len() == data.feeds.len(),
ErrorCode::OracleMismatchedVaaAndPriceUpdates
)?;
for (account, payload_data) in remaining_accounts.iter().zip(data.feeds.iter()) {
let pyth_lazer_oracle_loader: AccountLoader<PythLazerOracle> =
AccountLoader::try_from(account)?;
let mut pyth_lazer_oracle = pyth_lazer_oracle_loader.load_mut()?;
let feed_id = payload_data.feed_id.0;
// Verify the pda
let pda = Pubkey::find_program_address(
&[PYTH_LAZER_ORACLE_SEED, &feed_id.to_le_bytes()],
&crate::ID,
)
.0;
require_keys_eq!(
*account.key,
pda,
ErrorCode::OracleBadRemainingAccountPublicKey
);
let current_timestamp = pyth_lazer_oracle.publish_time;
if next_timestamp > current_timestamp {
let PayloadPropertyValue::Price(Some(price)) = payload_data.properties[0] else {
return Err(ErrorCode::InvalidPythLazerMessage.into());
};
let mut best_bid_price: Option<Price> = None;
let mut best_ask_price: Option<Price> = None;
for property in &payload_data.properties {
match property {
PayloadPropertyValue::BestBidPrice(price) => best_bid_price = *price,
PayloadPropertyValue::BestAskPrice(price) => best_ask_price = *price,
_ => {}
}
}
// Default to 20bps of the price for conf if bid > ask or one-sided market
let mut conf: i64 = price.0.get().safe_div(500)?;
if let (Some(bid), Some(ask)) = (best_bid_price, best_ask_price) {
if bid.0.get() < ask.0.get() {
conf = ask.0.get() - bid.0.get();
}
}
pyth_lazer_oracle.price = price.0.get();
pyth_lazer_oracle.posted_slot = Clock::get()?.slot;
pyth_lazer_oracle.publish_time = next_timestamp;
pyth_lazer_oracle.conf = conf.cast::<u64>()?;
pyth_lazer_oracle.exponent = -8;
msg!("Price updated to {}", price.0.get());
msg!(
"Posting new lazer update. current ts {} < next ts {}",
current_timestamp,
next_timestamp
);
} else {
msg!(
"Skipping new lazer update. current ts {} >= next ts {}",
current_timestamp,
next_timestamp
);
}
}
Ok(())
}
#[derive(Accounts)]
pub struct UpdatePythLazerOracle<'info> {
#[account(mut)]
pub keeper: Signer<'info>,
/// CHECK: Pyth lazer storage account not available to us
#[account(
address = PYTH_LAZER_STORAGE_ID @ ErrorCode::InvalidPythLazerStorageOwner
)]
pub pyth_lazer_storage: AccountInfo<'info>,
/// CHECK: checked by ed25519 verify
#[account(address = solana_program::sysvar::instructions::ID)]
pub ix_sysvar: AccountInfo<'info>,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/swift_user.rs
|
use std::cell::{Ref, RefMut};
use crate::error::{DriftResult, ErrorCode};
use crate::math::safe_unwrap::SafeUnwrap;
use crate::{validate, ID};
use anchor_lang::prelude::Pubkey;
use anchor_lang::*;
use anchor_lang::{account, zero_copy};
use borsh::{BorshDeserialize, BorshSerialize};
use prelude::AccountInfo;
use solana_program::msg;
use crate::state::traits::Size;
pub const SWIFT_PDA_SEED: &str = "SWIFT";
pub const SWIFT_SLOT_EVICTION_BUFFER: u64 = 10;
mod tests;
#[zero_copy]
#[derive(Default, Eq, PartialEq, Debug, BorshDeserialize, BorshSerialize)]
pub struct SwiftOrderId {
pub uuid: [u8; 8],
pub max_slot: u64,
pub order_id: u32,
pub padding: u32,
}
impl SwiftOrderId {
pub fn new(uuid: [u8; 8], max_slot: u64, order_id: u32) -> Self {
Self {
uuid,
max_slot,
order_id,
padding: 0,
}
}
}
impl Size for SwiftUserOrders {
const SIZE: usize = 816;
}
/**
* This struct is a duplicate of SwiftUserOrdersZeroCopy
* It is used to give anchor an struct to generate the idl for clients
* The struct SwiftUserOrdersZeroCopy is used to load the data in efficiently
*/
#[account]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct SwiftUserOrders {
pub user_pubkey: Pubkey,
pub padding: u32,
pub swift_order_data: Vec<SwiftOrderId>,
}
impl SwiftUserOrders {
/// 8 orders - 268 bytes - 0.00275616 SOL for rent
/// 16 orders - 460 bytes - 0.00409248 SOL for rent
/// 32 orders - 844 bytes - 0.00676512 SOL for rent
/// 64 orders - 1612 bytes - 0.012110400 SOL for rent
pub fn space(num_orders: usize) -> usize {
8 + 32 + 4 + 32 + num_orders * 24
}
pub fn validate(&self) -> DriftResult<()> {
validate!(
self.swift_order_data.len() >= 1 && self.swift_order_data.len() <= 128,
ErrorCode::DefaultError,
"SwiftUserOrders len must be between 1 and 128"
)?;
Ok(())
}
}
#[zero_copy]
#[derive(Default, Eq, PartialEq, Debug)]
pub struct SwiftUserOrdersFixed {
pub user_pubkey: Pubkey,
pub padding: u32,
pub len: u32,
}
pub struct SwiftUserOrdersZeroCopy<'a> {
pub fixed: Ref<'a, SwiftUserOrdersFixed>,
pub data: Ref<'a, [u8]>,
}
impl<'a> SwiftUserOrdersZeroCopy<'a> {
pub fn len(&self) -> u32 {
self.fixed.len
}
pub fn get(&self, index: u32) -> &SwiftOrderId {
let size = std::mem::size_of::<SwiftOrderId>();
let start = index as usize * size;
bytemuck::from_bytes(&self.data[start..start + size])
}
pub fn iter(&self) -> impl Iterator<Item = &SwiftOrderId> + '_ {
(0..self.len()).map(move |i| self.get(i))
}
}
pub struct SwiftUserOrdersZeroCopyMut<'a> {
pub fixed: RefMut<'a, SwiftUserOrdersFixed>,
pub data: RefMut<'a, [u8]>,
}
impl<'a> SwiftUserOrdersZeroCopyMut<'a> {
pub fn len(&self) -> u32 {
self.fixed.len
}
pub fn get_mut(&mut self, index: u32) -> &mut SwiftOrderId {
let size = std::mem::size_of::<SwiftOrderId>();
let start = index as usize * size;
bytemuck::from_bytes_mut(&mut self.data[start..start + size])
}
pub fn check_exists_and_prune_stale_swift_order_ids(
&mut self,
swift_order_id: SwiftOrderId,
current_slot: u64,
) -> bool {
let mut uuid_exists = false;
for i in 0..self.len() {
let existing_swift_order_id = self.get_mut(i);
if existing_swift_order_id.uuid == swift_order_id.uuid
&& existing_swift_order_id.max_slot + SWIFT_SLOT_EVICTION_BUFFER >= current_slot
{
uuid_exists = true;
} else {
if existing_swift_order_id.max_slot + SWIFT_SLOT_EVICTION_BUFFER < current_slot {
existing_swift_order_id.uuid = [0; 8];
existing_swift_order_id.max_slot = 0;
existing_swift_order_id.order_id = 0;
}
}
}
uuid_exists
}
pub fn add_swift_order_id(&mut self, swift_order_id: SwiftOrderId) -> DriftResult {
if swift_order_id.max_slot == 0
|| swift_order_id.order_id == 0
|| swift_order_id.uuid == [0; 8]
{
return Err(ErrorCode::InvalidSwiftOrderId.into());
}
for i in 0..self.len() {
if self.get_mut(i).max_slot == 0 {
*self.get_mut(i) = swift_order_id;
return Ok(());
}
}
Err(ErrorCode::SwiftUserOrdersAccountFull.into())
}
}
pub trait SwiftUserOrdersLoader<'a> {
fn load(&self) -> DriftResult<SwiftUserOrdersZeroCopy>;
fn load_mut(&self) -> DriftResult<SwiftUserOrdersZeroCopyMut>;
}
impl<'a> SwiftUserOrdersLoader<'a> for AccountInfo<'a> {
fn load(&self) -> DriftResult<SwiftUserOrdersZeroCopy> {
let owner = self.owner;
validate!(
owner == &ID,
ErrorCode::DefaultError,
"invalid swift user orders owner",
)?;
let data = self.try_borrow_data().safe_unwrap()?;
let (discriminator, data) = Ref::map_split(data, |d| d.split_at(8));
validate!(
*discriminator == SwiftUserOrders::discriminator(),
ErrorCode::DefaultError,
"invalid swift user orders discriminator",
)?;
let (fixed, data) = Ref::map_split(data, |d| d.split_at(40));
Ok(SwiftUserOrdersZeroCopy {
fixed: Ref::map(fixed, |b| bytemuck::from_bytes(b)),
data,
})
}
fn load_mut(&self) -> DriftResult<SwiftUserOrdersZeroCopyMut> {
let owner = self.owner;
validate!(
owner == &ID,
ErrorCode::DefaultError,
"invalid swift user orders owner",
)?;
let data = self.try_borrow_mut_data().safe_unwrap()?;
let (discriminator, data) = RefMut::map_split(data, |d| d.split_at_mut(8));
validate!(
*discriminator == SwiftUserOrders::discriminator(),
ErrorCode::DefaultError,
"invalid swift user orders discriminator",
)?;
let (fixed, data) = RefMut::map_split(data, |d| d.split_at_mut(40));
Ok(SwiftUserOrdersZeroCopyMut {
fixed: RefMut::map(fixed, |b| bytemuck::from_bytes_mut(b)),
data,
})
}
}
pub fn derive_swift_user_pda(user_account_pubkey: &Pubkey) -> DriftResult<Pubkey> {
let (swift_pubkey, _) = Pubkey::find_program_address(
&[SWIFT_PDA_SEED.as_bytes(), user_account_pubkey.as_ref()],
&ID,
);
Ok(swift_pubkey)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/settle_pnl_mode.rs
|
use crate::error::{DriftResult, ErrorCode};
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::msg;
use std::panic::Location;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq)]
pub enum SettlePnlMode {
MustSettle,
TrySettle,
}
impl SettlePnlMode {
#[track_caller]
#[inline(always)]
pub fn result(self, error_code: ErrorCode, market_index: u16, msg: &str) -> DriftResult {
let caller = Location::caller();
msg!(msg);
msg!(
"Error {:?} for market {} at {}:{}",
error_code,
market_index,
caller.file(),
caller.line()
);
match self {
SettlePnlMode::MustSettle => Err(error_code),
SettlePnlMode::TrySettle => Ok(()),
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fulfillment.rs
|
use solana_program::pubkey::Pubkey;
#[derive(Debug, PartialEq, Eq)]
pub enum PerpFulfillmentMethod {
AMM(Option<u64>),
Match(Pubkey, u16),
}
#[derive(Debug)]
pub enum SpotFulfillmentMethod {
ExternalMarket,
Match(Pubkey, u16),
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/events.rs
|
use anchor_lang::prelude::*;
use borsh::{BorshDeserialize, BorshSerialize};
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode::InvalidOrder};
use crate::math::casting::Cast;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::order_params::OrderParams;
use crate::state::traits::Size;
use crate::state::user::{MarketType, Order};
use anchor_lang::Discriminator;
use std::io::Write;
#[event]
pub struct NewUserRecord {
/// unix_timestamp of action
pub ts: i64,
pub user_authority: Pubkey,
pub user: Pubkey,
pub sub_account_id: u16,
pub name: [u8; 32],
pub referrer: Pubkey,
}
#[event]
pub struct DepositRecord {
/// unix_timestamp of action
pub ts: i64,
pub user_authority: Pubkey,
/// user account public key
pub user: Pubkey,
pub direction: DepositDirection,
pub deposit_record_id: u64,
/// precision: token mint precision
pub amount: u64,
/// spot market index
pub market_index: u16,
/// precision: PRICE_PRECISION
pub oracle_price: i64,
/// precision: SPOT_BALANCE_PRECISION
pub market_deposit_balance: u128,
/// precision: SPOT_BALANCE_PRECISION
pub market_withdraw_balance: u128,
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub market_cumulative_deposit_interest: u128,
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub market_cumulative_borrow_interest: u128,
/// precision: QUOTE_PRECISION
pub total_deposits_after: u64,
/// precision: QUOTE_PRECISION
pub total_withdraws_after: u64,
pub explanation: DepositExplanation,
pub transfer_user: Option<Pubkey>,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Default)]
pub enum DepositExplanation {
#[default]
None,
Transfer,
Borrow,
RepayBorrow,
}
#[event]
pub struct SpotInterestRecord {
pub ts: i64,
pub market_index: u16,
/// precision: SPOT_BALANCE_PRECISION
pub deposit_balance: u128,
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub cumulative_deposit_interest: u128,
/// precision: SPOT_BALANCE_PRECISION
pub borrow_balance: u128,
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub cumulative_borrow_interest: u128,
/// precision: PERCENTAGE_PRECISION
pub optimal_utilization: u32,
/// precision: PERCENTAGE_PRECISION
pub optimal_borrow_rate: u32,
/// precision: PERCENTAGE_PRECISION
pub max_borrow_rate: u32,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Default)]
pub enum DepositDirection {
#[default]
Deposit,
Withdraw,
}
#[event]
pub struct FundingPaymentRecord {
pub ts: i64,
pub user_authority: Pubkey,
pub user: Pubkey,
pub market_index: u16,
/// precision: QUOTE_PRECISION
pub funding_payment: i64,
/// precision: BASE_PRECISION
pub base_asset_amount: i64,
/// precision: FUNDING_RATE_PRECISION
pub user_last_cumulative_funding: i64,
/// precision: FUNDING_RATE_PRECISION
pub amm_cumulative_funding_long: i128,
/// precision: FUNDING_RATE_PRECISION
pub amm_cumulative_funding_short: i128,
}
#[event]
pub struct FundingRateRecord {
pub ts: i64,
pub record_id: u64,
pub market_index: u16,
/// precision: FUNDING_RATE_PRECISION
pub funding_rate: i64,
/// precision: FUNDING_RATE_PRECISION
pub funding_rate_long: i128,
/// precision: FUNDING_RATE_PRECISION
pub funding_rate_short: i128,
/// precision: FUNDING_RATE_PRECISION
pub cumulative_funding_rate_long: i128,
/// precision: FUNDING_RATE_PRECISION
pub cumulative_funding_rate_short: i128,
/// precision: PRICE_PRECISION
pub oracle_price_twap: i64,
/// precision: PRICE_PRECISION
pub mark_price_twap: u64,
/// precision: QUOTE_PRECISION
pub period_revenue: i64,
/// precision: BASE_PRECISION
pub base_asset_amount_with_amm: i128,
/// precision: BASE_PRECISION
pub base_asset_amount_with_unsettled_lp: i128,
}
#[event]
pub struct CurveRecord {
pub ts: i64,
pub record_id: u64,
pub peg_multiplier_before: u128,
pub base_asset_reserve_before: u128,
pub quote_asset_reserve_before: u128,
pub sqrt_k_before: u128,
pub peg_multiplier_after: u128,
pub base_asset_reserve_after: u128,
pub quote_asset_reserve_after: u128,
pub sqrt_k_after: u128,
/// precision: BASE_PRECISION
pub base_asset_amount_long: u128,
/// precision: BASE_PRECISION
pub base_asset_amount_short: u128,
/// precision: BASE_PRECISION
pub base_asset_amount_with_amm: i128,
/// precision: QUOTE_PRECISION
pub total_fee: i128,
/// precision: QUOTE_PRECISION
pub total_fee_minus_distributions: i128,
/// precision: QUOTE_PRECISION
pub adjustment_cost: i128,
/// precision: PRICE_PRECISION
pub oracle_price: i64,
pub fill_record: u128,
pub number_of_users: u32,
pub market_index: u16,
}
#[event]
pub struct SwiftOrderRecord {
pub user: Pubkey,
pub hash: String,
pub matching_order_params: OrderParams,
pub user_order_id: u32,
pub swift_order_max_slot: u64,
pub swift_order_uuid: [u8; 8],
pub ts: i64,
}
#[event]
pub struct OrderRecord {
pub ts: i64,
pub user: Pubkey,
pub order: Order,
}
impl Size for OrderRecord {
const SIZE: usize = 192;
}
#[event]
pub struct OrderActionRecord {
pub ts: i64,
pub action: OrderAction,
pub action_explanation: OrderActionExplanation,
pub market_index: u16,
pub market_type: MarketType,
pub filler: Option<Pubkey>,
/// precision: QUOTE_PRECISION
pub filler_reward: Option<u64>,
pub fill_record_id: Option<u64>,
/// precision: BASE_PRECISION (perp) or MINT_PRECISION (spot)
pub base_asset_amount_filled: Option<u64>,
/// precision: QUOTE_PRECISION
pub quote_asset_amount_filled: Option<u64>,
/// precision: QUOTE_PRECISION
pub taker_fee: Option<u64>,
/// precision: QUOTE_PRECISION
pub maker_fee: Option<i64>,
/// precision: QUOTE_PRECISION
pub referrer_reward: Option<u32>,
/// precision: QUOTE_PRECISION
pub quote_asset_amount_surplus: Option<i64>,
/// precision: QUOTE_PRECISION
pub spot_fulfillment_method_fee: Option<u64>,
pub taker: Option<Pubkey>,
pub taker_order_id: Option<u32>,
pub taker_order_direction: Option<PositionDirection>,
/// precision: BASE_PRECISION (perp) or MINT_PRECISION (spot)
pub taker_order_base_asset_amount: Option<u64>,
/// precision: BASE_PRECISION (perp) or MINT_PRECISION (spot)
pub taker_order_cumulative_base_asset_amount_filled: Option<u64>,
/// precision: QUOTE_PRECISION
pub taker_order_cumulative_quote_asset_amount_filled: Option<u64>,
pub maker: Option<Pubkey>,
pub maker_order_id: Option<u32>,
pub maker_order_direction: Option<PositionDirection>,
/// precision: BASE_PRECISION (perp) or MINT_PRECISION (spot)
pub maker_order_base_asset_amount: Option<u64>,
/// precision: BASE_PRECISION (perp) or MINT_PRECISION (spot)
pub maker_order_cumulative_base_asset_amount_filled: Option<u64>,
/// precision: QUOTE_PRECISION
pub maker_order_cumulative_quote_asset_amount_filled: Option<u64>,
/// precision: PRICE_PRECISION
pub oracle_price: i64,
}
impl Size for OrderActionRecord {
const SIZE: usize = 384;
}
pub fn get_order_action_record(
ts: i64,
action: OrderAction,
action_explanation: OrderActionExplanation,
market_index: u16,
filler: Option<Pubkey>,
fill_record_id: Option<u64>,
filler_reward: Option<u64>,
base_asset_amount_filled: Option<u64>,
quote_asset_amount_filled: Option<u64>,
taker_fee: Option<u64>,
maker_rebate: Option<u64>,
referrer_reward: Option<u64>,
quote_asset_amount_surplus: Option<i64>,
spot_fulfillment_method_fee: Option<u64>,
taker: Option<Pubkey>,
taker_order: Option<Order>,
maker: Option<Pubkey>,
maker_order: Option<Order>,
oracle_price: i64,
) -> DriftResult<OrderActionRecord> {
Ok(OrderActionRecord {
ts,
action,
action_explanation,
market_index,
market_type: if let Some(taker_order) = taker_order {
taker_order.market_type
} else if let Some(maker_order) = maker_order {
maker_order.market_type
} else {
return Err(InvalidOrder);
},
filler,
filler_reward,
fill_record_id,
base_asset_amount_filled,
quote_asset_amount_filled,
taker_fee,
maker_fee: match maker_rebate {
Some(maker_rebate) => Some(-maker_rebate.cast()?),
None => None,
},
referrer_reward: match referrer_reward {
Some(referrer_reward) if referrer_reward > 0 => Some(referrer_reward.cast()?),
_ => None,
},
quote_asset_amount_surplus,
spot_fulfillment_method_fee,
taker,
taker_order_id: taker_order.map(|order| order.order_id),
taker_order_direction: taker_order.map(|order| order.direction),
taker_order_base_asset_amount: taker_order.map(|order| order.base_asset_amount),
taker_order_cumulative_base_asset_amount_filled: taker_order
.map(|order| order.base_asset_amount_filled),
taker_order_cumulative_quote_asset_amount_filled: taker_order
.as_ref()
.map(|order| order.quote_asset_amount_filled),
maker,
maker_order_id: maker_order.map(|order| order.order_id),
maker_order_direction: maker_order.map(|order| order.direction),
maker_order_base_asset_amount: maker_order.map(|order| order.base_asset_amount),
maker_order_cumulative_base_asset_amount_filled: maker_order
.map(|order| order.base_asset_amount_filled),
maker_order_cumulative_quote_asset_amount_filled: maker_order
.map(|order| order.quote_asset_amount_filled),
oracle_price,
})
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Default)]
pub enum OrderAction {
#[default]
Place,
Cancel,
Fill,
Trigger,
Expire,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq)]
pub enum OrderActionExplanation {
None,
InsufficientFreeCollateral,
OraclePriceBreachedLimitPrice,
MarketOrderFilledToLimitPrice,
OrderExpired,
Liquidation,
OrderFilledWithAMM,
OrderFilledWithAMMJit,
OrderFilledWithMatch,
OrderFilledWithMatchJit,
MarketExpired,
RiskingIncreasingOrder,
ReduceOnlyOrderIncreasedPosition,
OrderFillWithSerum,
NoBorrowLiquidity,
OrderFillWithPhoenix,
OrderFilledWithAMMJitLPSplit,
OrderFilledWithLPJit,
DeriskLp,
OrderFilledWithOpenbookV2,
}
#[event]
#[derive(Default)]
pub struct LPRecord {
pub ts: i64,
pub user: Pubkey,
pub action: LPAction,
/// precision: AMM_RESERVE_PRECISION
pub n_shares: u64,
pub market_index: u16,
/// precision: BASE_PRECISION
pub delta_base_asset_amount: i64,
/// precision: QUOTE_PRECISION
pub delta_quote_asset_amount: i64,
/// realized pnl of the position settlement
/// precision: QUOTE_PRECISION
pub pnl: i64,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Default)]
pub enum LPAction {
#[default]
AddLiquidity,
RemoveLiquidity,
SettleLiquidity,
RemoveLiquidityDerisk,
}
impl Size for LPRecord {
const SIZE: usize = 112;
}
#[event]
#[derive(Default)]
pub struct LiquidationRecord {
pub ts: i64,
pub liquidation_type: LiquidationType,
pub user: Pubkey,
pub liquidator: Pubkey,
pub margin_requirement: u128,
pub total_collateral: i128,
pub margin_freed: u64,
pub liquidation_id: u16,
pub bankrupt: bool,
pub canceled_order_ids: Vec<u32>,
pub liquidate_perp: LiquidatePerpRecord,
pub liquidate_spot: LiquidateSpotRecord,
pub liquidate_borrow_for_perp_pnl: LiquidateBorrowForPerpPnlRecord,
pub liquidate_perp_pnl_for_deposit: LiquidatePerpPnlForDepositRecord,
pub perp_bankruptcy: PerpBankruptcyRecord,
pub spot_bankruptcy: SpotBankruptcyRecord,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Default)]
pub enum LiquidationType {
#[default]
LiquidatePerp,
LiquidateSpot,
LiquidateBorrowForPerpPnl,
LiquidatePerpPnlForDeposit,
PerpBankruptcy,
SpotBankruptcy,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
pub struct LiquidatePerpRecord {
pub market_index: u16,
pub oracle_price: i64,
pub base_asset_amount: i64,
pub quote_asset_amount: i64,
/// precision: AMM_RESERVE_PRECISION
pub lp_shares: u64,
pub fill_record_id: u64,
pub user_order_id: u32,
pub liquidator_order_id: u32,
/// precision: QUOTE_PRECISION
pub liquidator_fee: u64,
/// precision: QUOTE_PRECISION
pub if_fee: u64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
pub struct LiquidateSpotRecord {
pub asset_market_index: u16,
pub asset_price: i64,
pub asset_transfer: u128,
pub liability_market_index: u16,
pub liability_price: i64,
/// precision: token mint precision
pub liability_transfer: u128,
/// precision: token mint precision
pub if_fee: u64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
pub struct LiquidateBorrowForPerpPnlRecord {
pub perp_market_index: u16,
pub market_oracle_price: i64,
pub pnl_transfer: u128,
pub liability_market_index: u16,
pub liability_price: i64,
pub liability_transfer: u128,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
pub struct LiquidatePerpPnlForDepositRecord {
pub perp_market_index: u16,
pub market_oracle_price: i64,
pub pnl_transfer: u128,
pub asset_market_index: u16,
pub asset_price: i64,
pub asset_transfer: u128,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
pub struct PerpBankruptcyRecord {
pub market_index: u16,
pub pnl: i128,
pub if_payment: u128,
pub clawback_user: Option<Pubkey>,
pub clawback_user_payment: Option<u128>,
pub cumulative_funding_rate_delta: i128,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug, Default)]
pub struct SpotBankruptcyRecord {
pub market_index: u16,
pub borrow_amount: u128,
pub if_payment: u128,
pub cumulative_deposit_interest_delta: u128,
}
#[event]
#[derive(Default)]
pub struct SettlePnlRecord {
pub ts: i64,
pub user: Pubkey,
pub market_index: u16,
pub pnl: i128,
pub base_asset_amount: i64,
pub quote_asset_amount_after: i64,
pub quote_entry_amount: i64,
pub settle_price: i64,
pub explanation: SettlePnlExplanation,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Default)]
pub enum SettlePnlExplanation {
#[default]
None,
ExpiredPosition,
}
#[event]
#[derive(Default)]
pub struct InsuranceFundRecord {
pub ts: i64,
pub spot_market_index: u16,
pub perp_market_index: u16,
/// precision: PERCENTAGE_PRECISION
pub user_if_factor: u32,
/// precision: PERCENTAGE_PRECISION
pub total_if_factor: u32,
/// precision: token mint precision
pub vault_amount_before: u64,
/// precision: token mint precision
pub insurance_vault_amount_before: u64,
pub total_if_shares_before: u128,
pub total_if_shares_after: u128,
/// precision: token mint precision
pub amount: i64,
}
#[event]
#[derive(Default)]
pub struct InsuranceFundStakeRecord {
pub ts: i64,
pub user_authority: Pubkey,
pub action: StakeAction,
/// precision: token mint precision
pub amount: u64,
pub market_index: u16,
/// precision: token mint precision
pub insurance_vault_amount_before: u64,
pub if_shares_before: u128,
pub user_if_shares_before: u128,
pub total_if_shares_before: u128,
pub if_shares_after: u128,
pub user_if_shares_after: u128,
pub total_if_shares_after: u128,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Default)]
pub enum StakeAction {
#[default]
Stake,
UnstakeRequest,
UnstakeCancelRequest,
Unstake,
UnstakeTransfer,
StakeTransfer,
}
#[event]
#[derive(Default)]
pub struct SwapRecord {
pub ts: i64,
pub user: Pubkey,
/// precision: out market mint precision
pub amount_out: u64,
/// precision: in market mint precision
pub amount_in: u64,
pub out_market_index: u16,
pub in_market_index: u16,
/// precision: PRICE_PRECISION
pub out_oracle_price: i64,
/// precision: PRICE_PRECISION
pub in_oracle_price: i64,
pub fee: u64,
}
#[event]
pub struct SpotMarketVaultDepositRecord {
pub ts: i64,
pub market_index: u16,
/// precision: SPOT_BALANCE_PRECISION
pub deposit_balance: u128,
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub cumulative_deposit_interest_before: u128,
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub cumulative_deposit_interest_after: u128,
pub deposit_token_amount_before: u64,
pub amount: u64,
}
#[event]
pub struct DeleteUserRecord {
/// unix_timestamp of action
pub ts: i64,
pub user_authority: Pubkey,
pub user: Pubkey,
pub sub_account_id: u16,
pub keeper: Option<Pubkey>,
}
pub fn emit_stack<T: AnchorSerialize + Discriminator, const N: usize>(event: T) -> DriftResult {
let mut data_buf = [0u8; N];
let mut out_buf = [0u8; N];
emit_buffers(event, &mut data_buf[..], &mut out_buf[..])
}
pub fn emit_buffers<T: AnchorSerialize + Discriminator>(
event: T,
data_buf: &mut [u8],
out_buf: &mut [u8],
) -> DriftResult {
let mut data_writer = std::io::Cursor::new(data_buf);
data_writer
.write_all(&<T as Discriminator>::discriminator())
.safe_unwrap()?;
borsh::to_writer(&mut data_writer, &event).safe_unwrap()?;
let data_len = data_writer.position() as usize;
let out_len = base64::encode_config_slice(
&data_writer.into_inner()[0..data_len],
base64::STANDARD,
out_buf,
);
let msg_bytes = &out_buf[0..out_len];
let msg_str = unsafe { std::str::from_utf8_unchecked(msg_bytes) };
msg!(msg_str);
Ok(())
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/paused_operations.rs
|
use solana_program::msg;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, PartialEq, Debug, Eq)]
pub enum PerpOperation {
UpdateFunding = 0b00000001,
AmmFill = 0b00000010,
Fill = 0b00000100,
SettlePnl = 0b00001000,
SettlePnlWithPosition = 0b00010000,
Liquidation = 0b00100000,
AmmImmediateFill = 0b01000000,
}
const ALL_PERP_OPERATIONS: [PerpOperation; 7] = [
PerpOperation::UpdateFunding,
PerpOperation::AmmFill,
PerpOperation::Fill,
PerpOperation::SettlePnl,
PerpOperation::SettlePnlWithPosition,
PerpOperation::Liquidation,
PerpOperation::AmmImmediateFill,
];
impl PerpOperation {
pub fn is_operation_paused(current: u8, operation: PerpOperation) -> bool {
current & operation as u8 != 0
}
pub fn log_all_operations_paused(current: u8) {
for operation in ALL_PERP_OPERATIONS.iter() {
if Self::is_operation_paused(current, *operation) {
msg!("{:?} is paused", operation);
}
}
}
}
#[derive(Clone, Copy, PartialEq, Debug, Eq)]
pub enum SpotOperation {
UpdateCumulativeInterest = 0b00000001,
Fill = 0b00000010,
Deposit = 0b00000100,
Withdraw = 0b00001000,
Liquidation = 0b00010000,
}
const ALL_SPOT_OPERATIONS: [SpotOperation; 5] = [
SpotOperation::UpdateCumulativeInterest,
SpotOperation::Fill,
SpotOperation::Deposit,
SpotOperation::Withdraw,
SpotOperation::Liquidation,
];
impl SpotOperation {
pub fn is_operation_paused(current: u8, operation: SpotOperation) -> bool {
current & operation as u8 != 0
}
pub fn log_all_operations_paused(current: u8) {
for operation in ALL_SPOT_OPERATIONS.iter() {
if Self::is_operation_paused(current, *operation) {
msg!("{:?} is paused", operation);
}
}
}
}
#[derive(Clone, Copy, PartialEq, Debug, Eq)]
pub enum InsuranceFundOperation {
Init = 0b00000001,
Add = 0b00000010,
RequestRemove = 0b00000100,
Remove = 0b00001000,
}
const ALL_IF_OPERATIONS: [InsuranceFundOperation; 4] = [
InsuranceFundOperation::Init,
InsuranceFundOperation::Add,
InsuranceFundOperation::RequestRemove,
InsuranceFundOperation::Remove,
];
impl InsuranceFundOperation {
pub fn is_operation_paused(current: u8, operation: InsuranceFundOperation) -> bool {
current & operation as u8 != 0
}
pub fn log_all_operations_paused(current: u8) {
for operation in ALL_IF_OPERATIONS.iter() {
if Self::is_operation_paused(current, *operation) {
msg!("{:?} is paused", operation);
}
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/perp_market.rs
|
use crate::state::pyth_lazer_oracle::PythLazerOracle;
use anchor_lang::prelude::*;
use crate::state::state::State;
use std::cmp::max;
use crate::controller::position::{PositionDelta, PositionDirection};
use crate::error::{DriftResult, ErrorCode};
use crate::math::amm;
use crate::math::casting::Cast;
#[cfg(test)]
use crate::math::constants::{
AMM_RESERVE_PRECISION, MAX_CONCENTRATION_COEFFICIENT, PRICE_PRECISION_I64,
};
use crate::math::constants::{
AMM_RESERVE_PRECISION_I128, AMM_TO_QUOTE_PRECISION_RATIO, BID_ASK_SPREAD_PRECISION,
BID_ASK_SPREAD_PRECISION_U128, DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT,
LIQUIDATION_FEE_PRECISION, LP_FEE_SLICE_DENOMINATOR, LP_FEE_SLICE_NUMERATOR, MARGIN_PRECISION,
MARGIN_PRECISION_U128, MAX_LIQUIDATION_MULTIPLIER, PEG_PRECISION, PERCENTAGE_PRECISION,
PERCENTAGE_PRECISION_I128, PERCENTAGE_PRECISION_I64, PERCENTAGE_PRECISION_U64, PRICE_PRECISION,
SPOT_WEIGHT_PRECISION, TWENTY_FOUR_HOUR,
};
use crate::math::helpers::get_proportion_i128;
use crate::math::margin::{
calculate_size_discount_asset_weight, calculate_size_premium_liability_weight,
MarginRequirementType,
};
use crate::math::safe_math::SafeMath;
use crate::math::stats;
use crate::state::events::OrderActionExplanation;
use num_integer::Roots;
use crate::state::oracle::{
get_prelaunch_price, get_sb_on_demand_price, get_switchboard_price, HistoricalOracleData,
OracleSource,
};
use crate::state::spot_market::{AssetTier, SpotBalance, SpotBalanceType};
use crate::state::traits::{MarketIndexOffset, Size};
use borsh::{BorshDeserialize, BorshSerialize};
use crate::state::paused_operations::PerpOperation;
use drift_macros::assert_no_slop;
use static_assertions::const_assert_eq;
use super::oracle_map::OracleIdentifier;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum MarketStatus {
/// warm up period for initialization, fills are paused
#[default]
Initialized,
/// all operations allowed
Active,
/// Deprecated in favor of PausedOperations
FundingPaused,
/// Deprecated in favor of PausedOperations
AmmPaused,
/// Deprecated in favor of PausedOperations
FillPaused,
/// Deprecated in favor of PausedOperations
WithdrawPaused,
/// fills only able to reduce liability
ReduceOnly,
/// market has determined settlement price and positions are expired must be settled
Settlement,
/// market has no remaining participants
Delisted,
}
impl MarketStatus {
pub fn validate_not_deprecated(&self) -> DriftResult {
if matches!(
self,
MarketStatus::FundingPaused
| MarketStatus::AmmPaused
| MarketStatus::FillPaused
| MarketStatus::WithdrawPaused
) {
msg!("MarketStatus is deprecated");
Err(ErrorCode::DefaultError)
} else {
Ok(())
}
}
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum ContractType {
#[default]
Perpetual,
Future,
Prediction,
}
#[derive(
Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, PartialOrd, Ord, Default,
)]
pub enum ContractTier {
/// max insurance capped at A level
A,
/// max insurance capped at B level
B,
/// max insurance capped at C level
C,
/// no insurance
Speculative,
/// no insurance, another tranches below
#[default]
HighlySpeculative,
/// no insurance, only single position allowed
Isolated,
}
impl ContractTier {
pub fn is_as_safe_as(&self, best_contract: &ContractTier, best_asset: &AssetTier) -> bool {
self.is_as_safe_as_contract(best_contract) && self.is_as_safe_as_asset(best_asset)
}
pub fn is_as_safe_as_contract(&self, other: &ContractTier) -> bool {
// Contract Tier A safest
self <= other
}
pub fn is_as_safe_as_asset(&self, other: &AssetTier) -> bool {
// allow Contract Tier A,B,C to rank above Assets below Collateral status
if other == &AssetTier::Unlisted {
true
} else {
other >= &AssetTier::Cross && self <= &ContractTier::C
}
}
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, PartialOrd, Ord)]
pub enum AMMLiquiditySplit {
ProtocolOwned,
LPOwned,
Shared,
}
impl AMMLiquiditySplit {
pub fn get_order_action_explanation(&self) -> OrderActionExplanation {
match &self {
AMMLiquiditySplit::ProtocolOwned => OrderActionExplanation::OrderFilledWithAMMJit,
AMMLiquiditySplit::LPOwned => OrderActionExplanation::OrderFilledWithLPJit,
AMMLiquiditySplit::Shared => OrderActionExplanation::OrderFilledWithAMMJitLPSplit,
}
}
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, PartialOrd, Ord)]
pub enum AMMAvailability {
Immediate,
AfterMinDuration,
Unavailable,
}
#[account(zero_copy(unsafe))]
#[derive(Eq, PartialEq, Debug)]
#[repr(C)]
pub struct PerpMarket {
/// The perp market's address. It is a pda of the market index
pub pubkey: Pubkey,
/// The automated market maker
pub amm: AMM,
/// The market's pnl pool. When users settle negative pnl, the balance increases.
/// When users settle positive pnl, the balance decreases. Can not go negative.
pub pnl_pool: PoolBalance,
/// Encoded display name for the perp market e.g. SOL-PERP
pub name: [u8; 32],
/// The perp market's claim on the insurance fund
pub insurance_claim: InsuranceClaim,
/// The max pnl imbalance before positive pnl asset weight is discounted
/// pnl imbalance is the difference between long and short pnl. When it's greater than 0,
/// the amm has negative pnl and the initial asset weight for positive pnl is discounted
/// precision = QUOTE_PRECISION
pub unrealized_pnl_max_imbalance: u64,
/// The ts when the market will be expired. Only set if market is in reduce only mode
pub expiry_ts: i64,
/// The price at which positions will be settled. Only set if market is expired
/// precision = PRICE_PRECISION
pub expiry_price: i64,
/// Every trade has a fill record id. This is the next id to be used
pub next_fill_record_id: u64,
/// Every funding rate update has a record id. This is the next id to be used
pub next_funding_rate_record_id: u64,
/// Every amm k updated has a record id. This is the next id to be used
pub next_curve_record_id: u64,
/// The initial margin fraction factor. Used to increase margin ratio for large positions
/// precision: MARGIN_PRECISION
pub imf_factor: u32,
/// The imf factor for unrealized pnl. Used to discount asset weight for large positive pnl
/// precision: MARGIN_PRECISION
pub unrealized_pnl_imf_factor: u32,
/// The fee the liquidator is paid for taking over perp position
/// precision: LIQUIDATOR_FEE_PRECISION
pub liquidator_fee: u32,
/// The fee the insurance fund receives from liquidation
/// precision: LIQUIDATOR_FEE_PRECISION
pub if_liquidation_fee: u32,
/// The margin ratio which determines how much collateral is required to open a position
/// e.g. margin ratio of .1 means a user must have $100 of total collateral to open a $1000 position
/// precision: MARGIN_PRECISION
pub margin_ratio_initial: u32,
/// The margin ratio which determines when a user will be liquidated
/// e.g. margin ratio of .05 means a user must have $50 of total collateral to maintain a $1000 position
/// else they will be liquidated
/// precision: MARGIN_PRECISION
pub margin_ratio_maintenance: u32,
/// The initial asset weight for positive pnl. Negative pnl always has an asset weight of 1
/// precision: SPOT_WEIGHT_PRECISION
pub unrealized_pnl_initial_asset_weight: u32,
/// The maintenance asset weight for positive pnl. Negative pnl always has an asset weight of 1
/// precision: SPOT_WEIGHT_PRECISION
pub unrealized_pnl_maintenance_asset_weight: u32,
/// number of users in a position (base)
pub number_of_users_with_base: u32,
/// number of users in a position (pnl) or pnl (quote)
pub number_of_users: u32,
pub market_index: u16,
/// Whether a market is active, reduce only, expired, etc
/// Affects whether users can open/close positions
pub status: MarketStatus,
/// Currently only Perpetual markets are supported
pub contract_type: ContractType,
/// The contract tier determines how much insurance a market can receive, with more speculative markets receiving less insurance
/// It also influences the order perp markets can be liquidated, with less speculative markets being liquidated first
pub contract_tier: ContractTier,
pub paused_operations: u8,
/// The spot market that pnl is settled in
pub quote_spot_market_index: u16,
/// Between -100 and 100, represents what % to increase/decrease the fee by
/// E.g. if this is -50 and the fee is 5bps, the new fee will be 2.5bps
/// if this is 50 and the fee is 5bps, the new fee will be 7.5bps
pub fee_adjustment: i16,
/// fuel multiplier for perp funding
/// precision: 10
pub fuel_boost_position: u8,
/// fuel multiplier for perp taker
/// precision: 10
pub fuel_boost_taker: u8,
/// fuel multiplier for perp maker
/// precision: 10
pub fuel_boost_maker: u8,
pub pool_id: u8,
pub high_leverage_margin_ratio_initial: u16,
pub high_leverage_margin_ratio_maintenance: u16,
pub padding: [u8; 38],
}
impl Default for PerpMarket {
fn default() -> Self {
PerpMarket {
pubkey: Pubkey::default(),
amm: AMM::default(),
pnl_pool: PoolBalance::default(),
name: [0; 32],
insurance_claim: InsuranceClaim::default(),
unrealized_pnl_max_imbalance: 0,
expiry_ts: 0,
expiry_price: 0,
next_fill_record_id: 0,
next_funding_rate_record_id: 0,
next_curve_record_id: 0,
imf_factor: 0,
unrealized_pnl_imf_factor: 0,
liquidator_fee: 0,
if_liquidation_fee: 0,
margin_ratio_initial: 0,
margin_ratio_maintenance: 0,
unrealized_pnl_initial_asset_weight: 0,
unrealized_pnl_maintenance_asset_weight: 0,
number_of_users_with_base: 0,
number_of_users: 0,
market_index: 0,
status: MarketStatus::default(),
contract_type: ContractType::default(),
contract_tier: ContractTier::default(),
paused_operations: 0,
quote_spot_market_index: 0,
fee_adjustment: 0,
fuel_boost_position: 0,
fuel_boost_taker: 0,
fuel_boost_maker: 0,
pool_id: 0,
high_leverage_margin_ratio_initial: 0,
high_leverage_margin_ratio_maintenance: 0,
padding: [0; 38],
}
}
}
impl Size for PerpMarket {
const SIZE: usize = 1216;
}
impl MarketIndexOffset for PerpMarket {
const MARKET_INDEX_OFFSET: usize = 1160;
}
impl PerpMarket {
pub fn oracle_id(&self) -> OracleIdentifier {
(self.amm.oracle, self.amm.oracle_source)
}
pub fn is_in_settlement(&self, now: i64) -> bool {
let in_settlement = matches!(
self.status,
MarketStatus::Settlement | MarketStatus::Delisted
);
let expired = self.expiry_ts != 0 && now >= self.expiry_ts;
in_settlement || expired
}
pub fn is_reduce_only(&self) -> DriftResult<bool> {
Ok(self.status == MarketStatus::ReduceOnly)
}
pub fn is_operation_paused(&self, operation: PerpOperation) -> bool {
PerpOperation::is_operation_paused(self.paused_operations, operation)
}
pub fn can_skip_auction_duration(
&self,
state: &State,
amm_lp_allowed_to_jit_make: bool,
) -> DriftResult<bool> {
if state.amm_immediate_fill_paused()? {
return Ok(false);
}
let amm_low_inventory_and_profitable =
self.amm.net_revenue_since_last_funding > 0 && amm_lp_allowed_to_jit_make;
let amm_oracle_no_latency = self.amm.oracle_source == OracleSource::Prelaunch;
let can_skip = amm_low_inventory_and_profitable || amm_oracle_no_latency;
if can_skip {
msg!("market {} amm skipping auction duration", self.market_index);
crate::dlog!(
self.amm.net_revenue_since_last_funding,
amm_lp_allowed_to_jit_make
);
crate::dlog!(amm_low_inventory_and_profitable, amm_oracle_no_latency);
}
Ok(can_skip)
}
pub fn has_too_much_drawdown(&self) -> DriftResult<bool> {
let quote_drawdown_limit_breached = match self.contract_tier {
ContractTier::A | ContractTier::B => {
self.amm.net_revenue_since_last_funding
<= DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT * 400
}
_ => {
self.amm.net_revenue_since_last_funding
<= DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT * 200
}
};
if quote_drawdown_limit_breached {
let percent_drawdown = self
.amm
.net_revenue_since_last_funding
.cast::<i128>()?
.safe_mul(PERCENTAGE_PRECISION_I128)?
.safe_div(self.amm.total_fee_minus_distributions.max(1))?;
let percent_drawdown_limit_breached = match self.contract_tier {
ContractTier::A => percent_drawdown <= -PERCENTAGE_PRECISION_I128 / 50,
ContractTier::B => percent_drawdown <= -PERCENTAGE_PRECISION_I128 / 33,
ContractTier::C => percent_drawdown <= -PERCENTAGE_PRECISION_I128 / 25,
_ => percent_drawdown <= -PERCENTAGE_PRECISION_I128 / 20,
};
if percent_drawdown_limit_breached {
msg!("AMM has too much on-the-hour drawdown (percentage={}, quote={}) to accept fills",
percent_drawdown,
self.amm.net_revenue_since_last_funding
);
return Ok(true);
}
}
Ok(false)
}
pub fn get_max_confidence_interval_multiplier(self) -> DriftResult<u64> {
// assuming validity_guard_rails max confidence pct is 2%
Ok(match self.contract_tier {
ContractTier::A => 1, // 2%
ContractTier::B => 1, // 2%
ContractTier::C => 2, // 4%
ContractTier::Speculative => 10, // 20%
ContractTier::HighlySpeculative => 50, // 100%
ContractTier::Isolated => 50, // 100%
})
}
pub fn get_sanitize_clamp_denominator(self) -> DriftResult<Option<i64>> {
Ok(match self.contract_tier {
ContractTier::A => Some(10_i64), // 10%
ContractTier::B => Some(5_i64), // 20%
ContractTier::C => Some(2_i64), // 50%
ContractTier::Speculative => None, // DEFAULT_MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR
ContractTier::HighlySpeculative => None, // DEFAULT_MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR
ContractTier::Isolated => None, // DEFAULT_MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR
})
}
pub fn get_auction_end_min_max_divisors(self) -> DriftResult<(u64, u64)> {
Ok(match self.contract_tier {
ContractTier::A => (1000, 50), // 10 bps, 2%
ContractTier::B => (1000, 20), // 10 bps, 5%
ContractTier::C => (500, 20), // 50 bps, 5%
ContractTier::Speculative => (100, 10), // 1%, 10%
ContractTier::HighlySpeculative => (50, 5), // 2%, 20%
ContractTier::Isolated => (50, 5), // 2%, 20%
})
}
pub fn get_max_price_divergence_for_funding_rate(
self,
oracle_price_twap: i64,
) -> DriftResult<i64> {
// clamp to to 3% price divergence for safer markets and higher for lower contract tiers
if self.contract_tier.is_as_safe_as_contract(&ContractTier::B) {
oracle_price_twap.safe_div(33) // 3%
} else if self.contract_tier.is_as_safe_as_contract(&ContractTier::C) {
oracle_price_twap.safe_div(20) // 5%
} else {
oracle_price_twap.safe_div(10) // 10%
}
}
pub fn is_high_leverage_mode_enabled(&self) -> bool {
self.high_leverage_margin_ratio_initial > 0
&& self.high_leverage_margin_ratio_maintenance > 0
}
pub fn get_margin_ratio(
&self,
size: u128,
margin_type: MarginRequirementType,
user_high_leverage_mode: bool,
) -> DriftResult<u32> {
if self.status == MarketStatus::Settlement {
return Ok(0); // no liability weight on size
}
let (margin_ratio_initial, margin_ratio_maintenance) =
if user_high_leverage_mode && self.is_high_leverage_mode_enabled() {
(
self.high_leverage_margin_ratio_initial.cast::<u32>()?,
self.high_leverage_margin_ratio_maintenance.cast::<u32>()?,
)
} else {
(self.margin_ratio_initial, self.margin_ratio_maintenance)
};
let default_margin_ratio = match margin_type {
MarginRequirementType::Initial => margin_ratio_initial,
MarginRequirementType::Fill => {
margin_ratio_initial.safe_add(margin_ratio_maintenance)? / 2
}
MarginRequirementType::Maintenance => margin_ratio_maintenance,
};
let size_adj_margin_ratio = calculate_size_premium_liability_weight(
size,
self.imf_factor,
default_margin_ratio,
MARGIN_PRECISION_U128,
)?;
let margin_ratio = default_margin_ratio.max(size_adj_margin_ratio);
Ok(margin_ratio)
}
pub fn get_max_liquidation_fee(&self) -> DriftResult<u32> {
let max_liquidation_fee = (self.liquidator_fee.safe_mul(MAX_LIQUIDATION_MULTIPLIER)?).min(
self.margin_ratio_maintenance
.safe_mul(LIQUIDATION_FEE_PRECISION / MARGIN_PRECISION)
.unwrap_or(u32::MAX),
);
Ok(max_liquidation_fee)
}
pub fn get_unrealized_asset_weight(
&self,
unrealized_pnl: i128,
margin_type: MarginRequirementType,
) -> DriftResult<u32> {
let mut margin_asset_weight = match margin_type {
MarginRequirementType::Initial | MarginRequirementType::Fill => {
self.unrealized_pnl_initial_asset_weight
}
MarginRequirementType::Maintenance => self.unrealized_pnl_maintenance_asset_weight,
};
if margin_asset_weight > 0
&& matches!(
margin_type,
MarginRequirementType::Fill | MarginRequirementType::Initial
)
&& self.unrealized_pnl_max_imbalance > 0
{
let net_unsettled_pnl = amm::calculate_net_user_pnl(
&self.amm,
self.amm.historical_oracle_data.last_oracle_price,
)?;
if net_unsettled_pnl > self.unrealized_pnl_max_imbalance.cast::<i128>()? {
margin_asset_weight = margin_asset_weight
.cast::<u128>()?
.safe_mul(self.unrealized_pnl_max_imbalance.cast()?)?
.safe_div(net_unsettled_pnl.unsigned_abs())?
.cast()?;
}
}
// the asset weight for a position's unrealized pnl + unsettled pnl in the margin system
// > 0 (positive balance)
// < 0 (negative balance) always has asset weight = 1
let unrealized_asset_weight = if unrealized_pnl > 0 {
// todo: only discount the initial margin s.t. no one gets liquidated over upnl?
// a larger imf factor -> lower asset weight
match margin_type {
MarginRequirementType::Initial | MarginRequirementType::Fill => {
if margin_asset_weight > 0 {
calculate_size_discount_asset_weight(
unrealized_pnl
.unsigned_abs()
.safe_mul(AMM_TO_QUOTE_PRECISION_RATIO)?,
self.unrealized_pnl_imf_factor,
margin_asset_weight,
)?
} else {
0
}
}
MarginRequirementType::Maintenance => self.unrealized_pnl_maintenance_asset_weight,
}
} else {
SPOT_WEIGHT_PRECISION
};
Ok(unrealized_asset_weight)
}
pub fn get_open_interest(&self) -> u128 {
self.amm
.base_asset_amount_long
.abs()
.max(self.amm.base_asset_amount_short.abs())
.unsigned_abs()
}
pub fn get_market_depth_for_funding_rate(&self) -> DriftResult<u64> {
// base amount used on user orders for funding calculation
let open_interest = self.get_open_interest();
let depth = (open_interest.safe_div(1000)?.cast::<u64>()?).clamp(
self.amm.min_order_size.safe_mul(100)?,
self.amm.min_order_size.safe_mul(5000)?,
);
Ok(depth)
}
pub fn update_market_with_counterparty(
&mut self,
delta: &PositionDelta,
new_settled_base_asset_amount: i64,
) -> DriftResult {
// indicates that position delta is settling lp counterparty
if delta.remainder_base_asset_amount.is_some() {
// todo: name for this is confusing, but adding is correct as is
// definition: net position of users in the market that has the LP as a counterparty (which have NOT settled)
self.amm.base_asset_amount_with_unsettled_lp = self
.amm
.base_asset_amount_with_unsettled_lp
.safe_add(new_settled_base_asset_amount.cast()?)?;
self.amm.quote_asset_amount_with_unsettled_lp = self
.amm
.quote_asset_amount_with_unsettled_lp
.safe_add(delta.quote_asset_amount.cast()?)?;
}
Ok(())
}
pub fn is_price_divergence_ok_for_settle_pnl(&self, oracle_price: i64) -> DriftResult<bool> {
let oracle_divergence = oracle_price
.safe_sub(self.amm.historical_oracle_data.last_oracle_price_twap_5min)?
.safe_mul(PERCENTAGE_PRECISION_I64)?
.safe_div(
self.amm
.historical_oracle_data
.last_oracle_price_twap_5min
.min(oracle_price),
)?
.unsigned_abs();
let oracle_divergence_limit = match self.contract_tier {
ContractTier::A => PERCENTAGE_PRECISION_U64 / 200, // 50 bps
ContractTier::B => PERCENTAGE_PRECISION_U64 / 200, // 50 bps
ContractTier::C => PERCENTAGE_PRECISION_U64 / 100, // 100 bps
ContractTier::Speculative => PERCENTAGE_PRECISION_U64 / 40, // 250 bps
ContractTier::HighlySpeculative => PERCENTAGE_PRECISION_U64 / 40, // 250 bps
ContractTier::Isolated => PERCENTAGE_PRECISION_U64 / 40, // 250 bps
};
if oracle_divergence >= oracle_divergence_limit {
msg!(
"market_index={} price divergence too large to safely settle pnl: {} >= {}",
self.market_index,
oracle_divergence,
oracle_divergence_limit
);
return Ok(false);
}
let min_price =
oracle_price.min(self.amm.historical_oracle_data.last_oracle_price_twap_5min);
let std_limit = match self.contract_tier {
ContractTier::A => min_price / 50, // 200 bps
ContractTier::B => min_price / 50, // 200 bps
ContractTier::C => min_price / 20, // 500 bps
ContractTier::Speculative => min_price / 10, // 1000 bps
ContractTier::HighlySpeculative => min_price / 10, // 1000 bps
ContractTier::Isolated => min_price / 10, // 1000 bps
}
.unsigned_abs();
if self.amm.oracle_std.max(self.amm.mark_std) >= std_limit {
msg!(
"market_index={} std too large to safely settle pnl: {} >= {}",
self.market_index,
self.amm.oracle_std.max(self.amm.mark_std),
std_limit
);
return Ok(false);
}
Ok(true)
}
pub fn can_sanitize_market_order_auctions(&self) -> bool {
self.amm.oracle_source != OracleSource::Prelaunch
}
pub fn is_prediction_market(&self) -> bool {
self.contract_type == ContractType::Prediction
}
pub fn get_quote_asset_reserve_prediction_market_bounds(
&self,
direction: PositionDirection,
) -> DriftResult<(u128, u128)> {
let mut quote_asset_reserve_lower_bound = 0_u128;
//precision scaling: 1e6 -> 1e12 -> 1e6
let peg_sqrt = (self
.amm
.peg_multiplier
.safe_mul(PEG_PRECISION)?
.saturating_add(1))
.nth_root(2)
.saturating_add(1);
// $1 limit
let mut quote_asset_reserve_upper_bound = self
.amm
.sqrt_k
.safe_mul(peg_sqrt)?
.safe_div(self.amm.peg_multiplier)?;
// for price [0,1] maintain following invariants:
if direction == PositionDirection::Long {
// lowest ask price is $0.05
quote_asset_reserve_lower_bound = self
.amm
.sqrt_k
.safe_mul(22361)?
.safe_mul(peg_sqrt)?
.safe_div(100000)?
.safe_div(self.amm.peg_multiplier)?
} else {
// highest bid price is $0.95
quote_asset_reserve_upper_bound = self
.amm
.sqrt_k
.safe_mul(97467)?
.safe_mul(peg_sqrt)?
.safe_div(100000)?
.safe_div(self.amm.peg_multiplier)?
}
Ok((
quote_asset_reserve_lower_bound,
quote_asset_reserve_upper_bound,
))
}
}
#[cfg(test)]
impl PerpMarket {
pub fn default_test() -> Self {
let amm = AMM::default_test();
PerpMarket {
amm,
margin_ratio_initial: 1000,
margin_ratio_maintenance: 500,
..PerpMarket::default()
}
}
pub fn default_btc_test() -> Self {
let amm = AMM::default_btc_test();
PerpMarket {
amm,
margin_ratio_initial: 1000, // 10x
margin_ratio_maintenance: 500, // 5x
status: MarketStatus::Initialized,
..PerpMarket::default()
}
}
}
#[zero_copy(unsafe)]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct InsuranceClaim {
/// The amount of revenue last settled
/// Positive if funds left the perp market,
/// negative if funds were pulled into the perp market
/// precision: QUOTE_PRECISION
pub revenue_withdraw_since_last_settle: i64,
/// The max amount of revenue that can be withdrawn per period
/// precision: QUOTE_PRECISION
pub max_revenue_withdraw_per_period: u64,
/// The max amount of insurance that perp market can use to resolve bankruptcy and pnl deficits
/// precision: QUOTE_PRECISION
pub quote_max_insurance: u64,
/// The amount of insurance that has been used to resolve bankruptcy and pnl deficits
/// precision: QUOTE_PRECISION
pub quote_settled_insurance: u64,
/// The last time revenue was settled in/out of market
pub last_revenue_withdraw_ts: i64,
}
#[zero_copy(unsafe)]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct PoolBalance {
/// To get the pool's token amount, you must multiply the scaled balance by the market's cumulative
/// deposit interest
/// precision: SPOT_BALANCE_PRECISION
pub scaled_balance: u128,
/// The spot market the pool is for
pub market_index: u16,
pub padding: [u8; 6],
}
impl SpotBalance for PoolBalance {
fn market_index(&self) -> u16 {
self.market_index
}
fn balance_type(&self) -> &SpotBalanceType {
&SpotBalanceType::Deposit
}
fn balance(&self) -> u128 {
self.scaled_balance
}
fn increase_balance(&mut self, delta: u128) -> DriftResult {
self.scaled_balance = self.scaled_balance.safe_add(delta)?;
Ok(())
}
fn decrease_balance(&mut self, delta: u128) -> DriftResult {
self.scaled_balance = self.scaled_balance.safe_sub(delta)?;
Ok(())
}
fn update_balance_type(&mut self, _balance_type: SpotBalanceType) -> DriftResult {
Err(ErrorCode::CantUpdatePoolBalanceType)
}
}
#[assert_no_slop]
#[zero_copy(unsafe)]
#[derive(Debug, PartialEq, Eq)]
#[repr(C)]
pub struct AMM {
/// oracle price data public key
pub oracle: Pubkey,
/// stores historically witnessed oracle data
pub historical_oracle_data: HistoricalOracleData,
/// accumulated base asset amount since inception per lp share
/// precision: QUOTE_PRECISION
pub base_asset_amount_per_lp: i128,
/// accumulated quote asset amount since inception per lp share
/// precision: QUOTE_PRECISION
pub quote_asset_amount_per_lp: i128,
/// partition of fees from perp market trading moved from pnl settlements
pub fee_pool: PoolBalance,
/// `x` reserves for constant product mm formula (x * y = k)
/// precision: AMM_RESERVE_PRECISION
pub base_asset_reserve: u128,
/// `y` reserves for constant product mm formula (x * y = k)
/// precision: AMM_RESERVE_PRECISION
pub quote_asset_reserve: u128,
/// determines how close the min/max base asset reserve sit vs base reserves
/// allow for decreasing slippage without increasing liquidity and v.v.
/// precision: PERCENTAGE_PRECISION
pub concentration_coef: u128,
/// minimum base_asset_reserve allowed before AMM is unavailable
/// precision: AMM_RESERVE_PRECISION
pub min_base_asset_reserve: u128,
/// maximum base_asset_reserve allowed before AMM is unavailable
/// precision: AMM_RESERVE_PRECISION
pub max_base_asset_reserve: u128,
/// `sqrt(k)` in constant product mm formula (x * y = k). stored to avoid drift caused by integer math issues
/// precision: AMM_RESERVE_PRECISION
pub sqrt_k: u128,
/// normalizing numerical factor for y, its use offers lowest slippage in cp-curve when market is balanced
/// precision: PEG_PRECISION
pub peg_multiplier: u128,
/// y when market is balanced. stored to save computation
/// precision: AMM_RESERVE_PRECISION
pub terminal_quote_asset_reserve: u128,
/// always non-negative. tracks number of total longs in market (regardless of counterparty)
/// precision: BASE_PRECISION
pub base_asset_amount_long: i128,
/// always non-positive. tracks number of total shorts in market (regardless of counterparty)
/// precision: BASE_PRECISION
pub base_asset_amount_short: i128,
/// tracks net position (longs-shorts) in market with AMM as counterparty
/// precision: BASE_PRECISION
pub base_asset_amount_with_amm: i128,
/// tracks net position (longs-shorts) in market with LPs as counterparty
/// precision: BASE_PRECISION
pub base_asset_amount_with_unsettled_lp: i128,
/// max allowed open interest, blocks trades that breach this value
/// precision: BASE_PRECISION
pub max_open_interest: u128,
/// sum of all user's perp quote_asset_amount in market
/// precision: QUOTE_PRECISION
pub quote_asset_amount: i128,
/// sum of all long user's quote_entry_amount in market
/// precision: QUOTE_PRECISION
pub quote_entry_amount_long: i128,
/// sum of all short user's quote_entry_amount in market
/// precision: QUOTE_PRECISION
pub quote_entry_amount_short: i128,
/// sum of all long user's quote_break_even_amount in market
/// precision: QUOTE_PRECISION
pub quote_break_even_amount_long: i128,
/// sum of all short user's quote_break_even_amount in market
/// precision: QUOTE_PRECISION
pub quote_break_even_amount_short: i128,
/// total user lp shares of sqrt_k (protocol owned liquidity = sqrt_k - last_funding_rate)
/// precision: AMM_RESERVE_PRECISION
pub user_lp_shares: u128,
/// last funding rate in this perp market (unit is quote per base)
/// precision: QUOTE_PRECISION
pub last_funding_rate: i64,
/// last funding rate for longs in this perp market (unit is quote per base)
/// precision: QUOTE_PRECISION
pub last_funding_rate_long: i64,
/// last funding rate for shorts in this perp market (unit is quote per base)
/// precision: QUOTE_PRECISION
pub last_funding_rate_short: i64,
/// estimate of last 24h of funding rate perp market (unit is quote per base)
/// precision: QUOTE_PRECISION
pub last_24h_avg_funding_rate: i64,
/// total fees collected by this perp market
/// precision: QUOTE_PRECISION
pub total_fee: i128,
/// total fees collected by the vAMM's bid/ask spread
/// precision: QUOTE_PRECISION
pub total_mm_fee: i128,
/// total fees collected by exchange fee schedule
/// precision: QUOTE_PRECISION
pub total_exchange_fee: u128,
/// total fees minus any recognized upnl and pool withdraws
/// precision: QUOTE_PRECISION
pub total_fee_minus_distributions: i128,
/// sum of all fees from fee pool withdrawn to revenue pool
/// precision: QUOTE_PRECISION
pub total_fee_withdrawn: u128,
/// all fees collected by market for liquidations
/// precision: QUOTE_PRECISION
pub total_liquidation_fee: u128,
/// accumulated funding rate for longs since inception in market
pub cumulative_funding_rate_long: i128,
/// accumulated funding rate for shorts since inception in market
pub cumulative_funding_rate_short: i128,
/// accumulated social loss paid by users since inception in market
pub total_social_loss: u128,
/// transformed base_asset_reserve for users going long
/// precision: AMM_RESERVE_PRECISION
pub ask_base_asset_reserve: u128,
/// transformed quote_asset_reserve for users going long
/// precision: AMM_RESERVE_PRECISION
pub ask_quote_asset_reserve: u128,
/// transformed base_asset_reserve for users going short
/// precision: AMM_RESERVE_PRECISION
pub bid_base_asset_reserve: u128,
/// transformed quote_asset_reserve for users going short
/// precision: AMM_RESERVE_PRECISION
pub bid_quote_asset_reserve: u128,
/// the last seen oracle price partially shrunk toward the amm reserve price
/// precision: PRICE_PRECISION
pub last_oracle_normalised_price: i64,
/// the gap between the oracle price and the reserve price = y * peg_multiplier / x
pub last_oracle_reserve_price_spread_pct: i64,
/// average estimate of bid price over funding_period
/// precision: PRICE_PRECISION
pub last_bid_price_twap: u64,
/// average estimate of ask price over funding_period
/// precision: PRICE_PRECISION
pub last_ask_price_twap: u64,
/// average estimate of (bid+ask)/2 price over funding_period
/// precision: PRICE_PRECISION
pub last_mark_price_twap: u64,
/// average estimate of (bid+ask)/2 price over FIVE_MINUTES
pub last_mark_price_twap_5min: u64,
/// the last blockchain slot the amm was updated
pub last_update_slot: u64,
/// the pct size of the oracle confidence interval
/// precision: PERCENTAGE_PRECISION
pub last_oracle_conf_pct: u64,
/// the total_fee_minus_distribution change since the last funding update
/// precision: QUOTE_PRECISION
pub net_revenue_since_last_funding: i64,
/// the last funding rate update unix_timestamp
pub last_funding_rate_ts: i64,
/// the peridocity of the funding rate updates
pub funding_period: i64,
/// the base step size (increment) of orders
/// precision: BASE_PRECISION
pub order_step_size: u64,
/// the price tick size of orders
/// precision: PRICE_PRECISION
pub order_tick_size: u64,
/// the minimum base size of an order
/// precision: BASE_PRECISION
pub min_order_size: u64,
/// the max base size a single user can have
/// precision: BASE_PRECISION
pub max_position_size: u64,
/// estimated total of volume in market
/// QUOTE_PRECISION
pub volume_24h: u64,
/// the volume intensity of long fills against AMM
pub long_intensity_volume: u64,
/// the volume intensity of short fills against AMM
pub short_intensity_volume: u64,
/// the blockchain unix timestamp at the time of the last trade
pub last_trade_ts: i64,
/// estimate of standard deviation of the fill (mark) prices
/// precision: PRICE_PRECISION
pub mark_std: u64,
/// estimate of standard deviation of the oracle price at each update
/// precision: PRICE_PRECISION
pub oracle_std: u64,
/// the last unix_timestamp the mark twap was updated
pub last_mark_price_twap_ts: i64,
/// the minimum spread the AMM can quote. also used as step size for some spread logic increases.
pub base_spread: u32,
/// the maximum spread the AMM can quote
pub max_spread: u32,
/// the spread for asks vs the reserve price
pub long_spread: u32,
/// the spread for bids vs the reserve price
pub short_spread: u32,
/// the count intensity of long fills against AMM
pub long_intensity_count: u32,
/// the count intensity of short fills against AMM
pub short_intensity_count: u32,
/// the fraction of total available liquidity a single fill on the AMM can consume
pub max_fill_reserve_fraction: u16,
/// the maximum slippage a single fill on the AMM can push
pub max_slippage_ratio: u16,
/// the update intensity of AMM formulaic updates (adjusting k). 0-100
pub curve_update_intensity: u8,
/// the jit intensity of AMM. larger intensity means larger participation in jit. 0 means no jit participation.
/// (0, 100] is intensity for protocol-owned AMM. (100, 200] is intensity for user LP-owned AMM.
pub amm_jit_intensity: u8,
/// the oracle provider information. used to decode/scale the oracle public key
pub oracle_source: OracleSource,
/// tracks whether the oracle was considered valid at the last AMM update
pub last_oracle_valid: bool,
/// the target value for `base_asset_amount_per_lp`, used during AMM JIT with LP split
/// precision: BASE_PRECISION
pub target_base_asset_amount_per_lp: i32,
/// expo for unit of per_lp, base 10 (if per_lp_base=X, then per_lp unit is 10^X)
pub per_lp_base: i8,
pub padding1: u8,
pub padding2: u16,
pub total_fee_earned_per_lp: u64,
pub net_unsettled_funding_pnl: i64,
pub quote_asset_amount_with_unsettled_lp: i64,
pub reference_price_offset: i32,
pub padding: [u8; 12],
}
impl Default for AMM {
fn default() -> Self {
AMM {
oracle: Pubkey::default(),
historical_oracle_data: HistoricalOracleData::default(),
base_asset_amount_per_lp: 0,
quote_asset_amount_per_lp: 0,
fee_pool: PoolBalance::default(),
base_asset_reserve: 0,
quote_asset_reserve: 0,
concentration_coef: 0,
min_base_asset_reserve: 0,
max_base_asset_reserve: 0,
sqrt_k: 0,
peg_multiplier: 0,
terminal_quote_asset_reserve: 0,
base_asset_amount_long: 0,
base_asset_amount_short: 0,
base_asset_amount_with_amm: 0,
base_asset_amount_with_unsettled_lp: 0,
max_open_interest: 0,
quote_asset_amount: 0,
quote_entry_amount_long: 0,
quote_entry_amount_short: 0,
quote_break_even_amount_long: 0,
quote_break_even_amount_short: 0,
user_lp_shares: 0,
last_funding_rate: 0,
last_funding_rate_long: 0,
last_funding_rate_short: 0,
last_24h_avg_funding_rate: 0,
total_fee: 0,
total_mm_fee: 0,
total_exchange_fee: 0,
total_fee_minus_distributions: 0,
total_fee_withdrawn: 0,
total_liquidation_fee: 0,
cumulative_funding_rate_long: 0,
cumulative_funding_rate_short: 0,
total_social_loss: 0,
ask_base_asset_reserve: 0,
ask_quote_asset_reserve: 0,
bid_base_asset_reserve: 0,
bid_quote_asset_reserve: 0,
last_oracle_normalised_price: 0,
last_oracle_reserve_price_spread_pct: 0,
last_bid_price_twap: 0,
last_ask_price_twap: 0,
last_mark_price_twap: 0,
last_mark_price_twap_5min: 0,
last_update_slot: 0,
last_oracle_conf_pct: 0,
net_revenue_since_last_funding: 0,
last_funding_rate_ts: 0,
funding_period: 0,
order_step_size: 0,
order_tick_size: 0,
min_order_size: 1,
max_position_size: 0,
volume_24h: 0,
long_intensity_volume: 0,
short_intensity_volume: 0,
last_trade_ts: 0,
mark_std: 0,
oracle_std: 0,
last_mark_price_twap_ts: 0,
base_spread: 0,
max_spread: 0,
long_spread: 0,
short_spread: 0,
long_intensity_count: 0,
short_intensity_count: 0,
max_fill_reserve_fraction: 0,
max_slippage_ratio: 0,
curve_update_intensity: 0,
amm_jit_intensity: 0,
oracle_source: OracleSource::default(),
last_oracle_valid: false,
target_base_asset_amount_per_lp: 0,
per_lp_base: 0,
padding1: 0,
padding2: 0,
total_fee_earned_per_lp: 0,
net_unsettled_funding_pnl: 0,
quote_asset_amount_with_unsettled_lp: 0,
reference_price_offset: 0,
padding: [0; 12],
}
}
}
impl AMM {
pub fn get_fallback_price(
self,
direction: &PositionDirection,
amm_available_liquidity: u64,
oracle_price: i64,
seconds_til_order_expiry: i64,
) -> DriftResult<u64> {
// PRICE_PRECISION
if direction.eq(&PositionDirection::Long) {
// pick amm ask + buffer if theres liquidity
// otherwise be aggressive vs oracle + 1hr premium
if amm_available_liquidity >= self.min_order_size {
let reserve_price = self.reserve_price()?;
let amm_ask_price: i64 = self.ask_price(reserve_price)?.cast()?;
amm_ask_price
.safe_add(amm_ask_price / (seconds_til_order_expiry * 20).clamp(100, 200))?
.cast::<u64>()
} else {
oracle_price
.safe_add(
self.last_ask_price_twap
.cast::<i64>()?
.safe_sub(self.historical_oracle_data.last_oracle_price_twap)?
.max(0),
)?
.safe_add(oracle_price / (seconds_til_order_expiry * 2).clamp(10, 50))?
.cast::<u64>()
}
} else {
// pick amm bid - buffer if theres liquidity
// otherwise be aggressive vs oracle + 1hr bid premium
if amm_available_liquidity >= self.min_order_size {
let reserve_price = self.reserve_price()?;
let amm_bid_price: i64 = self.bid_price(reserve_price)?.cast()?;
amm_bid_price
.safe_sub(amm_bid_price / (seconds_til_order_expiry * 20).clamp(100, 200))?
.cast::<u64>()
} else {
oracle_price
.safe_add(
self.last_bid_price_twap
.cast::<i64>()?
.safe_sub(self.historical_oracle_data.last_oracle_price_twap)?
.min(0),
)?
.safe_sub(oracle_price / (seconds_til_order_expiry * 2).clamp(10, 50))?
.max(0)
.cast::<u64>()
}
}
}
pub fn get_lower_bound_sqrt_k(self) -> DriftResult<u128> {
Ok(self.sqrt_k.min(
self.user_lp_shares
.safe_add(self.user_lp_shares.safe_div(1000)?)?
.max(self.min_order_size.cast()?)
.max(self.base_asset_amount_with_amm.unsigned_abs().cast()?),
))
}
pub fn get_protocol_owned_position(self) -> DriftResult<i64> {
self.base_asset_amount_with_amm
.safe_add(self.base_asset_amount_with_unsettled_lp)?
.cast::<i64>()
}
pub fn get_max_reference_price_offset(self) -> DriftResult<i64> {
if self.curve_update_intensity <= 100 {
return Ok(0);
}
let lower_bound_multiplier: i64 =
self.curve_update_intensity.safe_sub(100)?.cast::<i64>()?;
// always allow 1-100 bps of price offset, up to a fifth of the market's max_spread
let lb_bps =
(PERCENTAGE_PRECISION.cast::<i64>()? / 10000).safe_mul(lower_bound_multiplier)?;
let max_offset = (self.max_spread.cast::<i64>()? / 5).max(lb_bps);
Ok(max_offset)
}
pub fn get_per_lp_base_unit(self) -> DriftResult<i128> {
let scalar: i128 = 10_i128.pow(self.per_lp_base.abs().cast()?);
if self.per_lp_base > 0 {
AMM_RESERVE_PRECISION_I128.safe_mul(scalar)
} else {
AMM_RESERVE_PRECISION_I128.safe_div(scalar)
}
}
pub fn calculate_lp_base_delta(
&self,
per_lp_delta_base: i128,
base_unit: i128,
) -> DriftResult<i128> {
// calculate dedicated for user lp shares
let lp_delta_base =
get_proportion_i128(per_lp_delta_base, self.user_lp_shares, base_unit.cast()?)?;
Ok(lp_delta_base)
}
pub fn calculate_per_lp_delta(
&self,
delta: &PositionDelta,
fee_to_market: i128,
liquidity_split: AMMLiquiditySplit,
base_unit: i128,
) -> DriftResult<(i128, i128, i128)> {
let total_lp_shares = if liquidity_split == AMMLiquiditySplit::LPOwned {
self.user_lp_shares
} else {
self.sqrt_k
};
// update Market per lp position
let per_lp_delta_base = get_proportion_i128(
delta.base_asset_amount.cast()?,
base_unit.cast()?,
total_lp_shares, //.safe_div_ceil(rebase_divisor.cast()?)?,
)?;
let mut per_lp_delta_quote = get_proportion_i128(
delta.quote_asset_amount.cast()?,
base_unit.cast()?,
total_lp_shares, //.safe_div_ceil(rebase_divisor.cast()?)?,
)?;
// user position delta is short => lp position delta is long
if per_lp_delta_base < 0 {
// add one => lp subtract 1
per_lp_delta_quote = per_lp_delta_quote.safe_add(1)?;
}
// 1/5 of fee auto goes to market
// the rest goes to lps/market proportional
let per_lp_fee: i128 = if fee_to_market > 0 {
get_proportion_i128(
fee_to_market,
LP_FEE_SLICE_NUMERATOR,
LP_FEE_SLICE_DENOMINATOR,
)?
.safe_mul(base_unit)?
.safe_div(total_lp_shares.cast::<i128>()?)?
} else {
0
};
Ok((per_lp_delta_base, per_lp_delta_quote, per_lp_fee))
}
pub fn get_target_base_asset_amount_per_lp(&self) -> DriftResult<i128> {
if self.target_base_asset_amount_per_lp == 0 {
return Ok(0_i128);
}
let target_base_asset_amount_per_lp: i128 = if self.per_lp_base > 0 {
let rebase_divisor = 10_i128.pow(self.per_lp_base.abs().cast()?);
self.target_base_asset_amount_per_lp
.cast::<i128>()?
.safe_mul(rebase_divisor)?
} else if self.per_lp_base < 0 {
let rebase_divisor = 10_i128.pow(self.per_lp_base.abs().cast()?);
self.target_base_asset_amount_per_lp
.cast::<i128>()?
.safe_div(rebase_divisor)?
} else {
self.target_base_asset_amount_per_lp.cast::<i128>()?
};
Ok(target_base_asset_amount_per_lp)
}
pub fn imbalanced_base_asset_amount_with_lp(&self) -> DriftResult<i128> {
let target_lp_gap = self
.base_asset_amount_per_lp
.safe_sub(self.get_target_base_asset_amount_per_lp()?)?;
let base_unit = self.get_per_lp_base_unit()?.cast()?;
get_proportion_i128(target_lp_gap, self.user_lp_shares, base_unit)
}
pub fn amm_wants_to_jit_make(&self, taker_direction: PositionDirection) -> DriftResult<bool> {
let amm_wants_to_jit_make = match taker_direction {
PositionDirection::Long => {
self.base_asset_amount_with_amm < -(self.order_step_size.cast()?)
}
PositionDirection::Short => {
self.base_asset_amount_with_amm > (self.order_step_size.cast()?)
}
};
Ok(amm_wants_to_jit_make && self.amm_jit_is_active())
}
pub fn amm_lp_wants_to_jit_make(
&self,
taker_direction: PositionDirection,
) -> DriftResult<bool> {
if self.user_lp_shares == 0 {
return Ok(false);
}
let amm_lp_wants_to_jit_make = match taker_direction {
PositionDirection::Long => {
self.base_asset_amount_per_lp > self.get_target_base_asset_amount_per_lp()?
}
PositionDirection::Short => {
self.base_asset_amount_per_lp < self.get_target_base_asset_amount_per_lp()?
}
};
Ok(amm_lp_wants_to_jit_make && self.amm_lp_jit_is_active())
}
pub fn amm_lp_allowed_to_jit_make(&self, amm_wants_to_jit_make: bool) -> DriftResult<bool> {
// only allow lps to make when the amm inventory is below a certain level of available liquidity
// i.e. 10%
if amm_wants_to_jit_make {
// inventory scale
let (max_bids, max_asks) = amm::_calculate_market_open_bids_asks(
self.base_asset_reserve,
self.min_base_asset_reserve,
self.max_base_asset_reserve,
)?;
let min_side_liquidity = max_bids.min(max_asks.abs());
let protocol_owned_min_side_liquidity = get_proportion_i128(
min_side_liquidity,
self.sqrt_k.safe_sub(self.user_lp_shares)?,
self.sqrt_k,
)?;
Ok(self.base_asset_amount_with_amm.abs()
< protocol_owned_min_side_liquidity.safe_div(10)?)
} else {
Ok(true)
}
}
pub fn amm_jit_is_active(&self) -> bool {
self.amm_jit_intensity > 0
}
pub fn amm_lp_jit_is_active(&self) -> bool {
self.amm_jit_intensity > 100
}
pub fn reserve_price(&self) -> DriftResult<u64> {
amm::calculate_price(
self.quote_asset_reserve,
self.base_asset_reserve,
self.peg_multiplier,
)
}
pub fn bid_price(&self, reserve_price: u64) -> DriftResult<u64> {
reserve_price
.cast::<u128>()?
.safe_mul(BID_ASK_SPREAD_PRECISION_U128.safe_sub(self.short_spread.cast()?)?)?
.safe_div(BID_ASK_SPREAD_PRECISION_U128)?
.cast()
}
pub fn ask_price(&self, reserve_price: u64) -> DriftResult<u64> {
reserve_price
.cast::<u128>()?
.safe_mul(BID_ASK_SPREAD_PRECISION_U128.safe_add(self.long_spread.cast()?)?)?
.safe_div(BID_ASK_SPREAD_PRECISION_U128)?
.cast::<u64>()
}
pub fn bid_ask_price(&self, reserve_price: u64) -> DriftResult<(u64, u64)> {
let bid_price = self.bid_price(reserve_price)?;
let ask_price = self.ask_price(reserve_price)?;
Ok((bid_price, ask_price))
}
pub fn last_ask_premium(&self) -> DriftResult<i64> {
let reserve_price = self.reserve_price()?;
let ask_price = self.ask_price(reserve_price)?.cast::<i64>()?;
ask_price.safe_sub(self.historical_oracle_data.last_oracle_price)
}
pub fn last_bid_discount(&self) -> DriftResult<i64> {
let reserve_price = self.reserve_price()?;
let bid_price = self.bid_price(reserve_price)?.cast::<i64>()?;
self.historical_oracle_data
.last_oracle_price
.safe_sub(bid_price)
}
pub fn can_lower_k(&self) -> DriftResult<bool> {
let (max_bids, max_asks) = amm::calculate_market_open_bids_asks(self)?;
let min_order_size_u128 = self.min_order_size.cast::<u128>()?;
let can_lower = (self.base_asset_amount_with_amm.unsigned_abs()
< max_bids.unsigned_abs().min(max_asks.unsigned_abs()))
&& (self
.base_asset_amount_with_amm
.unsigned_abs()
.max(min_order_size_u128)
< self.sqrt_k.safe_sub(self.user_lp_shares)?)
&& (min_order_size_u128 < max_bids.unsigned_abs().max(max_asks.unsigned_abs()));
Ok(can_lower)
}
pub fn get_oracle_twap(
&self,
price_oracle: &AccountInfo,
slot: u64,
) -> DriftResult<Option<i64>> {
match self.oracle_source {
OracleSource::Pyth | OracleSource::PythStableCoin => {
Ok(Some(self.get_pyth_twap(price_oracle, &OracleSource::Pyth)?))
}
OracleSource::Pyth1K => Ok(Some(
self.get_pyth_twap(price_oracle, &OracleSource::Pyth1K)?,
)),
OracleSource::Pyth1M => Ok(Some(
self.get_pyth_twap(price_oracle, &OracleSource::Pyth1M)?,
)),
OracleSource::Switchboard => Ok(Some(get_switchboard_price(price_oracle, slot)?.price)),
OracleSource::SwitchboardOnDemand => {
Ok(Some(get_sb_on_demand_price(price_oracle, slot)?.price))
}
OracleSource::QuoteAsset => {
msg!("Can't get oracle twap for quote asset");
Err(ErrorCode::DefaultError)
}
OracleSource::Prelaunch => Ok(Some(get_prelaunch_price(price_oracle, slot)?.price)),
OracleSource::PythPull | OracleSource::PythStableCoinPull => Ok(Some(
self.get_pyth_twap(price_oracle, &OracleSource::PythPull)?,
)),
OracleSource::Pyth1KPull => Ok(Some(
self.get_pyth_twap(price_oracle, &OracleSource::Pyth1KPull)?,
)),
OracleSource::Pyth1MPull => Ok(Some(
self.get_pyth_twap(price_oracle, &OracleSource::Pyth1MPull)?,
)),
OracleSource::PythLazer => Ok(Some(
self.get_pyth_twap(price_oracle, &OracleSource::PythLazer)?,
)),
}
}
pub fn get_pyth_twap(
&self,
price_oracle: &AccountInfo,
oracle_source: &OracleSource,
) -> DriftResult<i64> {
let multiple = oracle_source.get_pyth_multiple();
let mut pyth_price_data: &[u8] = &price_oracle
.try_borrow_data()
.or(Err(ErrorCode::UnableToLoadOracle))?;
let oracle_price: i64;
let oracle_twap: i64;
let oracle_exponent: i32;
if oracle_source.is_pyth_pull_oracle() {
let price_message =
pyth_solana_receiver_sdk::price_update::PriceUpdateV2::try_deserialize(
&mut pyth_price_data,
)
.or(Err(crate::error::ErrorCode::UnableToLoadOracle))?;
oracle_price = price_message.price_message.price;
oracle_twap = price_message.price_message.ema_price;
oracle_exponent = price_message.price_message.exponent;
} else if oracle_source.is_pyth_push_oracle() {
let price_data = pyth_client::cast::<pyth_client::Price>(pyth_price_data);
oracle_price = price_data.agg.price;
oracle_twap = price_data.twap.val;
oracle_exponent = price_data.expo;
} else {
let price_data = PythLazerOracle::try_deserialize(&mut pyth_price_data)
.or(Err(ErrorCode::UnableToLoadOracle))?;
oracle_price = price_data.price;
oracle_twap = price_data.price;
oracle_exponent = price_data.exponent;
}
assert!(oracle_twap > oracle_price / 10);
let oracle_precision = 10_u128
.pow(oracle_exponent.unsigned_abs())
.safe_div(multiple)?;
let mut oracle_scale_mult = 1;
let mut oracle_scale_div = 1;
if oracle_precision > PRICE_PRECISION {
oracle_scale_div = oracle_precision.safe_div(PRICE_PRECISION)?;
} else {
oracle_scale_mult = PRICE_PRECISION.safe_div(oracle_precision)?;
}
oracle_twap
.cast::<i128>()?
.safe_mul(oracle_scale_mult.cast()?)?
.safe_div(oracle_scale_div.cast()?)?
.cast::<i64>()
}
pub fn update_volume_24h(
&mut self,
quote_asset_amount: u64,
position_direction: PositionDirection,
now: i64,
) -> DriftResult {
let since_last = max(1_i64, now.safe_sub(self.last_trade_ts)?);
amm::update_amm_long_short_intensity(self, now, quote_asset_amount, position_direction)?;
self.volume_24h = stats::calculate_rolling_sum(
self.volume_24h,
quote_asset_amount,
since_last,
TWENTY_FOUR_HOUR,
)?;
self.last_trade_ts = now;
Ok(())
}
pub fn get_new_oracle_conf_pct(
&self,
confidence: u64, // price precision
reserve_price: u64, // price precision
now: i64,
) -> DriftResult<u64> {
// use previous value decayed as lower bound to avoid shrinking too quickly
let upper_bound_divisor = 21_u64;
let lower_bound_divisor = 5_u64;
let since_last = now
.safe_sub(self.historical_oracle_data.last_oracle_price_twap_ts)?
.max(0);
let confidence_lower_bound = if since_last > 0 {
let confidence_divisor = upper_bound_divisor
.saturating_sub(since_last.cast::<u64>()?)
.max(lower_bound_divisor);
self.last_oracle_conf_pct
.safe_sub(self.last_oracle_conf_pct / confidence_divisor)?
} else {
self.last_oracle_conf_pct
};
Ok(confidence
.safe_mul(BID_ASK_SPREAD_PRECISION)?
.safe_div(reserve_price)?
.max(confidence_lower_bound))
}
pub fn is_recent_oracle_valid(&self, current_slot: u64) -> DriftResult<bool> {
Ok(self.last_oracle_valid && current_slot == self.last_update_slot)
}
}
#[cfg(test)]
impl AMM {
pub fn default_test() -> Self {
let default_reserves = 100 * AMM_RESERVE_PRECISION;
// make sure tests dont have the default sqrt_k = 0
AMM {
base_asset_reserve: default_reserves,
quote_asset_reserve: default_reserves,
sqrt_k: default_reserves,
concentration_coef: MAX_CONCENTRATION_COEFFICIENT,
order_step_size: 1,
order_tick_size: 1,
max_base_asset_reserve: u64::MAX as u128,
min_base_asset_reserve: 0,
terminal_quote_asset_reserve: default_reserves,
peg_multiplier: crate::math::constants::PEG_PRECISION,
max_fill_reserve_fraction: 1,
max_spread: 1000,
historical_oracle_data: HistoricalOracleData {
last_oracle_price: PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
last_oracle_valid: true,
..AMM::default()
}
}
pub fn default_btc_test() -> Self {
AMM {
base_asset_reserve: 65 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 63015384615,
terminal_quote_asset_reserve: 64 * AMM_RESERVE_PRECISION,
sqrt_k: 64 * AMM_RESERVE_PRECISION,
peg_multiplier: 19_400_000_000,
concentration_coef: MAX_CONCENTRATION_COEFFICIENT,
max_base_asset_reserve: 90 * AMM_RESERVE_PRECISION,
min_base_asset_reserve: 45 * AMM_RESERVE_PRECISION,
base_asset_amount_with_amm: -(AMM_RESERVE_PRECISION as i128),
mark_std: PRICE_PRECISION as u64,
quote_asset_amount: 19_000_000_000, // short 1 BTC @ $19000
historical_oracle_data: HistoricalOracleData {
last_oracle_price: 19_400 * PRICE_PRECISION_I64,
last_oracle_price_twap: 19_400 * PRICE_PRECISION_I64,
last_oracle_price_twap_ts: 1662800000_i64,
..HistoricalOracleData::default()
},
last_mark_price_twap_ts: 1662800000,
curve_update_intensity: 100,
base_spread: 250,
max_spread: 975,
funding_period: 3600,
last_oracle_valid: true,
..AMM::default()
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/order_params.rs
|
use crate::controller::position::PositionDirection;
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::events::OrderActionExplanation;
use crate::state::perp_market::{ContractTier, PerpMarket};
use crate::state::user::{MarketType, OrderTriggerCondition, OrderType};
use crate::{
MAX_PREDICTION_MARKET_PRICE_I64, ONE_HUNDRED_THOUSAND_QUOTE, PERCENTAGE_PRECISION_I64,
PERCENTAGE_PRECISION_U64, PRICE_PRECISION_I64,
};
use anchor_lang::prelude::*;
use borsh::{BorshDeserialize, BorshSerialize};
use std::ops::Div;
#[cfg(test)]
mod tests;
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default, Copy, Eq, PartialEq, Debug)]
pub struct OrderParams {
pub order_type: OrderType,
pub market_type: MarketType,
pub direction: PositionDirection,
pub user_order_id: u8,
pub base_asset_amount: u64,
pub price: u64,
pub market_index: u16,
pub reduce_only: bool,
pub post_only: PostOnlyParam,
pub immediate_or_cancel: bool,
pub max_ts: Option<i64>,
pub trigger_price: Option<u64>,
pub trigger_condition: OrderTriggerCondition,
pub oracle_price_offset: Option<i32>, // price offset from oracle for order (~ +/- 2147 max)
pub auction_duration: Option<u8>, // specified in slots
pub auction_start_price: Option<i64>, // specified in price or oracle_price_offset
pub auction_end_price: Option<i64>, // specified in price or oracle_price_offset
}
impl OrderParams {
pub fn update_perp_auction_params_limit_orders(
&mut self,
perp_market: &PerpMarket,
oracle_price: i64,
) -> DriftResult {
if self.post_only != PostOnlyParam::None {
return Ok(());
}
let oracle_price_offset = self.oracle_price_offset.unwrap_or(0);
let is_oracle_offset_oracle = oracle_price_offset != 0;
if !is_oracle_offset_oracle && self.price == 0 {
return Ok(());
}
let auction_start_price_offset =
OrderParams::get_perp_baseline_start_price_offset(perp_market, self.direction)?;
let mut new_auction_start_price = oracle_price.safe_add(auction_start_price_offset)?;
if perp_market.is_prediction_market() {
new_auction_start_price = new_auction_start_price.min(MAX_PREDICTION_MARKET_PRICE_I64);
}
if self.auction_duration.unwrap_or(0) == 0 {
match self.direction {
PositionDirection::Long => {
let ask_premium = perp_market.amm.last_ask_premium()?;
let est_ask = oracle_price.safe_add(ask_premium)?.cast()?;
let crosses = if is_oracle_offset_oracle {
oracle_price_offset.cast::<i64>()?
> (est_ask as i64).safe_sub(oracle_price)?
} else {
self.price > est_ask
};
if !crosses {
// if auction duration is empty and limit doesnt cross vamm premium, return early
return Ok(());
} else {
let mut new_auction_start_price =
new_auction_start_price.min(est_ask as i64);
if is_oracle_offset_oracle {
new_auction_start_price =
new_auction_start_price.safe_sub(oracle_price)?;
msg!(
"Updating oracle auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(new_auction_start_price);
msg!(
"Updating oracle auction end price to {}",
oracle_price_offset
);
self.auction_end_price = Some(oracle_price_offset as i64);
} else {
msg!(
"Updating auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(new_auction_start_price);
msg!("Updating auction end price to {}", self.price);
self.auction_end_price = Some(self.price as i64);
}
}
}
PositionDirection::Short => {
let bid_discount = perp_market.amm.last_bid_discount()?;
let est_bid = oracle_price.safe_sub(bid_discount)?.cast()?;
let crosses = if is_oracle_offset_oracle {
oracle_price_offset.cast::<i64>()?
< (est_bid as i64).safe_sub(oracle_price)?
} else {
self.price < est_bid
};
if !crosses {
// if auction duration is empty and limit doesnt cross vamm discount, return early
return Ok(());
} else {
let mut new_auction_start_price =
new_auction_start_price.max(est_bid as i64);
if is_oracle_offset_oracle {
new_auction_start_price =
new_auction_start_price.safe_sub(oracle_price)?;
msg!(
"Updating oracle auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(new_auction_start_price);
msg!(
"Updating oracle auction end price to {}",
oracle_price_offset
);
self.auction_end_price = Some(oracle_price_offset as i64);
} else {
msg!(
"Updating auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(new_auction_start_price);
msg!("Updating auction end price to {}", self.price);
self.auction_end_price = Some(self.price as i64);
}
}
}
}
} else {
match self.auction_start_price {
Some(auction_start_price) => {
let improves_long = self.direction == PositionDirection::Long
&& new_auction_start_price < auction_start_price;
let improves_short = self.direction == PositionDirection::Short
&& new_auction_start_price > auction_start_price;
if improves_long || improves_short {
if is_oracle_offset_oracle {
msg!(
"Updating oracle limit auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(auction_start_price_offset);
} else {
msg!(
"Updating limit auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(new_auction_start_price);
}
}
}
None => {
if is_oracle_offset_oracle {
msg!(
"Updating oracle limit auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(auction_start_price_offset);
} else {
msg!(
"Updating limit auction start price to {}",
new_auction_start_price
);
self.auction_start_price = Some(new_auction_start_price);
}
}
}
if self.auction_end_price.is_none() {
if is_oracle_offset_oracle {
msg!(
"Updating oracle limit auction end price to {}",
oracle_price_offset
);
self.auction_end_price = Some(oracle_price_offset as i64);
} else {
msg!("Updating limit auction end price to {}", self.price);
self.auction_end_price = Some(self.price as i64);
}
}
}
let auction_duration_before = self.auction_duration;
let new_auction_duration = get_auction_duration(
self.auction_end_price
.safe_unwrap()?
.safe_sub(self.auction_start_price.safe_unwrap()?)?
.unsigned_abs(),
oracle_price.unsigned_abs(),
perp_market.contract_tier,
)?;
self.auction_duration = Some(
auction_duration_before
.unwrap_or(0)
.max(new_auction_duration),
);
if auction_duration_before != self.auction_duration {
msg!(
"Updating auction duration to {}",
self.auction_duration.safe_unwrap()?
);
}
Ok(())
}
pub fn get_auction_start_price_offset(self, oracle_price: i64) -> DriftResult<i64> {
let start_offset = if self.order_type == OrderType::Oracle {
self.auction_start_price.unwrap_or(0)
} else if let Some(auction_start_price) = self.auction_start_price {
auction_start_price.safe_sub(oracle_price)?
} else {
return Ok(0);
};
Ok(start_offset)
}
pub fn get_auction_end_price_offset(self, oracle_price: i64) -> DriftResult<i64> {
let end_offset = if self.order_type == OrderType::Oracle {
self.auction_end_price.unwrap_or(0)
} else if let Some(auction_end_price) = self.auction_end_price {
auction_end_price.safe_sub(oracle_price)?
} else {
return Ok(0);
};
Ok(end_offset)
}
pub fn update_perp_auction_params_market_and_oracle_orders(
&mut self,
perp_market: &PerpMarket,
oracle_price: i64,
is_market_order: bool,
) -> DriftResult {
if self.auction_duration.is_none()
|| self.auction_start_price.is_none()
|| self.auction_end_price.is_none()
{
let (auction_start_price, auction_end_price, auction_duration) = if is_market_order {
OrderParams::derive_market_order_auction_params(
perp_market,
self.direction,
oracle_price,
self.price,
PERCENTAGE_PRECISION_I64 / 400, // 25 bps
)?
} else {
OrderParams::derive_oracle_order_auction_params(
perp_market,
self.direction,
oracle_price,
self.oracle_price_offset,
PERCENTAGE_PRECISION_I64 / 400, // 25 bps
)?
};
self.auction_start_price = Some(auction_start_price);
self.auction_end_price = Some(auction_end_price);
self.auction_duration = Some(auction_duration);
msg!(
"Updating auction start price to {}",
self.auction_start_price.safe_unwrap()?
);
msg!(
"Updating auction end price to {}",
self.auction_end_price.safe_unwrap()?
);
msg!(
"Updating auction duration to {}",
self.auction_duration.safe_unwrap()?
);
return Ok(());
}
// only update auction start price if the contract tier isn't Isolated
if perp_market.can_sanitize_market_order_auctions() {
let (new_start_price_offset, new_end_price_offset) =
OrderParams::get_perp_baseline_start_end_price_offset(
perp_market,
self.direction,
2,
)?;
let current_start_price_offset = self.get_auction_start_price_offset(oracle_price)?;
let current_end_price_offset = self.get_auction_end_price_offset(oracle_price)?;
match self.direction {
PositionDirection::Long => {
if current_start_price_offset > new_start_price_offset {
self.auction_start_price = if !is_market_order {
Some(new_start_price_offset)
} else {
Some(new_start_price_offset.safe_add(oracle_price)?)
};
msg!(
"Updating auction start price to {}",
self.auction_start_price.safe_unwrap()?
);
}
if current_end_price_offset > new_end_price_offset {
self.auction_end_price = if !is_market_order {
Some(new_end_price_offset)
} else {
Some(new_end_price_offset.safe_add(oracle_price)?)
};
msg!(
"Updating auction end price to {}",
self.auction_end_price.safe_unwrap()?
);
}
}
PositionDirection::Short => {
if current_start_price_offset < new_start_price_offset {
self.auction_start_price = if !is_market_order {
Some(new_start_price_offset)
} else {
Some(new_start_price_offset.safe_add(oracle_price)?)
};
msg!(
"Updating auction start price to {}",
self.auction_start_price.safe_unwrap()?
);
}
if current_end_price_offset < new_end_price_offset {
self.auction_end_price = if !is_market_order {
Some(new_end_price_offset)
} else {
Some(new_end_price_offset.safe_add(oracle_price)?)
};
msg!(
"Updating auction end price to {}",
self.auction_end_price.safe_unwrap()?
);
}
}
}
}
let auction_duration_before = self.auction_duration;
let new_auction_duration = get_auction_duration(
self.auction_end_price
.safe_unwrap()?
.safe_sub(self.auction_start_price.safe_unwrap()?)?
.unsigned_abs(),
oracle_price.unsigned_abs(),
perp_market.contract_tier,
)?;
self.auction_duration = Some(
auction_duration_before
.unwrap_or(0)
.max(new_auction_duration),
);
if auction_duration_before != self.auction_duration {
msg!(
"Updating auction duration to {}",
self.auction_duration.safe_unwrap()?
);
}
Ok(())
}
pub fn derive_market_order_auction_params(
perp_market: &PerpMarket,
direction: PositionDirection,
oracle_price: i64,
limit_price: u64,
start_buffer: i64,
) -> DriftResult<(i64, i64, u8)> {
let (mut auction_start_price, mut auction_end_price) = if limit_price != 0 {
let (auction_start_price_offset, auction_end_price_offset) =
OrderParams::get_perp_baseline_start_end_price_offset(perp_market, direction, 2)?;
let mut auction_start_price = oracle_price.safe_add(auction_start_price_offset)?;
let mut auction_end_price = oracle_price.safe_add(auction_end_price_offset)?;
let limit_price = limit_price as i64;
if direction == PositionDirection::Long {
auction_start_price = auction_start_price.min(limit_price);
auction_end_price = auction_end_price.min(limit_price);
} else {
auction_start_price = auction_start_price.max(limit_price);
auction_end_price = auction_end_price.max(limit_price);
};
(auction_start_price, auction_end_price)
} else {
let (auction_start_price_offset, auction_end_price_offset) =
OrderParams::get_perp_baseline_start_end_price_offset(perp_market, direction, 1)?;
let auction_start_price = oracle_price.safe_add(auction_start_price_offset)?;
let auction_end_price = oracle_price.safe_add(auction_end_price_offset)?;
(auction_start_price, auction_end_price)
};
if start_buffer != 0 {
let start_buffer_price = oracle_price
.safe_mul(start_buffer)?
.safe_div(PERCENTAGE_PRECISION_I64)?;
if direction == PositionDirection::Long {
auction_start_price = auction_start_price.safe_sub(start_buffer_price)?;
} else {
auction_start_price = auction_start_price.safe_add(start_buffer_price)?;
}
}
if perp_market.is_prediction_market() {
auction_start_price = auction_start_price.min(MAX_PREDICTION_MARKET_PRICE_I64);
auction_end_price = auction_end_price.min(MAX_PREDICTION_MARKET_PRICE_I64);
}
let auction_duration = get_auction_duration(
auction_end_price
.safe_sub(auction_start_price)?
.unsigned_abs(),
oracle_price.unsigned_abs(),
perp_market.contract_tier,
)?;
Ok((auction_start_price, auction_end_price, auction_duration))
}
pub fn derive_oracle_order_auction_params(
perp_market: &PerpMarket,
direction: PositionDirection,
oracle_price: i64,
oracle_price_offset: Option<i32>,
start_buffer: i64,
) -> DriftResult<(i64, i64, u8)> {
let (mut auction_start_price, auction_end_price) = if let Some(oracle_price_offset) =
oracle_price_offset
{
let mut auction_start_price_offset =
OrderParams::get_perp_baseline_start_price_offset(perp_market, direction)?;
let oracle_price_offset = oracle_price_offset as i64;
if direction == PositionDirection::Long {
auction_start_price_offset = auction_start_price_offset.min(oracle_price_offset)
} else {
auction_start_price_offset = auction_start_price_offset.max(oracle_price_offset)
};
(auction_start_price_offset, oracle_price_offset)
} else {
let (auction_start_price_offset, auction_end_price_offset) =
OrderParams::get_perp_baseline_start_end_price_offset(perp_market, direction, 1)?;
(auction_start_price_offset, auction_end_price_offset)
};
if start_buffer != 0 {
let start_buffer_price = oracle_price
.safe_mul(start_buffer)?
.safe_div(PERCENTAGE_PRECISION_I64)?;
if direction == PositionDirection::Long {
auction_start_price = auction_start_price.safe_sub(start_buffer_price)?;
} else {
auction_start_price = auction_start_price.safe_add(start_buffer_price)?;
}
}
let auction_duration = get_auction_duration(
auction_end_price
.safe_sub(auction_start_price)?
.unsigned_abs(),
oracle_price.unsigned_abs(),
perp_market.contract_tier,
)?;
Ok((auction_start_price, auction_end_price, auction_duration))
}
pub fn update_perp_auction_params(
&mut self,
perp_market: &PerpMarket,
oracle_price: i64,
) -> DriftResult {
#[cfg(feature = "anchor-test")]
return Ok(());
match self.order_type {
OrderType::Limit => {
self.update_perp_auction_params_limit_orders(perp_market, oracle_price)?;
}
OrderType::Market | OrderType::Oracle => {
self.update_perp_auction_params_market_and_oracle_orders(
perp_market,
oracle_price,
self.order_type == OrderType::Market,
)?;
}
_ => {}
}
Ok(())
}
pub fn get_perp_baseline_start_price_offset(
perp_market: &PerpMarket,
direction: PositionDirection,
) -> DriftResult<i64> {
if perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_ts
.safe_sub(perp_market.amm.last_mark_price_twap_ts)?
.abs()
>= 60
|| perp_market.amm.volume_24h <= ONE_HUNDRED_THOUSAND_QUOTE
{
// if uncertain with timestamp mismatch, enforce within N bps
let price_divisor = if perp_market
.contract_tier
.is_as_safe_as_contract(&ContractTier::B)
{
500
} else {
100
};
return Ok(match direction {
PositionDirection::Long => {
perp_market.amm.last_bid_price_twap.cast::<i64>()? / price_divisor
}
PositionDirection::Short => {
-(perp_market.amm.last_ask_price_twap.cast::<i64>()? / price_divisor)
}
});
}
// price offsets baselines for perp market auctions
let mark_twap_slow = match direction {
PositionDirection::Long => perp_market.amm.last_bid_price_twap,
PositionDirection::Short => perp_market.amm.last_ask_price_twap,
}
.cast::<i64>()?;
let baseline_start_price_offset_slow = mark_twap_slow.safe_sub(
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap,
)?;
let baseline_start_price_offset_fast = perp_market
.amm
.last_mark_price_twap_5min
.cast::<i64>()?
.safe_sub(
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap_5min,
)?;
let frac_of_long_spread_in_price: i64 = perp_market
.amm
.long_spread
.cast::<i64>()?
.safe_mul(mark_twap_slow)?
.safe_div(PRICE_PRECISION_I64 * 10)?;
let frac_of_short_spread_in_price: i64 = perp_market
.amm
.short_spread
.cast::<i64>()?
.safe_mul(mark_twap_slow)?
.safe_div(PRICE_PRECISION_I64 * 10)?;
let baseline_start_price_offset = match direction {
PositionDirection::Long => baseline_start_price_offset_slow
.safe_add(frac_of_long_spread_in_price)?
.min(baseline_start_price_offset_fast.safe_sub(frac_of_short_spread_in_price)?),
PositionDirection::Short => baseline_start_price_offset_slow
.safe_sub(frac_of_short_spread_in_price)?
.max(baseline_start_price_offset_fast.safe_add(frac_of_long_spread_in_price)?),
};
Ok(baseline_start_price_offset)
}
pub fn get_perp_baseline_start_end_price_offset(
perp_market: &PerpMarket,
direction: PositionDirection,
end_buffer_scalar: u64,
) -> DriftResult<(i64, i64)> {
let oracle_twap = perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap
.unsigned_abs();
let baseline_start_price_offset =
OrderParams::get_perp_baseline_start_price_offset(perp_market, direction)?;
let (min_divisor, max_divisor) = perp_market.get_auction_end_min_max_divisors()?;
let amm_spread_side_pct = if direction == PositionDirection::Short {
perp_market.amm.short_spread
} else {
perp_market.amm.long_spread
};
let mut baseline_end_price_buffer = perp_market
.amm
.mark_std
.max(perp_market.amm.oracle_std)
.max(
amm_spread_side_pct
.cast::<u64>()?
.safe_mul(oracle_twap)?
.safe_div(PERCENTAGE_PRECISION_U64)?,
);
if end_buffer_scalar >= 1 {
baseline_end_price_buffer = baseline_end_price_buffer.safe_mul(end_buffer_scalar)?
}
baseline_end_price_buffer =
baseline_end_price_buffer.clamp(oracle_twap / min_divisor, oracle_twap / max_divisor);
let baseline_end_price_offset = if direction == PositionDirection::Short {
let auction_end_price = perp_market
.amm
.last_bid_price_twap
.safe_sub(baseline_end_price_buffer)?
.cast::<i64>()?
.safe_sub(
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap,
)?;
auction_end_price.min(baseline_start_price_offset)
} else {
let auction_end_price = perp_market
.amm
.last_ask_price_twap
.safe_add(baseline_end_price_buffer)?
.cast::<i64>()?
.safe_sub(
perp_market
.amm
.historical_oracle_data
.last_oracle_price_twap,
)?;
auction_end_price.max(baseline_start_price_offset)
};
Ok((baseline_start_price_offset, baseline_end_price_offset))
}
pub fn get_close_perp_params(
market: &PerpMarket,
direction_to_close: PositionDirection,
base_asset_amount: u64,
) -> DriftResult<OrderParams> {
let (auction_start_price, auction_end_price) =
OrderParams::get_perp_baseline_start_end_price_offset(market, direction_to_close, 1)?;
let params = OrderParams {
market_type: MarketType::Perp,
direction: direction_to_close,
order_type: OrderType::Oracle,
market_index: market.market_index,
base_asset_amount,
reduce_only: true,
auction_start_price: Some(auction_start_price),
auction_end_price: Some(auction_end_price),
auction_duration: Some(80),
oracle_price_offset: Some(auction_end_price.cast()?),
..OrderParams::default()
};
Ok(params)
}
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Eq, PartialEq, Debug)]
pub struct SwiftServerMessage {
pub uuid: [u8; 8],
pub swift_order_signature: [u8; 64],
pub slot: u64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default, Eq, PartialEq, Debug)]
pub struct SwiftOrderParamsMessage {
pub swift_order_params: OrderParams,
pub sub_account_id: u16,
pub take_profit_order_params: Option<SwiftTriggerOrderParams>,
pub stop_loss_order_params: Option<SwiftTriggerOrderParams>,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default, Eq, PartialEq, Debug)]
pub struct SwiftTriggerOrderParams {
pub trigger_price: u64,
pub base_asset_amount: u64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Eq, PartialEq, Debug, Copy)]
pub struct RFQMakerOrderParams {
pub uuid: [u8; 8],
pub authority: Pubkey,
pub sub_account_id: u16,
pub market_index: u16,
pub market_type: MarketType,
pub base_asset_amount: u64,
pub price: u64,
pub direction: PositionDirection,
pub max_ts: i64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Eq, PartialEq, Debug)]
pub struct RFQMakerMessage {
pub order_params: RFQMakerOrderParams,
pub signature: [u8; 64],
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Eq, PartialEq, Debug)]
pub struct RFQMatch {
pub base_asset_amount: u64,
pub maker_order_params: RFQMakerOrderParams,
pub maker_signature: [u8; 64],
}
fn get_auction_duration(
price_diff: u64,
price: u64,
contract_tier: ContractTier,
) -> DriftResult<u8> {
let percent_diff = price_diff.safe_mul(PERCENTAGE_PRECISION_U64)?.div(price);
let slots_per_bp = if contract_tier.is_as_safe_as_contract(&ContractTier::B) {
100
} else {
60
};
Ok(percent_diff
.safe_mul(slots_per_bp)?
.safe_div_ceil(PERCENTAGE_PRECISION_U64 / 100)? // 1% = 60 slots
.clamp(10, 180) as u8) // 180 slots max
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum PostOnlyParam {
#[default]
None,
MustPostOnly, // Tx fails if order can't be post only
TryPostOnly, // Tx succeeds and order not placed if can't be post only
Slide, // Modify price to be post only if can't be post only
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Default)]
pub struct ModifyOrderParams {
pub direction: Option<PositionDirection>,
pub base_asset_amount: Option<u64>,
pub price: Option<u64>,
pub reduce_only: Option<bool>,
pub post_only: Option<PostOnlyParam>,
pub immediate_or_cancel: Option<bool>,
pub max_ts: Option<i64>,
pub trigger_price: Option<u64>,
pub trigger_condition: Option<OrderTriggerCondition>,
pub oracle_price_offset: Option<i32>,
pub auction_duration: Option<u8>,
pub auction_start_price: Option<i64>,
pub auction_end_price: Option<i64>,
pub policy: Option<u8>,
}
impl ModifyOrderParams {
pub fn must_modify(&self) -> bool {
self.policy.unwrap_or(0) & ModifyOrderPolicy::MustModify as u8 != 0
}
pub fn exclude_previous_fill(&self) -> bool {
self.policy.unwrap_or(0) & ModifyOrderPolicy::ExcludePreviousFill as u8 != 0
}
}
pub enum ModifyOrderPolicy {
MustModify = 1,
ExcludePreviousFill = 2,
}
#[derive(Clone)]
pub struct PlaceOrderOptions {
pub swift_taker_order_slot: Option<u64>,
pub try_expire_orders: bool,
pub enforce_margin_check: bool,
pub risk_increasing: bool,
pub explanation: OrderActionExplanation,
pub is_rfq_order: bool,
}
impl Default for PlaceOrderOptions {
fn default() -> Self {
Self {
swift_taker_order_slot: None,
try_expire_orders: true,
enforce_margin_check: true,
risk_increasing: false,
explanation: OrderActionExplanation::None,
is_rfq_order: false,
}
}
}
impl PlaceOrderOptions {
pub fn update_risk_increasing(&mut self, risk_increasing: bool) {
self.risk_increasing = self.risk_increasing || risk_increasing;
}
pub fn explanation(mut self, explanation: OrderActionExplanation) -> Self {
self.explanation = explanation;
self
}
pub fn is_liquidation(&self) -> bool {
self.explanation == OrderActionExplanation::Liquidation
}
pub fn set_order_slot(&mut self, slot: u64) {
self.swift_taker_order_slot = Some(slot);
}
pub fn get_order_slot(&self, order_slot: u64) -> u64 {
let mut min_order_slot = order_slot;
if let Some(swift_taker_order_slot) = self.swift_taker_order_slot {
min_order_slot = order_slot.min(swift_taker_order_slot);
}
min_order_slot
}
pub fn set_is_rfq(&mut self, is_rfq_order: bool) {
self.is_rfq_order = is_rfq_order;
}
pub fn is_swift_order(&self) -> bool {
self.swift_taker_order_slot.is_some()
}
}
pub enum PlaceAndTakeOrderSuccessCondition {
PartialFill = 1,
FullFill = 2,
}
pub fn parse_optional_params(optional_params: Option<u32>) -> (u8, u8) {
match optional_params {
Some(optional_params) => (
(optional_params & 255) as u8,
((optional_params >> 8) & 255) as u8,
),
None => (0, 100),
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/load_ref.rs
|
use anchor_lang::prelude::*;
use anchor_lang::ZeroCopy;
use arrayref::array_ref;
use std::cell::{Ref, RefMut};
use std::mem;
pub fn load_ref<'a, T: ZeroCopy + Owner>(account_info: &'a AccountInfo) -> Result<Ref<'a, T>> {
let data = account_info.try_borrow_data()?;
if data.len() < T::discriminator().len() {
return Err(ErrorCode::AccountDiscriminatorNotFound.into());
}
let disc_bytes = array_ref![data, 0, 8];
if disc_bytes != &T::discriminator() {
return Err(ErrorCode::AccountDiscriminatorMismatch.into());
}
Ok(Ref::map(data, |data| {
bytemuck::from_bytes(&data[8..mem::size_of::<T>() + 8])
}))
}
pub fn load_ref_mut<'a, T: ZeroCopy + Owner>(
account_info: &'a AccountInfo,
) -> Result<RefMut<'a, T>> {
let data = account_info.try_borrow_mut_data()?;
if data.len() < T::discriminator().len() {
return Err(ErrorCode::AccountDiscriminatorNotFound.into());
}
let disc_bytes = array_ref![data, 0, 8];
if disc_bytes != &T::discriminator() {
return Err(ErrorCode::AccountDiscriminatorMismatch.into());
}
Ok(RefMut::map(data, |data| {
bytemuck::from_bytes_mut(&mut data[8..mem::size_of::<T>() + 8])
}))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/user_map.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::traits::Size;
use crate::state::user::{User, UserStats};
use crate::validate;
use anchor_lang::prelude::AccountLoader;
use anchor_lang::Discriminator;
use arrayref::array_ref;
use solana_program::account_info::AccountInfo;
use solana_program::msg;
use solana_program::pubkey::Pubkey;
use std::cell::{Ref, RefMut};
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::iter::Peekable;
use std::panic::Location;
use std::slice::Iter;
pub struct UserMap<'a>(pub BTreeMap<Pubkey, AccountLoader<'a, User>>);
impl<'a> UserMap<'a> {
#[track_caller]
#[inline(always)]
pub fn get_ref(&self, user: &Pubkey) -> DriftResult<Ref<User>> {
let loader = match self.0.get(user) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find user {} at {}:{}",
user,
caller.file(),
caller.line()
);
return Err(ErrorCode::UserNotFound);
}
};
match loader.load() {
Ok(user) => Ok(user),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load user {} at {}:{}",
user,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadUserAccount)
}
}
}
#[track_caller]
#[inline(always)]
pub fn get_ref_mut(&self, user: &Pubkey) -> DriftResult<RefMut<User>> {
let loader = match self.0.get(user) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find user {} at {}:{}",
user,
caller.file(),
caller.line()
);
return Err(ErrorCode::UserNotFound);
}
};
match loader.load_mut() {
Ok(user) => Ok(user),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load user {} at {}:{}",
user,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadUserAccount)
}
}
}
pub fn insert(&mut self, user: Pubkey, account_loader: AccountLoader<'a, User>) -> DriftResult {
validate!(
!self.0.contains_key(&user),
ErrorCode::InvalidUserAccount,
"User already exists in map {:?}",
user
)?;
self.0.insert(user, account_loader);
Ok(())
}
pub fn empty() -> UserMap<'a> {
UserMap(BTreeMap::new())
}
}
#[cfg(test)]
impl<'a> UserMap<'a> {
pub fn load_one<'b: 'a>(account_info: &'b AccountInfo<'a>) -> DriftResult<UserMap<'a>> {
let mut user_map = UserMap(BTreeMap::new());
let user_discriminator: [u8; 8] = User::discriminator();
let user_key = account_info.key;
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadUserData))?;
let expected_data_len = User::SIZE;
if data.len() < expected_data_len {
return Err(ErrorCode::CouldNotLoadUserData);
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &user_discriminator {
return Err(ErrorCode::CouldNotLoadUserData);
}
let is_writable = account_info.is_writable;
if !is_writable {
return Err(ErrorCode::UserWrongMutability);
}
let user_account_loader: AccountLoader<User> =
AccountLoader::try_from(account_info).or(Err(ErrorCode::InvalidUserAccount))?;
user_map.insert(*user_key, user_account_loader)?;
Ok(user_map)
}
}
pub struct UserStatsMap<'a>(pub BTreeMap<Pubkey, AccountLoader<'a, UserStats>>);
impl<'a> UserStatsMap<'a> {
#[track_caller]
#[inline(always)]
pub fn get_ref(&self, authority: &Pubkey) -> DriftResult<Ref<UserStats>> {
let loader = match self.0.get(authority) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find user stats {} at {}:{}",
authority,
caller.file(),
caller.line()
);
return Err(ErrorCode::UserStatsNotFound);
}
};
match loader.load() {
Ok(user_stats) => Ok(user_stats),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not user stats {} at {}:{}",
authority,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadUserStatsAccount)
}
}
}
#[track_caller]
#[inline(always)]
pub fn get_ref_mut(&self, authority: &Pubkey) -> DriftResult<RefMut<UserStats>> {
let loader = match self.0.get(authority) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find user stats {} at {}:{}",
authority,
caller.file(),
caller.line()
);
return Err(ErrorCode::UserStatsNotFound);
}
};
match loader.load_mut() {
Ok(perp_market) => Ok(perp_market),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not user stats {} at {}:{}",
authority,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadUserStatsAccount)
}
}
}
pub fn insert(
&mut self,
authority: Pubkey,
account_loader: AccountLoader<'a, UserStats>,
) -> DriftResult {
validate!(
!self.0.contains_key(&authority),
ErrorCode::InvalidUserStatsAccount,
"User stats already exists in map {:?}",
authority
)?;
self.0.insert(authority, account_loader);
Ok(())
}
pub fn empty() -> UserStatsMap<'a> {
UserStatsMap(BTreeMap::new())
}
}
#[cfg(test)]
impl<'a> UserStatsMap<'a> {
pub fn load_one<'b: 'a>(account_info: &'b AccountInfo<'a>) -> DriftResult<UserStatsMap<'a>> {
let mut user_stats_map = UserStatsMap(BTreeMap::new());
let user_stats_discriminator: [u8; 8] = UserStats::discriminator();
let _user_stats_key = account_info.key;
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadUserStatsData))?;
let expected_data_len = UserStats::SIZE;
if data.len() < expected_data_len {
return Err(ErrorCode::DefaultError);
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &user_stats_discriminator {
return Err(ErrorCode::DefaultError);
}
let authority_slice = array_ref![data, 8, 32];
let authority = Pubkey::from(*authority_slice);
let is_writable = account_info.is_writable;
if !is_writable {
return Err(ErrorCode::UserStatsWrongMutability);
}
let user_stats_account_loader: AccountLoader<UserStats> =
AccountLoader::try_from(account_info).or(Err(ErrorCode::InvalidUserStatsAccount))?;
user_stats_map
.0
.insert(authority, user_stats_account_loader);
Ok(user_stats_map)
}
}
pub fn load_user_maps<'a: 'b, 'b>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'b>>>,
must_be_writable: bool,
) -> DriftResult<(UserMap<'b>, UserStatsMap<'b>)> {
let mut user_map = UserMap::empty();
let mut user_stats_map = UserStatsMap::empty();
let user_discriminator: [u8; 8] = User::discriminator();
let user_stats_discriminator: [u8; 8] = UserStats::discriminator();
while let Some(user_account_info) = account_info_iter.peek() {
let user_key = user_account_info.key;
let data = user_account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadUserData))?;
let expected_data_len = User::SIZE;
if data.len() < expected_data_len {
break;
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &user_discriminator {
break;
}
let user_account_info = account_info_iter.next().safe_unwrap()?;
let is_writable = user_account_info.is_writable;
if !is_writable && must_be_writable {
return Err(ErrorCode::UserWrongMutability);
}
let user_account_loader: AccountLoader<User> =
AccountLoader::try_from(user_account_info).or(Err(ErrorCode::InvalidUserAccount))?;
user_map.0.insert(*user_key, user_account_loader);
validate!(
account_info_iter.peek().is_some(),
ErrorCode::UserStatsNotFound
)?;
let user_stats_account_info = account_info_iter.peek().safe_unwrap()?;
let data = user_stats_account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadUserStatsData))?;
let expected_data_len = UserStats::SIZE;
if data.len() < expected_data_len {
return Err(ErrorCode::InvalidUserStatsAccount);
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &user_stats_discriminator {
return Err(ErrorCode::InvalidUserStatsAccount);
}
let authority_slice = array_ref![data, 8, 32];
let authority = Pubkey::try_from(*authority_slice).safe_unwrap()?;
let user_stats_account_info = account_info_iter.next().safe_unwrap()?;
if user_stats_map.0.contains_key(&authority) {
continue;
}
let is_writable = user_stats_account_info.is_writable;
if !is_writable && must_be_writable {
return Err(ErrorCode::UserStatsWrongMutability);
}
let user_stats_account_loader: AccountLoader<UserStats> =
AccountLoader::try_from(user_stats_account_info)
.or(Err(ErrorCode::InvalidUserStatsAccount))?;
user_stats_map.insert(authority, user_stats_account_loader)?;
}
Ok((user_map, user_stats_map))
}
pub fn load_user_map<'a: 'b, 'b>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'b>>>,
must_be_writable: bool,
) -> DriftResult<UserMap<'b>> {
let mut user_map = UserMap::empty();
let user_discriminator: [u8; 8] = User::discriminator();
let user_stats_discriminator: [u8; 8] = UserStats::discriminator();
while let Some(user_account_info) = account_info_iter.peek() {
let user_key = user_account_info.key;
let data = user_account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadUserData))?;
let expected_user_data_len = User::SIZE;
let expected_user_stats_len = UserStats::SIZE;
if data.len() < expected_user_data_len && data.len() < expected_user_stats_len {
break;
}
let account_discriminator = array_ref![data, 0, 8];
// if it is user stats, for backwards compatability, just move iter forward
if account_discriminator == &user_stats_discriminator {
account_info_iter.next().safe_unwrap()?;
continue;
}
if account_discriminator != &user_discriminator {
break;
}
let user_account_info = account_info_iter.next().safe_unwrap()?;
let is_writable = user_account_info.is_writable;
if !is_writable && must_be_writable {
return Err(ErrorCode::UserWrongMutability);
}
let user_account_loader: AccountLoader<User> =
AccountLoader::try_from(user_account_info).or(Err(ErrorCode::InvalidUserAccount))?;
user_map.0.insert(*user_key, user_account_loader);
}
Ok(user_map)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/user.rs
|
use crate::controller::lp::apply_lp_rebase_to_perp_position;
use crate::controller::position::{add_new_position, get_position_index, PositionDirection};
use crate::error::{DriftResult, ErrorCode};
use crate::math::auction::{calculate_auction_price, is_auction_complete};
use crate::math::casting::Cast;
use crate::math::constants::{
EPOCH_DURATION, FUEL_START_TS, OPEN_ORDER_MARGIN_REQUIREMENT,
PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO, QUOTE_PRECISION, QUOTE_SPOT_MARKET_INDEX, THIRTY_DAY,
};
use crate::math::lp::{calculate_lp_open_bids_asks, calculate_settle_lp_metrics};
use crate::math::margin::MarginRequirementType;
use crate::math::orders::{standardize_base_asset_amount, standardize_price};
use crate::math::position::{
calculate_base_asset_value_and_pnl_with_oracle_price,
calculate_base_asset_value_with_oracle_price, calculate_perp_liability_value,
};
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::{
get_signed_token_amount, get_strict_token_value, get_token_amount, get_token_value,
};
use crate::math::stats::calculate_rolling_sum;
use crate::state::oracle::StrictOraclePrice;
use crate::state::perp_market::{ContractType, PerpMarket};
use crate::state::spot_market::{SpotBalance, SpotBalanceType, SpotMarket};
use crate::state::traits::Size;
use crate::{get_then_update_id, ID, PERCENTAGE_PRECISION_I64, QUOTE_PRECISION_U64};
use crate::{math_error, SPOT_WEIGHT_PRECISION_I128};
use crate::{safe_increment, SPOT_WEIGHT_PRECISION};
use crate::{validate, MAX_PREDICTION_MARKET_PRICE};
use anchor_lang::prelude::*;
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::msg;
use std::cmp::max;
use std::fmt;
use std::ops::Neg;
use std::panic::Location;
use crate::math::margin::{
calculate_margin_requirement_and_total_collateral_and_liability_info,
validate_any_isolated_tier_requirements,
};
use crate::state::margin_calculation::{MarginCalculation, MarginContext};
use crate::state::oracle_map::OracleMap;
use crate::state::perp_market_map::PerpMarketMap;
use crate::state::spot_market_map::SpotMarketMap;
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq)]
pub enum UserStatus {
// Active = 0
BeingLiquidated = 0b00000001,
Bankrupt = 0b00000010,
ReduceOnly = 0b00000100,
AdvancedLp = 0b00001000,
ProtectedMakerOrders = 0b00010000,
}
// implement SIZE const for User
impl Size for User {
const SIZE: usize = 4376;
}
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct User {
/// The owner/authority of the account
pub authority: Pubkey,
/// An addresses that can control the account on the authority's behalf. Has limited power, cant withdraw
pub delegate: Pubkey,
/// Encoded display name e.g. "toly"
pub name: [u8; 32],
/// The user's spot positions
pub spot_positions: [SpotPosition; 8],
/// The user's perp positions
pub perp_positions: [PerpPosition; 8],
/// The user's orders
pub orders: [Order; 32],
/// The last time the user added perp lp positions
pub last_add_perp_lp_shares_ts: i64,
/// The total values of deposits the user has made
/// precision: QUOTE_PRECISION
pub total_deposits: u64,
/// The total values of withdrawals the user has made
/// precision: QUOTE_PRECISION
pub total_withdraws: u64,
/// The total socialized loss the users has incurred upon the protocol
/// precision: QUOTE_PRECISION
pub total_social_loss: u64,
/// Fees (taker fees, maker rebate, referrer reward, filler reward) and pnl for perps
/// precision: QUOTE_PRECISION
pub settled_perp_pnl: i64,
/// Fees (taker fees, maker rebate, filler reward) for spot
/// precision: QUOTE_PRECISION
pub cumulative_spot_fees: i64,
/// Cumulative funding paid/received for perps
/// precision: QUOTE_PRECISION
pub cumulative_perp_funding: i64,
/// The amount of margin freed during liquidation. Used to force the liquidation to occur over a period of time
/// Defaults to zero when not being liquidated
/// precision: QUOTE_PRECISION
pub liquidation_margin_freed: u64,
/// The last slot a user was active. Used to determine if a user is idle
pub last_active_slot: u64,
/// Every user order has an order id. This is the next order id to be used
pub next_order_id: u32,
/// Custom max initial margin ratio for the user
pub max_margin_ratio: u32,
/// The next liquidation id to be used for user
pub next_liquidation_id: u16,
/// The sub account id for this user
pub sub_account_id: u16,
/// Whether the user is active, being liquidated or bankrupt
pub status: u8,
/// Whether the user has enabled margin trading
pub is_margin_trading_enabled: bool,
/// User is idle if they haven't interacted with the protocol in 1 week and they have no orders, perp positions or borrows
/// Off-chain keeper bots can ignore users that are idle
pub idle: bool,
/// number of open orders
pub open_orders: u8,
/// Whether or not user has open order
pub has_open_order: bool,
/// number of open orders with auction
pub open_auctions: u8,
/// Whether or not user has open order with auction
pub has_open_auction: bool,
pub margin_mode: MarginMode,
pub pool_id: u8,
pub padding1: [u8; 3],
pub last_fuel_bonus_update_ts: u32,
pub padding: [u8; 12],
}
impl User {
pub fn is_being_liquidated(&self) -> bool {
self.status & (UserStatus::BeingLiquidated as u8 | UserStatus::Bankrupt as u8) > 0
}
pub fn is_bankrupt(&self) -> bool {
self.status & (UserStatus::Bankrupt as u8) > 0
}
pub fn is_reduce_only(&self) -> bool {
self.status & (UserStatus::ReduceOnly as u8) > 0
}
pub fn is_advanced_lp(&self) -> bool {
self.status & (UserStatus::AdvancedLp as u8) > 0
}
pub fn is_protected_maker(&self) -> bool {
self.status & (UserStatus::ProtectedMakerOrders as u8) > 0
}
pub fn add_user_status(&mut self, status: UserStatus) {
self.status |= status as u8;
}
pub fn remove_user_status(&mut self, status: UserStatus) {
self.status &= !(status as u8);
}
pub fn get_spot_position_index(&self, market_index: u16) -> DriftResult<usize> {
// first spot position is always quote asset
if market_index == 0 {
validate!(
self.spot_positions[0].market_index == 0,
ErrorCode::DefaultError,
"User position 0 not market_index=0"
)?;
return Ok(0);
}
self.spot_positions
.iter()
.position(|spot_position| spot_position.market_index == market_index)
.ok_or(ErrorCode::CouldNotFindSpotPosition)
}
pub fn get_spot_position(&self, market_index: u16) -> DriftResult<&SpotPosition> {
self.get_spot_position_index(market_index)
.map(|market_index| &self.spot_positions[market_index])
}
pub fn get_spot_position_mut(&mut self, market_index: u16) -> DriftResult<&mut SpotPosition> {
self.get_spot_position_index(market_index)
.map(move |market_index| &mut self.spot_positions[market_index])
}
pub fn get_quote_spot_position(&self) -> &SpotPosition {
match self.get_spot_position(QUOTE_SPOT_MARKET_INDEX) {
Ok(position) => position,
Err(_) => unreachable!(),
}
}
pub fn get_quote_spot_position_mut(&mut self) -> &mut SpotPosition {
match self.get_spot_position_mut(QUOTE_SPOT_MARKET_INDEX) {
Ok(position) => position,
Err(_) => unreachable!(),
}
}
pub fn add_spot_position(
&mut self,
market_index: u16,
balance_type: SpotBalanceType,
) -> DriftResult<usize> {
let new_spot_position_index = self
.spot_positions
.iter()
.enumerate()
.position(|(index, spot_position)| index != 0 && spot_position.is_available())
.ok_or(ErrorCode::NoSpotPositionAvailable)?;
let new_spot_position = SpotPosition {
market_index,
balance_type,
..SpotPosition::default()
};
self.spot_positions[new_spot_position_index] = new_spot_position;
Ok(new_spot_position_index)
}
pub fn force_get_spot_position_mut(
&mut self,
market_index: u16,
) -> DriftResult<&mut SpotPosition> {
self.get_spot_position_index(market_index)
.or_else(|_| self.add_spot_position(market_index, SpotBalanceType::Deposit))
.map(move |market_index| &mut self.spot_positions[market_index])
}
pub fn force_get_spot_position_index(&mut self, market_index: u16) -> DriftResult<usize> {
self.get_spot_position_index(market_index)
.or_else(|_| self.add_spot_position(market_index, SpotBalanceType::Deposit))
}
pub fn get_perp_position(&self, market_index: u16) -> DriftResult<&PerpPosition> {
Ok(&self.perp_positions[get_position_index(&self.perp_positions, market_index)?])
}
pub fn get_perp_position_mut(&mut self, market_index: u16) -> DriftResult<&mut PerpPosition> {
Ok(&mut self.perp_positions[get_position_index(&self.perp_positions, market_index)?])
}
pub fn force_get_perp_position_mut(
&mut self,
market_index: u16,
) -> DriftResult<&mut PerpPosition> {
let position_index = get_position_index(&self.perp_positions, market_index)
.or_else(|_| add_new_position(&mut self.perp_positions, market_index))?;
Ok(&mut self.perp_positions[position_index])
}
pub fn get_order_index(&self, order_id: u32) -> DriftResult<usize> {
self.orders
.iter()
.position(|order| order.order_id == order_id && order.status == OrderStatus::Open)
.ok_or(ErrorCode::OrderDoesNotExist)
}
pub fn get_order_index_by_user_order_id(&self, user_order_id: u8) -> DriftResult<usize> {
self.orders
.iter()
.position(|order| {
order.user_order_id == user_order_id && order.status == OrderStatus::Open
})
.ok_or(ErrorCode::OrderDoesNotExist)
}
pub fn get_order(&self, order_id: u32) -> Option<&Order> {
self.orders.iter().find(|order| order.order_id == order_id)
}
pub fn get_last_order_id(&self) -> u32 {
if self.next_order_id == 1 {
u32::MAX
} else {
self.next_order_id - 1
}
}
pub fn increment_total_deposits(
&mut self,
amount: u64,
price: i64,
precision: u128,
) -> DriftResult {
let value = amount
.cast::<u128>()?
.safe_mul(price.cast::<u128>()?)?
.safe_div(precision)?
.cast::<u64>()?;
self.total_deposits = self.total_deposits.saturating_add(value);
Ok(())
}
pub fn increment_total_withdraws(
&mut self,
amount: u64,
price: i64,
precision: u128,
) -> DriftResult {
let value = amount
.cast::<u128>()?
.safe_mul(price.cast()?)?
.safe_div(precision)?
.cast::<u64>()?;
self.total_withdraws = self.total_withdraws.saturating_add(value);
Ok(())
}
pub fn increment_total_socialized_loss(&mut self, value: u64) -> DriftResult {
self.total_social_loss = self.total_social_loss.saturating_add(value);
Ok(())
}
pub fn update_cumulative_spot_fees(&mut self, amount: i64) -> DriftResult {
safe_increment!(self.cumulative_spot_fees, amount);
Ok(())
}
pub fn update_cumulative_perp_funding(&mut self, amount: i64) -> DriftResult {
safe_increment!(self.cumulative_perp_funding, amount);
Ok(())
}
pub fn enter_liquidation(&mut self, slot: u64) -> DriftResult<u16> {
if self.is_being_liquidated() {
return self.next_liquidation_id.safe_sub(1);
}
self.add_user_status(UserStatus::BeingLiquidated);
self.liquidation_margin_freed = 0;
self.last_active_slot = slot;
Ok(get_then_update_id!(self, next_liquidation_id))
}
pub fn exit_liquidation(&mut self) {
self.remove_user_status(UserStatus::BeingLiquidated);
self.remove_user_status(UserStatus::Bankrupt);
self.liquidation_margin_freed = 0;
}
pub fn enter_bankruptcy(&mut self) {
self.remove_user_status(UserStatus::BeingLiquidated);
self.add_user_status(UserStatus::Bankrupt);
}
pub fn exit_bankruptcy(&mut self) {
self.remove_user_status(UserStatus::BeingLiquidated);
self.remove_user_status(UserStatus::Bankrupt);
self.liquidation_margin_freed = 0;
}
pub fn increment_margin_freed(&mut self, margin_free: u64) -> DriftResult {
self.liquidation_margin_freed = self.liquidation_margin_freed.safe_add(margin_free)?;
Ok(())
}
pub fn update_last_active_slot(&mut self, slot: u64) {
if !self.is_being_liquidated() {
self.last_active_slot = slot;
}
self.idle = false;
}
pub fn increment_open_orders(&mut self, is_auction: bool) {
self.open_orders = self.open_orders.saturating_add(1);
self.has_open_order = self.open_orders > 0;
if is_auction {
self.increment_open_auctions();
}
}
pub fn increment_open_auctions(&mut self) {
self.open_auctions = self.open_auctions.saturating_add(1);
self.has_open_auction = self.open_auctions > 0;
}
pub fn decrement_open_orders(&mut self, is_auction: bool) {
self.open_orders = self.open_orders.saturating_sub(1);
self.has_open_order = self.open_orders > 0;
if is_auction {
self.open_auctions = self.open_auctions.saturating_sub(1);
self.has_open_auction = self.open_auctions > 0;
}
}
pub fn update_reduce_only_status(&mut self, reduce_only: bool) -> DriftResult {
if reduce_only {
self.add_user_status(UserStatus::ReduceOnly);
} else {
self.remove_user_status(UserStatus::ReduceOnly);
}
Ok(())
}
pub fn update_advanced_lp_status(&mut self, advanced_lp: bool) -> DriftResult {
if advanced_lp {
self.add_user_status(UserStatus::AdvancedLp);
} else {
self.remove_user_status(UserStatus::AdvancedLp);
}
Ok(())
}
pub fn update_protected_maker_orders_status(
&mut self,
protected_maker_orders: bool,
) -> DriftResult {
if protected_maker_orders {
self.add_user_status(UserStatus::ProtectedMakerOrders);
} else {
self.remove_user_status(UserStatus::ProtectedMakerOrders);
}
Ok(())
}
pub fn has_room_for_new_order(&self) -> bool {
for order in self.orders.iter() {
if order.status == OrderStatus::Init {
return true;
}
}
false
}
pub fn is_high_leverage_mode(&self) -> bool {
self.margin_mode == MarginMode::HighLeverage
}
pub fn get_fuel_bonus_numerator(&self, now: i64) -> DriftResult<i64> {
if self.last_fuel_bonus_update_ts > 0 {
now.safe_sub(self.last_fuel_bonus_update_ts.cast()?)
} else {
// start ts for existing accounts pre fuel
if now > FUEL_START_TS {
now.safe_sub(FUEL_START_TS)
} else {
Ok(0)
}
}
}
pub fn calculate_margin_and_increment_fuel_bonus(
&mut self,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
context: MarginContext,
user_stats: &mut UserStats,
now: i64,
) -> DriftResult<MarginCalculation> {
let fuel_bonus_numerator = self.get_fuel_bonus_numerator(now)?;
validate!(
context.fuel_bonus_numerator == fuel_bonus_numerator,
ErrorCode::DefaultError,
"Bad fuel bonus update attempt {} != {} (last_fuel_bonus_update_ts = {} vs now = {})",
context.fuel_bonus_numerator,
fuel_bonus_numerator,
self.last_fuel_bonus_update_ts,
now
)?;
let margin_calculation =
calculate_margin_requirement_and_total_collateral_and_liability_info(
self,
perp_market_map,
spot_market_map,
oracle_map,
context,
)?;
user_stats.update_fuel_bonus(
self,
margin_calculation.fuel_deposits,
margin_calculation.fuel_borrows,
margin_calculation.fuel_positions,
now,
)?;
Ok(margin_calculation)
}
pub fn meets_withdraw_margin_requirement_and_increment_fuel_bonus(
&mut self,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
margin_requirement_type: MarginRequirementType,
withdraw_market_index: u16,
withdraw_amount: u128,
user_stats: &mut UserStats,
now: i64,
) -> DriftResult<bool> {
let strict = margin_requirement_type == MarginRequirementType::Initial;
let context = MarginContext::standard(margin_requirement_type)
.strict(strict)
.ignore_invalid_deposit_oracles(true)
.fuel_spot_delta(withdraw_market_index, withdraw_amount.cast::<i128>()?)
.fuel_numerator(self, now);
let calculation = calculate_margin_requirement_and_total_collateral_and_liability_info(
self,
perp_market_map,
spot_market_map,
oracle_map,
context,
)?;
if calculation.margin_requirement > 0 || calculation.get_num_of_liabilities()? > 0 {
validate!(
calculation.all_liability_oracles_valid,
ErrorCode::InvalidOracle,
"User attempting to withdraw with outstanding liabilities when an oracle is invalid"
)?;
}
validate_any_isolated_tier_requirements(self, calculation)?;
validate!(
calculation.meets_margin_requirement(),
ErrorCode::InsufficientCollateral,
"User attempting to withdraw where total_collateral {} is below initial_margin_requirement {}",
calculation.total_collateral,
calculation.margin_requirement
)?;
user_stats.update_fuel_bonus(
self,
calculation.fuel_deposits,
calculation.fuel_borrows,
calculation.fuel_positions,
now,
)?;
Ok(true)
}
pub fn can_skip_auction_duration(
&self,
user_stats: &UserStats,
is_auction: bool,
is_ioc: bool,
order_direction: PositionDirection,
order_price: u64,
oracle_price_offset: i32,
oracle_price: i64,
) -> DriftResult<bool> {
if self.next_order_id > 3000 {
return Ok(false);
}
if !is_auction || is_ioc {
return Ok(false);
}
if user_stats.number_of_sub_accounts_created > 10 {
return Ok(false);
}
if user_stats.disable_update_perp_bid_ask_twap {
return Ok(false);
}
return if order_price == 0 {
Ok(true)
} else {
let mut order_offset: i64 = if order_price != 0 {
order_price.cast::<i64>()?.safe_sub(oracle_price)?
} else {
oracle_price_offset.cast::<i64>()?
};
if order_direction == PositionDirection::Short {
order_offset = -order_offset;
}
// worst price is 10 bps past oracle
Ok(order_offset
.safe_mul(PERCENTAGE_PRECISION_I64)?
.safe_div(oracle_price)?
>= 1000)
};
}
}
pub fn derive_user_account(authority: &Pubkey, sub_account_id: u16) -> Pubkey {
let (account_drift_pda, _seed) = Pubkey::find_program_address(
&[
&b"user"[..],
authority.as_ref(),
&sub_account_id.to_le_bytes(),
],
&ID,
);
account_drift_pda
}
#[zero_copy(unsafe)]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct UserFees {
/// Total taker fee paid
/// precision: QUOTE_PRECISION
pub total_fee_paid: u64,
/// Total maker fee rebate
/// precision: QUOTE_PRECISION
pub total_fee_rebate: u64,
/// Total discount from holding token
/// precision: QUOTE_PRECISION
pub total_token_discount: u64,
/// Total discount from being referred
/// precision: QUOTE_PRECISION
pub total_referee_discount: u64,
/// Total reward to referrer
/// precision: QUOTE_PRECISION
pub total_referrer_reward: u64,
/// Total reward to referrer this epoch
/// precision: QUOTE_PRECISION
pub current_epoch_referrer_reward: u64,
}
#[zero_copy(unsafe)]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct SpotPosition {
/// The scaled balance of the position. To get the token amount, multiply by the cumulative deposit/borrow
/// interest of corresponding market.
/// precision: SPOT_BALANCE_PRECISION
pub scaled_balance: u64,
/// How many spot bids the user has open
/// precision: token mint precision
pub open_bids: i64,
/// How many spot asks the user has open
/// precision: token mint precision
pub open_asks: i64,
/// The cumulative deposits/borrows a user has made into a market
/// precision: token mint precision
pub cumulative_deposits: i64,
/// The market index of the corresponding spot market
pub market_index: u16,
/// Whether the position is deposit or borrow
pub balance_type: SpotBalanceType,
/// Number of open orders
pub open_orders: u8,
pub padding: [u8; 4],
}
impl SpotBalance for SpotPosition {
fn market_index(&self) -> u16 {
self.market_index
}
fn balance_type(&self) -> &SpotBalanceType {
&self.balance_type
}
fn balance(&self) -> u128 {
self.scaled_balance as u128
}
fn increase_balance(&mut self, delta: u128) -> DriftResult {
self.scaled_balance = self.scaled_balance.safe_add(delta.cast()?)?;
Ok(())
}
fn decrease_balance(&mut self, delta: u128) -> DriftResult {
self.scaled_balance = self.scaled_balance.safe_sub(delta.cast()?)?;
Ok(())
}
fn update_balance_type(&mut self, balance_type: SpotBalanceType) -> DriftResult {
self.balance_type = balance_type;
Ok(())
}
}
#[derive(Clone, Copy, Default, Eq, PartialEq, Debug)]
pub struct OrderFillSimulation {
pub token_amount: i128,
pub orders_value: i128,
pub token_value: i128,
pub weighted_token_value: i128,
pub free_collateral_contribution: i128,
}
impl OrderFillSimulation {
pub fn riskier_side(ask: Self, bid: Self) -> Self {
if ask.free_collateral_contribution <= bid.free_collateral_contribution {
ask
} else {
bid
}
}
pub fn risk_increasing(&self, after: Self) -> bool {
after.free_collateral_contribution < self.free_collateral_contribution
}
pub fn apply_user_custom_margin_ratio(
mut self,
spot_market: &SpotMarket,
oracle_price: i64,
user_custom_margin_ratio: u32,
) -> DriftResult<Self> {
if user_custom_margin_ratio == 0 {
return Ok(self);
}
if self.weighted_token_value < 0 {
let max_liability_weight = spot_market
.get_liability_weight(
self.token_amount.unsigned_abs(),
&MarginRequirementType::Initial,
)?
.max(user_custom_margin_ratio.safe_add(SPOT_WEIGHT_PRECISION)?);
self.weighted_token_value = self
.token_value
.safe_mul(max_liability_weight.cast()?)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)?;
} else if self.weighted_token_value > 0 {
let min_asset_weight = spot_market
.get_asset_weight(
self.token_amount.unsigned_abs(),
oracle_price,
&MarginRequirementType::Initial,
)?
.min(SPOT_WEIGHT_PRECISION.saturating_sub(user_custom_margin_ratio));
self.weighted_token_value = self
.token_value
.safe_mul(min_asset_weight.cast()?)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)?;
}
self.free_collateral_contribution =
self.weighted_token_value.safe_add(self.orders_value)?;
Ok(self)
}
}
impl SpotPosition {
pub fn is_available(&self) -> bool {
self.scaled_balance == 0 && self.open_orders == 0
}
pub fn has_open_order(&self) -> bool {
self.open_orders != 0 || self.open_bids != 0 || self.open_asks != 0
}
pub fn margin_requirement_for_open_orders(&self) -> DriftResult<u128> {
self.open_orders
.cast::<u128>()?
.safe_mul(OPEN_ORDER_MARGIN_REQUIREMENT)
}
pub fn get_token_amount(&self, spot_market: &SpotMarket) -> DriftResult<u128> {
get_token_amount(self.scaled_balance.cast()?, spot_market, &self.balance_type)
}
pub fn get_signed_token_amount(&self, spot_market: &SpotMarket) -> DriftResult<i128> {
get_signed_token_amount(
get_token_amount(self.scaled_balance.cast()?, spot_market, &self.balance_type)?,
&self.balance_type,
)
}
pub fn get_worst_case_fill_simulation(
&self,
spot_market: &SpotMarket,
strict_oracle_price: &StrictOraclePrice,
token_amount: Option<i128>,
margin_type: MarginRequirementType,
) -> DriftResult<OrderFillSimulation> {
let [bid_simulation, ask_simulation] = self.simulate_fills_both_sides(
spot_market,
strict_oracle_price,
token_amount,
margin_type,
)?;
Ok(OrderFillSimulation::riskier_side(
ask_simulation,
bid_simulation,
))
}
pub fn simulate_fills_both_sides(
&self,
spot_market: &SpotMarket,
strict_oracle_price: &StrictOraclePrice,
token_amount: Option<i128>,
margin_type: MarginRequirementType,
) -> DriftResult<[OrderFillSimulation; 2]> {
let token_amount = match token_amount {
Some(token_amount) => token_amount,
None => self.get_signed_token_amount(spot_market)?,
};
let token_value =
get_strict_token_value(token_amount, spot_market.decimals, strict_oracle_price)?;
let calculate_weighted_token_value = |token_amount: i128, token_value: i128| {
if token_value > 0 {
let asset_weight = spot_market.get_asset_weight(
token_amount.unsigned_abs(),
strict_oracle_price.current,
&margin_type,
)?;
token_value
.safe_mul(asset_weight.cast()?)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)
} else if token_value < 0 {
let liability_weight =
spot_market.get_liability_weight(token_amount.unsigned_abs(), &margin_type)?;
token_value
.safe_mul(liability_weight.cast()?)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)
} else {
Ok(0)
}
};
if self.open_bids == 0 && self.open_asks == 0 {
let weighted_token_value = calculate_weighted_token_value(token_amount, token_value)?;
let calculation = OrderFillSimulation {
token_amount,
orders_value: 0,
token_value,
weighted_token_value,
free_collateral_contribution: weighted_token_value,
};
return Ok([calculation, calculation]);
}
let simulate_side = |strict_oracle_price: &StrictOraclePrice,
token_amount: i128,
open_orders: i128| {
let order_value = get_token_value(
-open_orders,
spot_market.decimals,
strict_oracle_price.max(),
)?;
let token_amount_after_fill = token_amount.safe_add(open_orders)?;
let token_value_after_fill = token_value.safe_add(order_value.neg())?;
let weighted_token_value_after_fill =
calculate_weighted_token_value(token_amount_after_fill, token_value_after_fill)?;
let free_collateral_contribution =
weighted_token_value_after_fill.safe_add(order_value)?;
Ok(OrderFillSimulation {
token_amount: token_amount_after_fill,
orders_value: order_value,
token_value: token_value_after_fill,
weighted_token_value: weighted_token_value_after_fill,
free_collateral_contribution,
})
};
let bid_simulation =
simulate_side(strict_oracle_price, token_amount, self.open_bids.cast()?)?;
let ask_simulation =
simulate_side(strict_oracle_price, token_amount, self.open_asks.cast()?)?;
Ok([bid_simulation, ask_simulation])
}
pub fn is_borrow(&self) -> bool {
self.scaled_balance > 0 && self.balance_type == SpotBalanceType::Borrow
}
}
#[zero_copy(unsafe)]
#[derive(Default, Debug, Eq, PartialEq)]
#[repr(C)]
pub struct PerpPosition {
/// The perp market's last cumulative funding rate. Used to calculate the funding payment owed to user
/// precision: FUNDING_RATE_PRECISION
pub last_cumulative_funding_rate: i64,
/// the size of the users perp position
/// precision: BASE_PRECISION
pub base_asset_amount: i64,
/// Used to calculate the users pnl. Upon entry, is equal to base_asset_amount * avg entry price - fees
/// Updated when the user open/closes position or settles pnl. Includes fees/funding
/// precision: QUOTE_PRECISION
pub quote_asset_amount: i64,
/// The amount of quote the user would need to exit their position at to break even
/// Updated when the user open/closes position or settles pnl. Includes fees/funding
/// precision: QUOTE_PRECISION
pub quote_break_even_amount: i64,
/// The amount quote the user entered the position with. Equal to base asset amount * avg entry price
/// Updated when the user open/closes position. Excludes fees/funding
/// precision: QUOTE_PRECISION
pub quote_entry_amount: i64,
/// The amount of open bids the user has in this perp market
/// precision: BASE_PRECISION
pub open_bids: i64,
/// The amount of open asks the user has in this perp market
/// precision: BASE_PRECISION
pub open_asks: i64,
/// The amount of pnl settled in this market since opening the position
/// precision: QUOTE_PRECISION
pub settled_pnl: i64,
/// The number of lp (liquidity provider) shares the user has in this perp market
/// LP shares allow users to provide liquidity via the AMM
/// precision: BASE_PRECISION
pub lp_shares: u64,
/// The last base asset amount per lp the amm had
/// Used to settle the users lp position
/// precision: BASE_PRECISION
pub last_base_asset_amount_per_lp: i64,
/// The last quote asset amount per lp the amm had
/// Used to settle the users lp position
/// precision: QUOTE_PRECISION
pub last_quote_asset_amount_per_lp: i64,
/// Settling LP position can lead to a small amount of base asset being left over smaller than step size
/// This records that remainder so it can be settled later on
/// precision: BASE_PRECISION
pub remainder_base_asset_amount: i32,
/// The market index for the perp market
pub market_index: u16,
/// The number of open orders
pub open_orders: u8,
pub per_lp_base: i8,
}
impl PerpPosition {
pub fn is_for(&self, market_index: u16) -> bool {
self.market_index == market_index && !self.is_available()
}
pub fn is_available(&self) -> bool {
!self.is_open_position()
&& !self.has_open_order()
&& !self.has_unsettled_pnl()
&& !self.is_lp()
}
pub fn is_open_position(&self) -> bool {
self.base_asset_amount != 0
}
pub fn has_open_order(&self) -> bool {
self.open_orders != 0 || self.open_bids != 0 || self.open_asks != 0
}
pub fn margin_requirement_for_lp_shares(
&self,
order_step_size: u64,
valuation_price: i64,
) -> DriftResult<u128> {
if !self.is_lp() {
return Ok(0);
}
Ok(QUOTE_PRECISION.max(
order_step_size
.cast::<u128>()?
.safe_mul(valuation_price.cast()?)?
.safe_div(PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO)?,
))
}
pub fn margin_requirement_for_open_orders(&self) -> DriftResult<u128> {
self.open_orders
.cast::<u128>()?
.safe_mul(OPEN_ORDER_MARGIN_REQUIREMENT)
}
pub fn is_lp(&self) -> bool {
self.lp_shares > 0
}
pub fn simulate_settled_lp_position(
&self,
market: &PerpMarket,
valuation_price: i64,
) -> DriftResult<PerpPosition> {
let mut settled_position = *self;
if !settled_position.is_lp() {
return Ok(settled_position);
}
apply_lp_rebase_to_perp_position(market, &mut settled_position)?;
// compute lp metrics
let mut lp_metrics = calculate_settle_lp_metrics(&market.amm, &settled_position)?;
// compute settled position
let base_asset_amount = settled_position
.base_asset_amount
.safe_add(lp_metrics.base_asset_amount.cast()?)?;
let mut quote_asset_amount = settled_position
.quote_asset_amount
.safe_add(lp_metrics.quote_asset_amount.cast()?)?;
let mut new_remainder_base_asset_amount = settled_position
.remainder_base_asset_amount
.cast::<i64>()?
.safe_add(lp_metrics.remainder_base_asset_amount.cast()?)?;
if new_remainder_base_asset_amount.unsigned_abs() >= market.amm.order_step_size {
let (standardized_remainder_base_asset_amount, remainder_base_asset_amount) =
crate::math::orders::standardize_base_asset_amount_with_remainder_i128(
new_remainder_base_asset_amount.cast()?,
market.amm.order_step_size.cast()?,
)?;
lp_metrics.base_asset_amount = lp_metrics
.base_asset_amount
.safe_add(standardized_remainder_base_asset_amount)?;
new_remainder_base_asset_amount = remainder_base_asset_amount.cast()?;
} else {
new_remainder_base_asset_amount = new_remainder_base_asset_amount.cast()?;
}
// dust position in baa/qaa
if new_remainder_base_asset_amount != 0 {
let dust_base_asset_value = calculate_base_asset_value_with_oracle_price(
new_remainder_base_asset_amount.cast()?,
valuation_price,
)?
.safe_add(1)?;
quote_asset_amount = quote_asset_amount.safe_sub(dust_base_asset_value.cast()?)?;
}
let (lp_bids, lp_asks) = calculate_lp_open_bids_asks(&settled_position, market)?;
let open_bids = settled_position.open_bids.safe_add(lp_bids)?;
let open_asks = settled_position.open_asks.safe_add(lp_asks)?;
settled_position.base_asset_amount = base_asset_amount;
settled_position.quote_asset_amount = quote_asset_amount;
settled_position.open_bids = open_bids;
settled_position.open_asks = open_asks;
Ok(settled_position)
}
pub fn has_unsettled_pnl(&self) -> bool {
self.base_asset_amount == 0 && self.quote_asset_amount != 0
}
pub fn worst_case_base_asset_amount(
&self,
oracle_price: i64,
contract_type: ContractType,
) -> DriftResult<i128> {
self.worst_case_liability_value(oracle_price, contract_type)
.map(|v| v.0)
}
pub fn worst_case_liability_value(
&self,
oracle_price: i64,
contract_type: ContractType,
) -> DriftResult<(i128, u128)> {
let base_asset_amount_all_bids_fill = self
.base_asset_amount
.safe_add(self.open_bids)?
.cast::<i128>()?;
let base_asset_amount_all_asks_fill = self
.base_asset_amount
.safe_add(self.open_asks)?
.cast::<i128>()?;
let liability_value_all_bids_fill = calculate_perp_liability_value(
base_asset_amount_all_bids_fill,
oracle_price,
contract_type,
)?;
let liability_value_all_asks_fill = calculate_perp_liability_value(
base_asset_amount_all_asks_fill,
oracle_price,
contract_type,
)?;
if liability_value_all_asks_fill >= liability_value_all_bids_fill {
Ok((
base_asset_amount_all_asks_fill,
liability_value_all_asks_fill,
))
} else {
Ok((
base_asset_amount_all_bids_fill,
liability_value_all_bids_fill,
))
}
}
pub fn get_direction(&self) -> PositionDirection {
if self.base_asset_amount >= 0 {
PositionDirection::Long
} else {
PositionDirection::Short
}
}
pub fn get_direction_to_close(&self) -> PositionDirection {
if self.base_asset_amount >= 0 {
PositionDirection::Short
} else {
PositionDirection::Long
}
}
pub fn get_unrealized_pnl(&self, oracle_price: i64) -> DriftResult<i128> {
let (_, unrealized_pnl) =
calculate_base_asset_value_and_pnl_with_oracle_price(self, oracle_price)?;
Ok(unrealized_pnl)
}
pub fn get_base_asset_amount_with_remainder(&self) -> DriftResult<i128> {
if self.remainder_base_asset_amount != 0 {
self.base_asset_amount
.cast::<i128>()?
.safe_add(self.remainder_base_asset_amount.cast::<i128>()?)
} else {
self.base_asset_amount.cast::<i128>()
}
}
pub fn get_base_asset_amount_with_remainder_abs(&self) -> DriftResult<i128> {
Ok(self.get_base_asset_amount_with_remainder()?.abs())
}
pub fn get_claimable_pnl(&self, oracle_price: i64, pnl_pool_excess: i128) -> DriftResult<i128> {
let (_, unrealized_pnl) =
calculate_base_asset_value_and_pnl_with_oracle_price(self, oracle_price)?;
if unrealized_pnl > 0 {
// this limits the amount of positive pnl that can be settled to be the amount of positive pnl
// realized by reducing/closing position
let max_positive_pnl = self
.quote_asset_amount
.cast::<i128>()?
.safe_sub(self.quote_entry_amount.cast()?)
.map(|delta| delta.max(0))?
.safe_add(pnl_pool_excess.max(0))?;
if max_positive_pnl < unrealized_pnl {
msg!(
"Claimable pnl below position upnl: {} < {}",
max_positive_pnl,
unrealized_pnl
);
}
Ok(unrealized_pnl.min(max_positive_pnl))
} else {
Ok(unrealized_pnl)
}
}
}
pub(crate) type PerpPositions = [PerpPosition; 8];
#[cfg(test)]
use crate::math::constants::{AMM_TO_QUOTE_PRECISION_RATIO_I128, PRICE_PRECISION_I128};
#[cfg(test)]
impl PerpPosition {
pub fn get_breakeven_price(&self) -> DriftResult<i128> {
let base_with_remainder = self.get_base_asset_amount_with_remainder()?;
if base_with_remainder == 0 {
return Ok(0);
}
(-self.quote_break_even_amount.cast::<i128>()?)
.safe_mul(PRICE_PRECISION_I128)?
.safe_mul(AMM_TO_QUOTE_PRECISION_RATIO_I128)?
.safe_div(base_with_remainder)
}
pub fn get_entry_price(&self) -> DriftResult<i128> {
let base_with_remainder = self.get_base_asset_amount_with_remainder()?;
if base_with_remainder == 0 {
return Ok(0);
}
(-self.quote_entry_amount.cast::<i128>()?)
.safe_mul(PRICE_PRECISION_I128)?
.safe_mul(AMM_TO_QUOTE_PRECISION_RATIO_I128)?
.safe_div(base_with_remainder)
}
pub fn get_cost_basis(&self) -> DriftResult<i128> {
if self.base_asset_amount == 0 {
return Ok(0);
}
(-self.quote_asset_amount.cast::<i128>()?)
.safe_mul(PRICE_PRECISION_I128)?
.safe_mul(AMM_TO_QUOTE_PRECISION_RATIO_I128)?
.safe_div(self.base_asset_amount.cast()?)
}
}
#[zero_copy(unsafe)]
#[repr(C)]
#[derive(AnchorSerialize, AnchorDeserialize, PartialEq, Debug, Eq)]
pub struct Order {
/// The slot the order was placed
pub slot: u64,
/// The limit price for the order (can be 0 for market orders)
/// For orders with an auction, this price isn't used until the auction is complete
/// precision: PRICE_PRECISION
pub price: u64,
/// The size of the order
/// precision for perps: BASE_PRECISION
/// precision for spot: token mint precision
pub base_asset_amount: u64,
/// The amount of the order filled
/// precision for perps: BASE_PRECISION
/// precision for spot: token mint precision
pub base_asset_amount_filled: u64,
/// The amount of quote filled for the order
/// precision: QUOTE_PRECISION
pub quote_asset_amount_filled: u64,
/// At what price the order will be triggered. Only relevant for trigger orders
/// precision: PRICE_PRECISION
pub trigger_price: u64,
/// The start price for the auction. Only relevant for market/oracle orders
/// precision: PRICE_PRECISION
pub auction_start_price: i64,
/// The end price for the auction. Only relevant for market/oracle orders
/// precision: PRICE_PRECISION
pub auction_end_price: i64,
/// The time when the order will expire
pub max_ts: i64,
/// If set, the order limit price is the oracle price + this offset
/// precision: PRICE_PRECISION
pub oracle_price_offset: i32,
/// The id for the order. Each users has their own order id space
pub order_id: u32,
/// The perp/spot market index
pub market_index: u16,
/// Whether the order is open or unused
pub status: OrderStatus,
/// The type of order
pub order_type: OrderType,
/// Whether market is spot or perp
pub market_type: MarketType,
/// User generated order id. Can make it easier to place/cancel orders
pub user_order_id: u8,
/// What the users position was when the order was placed
pub existing_position_direction: PositionDirection,
/// Whether the user is going long or short. LONG = bid, SHORT = ask
pub direction: PositionDirection,
/// Whether the order is allowed to only reduce position size
pub reduce_only: bool,
/// Whether the order must be a maker
pub post_only: bool,
/// Whether the order must be canceled the same slot it is placed
pub immediate_or_cancel: bool,
/// Whether the order is triggered above or below the trigger price. Only relevant for trigger orders
pub trigger_condition: OrderTriggerCondition,
/// How many slots the auction lasts
pub auction_duration: u8,
pub padding: [u8; 3],
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Debug)]
pub enum AssetType {
Base,
Quote,
}
impl Order {
pub fn seconds_til_expiry(self, now: i64) -> i64 {
(self.max_ts - now).max(0)
}
pub fn has_oracle_price_offset(self) -> bool {
self.oracle_price_offset != 0
}
pub fn get_limit_price(
&self,
valid_oracle_price: Option<i64>,
fallback_price: Option<u64>,
slot: u64,
tick_size: u64,
is_prediction_market: bool,
) -> DriftResult<Option<u64>> {
let price = if self.has_auction_price(self.slot, self.auction_duration, slot)? {
Some(calculate_auction_price(
self,
slot,
tick_size,
valid_oracle_price,
is_prediction_market,
)?)
} else if self.has_oracle_price_offset() {
let oracle_price = valid_oracle_price.ok_or_else(|| {
msg!("Could not find oracle too calculate oracle offset limit price");
ErrorCode::OracleNotFound
})?;
let mut limit_price = oracle_price
.safe_add(self.oracle_price_offset.cast()?)?
.max(tick_size.cast()?)
.cast::<u64>()?;
if is_prediction_market {
limit_price = limit_price.min(MAX_PREDICTION_MARKET_PRICE)
}
Some(standardize_price(limit_price, tick_size, self.direction)?)
} else if self.price == 0 {
match fallback_price {
Some(price) => Some(standardize_price(price, tick_size, self.direction)?),
None => None,
}
} else {
Some(self.price)
};
Ok(price)
}
#[track_caller]
#[inline(always)]
pub fn force_get_limit_price(
&self,
valid_oracle_price: Option<i64>,
fallback_price: Option<u64>,
slot: u64,
tick_size: u64,
is_prediction_market: bool,
) -> DriftResult<u64> {
match self.get_limit_price(
valid_oracle_price,
fallback_price,
slot,
tick_size,
is_prediction_market,
)? {
Some(price) => Ok(price),
None => {
let caller = Location::caller();
msg!(
"Could not get limit price at {}:{}",
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToGetLimitPrice)
}
}
}
pub fn has_limit_price(self, slot: u64) -> DriftResult<bool> {
Ok(self.price > 0
|| self.has_oracle_price_offset()
|| !is_auction_complete(self.slot, self.auction_duration, slot)?)
}
pub fn is_auction_complete(self, slot: u64) -> DriftResult<bool> {
is_auction_complete(self.slot, self.auction_duration, slot)
}
pub fn has_auction(&self) -> bool {
self.auction_duration != 0
}
pub fn has_auction_price(
&self,
order_slot: u64,
auction_duration: u8,
slot: u64,
) -> DriftResult<bool> {
let auction_complete = is_auction_complete(order_slot, auction_duration, slot)?;
let has_auction_prices = self.auction_start_price != 0 || self.auction_end_price != 0;
Ok(!auction_complete && has_auction_prices)
}
/// Passing in an existing_position forces the function to consider the order's reduce only status
pub fn get_base_asset_amount_unfilled(
&self,
existing_position: Option<i64>,
) -> DriftResult<u64> {
let base_asset_amount_unfilled = self
.base_asset_amount
.safe_sub(self.base_asset_amount_filled)?;
let existing_position = match existing_position {
Some(existing_position) => existing_position,
None => {
return Ok(base_asset_amount_unfilled);
}
};
// if order is post only, can disregard reduce only
if !self.reduce_only || self.post_only {
return Ok(base_asset_amount_unfilled);
}
if existing_position == 0 {
return Ok(0);
}
match self.direction {
PositionDirection::Long => {
if existing_position > 0 {
Ok(0)
} else {
Ok(base_asset_amount_unfilled.min(existing_position.unsigned_abs()))
}
}
PositionDirection::Short => {
if existing_position < 0 {
Ok(0)
} else {
Ok(base_asset_amount_unfilled.min(existing_position.unsigned_abs()))
}
}
}
}
/// Stardardizes the base asset amount unfilled to the nearest step size
/// Particularly important for spot positions where existing position can be dust
pub fn get_standardized_base_asset_amount_unfilled(
&self,
existing_position: Option<i64>,
step_size: u64,
) -> DriftResult<u64> {
standardize_base_asset_amount(
self.get_base_asset_amount_unfilled(existing_position)?,
step_size,
)
}
pub fn must_be_triggered(&self) -> bool {
matches!(
self.order_type,
OrderType::TriggerMarket | OrderType::TriggerLimit
)
}
pub fn triggered(&self) -> bool {
matches!(
self.trigger_condition,
OrderTriggerCondition::TriggeredAbove | OrderTriggerCondition::TriggeredBelow
)
}
pub fn is_jit_maker(&self) -> bool {
self.post_only && self.immediate_or_cancel
}
pub fn is_open_order_for_market(&self, market_index: u16, market_type: &MarketType) -> bool {
self.market_index == market_index
&& self.status == OrderStatus::Open
&& &self.market_type == market_type
}
pub fn get_spot_position_update_direction(&self, asset_type: AssetType) -> SpotBalanceType {
match (self.direction, asset_type) {
(PositionDirection::Long, AssetType::Base) => SpotBalanceType::Deposit,
(PositionDirection::Long, AssetType::Quote) => SpotBalanceType::Borrow,
(PositionDirection::Short, AssetType::Base) => SpotBalanceType::Borrow,
(PositionDirection::Short, AssetType::Quote) => SpotBalanceType::Deposit,
}
}
pub fn is_market_order(&self) -> bool {
matches!(
self.order_type,
OrderType::Market | OrderType::TriggerMarket | OrderType::Oracle
)
}
pub fn is_limit_order(&self) -> bool {
matches!(self.order_type, OrderType::Limit | OrderType::TriggerLimit)
}
pub fn is_resting_limit_order(&self, slot: u64) -> DriftResult<bool> {
if !self.is_limit_order() {
return Ok(false);
}
Ok(self.post_only || self.is_auction_complete(slot)?)
}
}
impl Default for Order {
fn default() -> Self {
Self {
status: OrderStatus::Init,
order_type: OrderType::Limit,
market_type: MarketType::Perp,
slot: 0,
order_id: 0,
user_order_id: 0,
market_index: 0,
price: 0,
existing_position_direction: PositionDirection::Long,
base_asset_amount: 0,
base_asset_amount_filled: 0,
quote_asset_amount_filled: 0,
direction: PositionDirection::Long,
reduce_only: false,
post_only: false,
immediate_or_cancel: false,
trigger_price: 0,
trigger_condition: OrderTriggerCondition::Above,
oracle_price_offset: 0,
auction_start_price: 0,
auction_end_price: 0,
auction_duration: 0,
max_ts: 0,
padding: [0; 3],
}
}
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Debug)]
pub enum OrderStatus {
/// The order is not in use
Init,
/// Order is open
Open,
/// Order has been filled
Filled,
/// Order has been canceled
Canceled,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum OrderType {
Market,
#[default]
Limit,
TriggerMarket,
TriggerLimit,
/// Market order where the auction prices are oracle offsets
Oracle,
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum OrderTriggerCondition {
#[default]
Above,
Below,
TriggeredAbove, // above condition has been triggered
TriggeredBelow, // below condition has been triggered
}
#[derive(Default, Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq)]
pub enum MarketType {
#[default]
Spot,
Perp,
}
impl fmt::Display for MarketType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
MarketType::Spot => write!(f, "Spot"),
MarketType::Perp => write!(f, "Perp"),
}
}
}
#[account(zero_copy(unsafe))]
#[derive(Eq, PartialEq, Debug)]
#[repr(C)]
#[derive(Default)]
pub struct UserStats {
/// The authority for all of a users sub accounts
pub authority: Pubkey,
/// The address that referred this user
pub referrer: Pubkey,
/// Stats on the fees paid by the user
pub fees: UserFees,
/// The timestamp of the next epoch
/// Epoch is used to limit referrer rewards earned in single epoch
pub next_epoch_ts: i64,
/// Rolling 30day maker volume for user
/// precision: QUOTE_PRECISION
pub maker_volume_30d: u64,
/// Rolling 30day taker volume for user
/// precision: QUOTE_PRECISION
pub taker_volume_30d: u64,
/// Rolling 30day filler volume for user
/// precision: QUOTE_PRECISION
pub filler_volume_30d: u64,
/// last time the maker volume was updated
pub last_maker_volume_30d_ts: i64,
/// last time the taker volume was updated
pub last_taker_volume_30d_ts: i64,
/// last time the filler volume was updated
pub last_filler_volume_30d_ts: i64,
/// The amount of tokens staked in the quote spot markets if
pub if_staked_quote_asset_amount: u64,
/// The current number of sub accounts
pub number_of_sub_accounts: u16,
/// The number of sub accounts created. Can be greater than the number of sub accounts if user
/// has deleted sub accounts
pub number_of_sub_accounts_created: u16,
/// Flags for referrer status:
/// First bit (LSB): 1 if user is a referrer, 0 otherwise
/// Second bit: 1 if user was referred, 0 otherwise
pub referrer_status: u8,
pub disable_update_perp_bid_ask_twap: bool,
pub padding1: [u8; 2],
/// accumulated fuel for token amounts of insurance
pub fuel_insurance: u32,
/// accumulated fuel for notional of deposits
pub fuel_deposits: u32,
/// accumulate fuel bonus for notional of borrows
pub fuel_borrows: u32,
/// accumulated fuel for perp open interest
pub fuel_positions: u32,
/// accumulate fuel bonus for taker volume
pub fuel_taker: u32,
/// accumulate fuel bonus for maker volume
pub fuel_maker: u32,
/// The amount of tokens staked in the governance spot markets if
pub if_staked_gov_token_amount: u64,
/// last unix ts user stats data was used to update if fuel (u32 to save space)
pub last_fuel_if_bonus_update_ts: u32,
pub padding: [u8; 12],
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq)]
#[repr(u8)]
pub enum ReferrerStatus {
IsReferrer = 0b00000001,
IsReferred = 0b00000010,
}
impl ReferrerStatus {
pub fn is_referrer(status: u8) -> bool {
status & ReferrerStatus::IsReferrer as u8 != 0
}
pub fn is_referred(status: u8) -> bool {
status & ReferrerStatus::IsReferred as u8 != 0
}
}
impl Size for UserStats {
const SIZE: usize = 240;
}
impl UserStats {
pub fn get_fuel_bonus_numerator(
self,
last_fuel_bonus_update_ts: i64,
now: i64,
) -> DriftResult<i64> {
if last_fuel_bonus_update_ts != 0 {
let since_last = now.safe_sub(last_fuel_bonus_update_ts)?;
return Ok(since_last);
}
Ok(0)
}
pub fn update_fuel_bonus_trade(&mut self, fuel_taker: u32, fuel_maker: u32) -> DriftResult {
self.fuel_taker = self.fuel_taker.saturating_add(fuel_taker);
self.fuel_maker = self.fuel_maker.saturating_add(fuel_maker);
Ok(())
}
pub fn update_fuel_bonus(
&mut self,
user: &mut User,
fuel_deposits: u32,
fuel_borrows: u32,
fuel_positions: u32,
now: i64,
) -> DriftResult {
if user.last_fuel_bonus_update_ts != 0 || now > FUEL_START_TS {
self.fuel_deposits = self.fuel_deposits.saturating_add(fuel_deposits);
self.fuel_borrows = self.fuel_borrows.saturating_add(fuel_borrows);
self.fuel_positions = self.fuel_positions.saturating_add(fuel_positions);
user.last_fuel_bonus_update_ts = now.cast()?;
}
Ok(())
}
pub fn update_fuel_maker_bonus(
&mut self,
fuel_boost: u8,
quote_asset_amount: u64,
) -> DriftResult {
if fuel_boost > 0 {
self.fuel_maker = self.fuel_maker.saturating_add(
fuel_boost
.cast::<u64>()?
.saturating_mul(quote_asset_amount / QUOTE_PRECISION_U64)
.cast::<u32>()
.unwrap_or(u32::MAX),
); // todo of ratio
}
Ok(())
}
pub fn update_fuel_taker_bonus(
&mut self,
fuel_boost: u8,
quote_asset_amount: u64,
) -> DriftResult {
if fuel_boost > 0 {
self.fuel_taker = self.fuel_taker.saturating_add(
fuel_boost
.cast::<u64>()?
.saturating_mul(quote_asset_amount / QUOTE_PRECISION_U64)
.cast::<u32>()
.unwrap_or(u32::MAX),
); // todo of ratio
}
Ok(())
}
pub fn update_maker_volume_30d(
&mut self,
fuel_boost: u8,
quote_asset_amount: u64,
now: i64,
) -> DriftResult {
let since_last = max(1_i64, now.safe_sub(self.last_maker_volume_30d_ts)?);
self.update_fuel_maker_bonus(fuel_boost, quote_asset_amount)?;
self.maker_volume_30d = calculate_rolling_sum(
self.maker_volume_30d,
quote_asset_amount,
since_last,
THIRTY_DAY,
)?;
self.last_maker_volume_30d_ts = now;
Ok(())
}
pub fn update_taker_volume_30d(
&mut self,
fuel_boost: u8,
quote_asset_amount: u64,
now: i64,
) -> DriftResult {
let since_last = max(1_i64, now.safe_sub(self.last_taker_volume_30d_ts)?);
self.update_fuel_taker_bonus(fuel_boost, quote_asset_amount)?;
self.taker_volume_30d = calculate_rolling_sum(
self.taker_volume_30d,
quote_asset_amount,
since_last,
THIRTY_DAY,
)?;
self.last_taker_volume_30d_ts = now;
Ok(())
}
pub fn update_filler_volume(&mut self, quote_asset_amount: u64, now: i64) -> DriftResult {
let since_last = max(1_i64, now.safe_sub(self.last_filler_volume_30d_ts)?);
self.filler_volume_30d = calculate_rolling_sum(
self.filler_volume_30d,
quote_asset_amount,
since_last,
THIRTY_DAY,
)?;
self.last_filler_volume_30d_ts = now;
Ok(())
}
pub fn increment_total_fees(&mut self, fee: u64) -> DriftResult {
self.fees.total_fee_paid = self.fees.total_fee_paid.safe_add(fee)?;
Ok(())
}
pub fn increment_total_rebate(&mut self, fee: u64) -> DriftResult {
self.fees.total_fee_rebate = self.fees.total_fee_rebate.safe_add(fee)?;
Ok(())
}
pub fn increment_total_referrer_reward(&mut self, reward: u64, now: i64) -> DriftResult {
self.fees.total_referrer_reward = self.fees.total_referrer_reward.safe_add(reward)?;
self.fees.current_epoch_referrer_reward =
self.fees.current_epoch_referrer_reward.safe_add(reward)?;
if now > self.next_epoch_ts {
let n_epoch_durations = now
.safe_sub(self.next_epoch_ts)?
.safe_div(EPOCH_DURATION)?
.safe_add(1)?;
self.next_epoch_ts = self
.next_epoch_ts
.safe_add(EPOCH_DURATION.safe_mul(n_epoch_durations)?)?;
self.fees.current_epoch_referrer_reward = 0;
}
Ok(())
}
pub fn increment_total_referee_discount(&mut self, discount: u64) -> DriftResult {
self.fees.total_referee_discount = self.fees.total_referee_discount.safe_add(discount)?;
Ok(())
}
pub fn has_referrer(&self) -> bool {
!self.referrer.eq(&Pubkey::default())
}
pub fn get_total_30d_volume(&self) -> DriftResult<u64> {
self.taker_volume_30d.safe_add(self.maker_volume_30d)
}
pub fn get_age_ts(&self, now: i64) -> i64 {
// upper bound of age of the user stats account
let min_action_ts: i64 = self
.last_filler_volume_30d_ts
.min(self.last_maker_volume_30d_ts)
.min(self.last_taker_volume_30d_ts);
now.saturating_sub(min_action_ts).max(0)
}
pub fn is_referrer(&self) -> bool {
ReferrerStatus::is_referrer(self.referrer_status)
}
pub fn update_referrer_status(&mut self) {
if !self.referrer.eq(&Pubkey::default()) {
self.referrer_status |= ReferrerStatus::IsReferred as u8;
} else {
self.referrer_status &= !(ReferrerStatus::IsReferred as u8);
}
}
}
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct ReferrerName {
pub authority: Pubkey,
pub user: Pubkey,
pub user_stats: Pubkey,
pub name: [u8; 32],
}
impl Size for ReferrerName {
const SIZE: usize = 136;
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum MarginMode {
#[default]
Default,
HighLeverage,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/insurance_fund_stake.rs
|
use crate::error::DriftResult;
use crate::error::ErrorCode;
use crate::math::safe_math::SafeMath;
use crate::safe_decrement;
use crate::safe_increment;
use crate::state::spot_market::SpotMarket;
use crate::state::traits::Size;
use crate::validate;
use crate::{math_error, EPOCH_DURATION};
use anchor_lang::prelude::*;
#[cfg(test)]
mod tests;
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct InsuranceFundStake {
pub authority: Pubkey,
if_shares: u128,
pub last_withdraw_request_shares: u128, // get zero as 0 when not in escrow
pub if_base: u128, // exponent for if_shares decimal places (for rebase)
pub last_valid_ts: i64,
pub last_withdraw_request_value: u64,
pub last_withdraw_request_ts: i64,
pub cost_basis: i64,
pub market_index: u16,
pub padding: [u8; 14],
}
// implement SIZE const for InsuranceFundStake
impl Size for InsuranceFundStake {
const SIZE: usize = 136;
}
impl InsuranceFundStake {
pub fn new(authority: Pubkey, market_index: u16, now: i64) -> Self {
InsuranceFundStake {
authority,
market_index,
last_withdraw_request_shares: 0,
last_withdraw_request_value: 0,
last_withdraw_request_ts: 0,
cost_basis: 0,
if_base: 0,
last_valid_ts: now,
if_shares: 0,
padding: [0; 14],
}
}
fn validate_base(&self, spot_market: &SpotMarket) -> DriftResult {
validate!(
self.if_base == spot_market.insurance_fund.shares_base,
ErrorCode::InvalidIFRebase,
"if stake bases mismatch. user base: {} market base {}",
self.if_base,
spot_market.insurance_fund.shares_base
)?;
Ok(())
}
pub fn checked_if_shares(&self, spot_market: &SpotMarket) -> DriftResult<u128> {
self.validate_base(spot_market)?;
Ok(self.if_shares)
}
pub fn unchecked_if_shares(&self) -> u128 {
self.if_shares
}
pub fn increase_if_shares(&mut self, delta: u128, spot_market: &SpotMarket) -> DriftResult {
self.validate_base(spot_market)?;
safe_increment!(self.if_shares, delta);
Ok(())
}
pub fn decrease_if_shares(&mut self, delta: u128, spot_market: &SpotMarket) -> DriftResult {
self.validate_base(spot_market)?;
safe_decrement!(self.if_shares, delta);
Ok(())
}
pub fn update_if_shares(&mut self, new_shares: u128, spot_market: &SpotMarket) -> DriftResult {
self.validate_base(spot_market)?;
self.if_shares = new_shares;
Ok(())
}
}
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct ProtocolIfSharesTransferConfig {
pub whitelisted_signers: [Pubkey; 4],
pub max_transfer_per_epoch: u128,
pub current_epoch_transfer: u128,
pub next_epoch_ts: i64,
pub padding: [u128; 8],
}
// implement SIZE const for ProtocolIfSharesTransferConfig
impl Size for ProtocolIfSharesTransferConfig {
const SIZE: usize = 304;
}
impl ProtocolIfSharesTransferConfig {
pub fn validate_signer(&self, signer: &Pubkey) -> DriftResult {
validate!(
self.whitelisted_signers.contains(signer) && *signer != Pubkey::default(),
ErrorCode::DefaultError,
"signer {} not whitelisted",
signer
)?;
Ok(())
}
pub fn update_epoch(&mut self, now: i64) -> DriftResult {
if now > self.next_epoch_ts {
let n_epoch_durations = now
.safe_sub(self.next_epoch_ts)?
.safe_div(EPOCH_DURATION)?
.safe_add(1)?;
self.next_epoch_ts = self
.next_epoch_ts
.safe_add(EPOCH_DURATION.safe_mul(n_epoch_durations)?)?;
self.current_epoch_transfer = 0;
}
Ok(())
}
pub fn validate_transfer(&self, requested_transfer: u128) -> DriftResult {
let max_transfer = self
.max_transfer_per_epoch
.saturating_sub(self.current_epoch_transfer);
validate!(
requested_transfer < max_transfer,
ErrorCode::DefaultError,
"requested transfer {} exceeds max transfer {}",
requested_transfer,
max_transfer
)?;
Ok(())
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/spot_fulfillment_params.rs
|
use crate::error::DriftResult;
use crate::state::events::OrderActionExplanation;
use crate::state::spot_market::{SpotBalanceType, SpotMarket};
use crate::PositionDirection;
use std::cell::Ref;
pub trait SpotFulfillmentParams {
/// Where or not the taker order is filled externally using another solana program
fn is_external(&self) -> bool;
/// Returns the markets best bid and ask price, in PRICE_PRECISION
fn get_best_bid_and_ask(&self) -> DriftResult<(Option<u64>, Option<u64>)>;
/// Fulfills the taker order
///
/// # Arguments
///
/// *`taker_direction` - The direction of the taker order
/// *`taker_price` - The price of the taker order, in PRICE_PRECISION
/// *`taker_base_asset_amount` - The base amount for taker order, precision is 10^base_mint_decimals
/// *`taker_max_quote_asset_amount` - The max quote amount for taker order, precision is QUOTE_PRECISION (1e6)
/// *`now` - The current unix timestamp
fn fulfill_order(
&mut self,
taker_direction: PositionDirection,
taker_price: u64,
taker_base_asset_amount: u64,
taker_max_quote_asset_amount: u64,
) -> DriftResult<ExternalSpotFill>;
/// Gets the order action explanation to be logged in the OrderActionRecord
fn get_order_action_explanation(&self) -> DriftResult<OrderActionExplanation>;
/// Called at the end of instructions calling fill_spot_order, validates that the token amount in each market's vault
/// equals the markets deposits - borrows
fn validate_vault_amounts(
&self,
base_market: &Ref<SpotMarket>,
quote_market: &Ref<SpotMarket>,
) -> DriftResult<()>;
fn validate_markets(
&self,
base_market: &SpotMarket,
quote_market: &SpotMarket,
) -> DriftResult<()>;
}
pub struct ExternalSpotFill {
pub base_asset_amount_filled: u64,
pub base_update_direction: SpotBalanceType,
pub quote_asset_amount_filled: u64,
pub quote_update_direction: SpotBalanceType,
pub settled_referrer_rebate: u64,
pub unsettled_referrer_rebate: u64,
pub fee: u64,
}
impl ExternalSpotFill {
pub fn empty() -> ExternalSpotFill {
ExternalSpotFill {
base_asset_amount_filled: 0,
base_update_direction: SpotBalanceType::Deposit,
quote_asset_amount_filled: 0,
quote_update_direction: SpotBalanceType::Borrow,
settled_referrer_rebate: 0,
unsettled_referrer_rebate: 0,
fee: 0,
}
}
}
#[cfg(test)]
use crate::error::ErrorCode;
#[cfg(test)]
pub struct TestFulfillmentParams {}
#[cfg(test)]
impl SpotFulfillmentParams for TestFulfillmentParams {
fn is_external(&self) -> bool {
false
}
fn get_best_bid_and_ask(&self) -> DriftResult<(Option<u64>, Option<u64>)> {
Err(ErrorCode::InvalidSpotFulfillmentParams)
}
fn fulfill_order(
&mut self,
_taker_direction: PositionDirection,
_taker_price: u64,
_taker_base_asset_amount: u64,
_taker_max_quote_asset_amount: u64,
) -> DriftResult<ExternalSpotFill> {
Err(ErrorCode::InvalidSpotFulfillmentParams)
}
fn get_order_action_explanation(&self) -> DriftResult<OrderActionExplanation> {
Err(ErrorCode::InvalidSpotFulfillmentParams)
}
fn validate_vault_amounts(
&self,
_base_market: &Ref<SpotMarket>,
_quote_market: &Ref<SpotMarket>,
) -> DriftResult<()> {
Err(ErrorCode::InvalidSpotFulfillmentParams)
}
fn validate_markets(
&self,
base_market: &SpotMarket,
quote_market: &SpotMarket,
) -> DriftResult<()> {
Ok(())
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/margin_calculation.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
use crate::math::fuel::{calculate_perp_fuel_bonus, calculate_spot_fuel_bonus};
use crate::math::margin::MarginRequirementType;
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::get_strict_token_value;
use crate::state::oracle::StrictOraclePrice;
use crate::state::perp_market::PerpMarket;
use crate::state::spot_market::SpotMarket;
use crate::state::user::{PerpPosition, User};
use crate::{validate, MarketType, AMM_RESERVE_PRECISION_I128, MARGIN_PRECISION_U128};
use anchor_lang::{prelude::*, solana_program::msg};
#[derive(Clone, Copy, Debug)]
pub enum MarginCalculationMode {
Standard {
track_open_orders_fraction: bool,
},
Liquidation {
market_to_track_margin_requirement: Option<MarketIdentifier>,
},
}
#[derive(Clone, Copy, Debug)]
pub struct MarginContext {
pub margin_type: MarginRequirementType,
pub mode: MarginCalculationMode,
pub strict: bool,
pub ignore_invalid_deposit_oracles: bool,
pub margin_buffer: u128,
pub fuel_bonus_numerator: i64,
pub fuel_bonus: u64,
pub fuel_perp_delta: Option<(u16, i64)>,
pub fuel_spot_deltas: [(u16, i128); 2],
}
#[derive(PartialEq, Eq, Copy, Clone, Debug, AnchorSerialize, AnchorDeserialize)]
pub struct MarketIdentifier {
pub market_type: MarketType,
pub market_index: u16,
}
impl MarketIdentifier {
pub fn spot(market_index: u16) -> Self {
Self {
market_type: MarketType::Spot,
market_index,
}
}
pub fn perp(market_index: u16) -> Self {
Self {
market_type: MarketType::Perp,
market_index,
}
}
}
impl MarginContext {
pub fn standard(margin_type: MarginRequirementType) -> Self {
Self {
margin_type,
mode: MarginCalculationMode::Standard {
track_open_orders_fraction: false,
},
strict: false,
ignore_invalid_deposit_oracles: false,
margin_buffer: 0,
fuel_bonus_numerator: 0,
fuel_bonus: 0,
fuel_perp_delta: None,
fuel_spot_deltas: [(0, 0); 2],
}
}
pub fn strict(mut self, strict: bool) -> Self {
self.strict = strict;
self
}
pub fn ignore_invalid_deposit_oracles(mut self, ignore: bool) -> Self {
self.ignore_invalid_deposit_oracles = ignore;
self
}
pub fn margin_buffer(mut self, margin_buffer: u32) -> Self {
self.margin_buffer = margin_buffer as u128;
self
}
// how to change the user's spot position to match how it was prior to instruction change
// i.e. diffs are ADDED to perp
pub fn fuel_perp_delta(mut self, market_index: u16, delta: i64) -> Self {
self.fuel_perp_delta = Some((market_index, delta));
self
}
pub fn fuel_spot_delta(mut self, market_index: u16, delta: i128) -> Self {
self.fuel_spot_deltas[0] = (market_index, delta);
self
}
pub fn fuel_spot_deltas(mut self, deltas: [(u16, i128); 2]) -> Self {
self.fuel_spot_deltas = deltas;
self
}
pub fn fuel_numerator(mut self, user: &User, now: i64) -> Self {
self.fuel_bonus_numerator = user.get_fuel_bonus_numerator(now).unwrap();
self
}
pub fn track_open_orders_fraction(mut self) -> DriftResult<Self> {
match self.mode {
MarginCalculationMode::Standard {
track_open_orders_fraction: ref mut track,
} => {
*track = true;
}
_ => {
msg!("Cant track open orders fraction outside of standard mode");
return Err(ErrorCode::InvalidMarginCalculation);
}
}
Ok(self)
}
pub fn liquidation(margin_buffer: u32) -> Self {
Self {
margin_type: MarginRequirementType::Maintenance,
mode: MarginCalculationMode::Liquidation {
market_to_track_margin_requirement: None,
},
margin_buffer: margin_buffer as u128,
strict: false,
ignore_invalid_deposit_oracles: false,
fuel_bonus_numerator: 0,
fuel_bonus: 0,
fuel_perp_delta: None,
fuel_spot_deltas: [(0, 0); 2],
}
}
pub fn track_market_margin_requirement(
mut self,
market_identifier: MarketIdentifier,
) -> DriftResult<Self> {
match self.mode {
MarginCalculationMode::Liquidation {
market_to_track_margin_requirement: ref mut market_to_track,
..
} => {
*market_to_track = Some(market_identifier);
}
_ => {
msg!("Cant track market outside of liquidation mode");
return Err(ErrorCode::InvalidMarginCalculation);
}
}
Ok(self)
}
}
#[derive(Clone, Copy, Debug)]
pub struct MarginCalculation {
pub context: MarginContext,
pub total_collateral: i128,
pub margin_requirement: u128,
#[cfg(not(test))]
margin_requirement_plus_buffer: u128,
#[cfg(test)]
pub margin_requirement_plus_buffer: u128,
pub num_spot_liabilities: u8,
pub num_perp_liabilities: u8,
pub all_deposit_oracles_valid: bool,
pub all_liability_oracles_valid: bool,
pub with_perp_isolated_liability: bool,
pub with_spot_isolated_liability: bool,
pub total_spot_asset_value: i128,
pub total_spot_liability_value: u128,
pub total_perp_liability_value: u128,
pub total_perp_pnl: i128,
pub open_orders_margin_requirement: u128,
tracked_market_margin_requirement: u128,
pub fuel_deposits: u32,
pub fuel_borrows: u32,
pub fuel_positions: u32,
}
impl MarginCalculation {
pub fn new(context: MarginContext) -> Self {
Self {
context,
total_collateral: 0,
margin_requirement: 0,
margin_requirement_plus_buffer: 0,
num_spot_liabilities: 0,
num_perp_liabilities: 0,
all_deposit_oracles_valid: true,
all_liability_oracles_valid: true,
with_perp_isolated_liability: false,
with_spot_isolated_liability: false,
total_spot_asset_value: 0,
total_spot_liability_value: 0,
total_perp_liability_value: 0,
total_perp_pnl: 0,
open_orders_margin_requirement: 0,
tracked_market_margin_requirement: 0,
fuel_deposits: 0,
fuel_borrows: 0,
fuel_positions: 0,
}
}
pub fn add_total_collateral(&mut self, total_collateral: i128) -> DriftResult {
self.total_collateral = self.total_collateral.safe_add(total_collateral)?;
Ok(())
}
pub fn add_margin_requirement(
&mut self,
margin_requirement: u128,
liability_value: u128,
market_identifier: MarketIdentifier,
) -> DriftResult {
self.margin_requirement = self.margin_requirement.safe_add(margin_requirement)?;
if self.context.margin_buffer > 0 {
self.margin_requirement_plus_buffer =
self.margin_requirement_plus_buffer
.safe_add(margin_requirement.safe_add(
liability_value.safe_mul(self.context.margin_buffer)?
/ MARGIN_PRECISION_U128,
)?)?;
}
if let Some(market_to_track) = self.market_to_track_margin_requirement() {
if market_to_track == market_identifier {
self.tracked_market_margin_requirement = self
.tracked_market_margin_requirement
.safe_add(margin_requirement)?;
}
}
Ok(())
}
pub fn add_open_orders_margin_requirement(&mut self, margin_requirement: u128) -> DriftResult {
self.open_orders_margin_requirement = self
.open_orders_margin_requirement
.safe_add(margin_requirement)?;
Ok(())
}
pub fn add_spot_liability(&mut self) -> DriftResult {
self.num_spot_liabilities = self.num_spot_liabilities.safe_add(1)?;
Ok(())
}
pub fn add_perp_liability(&mut self) -> DriftResult {
self.num_perp_liabilities = self.num_perp_liabilities.safe_add(1)?;
Ok(())
}
#[cfg(feature = "drift-rs")]
pub fn add_spot_asset_value(&mut self, spot_asset_value: i128) -> DriftResult {
self.total_spot_asset_value = self.total_spot_asset_value.safe_add(spot_asset_value)?;
Ok(())
}
#[cfg(feature = "drift-rs")]
pub fn add_spot_liability_value(&mut self, spot_liability_value: u128) -> DriftResult {
self.total_spot_liability_value = self
.total_spot_liability_value
.safe_add(spot_liability_value)?;
Ok(())
}
#[cfg(feature = "drift-rs")]
pub fn add_perp_liability_value(&mut self, perp_liability_value: u128) -> DriftResult {
self.total_perp_liability_value = self
.total_perp_liability_value
.safe_add(perp_liability_value)?;
Ok(())
}
#[cfg(feature = "drift-rs")]
pub fn add_perp_pnl(&mut self, perp_pnl: i128) -> DriftResult {
self.total_perp_pnl = self.total_perp_pnl.safe_add(perp_pnl)?;
Ok(())
}
pub fn update_all_deposit_oracles_valid(&mut self, valid: bool) {
self.all_deposit_oracles_valid &= valid;
}
pub fn update_all_liability_oracles_valid(&mut self, valid: bool) {
self.all_liability_oracles_valid &= valid;
}
pub fn update_with_spot_isolated_liability(&mut self, isolated: bool) {
self.with_spot_isolated_liability |= isolated;
}
pub fn update_with_perp_isolated_liability(&mut self, isolated: bool) {
self.with_perp_isolated_liability |= isolated;
}
pub fn validate_num_spot_liabilities(&self) -> DriftResult {
if self.num_spot_liabilities > 0 {
validate!(
self.margin_requirement > 0,
ErrorCode::InvalidMarginRatio,
"num_spot_liabilities={} but margin_requirement=0",
self.num_spot_liabilities
)?;
}
Ok(())
}
pub fn get_num_of_liabilities(&self) -> DriftResult<u8> {
self.num_spot_liabilities
.safe_add(self.num_perp_liabilities)
}
pub fn meets_margin_requirement(&self) -> bool {
self.total_collateral >= self.margin_requirement as i128
}
pub fn meets_margin_requirement_with_buffer(&self) -> bool {
self.total_collateral >= self.margin_requirement_plus_buffer as i128
}
pub fn positions_meets_margin_requirement(&self) -> DriftResult<bool> {
Ok(self.total_collateral
>= self
.margin_requirement
.safe_sub(self.open_orders_margin_requirement)?
.cast::<i128>()?)
}
pub fn can_exit_liquidation(&self) -> DriftResult<bool> {
if !self.is_liquidation_mode() {
msg!("liquidation mode not enabled");
return Err(ErrorCode::InvalidMarginCalculation);
}
Ok(self.total_collateral >= self.margin_requirement_plus_buffer as i128)
}
pub fn margin_shortage(&self) -> DriftResult<u128> {
if self.context.margin_buffer == 0 {
msg!("margin buffer mode not enabled");
return Err(ErrorCode::InvalidMarginCalculation);
}
Ok(self
.margin_requirement_plus_buffer
.cast::<i128>()?
.safe_sub(self.total_collateral)?
.unsigned_abs())
}
pub fn tracked_market_margin_shortage(&self, margin_shortage: u128) -> DriftResult<u128> {
if self.market_to_track_margin_requirement().is_none() {
msg!("cant call tracked_market_margin_shortage");
return Err(ErrorCode::InvalidMarginCalculation);
}
if self.margin_requirement == 0 {
return Ok(0);
}
margin_shortage
.safe_mul(self.tracked_market_margin_requirement)?
.safe_div(self.margin_requirement)
}
pub fn get_free_collateral(&self) -> DriftResult<u128> {
self.total_collateral
.safe_sub(self.margin_requirement.cast::<i128>()?)?
.max(0)
.cast()
}
fn market_to_track_margin_requirement(&self) -> Option<MarketIdentifier> {
if let MarginCalculationMode::Liquidation {
market_to_track_margin_requirement: track_margin_requirement,
..
} = self.context.mode
{
track_margin_requirement
} else {
None
}
}
fn is_liquidation_mode(&self) -> bool {
matches!(self.context.mode, MarginCalculationMode::Liquidation { .. })
}
pub fn track_open_orders_fraction(&self) -> bool {
matches!(
self.context.mode,
MarginCalculationMode::Standard {
track_open_orders_fraction: true
}
)
}
pub fn update_fuel_perp_bonus(
&mut self,
perp_market: &PerpMarket,
perp_position: &PerpPosition,
base_asset_value: u128,
oracle_price: i64,
) -> DriftResult {
if perp_market.fuel_boost_position == 0 {
return Ok(());
}
let fuel_base_asset_value =
if let Some((market_index, perp_delta)) = self.context.fuel_perp_delta {
if market_index == perp_market.market_index {
perp_position
.base_asset_amount
.safe_add(perp_delta)?
.cast::<i128>()?
.safe_mul(oracle_price.cast()?)?
.safe_div(AMM_RESERVE_PRECISION_I128)?
.unsigned_abs()
} else {
base_asset_value
}
} else {
base_asset_value
};
let perp_fuel_oi_bonus = calculate_perp_fuel_bonus(
perp_market,
fuel_base_asset_value as i128,
self.context.fuel_bonus_numerator,
)?;
self.fuel_positions = self
.fuel_positions
.saturating_add(perp_fuel_oi_bonus.cast().unwrap_or(u32::MAX));
Ok(())
}
pub fn update_fuel_spot_bonus(
&mut self,
spot_market: &SpotMarket,
mut signed_token_amount: i128,
strict_price: &StrictOraclePrice,
) -> DriftResult {
if spot_market.fuel_boost_deposits == 0 && spot_market.fuel_boost_borrows == 0 {
return Ok(());
}
for &(market_index, delta) in &self.context.fuel_spot_deltas {
if spot_market.market_index == market_index && delta != 0 {
signed_token_amount = signed_token_amount.safe_add(delta)?;
}
}
if spot_market.fuel_boost_deposits > 0 && signed_token_amount > 0 {
let signed_token_value =
get_strict_token_value(signed_token_amount, spot_market.decimals, strict_price)?;
let fuel_bonus = calculate_spot_fuel_bonus(
spot_market,
signed_token_value,
self.context.fuel_bonus_numerator,
)?;
self.fuel_deposits = self
.fuel_deposits
.saturating_add(fuel_bonus.cast().unwrap_or(u32::MAX));
} else if spot_market.fuel_boost_borrows > 0 && signed_token_amount < 0 {
let signed_token_value =
get_strict_token_value(signed_token_amount, spot_market.decimals, strict_price)?;
let fuel_bonus = calculate_spot_fuel_bonus(
spot_market,
signed_token_value,
self.context.fuel_bonus_numerator,
)?;
self.fuel_borrows = self
.fuel_borrows
.saturating_add(fuel_bonus.cast().unwrap_or(u32::MAX));
}
Ok(())
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/spot_market.rs
|
use std::fmt;
use std::fmt::{Display, Formatter};
use anchor_lang::prelude::*;
use borsh::{BorshDeserialize, BorshSerialize};
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_RESERVE_PRECISION, FIVE_MINUTE, MARGIN_PRECISION, ONE_HOUR, SPOT_WEIGHT_PRECISION_U128,
};
#[cfg(test)]
use crate::math::constants::{PRICE_PRECISION_I64, SPOT_CUMULATIVE_INTEREST_PRECISION};
use crate::math::margin::{
calculate_size_discount_asset_weight, calculate_size_premium_liability_weight,
MarginRequirementType,
};
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::{calculate_utilization, get_token_amount, get_token_value};
use crate::math::stats::calculate_new_twap;
use crate::state::oracle::{HistoricalIndexData, HistoricalOracleData, OracleSource};
use crate::state::paused_operations::{InsuranceFundOperation, SpotOperation};
use crate::state::perp_market::{MarketStatus, PoolBalance};
use crate::state::traits::{MarketIndexOffset, Size};
use crate::{validate, PERCENTAGE_PRECISION};
use super::oracle_map::OracleIdentifier;
#[account(zero_copy(unsafe))]
#[derive(PartialEq, Eq, Debug)]
#[repr(C)]
pub struct SpotMarket {
/// The address of the spot market. It is a pda of the market index
pub pubkey: Pubkey,
/// The oracle used to price the markets deposits/borrows
pub oracle: Pubkey,
/// The token mint of the market
pub mint: Pubkey,
/// The vault used to store the market's deposits
/// The amount in the vault should be equal to or greater than deposits - borrows
pub vault: Pubkey,
/// The encoded display name for the market e.g. SOL
pub name: [u8; 32],
pub historical_oracle_data: HistoricalOracleData,
pub historical_index_data: HistoricalIndexData,
/// Revenue the protocol has collected in this markets token
/// e.g. for SOL-PERP, funds can be settled in usdc and will flow into the USDC revenue pool
pub revenue_pool: PoolBalance, // in base asset
/// The fees collected from swaps between this market and the quote market
/// Is settled to the quote markets revenue pool
pub spot_fee_pool: PoolBalance,
/// Details on the insurance fund covering bankruptcies in this markets token
/// Covers bankruptcies for borrows with this markets token and perps settling in this markets token
pub insurance_fund: InsuranceFund,
/// The total spot fees collected for this market
/// precision: QUOTE_PRECISION
pub total_spot_fee: u128,
/// The sum of the scaled balances for deposits across users and pool balances
/// To convert to the deposit token amount, multiply by the cumulative deposit interest
/// precision: SPOT_BALANCE_PRECISION
pub deposit_balance: u128,
/// The sum of the scaled balances for borrows across users and pool balances
/// To convert to the borrow token amount, multiply by the cumulative borrow interest
/// precision: SPOT_BALANCE_PRECISION
pub borrow_balance: u128,
/// The cumulative interest earned by depositors
/// Used to calculate the deposit token amount from the deposit balance
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub cumulative_deposit_interest: u128,
/// The cumulative interest earned by borrowers
/// Used to calculate the borrow token amount from the borrow balance
/// precision: SPOT_CUMULATIVE_INTEREST_PRECISION
pub cumulative_borrow_interest: u128,
/// The total socialized loss from borrows, in the mint's token
/// precision: token mint precision
pub total_social_loss: u128,
/// The total socialized loss from borrows, in the quote market's token
/// preicision: QUOTE_PRECISION
pub total_quote_social_loss: u128,
/// no withdraw limits/guards when deposits below this threshold
/// precision: token mint precision
pub withdraw_guard_threshold: u64,
/// The max amount of token deposits in this market
/// 0 if there is no limit
/// precision: token mint precision
pub max_token_deposits: u64,
/// 24hr average of deposit token amount
/// precision: token mint precision
pub deposit_token_twap: u64,
/// 24hr average of borrow token amount
/// precision: token mint precision
pub borrow_token_twap: u64,
/// 24hr average of utilization
/// which is borrow amount over token amount
/// precision: SPOT_UTILIZATION_PRECISION
pub utilization_twap: u64,
/// Last time the cumulative deposit and borrow interest was updated
pub last_interest_ts: u64,
/// Last time the deposit/borrow/utilization averages were updated
pub last_twap_ts: u64,
/// The time the market is set to expire. Only set if market is in reduce only mode
pub expiry_ts: i64,
/// Spot orders must be a multiple of the step size
/// precision: token mint precision
pub order_step_size: u64,
/// Spot orders must be a multiple of the tick size
/// precision: PRICE_PRECISION
pub order_tick_size: u64,
/// The minimum order size
/// precision: token mint precision
pub min_order_size: u64,
/// The maximum spot position size
/// if the limit is 0, there is no limit
/// precision: token mint precision
pub max_position_size: u64,
/// Every spot trade has a fill record id. This is the next id to use
pub next_fill_record_id: u64,
/// Every deposit has a deposit record id. This is the next id to use
pub next_deposit_record_id: u64,
/// The initial asset weight used to calculate a deposits contribution to a users initial total collateral
/// e.g. if the asset weight is .8, $100 of deposits contributes $80 to the users initial total collateral
/// precision: SPOT_WEIGHT_PRECISION
pub initial_asset_weight: u32,
/// The maintenance asset weight used to calculate a deposits contribution to a users maintenance total collateral
/// e.g. if the asset weight is .9, $100 of deposits contributes $90 to the users maintenance total collateral
/// precision: SPOT_WEIGHT_PRECISION
pub maintenance_asset_weight: u32,
/// The initial liability weight used to calculate a borrows contribution to a users initial margin requirement
/// e.g. if the liability weight is .9, $100 of borrows contributes $90 to the users initial margin requirement
/// precision: SPOT_WEIGHT_PRECISION
pub initial_liability_weight: u32,
/// The maintenance liability weight used to calculate a borrows contribution to a users maintenance margin requirement
/// e.g. if the liability weight is .8, $100 of borrows contributes $80 to the users maintenance margin requirement
/// precision: SPOT_WEIGHT_PRECISION
pub maintenance_liability_weight: u32,
/// The initial margin fraction factor. Used to increase liability weight/decrease asset weight for large positions
/// precision: MARGIN_PRECISION
pub imf_factor: u32,
/// The fee the liquidator is paid for taking over borrow/deposit
/// precision: LIQUIDATOR_FEE_PRECISION
pub liquidator_fee: u32,
/// The fee the insurance fund receives from liquidation
/// precision: LIQUIDATOR_FEE_PRECISION
pub if_liquidation_fee: u32,
/// The optimal utilization rate for this market.
/// Used to determine the markets borrow rate
/// precision: SPOT_UTILIZATION_PRECISION
pub optimal_utilization: u32,
/// The borrow rate for this market when the market has optimal utilization
/// precision: SPOT_RATE_PRECISION
pub optimal_borrow_rate: u32,
/// The borrow rate for this market when the market has 1000 utilization
/// precision: SPOT_RATE_PRECISION
pub max_borrow_rate: u32,
/// The market's token mint's decimals. To from decimals to a precision, 10^decimals
pub decimals: u32,
pub market_index: u16,
/// Whether or not spot trading is enabled
pub orders_enabled: bool,
pub oracle_source: OracleSource,
pub status: MarketStatus,
/// The asset tier affects how a deposit can be used as collateral and the priority for a borrow being liquidated
pub asset_tier: AssetTier,
pub paused_operations: u8,
pub if_paused_operations: u8,
pub fee_adjustment: i16,
/// What fraction of max_token_deposits
/// disabled when 0, 1 => 1/10000 => .01% of max_token_deposits
/// precision: X/10000
pub max_token_borrows_fraction: u16,
/// For swaps, the amount of token loaned out in the begin_swap ix
/// precision: token mint precision
pub flash_loan_amount: u64,
/// For swaps, the amount in the users token account in the begin_swap ix
/// Used to calculate how much of the token left the system in end_swap ix
/// precision: token mint precision
pub flash_loan_initial_token_amount: u64,
/// The total fees received from swaps
/// precision: token mint precision
pub total_swap_fee: u64,
/// When to begin scaling down the initial asset weight
/// disabled when 0
/// precision: QUOTE_PRECISION
pub scale_initial_asset_weight_start: u64,
/// The min borrow rate for this market when the market regardless of utilization
/// 1 => 1/200 => .5%
/// precision: X/200
pub min_borrow_rate: u8,
/// fuel multiplier for spot deposits
/// precision: 10
pub fuel_boost_deposits: u8,
/// fuel multiplier for spot borrows
/// precision: 10
pub fuel_boost_borrows: u8,
/// fuel multiplier for spot taker
/// precision: 10
pub fuel_boost_taker: u8,
/// fuel multiplier for spot maker
/// precision: 10
pub fuel_boost_maker: u8,
/// fuel multiplier for spot insurance stake
/// precision: 10
pub fuel_boost_insurance: u8,
pub token_program: u8,
pub pool_id: u8,
pub padding: [u8; 40],
}
impl Default for SpotMarket {
fn default() -> Self {
SpotMarket {
pubkey: Pubkey::default(),
oracle: Pubkey::default(),
mint: Pubkey::default(),
vault: Pubkey::default(),
name: [0; 32],
historical_oracle_data: HistoricalOracleData::default(),
historical_index_data: HistoricalIndexData::default(),
revenue_pool: PoolBalance::default(),
spot_fee_pool: PoolBalance::default(),
insurance_fund: InsuranceFund::default(),
total_spot_fee: 0,
deposit_balance: 0,
borrow_balance: 0,
cumulative_deposit_interest: 0,
cumulative_borrow_interest: 0,
total_social_loss: 0,
total_quote_social_loss: 0,
withdraw_guard_threshold: 0,
max_token_deposits: 0,
deposit_token_twap: 0,
borrow_token_twap: 0,
utilization_twap: 0,
last_interest_ts: 0,
last_twap_ts: 0,
expiry_ts: 0,
order_step_size: 1,
order_tick_size: 0,
min_order_size: 0,
max_position_size: 0,
next_fill_record_id: 0,
next_deposit_record_id: 0,
initial_asset_weight: 0,
maintenance_asset_weight: 0,
initial_liability_weight: 0,
maintenance_liability_weight: 0,
imf_factor: 0,
liquidator_fee: 0,
if_liquidation_fee: 0,
optimal_utilization: 0,
optimal_borrow_rate: 0,
max_borrow_rate: 0,
decimals: 0,
market_index: 0,
orders_enabled: false,
oracle_source: OracleSource::default(),
status: MarketStatus::default(),
asset_tier: AssetTier::default(),
paused_operations: 0,
if_paused_operations: 0,
fee_adjustment: 0,
max_token_borrows_fraction: 0,
flash_loan_amount: 0,
flash_loan_initial_token_amount: 0,
total_swap_fee: 0,
scale_initial_asset_weight_start: 0,
min_borrow_rate: 0,
fuel_boost_deposits: 0,
fuel_boost_borrows: 0,
fuel_boost_taker: 0,
fuel_boost_maker: 0,
fuel_boost_insurance: 0,
token_program: 0,
pool_id: 0,
padding: [0; 40],
}
}
}
impl Size for SpotMarket {
const SIZE: usize = 776;
}
impl MarketIndexOffset for SpotMarket {
const MARKET_INDEX_OFFSET: usize = 684;
}
impl SpotMarket {
pub fn oracle_id(&self) -> OracleIdentifier {
(self.oracle, self.oracle_source)
}
pub fn is_in_settlement(&self, now: i64) -> bool {
let in_settlement = matches!(
self.status,
MarketStatus::Settlement | MarketStatus::Delisted
);
let expired = self.expiry_ts != 0 && now >= self.expiry_ts;
in_settlement || expired
}
pub fn is_reduce_only(&self) -> bool {
self.status == MarketStatus::ReduceOnly
}
pub fn is_operation_paused(&self, operation: SpotOperation) -> bool {
SpotOperation::is_operation_paused(self.paused_operations, operation)
}
pub fn is_insurance_fund_operation_paused(&self, operation: InsuranceFundOperation) -> bool {
InsuranceFundOperation::is_operation_paused(self.if_paused_operations, operation)
}
pub fn fills_enabled(&self) -> bool {
matches!(self.status, MarketStatus::Active | MarketStatus::ReduceOnly)
&& !self.is_operation_paused(SpotOperation::Fill)
}
pub fn get_max_confidence_interval_multiplier(&self) -> DriftResult<u64> {
Ok(match self.asset_tier {
AssetTier::Collateral => 1, // 2%
AssetTier::Protected => 1, // 2%
AssetTier::Cross => 5, // 20%
AssetTier::Isolated => 50, // 100%
AssetTier::Unlisted => 50,
})
}
pub fn get_sanitize_clamp_denominator(&self) -> DriftResult<Option<i64>> {
Ok(match self.asset_tier {
AssetTier::Collateral => Some(10), // 10%
AssetTier::Protected => Some(10), // 10%
AssetTier::Cross => Some(5), // 20%
AssetTier::Isolated => Some(3), // 50%
AssetTier::Unlisted => None, // DEFAULT_MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR
})
}
pub fn get_asset_weight(
&self,
size: u128,
oracle_price: i64,
margin_requirement_type: &MarginRequirementType,
) -> DriftResult<u32> {
let size_precision = 10_u128.pow(self.decimals);
let size_in_amm_reserve_precision = if size_precision > AMM_RESERVE_PRECISION {
size / (size_precision / AMM_RESERVE_PRECISION)
} else {
(size * AMM_RESERVE_PRECISION) / size_precision
};
let default_asset_weight = match margin_requirement_type {
MarginRequirementType::Initial => self.get_scaled_initial_asset_weight(oracle_price)?,
MarginRequirementType::Fill => {
self.get_scaled_initial_asset_weight(oracle_price)?
.safe_add(self.maintenance_asset_weight)?
/ 2
}
MarginRequirementType::Maintenance => self.maintenance_asset_weight,
};
let size_based_asset_weight = calculate_size_discount_asset_weight(
size_in_amm_reserve_precision,
self.imf_factor,
default_asset_weight,
)?;
let asset_weight = size_based_asset_weight.min(default_asset_weight);
Ok(asset_weight)
}
pub fn get_scaled_initial_asset_weight(&self, oracle_price: i64) -> DriftResult<u32> {
if self.scale_initial_asset_weight_start == 0 {
return Ok(self.initial_asset_weight);
}
let deposits = self.get_deposits()?;
let deposit_value =
get_token_value(deposits.cast()?, self.decimals, oracle_price)?.cast::<u128>()?;
let scale_initial_asset_weight_start =
self.scale_initial_asset_weight_start.cast::<u128>()?;
let asset_weight = if deposit_value < scale_initial_asset_weight_start {
self.initial_asset_weight
} else {
self.initial_asset_weight
.cast::<u128>()?
.safe_mul(scale_initial_asset_weight_start)?
.safe_div(deposit_value)?
.cast::<u32>()?
};
Ok(asset_weight)
}
pub fn get_liability_weight(
&self,
size: u128,
margin_requirement_type: &MarginRequirementType,
) -> DriftResult<u32> {
let size_precision = 10_u128.pow(self.decimals);
let size_in_amm_reserve_precision = if size_precision > AMM_RESERVE_PRECISION {
size / (size_precision / AMM_RESERVE_PRECISION)
} else {
(size * AMM_RESERVE_PRECISION) / size_precision
};
let default_liability_weight = match margin_requirement_type {
MarginRequirementType::Initial => self.initial_liability_weight,
MarginRequirementType::Fill => {
self.initial_liability_weight
.safe_add(self.maintenance_liability_weight)?
/ 2
}
MarginRequirementType::Maintenance => self.maintenance_liability_weight,
};
let size_based_liability_weight = calculate_size_premium_liability_weight(
size_in_amm_reserve_precision,
self.imf_factor,
default_liability_weight,
SPOT_WEIGHT_PRECISION_U128,
)?;
let liability_weight = size_based_liability_weight.max(default_liability_weight);
Ok(liability_weight)
}
// get liability weight as if it were perp market margin requirement
pub fn get_margin_ratio(
&self,
margin_requirement_type: &MarginRequirementType,
) -> DriftResult<u32> {
let liability_weight = match margin_requirement_type {
MarginRequirementType::Initial => self.initial_liability_weight,
MarginRequirementType::Fill => return Err(ErrorCode::DefaultError),
MarginRequirementType::Maintenance => self.maintenance_liability_weight,
};
liability_weight.safe_sub(MARGIN_PRECISION)
}
pub fn get_deposits(&self) -> DriftResult<u128> {
get_token_amount(self.deposit_balance, self, &SpotBalanceType::Deposit)
}
pub fn get_borrows(&self) -> DriftResult<u128> {
get_token_amount(self.borrow_balance, self, &SpotBalanceType::Borrow)
}
pub fn validate_max_token_deposits_and_borrows(
&self,
do_max_borrow_check: bool,
) -> DriftResult {
let deposits = self.get_deposits()?;
let max_token_deposits = self.max_token_deposits.cast::<u128>()?;
validate!(
max_token_deposits == 0 || deposits <= max_token_deposits,
ErrorCode::MaxDeposit,
"max token amount ({}) < deposits ({})",
max_token_deposits,
deposits,
)?;
if do_max_borrow_check && self.max_token_borrows_fraction > 0 && self.max_token_deposits > 0
{
let borrows = self.get_borrows()?;
let max_token_borrows = self
.max_token_deposits
.safe_mul(self.max_token_borrows_fraction.cast()?)?
.safe_div(10000)?
.cast::<u128>()?;
validate!(
max_token_borrows == 0 || borrows <= max_token_borrows,
ErrorCode::MaxBorrows,
"max token amount ({}) < borrows ({})",
max_token_borrows,
borrows,
)?;
}
Ok(())
}
pub fn get_available_deposits(&self) -> DriftResult<u128> {
let deposit_token_amount =
get_token_amount(self.deposit_balance, self, &SpotBalanceType::Deposit)?;
let borrow_token_amount =
get_token_amount(self.borrow_balance, self, &SpotBalanceType::Borrow)?;
deposit_token_amount.safe_sub(borrow_token_amount)
}
pub fn get_precision(self) -> u64 {
10_u64.pow(self.decimals)
}
pub fn get_utilization(self) -> DriftResult<u128> {
let deposit_token_amount =
get_token_amount(self.deposit_balance, &self, &SpotBalanceType::Deposit)?;
let borrow_token_amount =
get_token_amount(self.borrow_balance, &self, &SpotBalanceType::Borrow)?;
calculate_utilization(deposit_token_amount, borrow_token_amount)
}
pub fn is_healthy_utilization(self) -> DriftResult<bool> {
let unhealthy_utilization = 800000; // 80%
let utilization: u64 = self.get_utilization()?.cast()?;
Ok(self.utilization_twap <= unhealthy_utilization && utilization <= unhealthy_utilization)
}
pub fn get_min_borrow_rate(self) -> DriftResult<u32> {
self.min_borrow_rate
.cast::<u32>()?
.safe_mul((PERCENTAGE_PRECISION / 200).cast()?)
}
pub fn update_historical_index_price(
&mut self,
best_bid: Option<u64>,
best_ask: Option<u64>,
now: i64,
) -> DriftResult {
let mut mid_price = 0;
if let Some(best_bid) = best_bid {
self.historical_index_data.last_index_bid_price = best_bid;
mid_price += best_bid;
}
if let Some(best_ask) = best_ask {
self.historical_index_data.last_index_ask_price = best_ask;
mid_price = if mid_price == 0 {
best_ask
} else {
mid_price.safe_add(best_ask)?.safe_div(2)?
};
}
self.historical_index_data.last_index_price_twap = calculate_new_twap(
mid_price.cast()?,
now,
self.historical_index_data.last_index_price_twap.cast()?,
self.historical_index_data.last_index_price_twap_ts,
ONE_HOUR,
)?
.cast()?;
self.historical_index_data.last_index_price_twap_5min = calculate_new_twap(
mid_price.cast()?,
now,
self.historical_index_data
.last_index_price_twap_5min
.cast()?,
self.historical_index_data.last_index_price_twap_ts,
FIVE_MINUTE as i64,
)?
.cast()?;
self.historical_index_data.last_index_price_twap_ts = now;
Ok(())
}
}
#[cfg(test)]
impl SpotMarket {
pub fn default_base_market() -> Self {
SpotMarket {
market_index: 1,
cumulative_deposit_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
cumulative_borrow_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
initial_liability_weight: 12000,
maintenance_liability_weight: 11000,
initial_asset_weight: 8000,
maintenance_asset_weight: 9000,
decimals: 9,
order_step_size: 1,
order_tick_size: 1,
status: MarketStatus::Active,
..SpotMarket::default()
}
}
pub fn default_quote_market() -> Self {
SpotMarket {
cumulative_deposit_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
cumulative_borrow_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
decimals: 6,
initial_liability_weight: 10000,
maintenance_liability_weight: 10000,
initial_asset_weight: 10000,
maintenance_asset_weight: 10000,
order_tick_size: 1,
status: MarketStatus::Active,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: PRICE_PRECISION_I64,
last_oracle_price_twap_5min: PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
..SpotMarket::default()
}
}
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Eq, Debug, Default)]
pub enum SpotBalanceType {
#[default]
Deposit,
Borrow,
}
impl Display for SpotBalanceType {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
match self {
SpotBalanceType::Deposit => write!(f, "SpotBalanceType::Deposit"),
SpotBalanceType::Borrow => write!(f, "SpotBalanceType::Borrow"),
}
}
}
pub trait SpotBalance {
fn market_index(&self) -> u16;
fn balance_type(&self) -> &SpotBalanceType;
fn balance(&self) -> u128;
fn increase_balance(&mut self, delta: u128) -> DriftResult;
fn decrease_balance(&mut self, delta: u128) -> DriftResult;
fn update_balance_type(&mut self, balance_type: SpotBalanceType) -> DriftResult;
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum SpotFulfillmentConfigStatus {
#[default]
Enabled,
Disabled,
}
#[derive(
Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, PartialOrd, Ord, Default,
)]
pub enum AssetTier {
/// full priviledge
Collateral,
/// collateral, but no borrow
Protected,
/// not collateral, allow multi-borrow
Cross,
/// not collateral, only single borrow
Isolated,
/// no privilege
#[default]
Unlisted,
}
#[zero_copy(unsafe)]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct InsuranceFund {
pub vault: Pubkey,
pub total_shares: u128,
pub user_shares: u128,
pub shares_base: u128, // exponent for lp shares (for rebasing)
pub unstaking_period: i64, // if_unstaking_period
pub last_revenue_settle_ts: i64,
pub revenue_settle_period: i64,
pub total_factor: u32, // percentage of interest for total insurance
pub user_factor: u32, // percentage of interest for user staked insurance
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/mod.rs
|
pub mod events;
pub mod fill_mode;
pub mod fulfillment;
pub mod fulfillment_params;
pub mod high_leverage_mode_config;
pub mod insurance_fund_stake;
pub mod load_ref;
pub mod margin_calculation;
pub mod oracle;
pub mod oracle_map;
pub mod order_params;
pub mod paused_operations;
pub mod perp_market;
pub mod perp_market_map;
pub mod protected_maker_mode_config;
pub mod pyth_lazer_oracle;
pub mod rfq_user;
pub mod settle_pnl_mode;
pub mod spot_fulfillment_params;
pub mod spot_market;
pub mod spot_market_map;
#[allow(clippy::module_inception)]
pub mod state;
pub mod swift_user;
pub mod traits;
pub mod user;
pub mod user_map;
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/state.rs
|
use anchor_lang::prelude::*;
use enumflags2::BitFlags;
use crate::error::DriftResult;
use crate::math::constants::{
FEE_DENOMINATOR, FEE_PERCENTAGE_DENOMINATOR, MAX_REFERRER_REWARD_EPOCH_UPPER_BOUND,
};
use crate::math::safe_math::SafeMath;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::traits::Size;
use crate::{LAMPORTS_PER_SOL_U64, PERCENTAGE_PRECISION_U64};
#[cfg(test)]
mod tests;
#[account]
#[derive(Default)]
#[repr(C)]
pub struct State {
pub admin: Pubkey,
pub whitelist_mint: Pubkey,
pub discount_mint: Pubkey,
pub signer: Pubkey,
pub srm_vault: Pubkey,
pub perp_fee_structure: FeeStructure,
pub spot_fee_structure: FeeStructure,
pub oracle_guard_rails: OracleGuardRails,
pub number_of_authorities: u64,
pub number_of_sub_accounts: u64,
pub lp_cooldown_time: u64,
pub liquidation_margin_buffer_ratio: u32,
pub settlement_duration: u16,
pub number_of_markets: u16,
pub number_of_spot_markets: u16,
pub signer_nonce: u8,
pub min_perp_auction_duration: u8,
pub default_market_order_time_in_force: u8,
pub default_spot_auction_duration: u8,
pub exchange_status: u8,
pub liquidation_duration: u8,
pub initial_pct_to_liquidate: u16,
pub max_number_of_sub_accounts: u16,
pub max_initialize_user_fee: u16,
pub padding: [u8; 10],
}
#[derive(BitFlags, Clone, Copy, PartialEq, Debug, Eq)]
pub enum ExchangeStatus {
// Active = 0b00000000
DepositPaused = 0b00000001,
WithdrawPaused = 0b00000010,
AmmPaused = 0b00000100,
FillPaused = 0b00001000,
LiqPaused = 0b00010000,
FundingPaused = 0b00100000,
SettlePnlPaused = 0b01000000,
AmmImmediateFillPaused = 0b10000000,
// Paused = 0b11111111
}
impl ExchangeStatus {
pub fn active() -> u8 {
BitFlags::<ExchangeStatus>::empty().bits() as u8
}
}
impl State {
pub fn get_exchange_status(&self) -> DriftResult<BitFlags<ExchangeStatus>> {
BitFlags::<ExchangeStatus>::from_bits(usize::from(self.exchange_status)).safe_unwrap()
}
pub fn amm_immediate_fill_paused(&self) -> DriftResult<bool> {
Ok(self
.get_exchange_status()?
.contains(ExchangeStatus::AmmImmediateFillPaused))
}
pub fn amm_paused(&self) -> DriftResult<bool> {
Ok(self
.get_exchange_status()?
.contains(ExchangeStatus::AmmPaused))
}
pub fn funding_paused(&self) -> DriftResult<bool> {
Ok(self
.get_exchange_status()?
.contains(ExchangeStatus::FundingPaused))
}
pub fn max_number_of_sub_accounts(&self) -> u64 {
if self.max_number_of_sub_accounts <= 5 {
return self.max_number_of_sub_accounts as u64;
}
(self.max_number_of_sub_accounts as u64).saturating_mul(100)
}
pub fn get_init_user_fee(&self) -> DriftResult<u64> {
let max_init_fee: u64 = (self.max_initialize_user_fee as u64) * LAMPORTS_PER_SOL_U64 / 100;
let target_utilization: u64 = 8 * PERCENTAGE_PRECISION_U64 / 10;
let account_space_utilization: u64 = self
.number_of_sub_accounts
.safe_mul(PERCENTAGE_PRECISION_U64)?
.safe_div(self.max_number_of_sub_accounts().max(1))?;
let init_fee: u64 = if account_space_utilization > target_utilization {
max_init_fee
.safe_mul(account_space_utilization.safe_sub(target_utilization)?)?
.safe_div(PERCENTAGE_PRECISION_U64.safe_sub(target_utilization)?)?
} else {
0
};
Ok(init_fee)
}
}
impl Size for State {
const SIZE: usize = 992;
}
#[derive(Copy, AnchorSerialize, AnchorDeserialize, Clone, Debug)]
pub struct OracleGuardRails {
pub price_divergence: PriceDivergenceGuardRails,
pub validity: ValidityGuardRails,
}
impl Default for OracleGuardRails {
fn default() -> Self {
OracleGuardRails {
price_divergence: PriceDivergenceGuardRails::default(),
validity: ValidityGuardRails {
slots_before_stale_for_amm: 10, // ~5 seconds
slots_before_stale_for_margin: 120, // ~60 seconds
confidence_interval_max_size: 20_000, // 2% of price
too_volatile_ratio: 5, // 5x or 80% down
},
}
}
}
impl OracleGuardRails {
pub fn max_oracle_twap_5min_percent_divergence(&self) -> u64 {
self.price_divergence
.oracle_twap_5min_percent_divergence
.max(PERCENTAGE_PRECISION_U64 / 2)
}
}
#[derive(Copy, AnchorSerialize, AnchorDeserialize, Clone, Debug)]
pub struct PriceDivergenceGuardRails {
pub mark_oracle_percent_divergence: u64,
pub oracle_twap_5min_percent_divergence: u64,
}
impl Default for PriceDivergenceGuardRails {
fn default() -> Self {
PriceDivergenceGuardRails {
mark_oracle_percent_divergence: PERCENTAGE_PRECISION_U64 / 10,
oracle_twap_5min_percent_divergence: PERCENTAGE_PRECISION_U64 / 2,
}
}
}
#[derive(Copy, AnchorSerialize, AnchorDeserialize, Clone, Default, Debug)]
pub struct ValidityGuardRails {
pub slots_before_stale_for_amm: i64,
pub slots_before_stale_for_margin: i64,
pub confidence_interval_max_size: u64,
pub too_volatile_ratio: i64,
}
#[derive(AnchorSerialize, AnchorDeserialize, Clone, Debug)]
pub struct FeeStructure {
pub fee_tiers: [FeeTier; 10],
pub filler_reward_structure: OrderFillerRewardStructure,
pub referrer_reward_epoch_upper_bound: u64,
pub flat_filler_fee: u64,
}
impl Default for FeeStructure {
fn default() -> Self {
FeeStructure::perps_default()
}
}
#[derive(AnchorSerialize, AnchorDeserialize, Copy, Clone, Debug)]
pub struct FeeTier {
pub fee_numerator: u32,
pub fee_denominator: u32,
pub maker_rebate_numerator: u32,
pub maker_rebate_denominator: u32,
pub referrer_reward_numerator: u32,
pub referrer_reward_denominator: u32,
pub referee_fee_numerator: u32,
pub referee_fee_denominator: u32,
}
impl Default for FeeTier {
fn default() -> Self {
FeeTier {
fee_numerator: 0,
fee_denominator: FEE_DENOMINATOR,
maker_rebate_numerator: 0,
maker_rebate_denominator: FEE_DENOMINATOR,
referrer_reward_numerator: 0,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR,
referee_fee_numerator: 0,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR,
}
}
}
#[derive(AnchorSerialize, AnchorDeserialize, Default, Clone, Debug)]
pub struct OrderFillerRewardStructure {
pub reward_numerator: u32,
pub reward_denominator: u32,
pub time_based_reward_lower_bound: u128, // minimum filler reward for time-based reward
}
impl FeeStructure {
pub fn perps_default() -> Self {
let mut fee_tiers = [FeeTier::default(); 10];
fee_tiers[0] = FeeTier {
fee_numerator: 100,
fee_denominator: FEE_DENOMINATOR, // 10 bps
maker_rebate_numerator: 20,
maker_rebate_denominator: FEE_DENOMINATOR, // 2bps
referrer_reward_numerator: 15,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR, // 15% of taker fee
referee_fee_numerator: 5,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR, // 5%
};
fee_tiers[1] = FeeTier {
fee_numerator: 90,
fee_denominator: FEE_DENOMINATOR, // 8 bps
maker_rebate_numerator: 20,
maker_rebate_denominator: FEE_DENOMINATOR, // 2bps
referrer_reward_numerator: 15,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR, // 15% of taker fee
referee_fee_numerator: 5,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR, // 5%
};
fee_tiers[2] = FeeTier {
fee_numerator: 80,
fee_denominator: FEE_DENOMINATOR, // 6 bps
maker_rebate_numerator: 20,
maker_rebate_denominator: FEE_DENOMINATOR, // 2bps
referrer_reward_numerator: 15,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR, // 15% of taker fee
referee_fee_numerator: 5,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR, // 5%
};
fee_tiers[3] = FeeTier {
fee_numerator: 70,
fee_denominator: FEE_DENOMINATOR, // 5 bps
maker_rebate_numerator: 20,
maker_rebate_denominator: FEE_DENOMINATOR, // 2bps
referrer_reward_numerator: 15,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR, // 15% of taker fee
referee_fee_numerator: 5,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR, // 5%
};
fee_tiers[4] = FeeTier {
fee_numerator: 60,
fee_denominator: FEE_DENOMINATOR, // 4 bps
maker_rebate_numerator: 20,
maker_rebate_denominator: FEE_DENOMINATOR, // 2bps
referrer_reward_numerator: 15,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR, // 15% of taker fee
referee_fee_numerator: 5,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR, // 5%
};
fee_tiers[5] = FeeTier {
fee_numerator: 50,
fee_denominator: FEE_DENOMINATOR, // 3.5 bps
maker_rebate_numerator: 20,
maker_rebate_denominator: FEE_DENOMINATOR, // 2bps
referrer_reward_numerator: 15,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR, // 15% of taker fee
referee_fee_numerator: 5,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR, // 5%
};
FeeStructure {
fee_tiers,
filler_reward_structure: OrderFillerRewardStructure {
reward_numerator: 10,
reward_denominator: FEE_PERCENTAGE_DENOMINATOR,
time_based_reward_lower_bound: 10_000, // 1 cent
},
flat_filler_fee: 10_000,
referrer_reward_epoch_upper_bound: MAX_REFERRER_REWARD_EPOCH_UPPER_BOUND,
}
}
pub fn spot_default() -> Self {
let mut fee_tiers = [FeeTier::default(); 10];
fee_tiers[0] = FeeTier {
fee_numerator: 100,
fee_denominator: FEE_DENOMINATOR, // 10 bps
maker_rebate_numerator: 20,
maker_rebate_denominator: FEE_DENOMINATOR, // 2bps
referrer_reward_numerator: 0,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR, // 0% of taker fee
referee_fee_numerator: 0,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR, // 0%
};
FeeStructure {
fee_tiers,
filler_reward_structure: OrderFillerRewardStructure {
reward_numerator: 10,
reward_denominator: FEE_PERCENTAGE_DENOMINATOR,
time_based_reward_lower_bound: 10_000, // 1 cent
},
flat_filler_fee: 10_000,
referrer_reward_epoch_upper_bound: MAX_REFERRER_REWARD_EPOCH_UPPER_BOUND,
}
}
}
#[cfg(test)]
impl FeeStructure {
pub fn test_default() -> Self {
let mut fee_tiers = [FeeTier::default(); 10];
fee_tiers[0] = FeeTier {
fee_numerator: 100,
fee_denominator: FEE_DENOMINATOR,
maker_rebate_numerator: 60,
maker_rebate_denominator: FEE_DENOMINATOR,
referrer_reward_numerator: 10,
referrer_reward_denominator: FEE_PERCENTAGE_DENOMINATOR,
referee_fee_numerator: 10,
referee_fee_denominator: FEE_PERCENTAGE_DENOMINATOR,
};
FeeStructure {
fee_tiers,
filler_reward_structure: OrderFillerRewardStructure {
reward_numerator: 10,
reward_denominator: FEE_PERCENTAGE_DENOMINATOR,
time_based_reward_lower_bound: 10_000, // 1 cent
},
..FeeStructure::perps_default()
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/oracle.rs
|
use anchor_lang::prelude::*;
use std::cell::Ref;
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
use crate::math::constants::{PRICE_PRECISION, PRICE_PRECISION_I64, PRICE_PRECISION_U64};
use crate::math::safe_math::SafeMath;
use switchboard::{AggregatorAccountData, SwitchboardDecimal};
use switchboard_on_demand::{PullFeedAccountData, SB_ON_DEMAND_PRECISION};
use crate::error::ErrorCode::{InvalidOracle, UnableToLoadOracle};
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::load_ref::load_ref;
use crate::state::perp_market::PerpMarket;
use crate::state::pyth_lazer_oracle::PythLazerOracle;
use crate::state::traits::Size;
use crate::validate;
#[cfg(test)]
mod tests;
#[derive(Default, AnchorSerialize, AnchorDeserialize, Clone, Copy, Eq, PartialEq, Debug)]
pub struct HistoricalOracleData {
/// precision: PRICE_PRECISION
pub last_oracle_price: i64,
/// precision: PRICE_PRECISION
pub last_oracle_conf: u64,
/// number of slots since last update
pub last_oracle_delay: i64,
/// precision: PRICE_PRECISION
pub last_oracle_price_twap: i64,
/// precision: PRICE_PRECISION
pub last_oracle_price_twap_5min: i64,
/// unix_timestamp of last snapshot
pub last_oracle_price_twap_ts: i64,
}
impl HistoricalOracleData {
pub fn default_quote_oracle() -> Self {
HistoricalOracleData {
last_oracle_price: PRICE_PRECISION_I64,
last_oracle_conf: 0,
last_oracle_delay: 0,
last_oracle_price_twap: PRICE_PRECISION_I64,
last_oracle_price_twap_5min: PRICE_PRECISION_I64,
..HistoricalOracleData::default()
}
}
pub fn default_price(price: i64) -> Self {
HistoricalOracleData {
last_oracle_price: price,
last_oracle_conf: 0,
last_oracle_delay: 10,
last_oracle_price_twap: price,
last_oracle_price_twap_5min: price,
..HistoricalOracleData::default()
}
}
pub fn default_with_current_oracle(oracle_price_data: OraclePriceData) -> Self {
HistoricalOracleData {
last_oracle_price: oracle_price_data.price,
last_oracle_conf: oracle_price_data.confidence,
last_oracle_delay: oracle_price_data.delay,
last_oracle_price_twap: oracle_price_data.price,
last_oracle_price_twap_5min: oracle_price_data.price,
// last_oracle_price_twap_ts: now,
..HistoricalOracleData::default()
}
}
}
#[derive(Default, AnchorSerialize, AnchorDeserialize, Clone, Copy, Eq, PartialEq, Debug)]
pub struct HistoricalIndexData {
/// precision: PRICE_PRECISION
pub last_index_bid_price: u64,
/// precision: PRICE_PRECISION
pub last_index_ask_price: u64,
/// precision: PRICE_PRECISION
pub last_index_price_twap: u64,
/// precision: PRICE_PRECISION
pub last_index_price_twap_5min: u64,
/// unix_timestamp of last snapshot
pub last_index_price_twap_ts: i64,
}
impl HistoricalIndexData {
pub fn default_quote_oracle() -> Self {
HistoricalIndexData {
last_index_bid_price: PRICE_PRECISION_U64,
last_index_ask_price: PRICE_PRECISION_U64,
last_index_price_twap: PRICE_PRECISION_U64,
last_index_price_twap_5min: PRICE_PRECISION_U64,
..HistoricalIndexData::default()
}
}
pub fn default_with_current_oracle(oracle_price_data: OraclePriceData) -> DriftResult<Self> {
let price = oracle_price_data.price.cast::<u64>().safe_unwrap()?;
Ok(HistoricalIndexData {
last_index_bid_price: price,
last_index_ask_price: price,
last_index_price_twap: price,
last_index_price_twap_5min: price,
..HistoricalIndexData::default()
})
}
}
#[derive(
AnchorSerialize, AnchorDeserialize, Clone, Copy, Eq, PartialEq, Debug, Default, Ord, PartialOrd,
)]
pub enum OracleSource {
#[default]
Pyth,
Switchboard,
QuoteAsset,
Pyth1K,
Pyth1M,
PythStableCoin,
Prelaunch,
PythPull,
Pyth1KPull,
Pyth1MPull,
PythStableCoinPull,
SwitchboardOnDemand,
PythLazer,
}
impl OracleSource {
pub fn is_pyth_pull_oracle(&self) -> bool {
matches!(
self,
OracleSource::PythPull
| OracleSource::Pyth1KPull
| OracleSource::Pyth1MPull
| OracleSource::PythStableCoinPull
)
}
pub fn is_pyth_push_oracle(&self) -> bool {
matches!(
self,
OracleSource::Pyth
| OracleSource::Pyth1K
| OracleSource::Pyth1M
| OracleSource::PythStableCoin
)
}
pub fn get_pyth_multiple(&self) -> u128 {
match self {
OracleSource::Pyth
| OracleSource::PythPull
| OracleSource::PythLazer
| OracleSource::PythStableCoin
| OracleSource::PythStableCoinPull => 1,
OracleSource::Pyth1K | OracleSource::Pyth1KPull => 1000,
OracleSource::Pyth1M | OracleSource::Pyth1MPull => 1000000,
_ => {
panic!("Calling get_pyth_multiple on non-pyth oracle source");
}
}
}
}
#[derive(Default, Clone, Copy, Debug)]
pub struct OraclePriceData {
pub price: i64,
pub confidence: u64,
pub delay: i64,
pub has_sufficient_number_of_data_points: bool,
}
impl OraclePriceData {
pub fn default_usd() -> Self {
OraclePriceData {
price: PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
}
}
}
pub fn get_oracle_price(
oracle_source: &OracleSource,
price_oracle: &AccountInfo,
clock_slot: u64,
) -> DriftResult<OraclePriceData> {
match oracle_source {
OracleSource::Pyth => get_pyth_price(price_oracle, clock_slot, oracle_source),
OracleSource::Pyth1K => get_pyth_price(price_oracle, clock_slot, oracle_source),
OracleSource::Pyth1M => get_pyth_price(price_oracle, clock_slot, oracle_source),
OracleSource::PythStableCoin => {
get_pyth_stable_coin_price(price_oracle, clock_slot, oracle_source)
}
OracleSource::Switchboard => get_switchboard_price(price_oracle, clock_slot),
OracleSource::SwitchboardOnDemand => get_sb_on_demand_price(price_oracle, clock_slot),
OracleSource::QuoteAsset => Ok(OraclePriceData {
price: PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
}),
OracleSource::Prelaunch => get_prelaunch_price(price_oracle, clock_slot),
OracleSource::PythPull => get_pyth_price(price_oracle, clock_slot, oracle_source),
OracleSource::Pyth1KPull => get_pyth_price(price_oracle, clock_slot, oracle_source),
OracleSource::Pyth1MPull => get_pyth_price(price_oracle, clock_slot, oracle_source),
OracleSource::PythStableCoinPull => {
get_pyth_stable_coin_price(price_oracle, clock_slot, oracle_source)
}
OracleSource::PythLazer => get_pyth_price(price_oracle, clock_slot, oracle_source),
}
}
pub fn get_pyth_price(
price_oracle: &AccountInfo,
clock_slot: u64,
oracle_source: &OracleSource,
) -> DriftResult<OraclePriceData> {
let multiple = oracle_source.get_pyth_multiple();
let mut pyth_price_data: &[u8] = &price_oracle
.try_borrow_data()
.or(Err(crate::error::ErrorCode::UnableToLoadOracle))?;
let oracle_price: i64;
let oracle_conf: u64;
let mut has_sufficient_number_of_data_points: bool = true;
let mut oracle_precision: u128;
let published_slot: u64;
if oracle_source.is_pyth_pull_oracle() {
let price_message = pyth_solana_receiver_sdk::price_update::PriceUpdateV2::try_deserialize(
&mut pyth_price_data,
)
.unwrap();
oracle_price = price_message.price_message.price;
oracle_conf = price_message.price_message.conf;
oracle_precision = 10_u128.pow(price_message.price_message.exponent.unsigned_abs());
published_slot = price_message.posted_slot;
} else if oracle_source.is_pyth_push_oracle() {
let price_data = pyth_client::cast::<pyth_client::Price>(pyth_price_data);
oracle_price = price_data.agg.price;
oracle_conf = price_data.agg.conf;
let min_publishers = price_data.num.min(3);
let publisher_count = price_data.num_qt;
#[cfg(feature = "mainnet-beta")]
{
has_sufficient_number_of_data_points = publisher_count >= min_publishers;
}
#[cfg(not(feature = "mainnet-beta"))]
{
has_sufficient_number_of_data_points = true;
}
oracle_precision = 10_u128.pow(price_data.expo.unsigned_abs());
published_slot = price_data.valid_slot;
} else {
let price_data = PythLazerOracle::try_deserialize(&mut pyth_price_data).unwrap();
oracle_price = price_data.price;
oracle_conf = price_data.conf;
oracle_precision = 10_u128.pow(price_data.exponent.unsigned_abs());
published_slot = price_data.posted_slot;
}
if oracle_precision <= multiple {
msg!("Multiple larger than oracle precision");
return Err(crate::error::ErrorCode::InvalidOracle);
}
oracle_precision = oracle_precision.safe_div(multiple)?;
let mut oracle_scale_mult = 1;
let mut oracle_scale_div = 1;
if oracle_precision > PRICE_PRECISION {
oracle_scale_div = oracle_precision.safe_div(PRICE_PRECISION)?;
} else {
oracle_scale_mult = PRICE_PRECISION.safe_div(oracle_precision)?;
}
let oracle_price_scaled = (oracle_price)
.cast::<i128>()?
.safe_mul(oracle_scale_mult.cast()?)?
.safe_div(oracle_scale_div.cast()?)?
.cast::<i64>()?;
let oracle_conf_scaled = (oracle_conf)
.cast::<u128>()?
.safe_mul(oracle_scale_mult)?
.safe_div(oracle_scale_div)?
.cast::<u64>()?;
let oracle_delay: i64 = clock_slot.cast::<i64>()?.safe_sub(published_slot.cast()?)?;
Ok(OraclePriceData {
price: oracle_price_scaled,
confidence: oracle_conf_scaled,
delay: oracle_delay,
has_sufficient_number_of_data_points,
})
}
pub fn get_pyth_stable_coin_price(
price_oracle: &AccountInfo,
clock_slot: u64,
oracle_source: &OracleSource,
) -> DriftResult<OraclePriceData> {
let mut oracle_price_data = get_pyth_price(price_oracle, clock_slot, oracle_source)?;
let price = oracle_price_data.price;
let confidence = oracle_price_data.confidence;
let five_bps = 500_i64;
if price.safe_sub(PRICE_PRECISION_I64)?.abs() <= five_bps.min(confidence.cast()?) {
oracle_price_data.price = PRICE_PRECISION_I64;
}
Ok(oracle_price_data)
}
pub fn get_switchboard_price(
price_oracle: &AccountInfo,
clock_slot: u64,
) -> DriftResult<OraclePriceData> {
let aggregator_data: Ref<AggregatorAccountData> =
load_ref(price_oracle).or(Err(ErrorCode::UnableToLoadOracle))?;
let price = convert_switchboard_decimal(&aggregator_data.latest_confirmed_round.result)?
.cast::<i64>()?;
let confidence =
convert_switchboard_decimal(&aggregator_data.latest_confirmed_round.std_deviation)?
.cast::<i64>()?;
// std deviation should always be positive, if we get a negative make it u128::MAX so it's flagged as bad value
let confidence = if confidence < 0 {
u64::MAX
} else {
let price_10bps = price.unsigned_abs().safe_div(1000)?;
confidence.unsigned_abs().max(price_10bps)
};
let delay = clock_slot.cast::<i64>()?.safe_sub(
aggregator_data
.latest_confirmed_round
.round_open_slot
.cast()?,
)?;
let has_sufficient_number_of_data_points =
aggregator_data.latest_confirmed_round.num_success >= aggregator_data.min_oracle_results;
Ok(OraclePriceData {
price,
confidence,
delay,
has_sufficient_number_of_data_points,
})
}
pub fn get_sb_on_demand_price(
price_oracle: &AccountInfo,
clock_slot: u64,
) -> DriftResult<OraclePriceData> {
let pull_feed_account_info: Ref<PullFeedAccountData> =
load_ref(price_oracle).or(Err(ErrorCode::UnableToLoadOracle))?;
let latest_oracle_submssions: Vec<switchboard_on_demand::OracleSubmission> =
pull_feed_account_info.latest_submissions();
let average_price = latest_oracle_submssions
.iter()
.map(|submission| submission.value)
.sum::<i128>()
/ latest_oracle_submssions.len() as i128;
let price = convert_sb_i128(&average_price)?.cast::<i64>()?;
let confidence = convert_sb_i128(
&pull_feed_account_info
.range()
.ok_or(ErrorCode::UnableToLoadOracle)?,
)?
.cast::<i64>()?
.unsigned_abs();
let delay = clock_slot
.cast::<i64>()?
.safe_sub(latest_oracle_submssions[0].landed_at.cast()?)?;
let has_sufficient_number_of_data_points = true;
Ok(OraclePriceData {
price,
confidence,
delay,
has_sufficient_number_of_data_points,
})
}
/// Given a decimal number represented as a mantissa (the digits) plus an
/// original_precision (10.pow(some number of decimals)), scale the
/// mantissa/digits to make sense with a new_precision.
fn convert_switchboard_decimal(switchboard_decimal: &SwitchboardDecimal) -> DriftResult<i128> {
let switchboard_precision = 10_u128.pow(switchboard_decimal.scale);
if switchboard_precision > PRICE_PRECISION {
switchboard_decimal
.mantissa
.safe_div((switchboard_precision / PRICE_PRECISION) as i128)
} else {
switchboard_decimal
.mantissa
.safe_mul((PRICE_PRECISION / switchboard_precision) as i128)
}
}
/// Given a decimal number represented as a mantissa (the digits) plus an
/// original_precision (10.pow(some number of decimals)), scale the
/// mantissa/digits to make sense with a new_precision.
fn convert_sb_i128(switchboard_i128: &i128) -> DriftResult<i128> {
let switchboard_precision = 10_u128.pow(SB_ON_DEMAND_PRECISION);
if switchboard_precision > PRICE_PRECISION {
switchboard_i128.safe_div((switchboard_precision / PRICE_PRECISION) as i128)
} else {
switchboard_i128.safe_mul((PRICE_PRECISION / switchboard_precision) as i128)
}
}
pub fn get_prelaunch_price(price_oracle: &AccountInfo, slot: u64) -> DriftResult<OraclePriceData> {
let oracle: Ref<PrelaunchOracle> = load_ref(price_oracle).or(Err(UnableToLoadOracle))?;
Ok(OraclePriceData {
price: oracle.price,
confidence: oracle.confidence,
delay: oracle.amm_last_update_slot.saturating_sub(slot).cast()?,
has_sufficient_number_of_data_points: true,
})
}
#[derive(Clone, Copy)]
pub struct StrictOraclePrice {
pub current: i64,
pub twap_5min: Option<i64>,
}
impl StrictOraclePrice {
pub fn new(price: i64, twap_5min: i64, enabled: bool) -> Self {
Self {
current: price,
twap_5min: if enabled { Some(twap_5min) } else { None },
}
}
pub fn max(&self) -> i64 {
match self.twap_5min {
Some(twap) => self.current.max(twap),
None => self.current,
}
}
pub fn min(&self) -> i64 {
match self.twap_5min {
Some(twap) => self.current.min(twap),
None => self.current,
}
}
pub fn validate(&self) -> DriftResult {
validate!(
self.current > 0,
ErrorCode::InvalidOracle,
"oracle_price_data={} (<= 0)",
self.current,
)?;
if let Some(twap) = self.twap_5min {
validate!(
twap > 0,
ErrorCode::InvalidOracle,
"oracle_price_twap={} (<= 0)",
twap
)?;
}
Ok(())
}
}
#[cfg(test)]
impl StrictOraclePrice {
pub fn test(price: i64) -> Self {
Self {
current: price,
twap_5min: None,
}
}
}
#[account(zero_copy(unsafe))]
#[derive(Eq, PartialEq, Debug)]
#[repr(C)]
pub struct PrelaunchOracle {
pub price: i64,
pub max_price: i64,
pub confidence: u64,
// last slot oracle was updated, should be greater than or equal to last_update_slot
pub last_update_slot: u64,
// amm.last_update_slot at time oracle was updated
pub amm_last_update_slot: u64,
pub perp_market_index: u16,
pub padding: [u8; 70],
}
impl Default for PrelaunchOracle {
fn default() -> Self {
PrelaunchOracle {
price: 0,
max_price: 0,
confidence: 0,
last_update_slot: 0,
amm_last_update_slot: 0,
perp_market_index: 0,
padding: [0; 70],
}
}
}
impl Size for PrelaunchOracle {
const SIZE: usize = 112 + 8;
}
impl PrelaunchOracle {
pub fn update(&mut self, perp_market: &PerpMarket, slot: u64) -> DriftResult {
let last_twap = perp_market.amm.last_mark_price_twap.cast::<i64>()?;
let new_price = if self.max_price <= last_twap {
msg!(
"mark twap {} >= max price {}, using max",
last_twap,
self.max_price
);
self.max_price
} else {
last_twap
};
self.price = new_price;
let spread_twap = perp_market
.amm
.last_ask_price_twap
.cast::<i64>()?
.safe_sub(perp_market.amm.last_bid_price_twap.cast()?)?
.unsigned_abs();
let mark_std = perp_market.amm.mark_std;
self.confidence = spread_twap.max(mark_std);
self.amm_last_update_slot = perp_market.amm.last_update_slot;
self.last_update_slot = slot;
msg!(
"setting price = {} confidence = {}",
self.price,
self.confidence
);
Ok(())
}
pub fn validate(&self) -> DriftResult {
validate!(self.price != 0, InvalidOracle, "price == 0",)?;
validate!(self.max_price != 0, InvalidOracle, "max price == 0",)?;
validate!(
self.price <= self.max_price,
InvalidOracle,
"price {} > max price {}",
self.price,
self.max_price
)?;
Ok(())
}
}
#[derive(Debug, Clone, Copy, AnchorSerialize, AnchorDeserialize, PartialEq, Eq)]
pub struct PrelaunchOracleParams {
pub perp_market_index: u16,
pub price: Option<i64>,
pub max_price: Option<i64>,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/oracle_map.rs
|
use crate::error::ErrorCode::UnableToLoadOracle;
use crate::error::{DriftResult, ErrorCode};
use crate::ids::{
drift_oracle_receiver_program, pyth_lazer_program, pyth_program, switchboard_on_demand,
switchboard_program,
};
use crate::math::constants::PRICE_PRECISION_I64;
use crate::math::oracle::{oracle_validity, OracleValidity};
use crate::state::oracle::{get_oracle_price, OraclePriceData, OracleSource, PrelaunchOracle};
use crate::state::state::OracleGuardRails;
use crate::state::user::MarketType;
use anchor_lang::prelude::{AccountInfo, Pubkey};
use anchor_lang::Discriminator;
use anchor_lang::Key;
use arrayref::array_ref;
use solana_program::msg;
use std::collections::BTreeMap;
use std::iter::Peekable;
use std::slice::Iter;
use super::pyth_lazer_oracle::PythLazerOracle;
use super::state::ValidityGuardRails;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::traits::Size;
use crate::validate;
pub(crate) type OracleIdentifier = (Pubkey, OracleSource);
const EXTERNAL_ORACLE_PROGRAM_IDS: [Pubkey; 4] = [
pyth_program::id(),
drift_oracle_receiver_program::id(),
switchboard_program::id(),
switchboard_on_demand::id(),
];
pub struct OracleMap<'a> {
oracles: BTreeMap<Pubkey, AccountInfo<'a>>,
price_data: BTreeMap<OracleIdentifier, OraclePriceData>,
validity: BTreeMap<OracleIdentifier, OracleValidity>,
pub slot: u64,
pub oracle_guard_rails: OracleGuardRails,
pub quote_asset_price_data: OraclePriceData,
}
impl<'a> OracleMap<'a> {
pub fn contains(&self, pubkey: &Pubkey) -> bool {
self.oracles.contains_key(pubkey) || pubkey == &Pubkey::default()
}
pub fn get_account_info(&self, pubkey: &Pubkey) -> DriftResult<AccountInfo<'a>> {
Ok(self
.oracles
.get(pubkey)
.ok_or(ErrorCode::OracleNotFound)?
.clone())
}
fn should_get_quote_asset_price_data(&self, pubkey: &Pubkey) -> bool {
pubkey == &Pubkey::default()
}
pub fn get_price_data(&mut self, id: &OracleIdentifier) -> DriftResult<&OraclePriceData> {
if self.should_get_quote_asset_price_data(&id.0) {
return Ok(&self.quote_asset_price_data);
}
if self.price_data.contains_key(id) {
return self.price_data.get(id).safe_unwrap();
}
let account_info = match self.oracles.get(&id.0) {
Some(account_info) => account_info,
None => {
msg!("oracle pubkey not found in oracle_map: {}", id.0);
return Err(ErrorCode::OracleNotFound);
}
};
let price_data = get_oracle_price(&id.1, account_info, self.slot)?;
self.price_data.insert(*id, price_data);
self.price_data.get(id).safe_unwrap()
}
pub fn get_price_data_and_validity(
&mut self,
market_type: MarketType,
market_index: u16,
oracle_id: &OracleIdentifier,
last_oracle_price_twap: i64,
max_confidence_interval_multiplier: u64,
) -> DriftResult<(&OraclePriceData, OracleValidity)> {
if self.should_get_quote_asset_price_data(&oracle_id.0) {
return Ok((&self.quote_asset_price_data, OracleValidity::Valid));
}
if self.price_data.contains_key(oracle_id) {
let oracle_price_data = self.price_data.get(oracle_id).safe_unwrap()?;
let oracle_validity = if let Some(oracle_validity) = self.validity.get(oracle_id) {
*oracle_validity
} else {
let oracle_validity = oracle_validity(
market_type,
market_index,
last_oracle_price_twap,
oracle_price_data,
&self.oracle_guard_rails.validity,
max_confidence_interval_multiplier,
&oracle_id.1,
true,
)?;
self.validity.insert(*oracle_id, oracle_validity);
oracle_validity
};
return Ok((oracle_price_data, oracle_validity));
}
let account_info = match self.oracles.get(&oracle_id.0) {
Some(account_info) => account_info,
None => {
msg!("oracle pubkey not found in oracle_map: {}", oracle_id.0);
return Err(ErrorCode::OracleNotFound);
}
};
let price_data = get_oracle_price(&oracle_id.1, account_info, self.slot)?;
self.price_data.insert(*oracle_id, price_data);
let oracle_price_data = self.price_data.get(oracle_id).safe_unwrap()?;
let oracle_validity = oracle_validity(
market_type,
market_index,
last_oracle_price_twap,
oracle_price_data,
&self.oracle_guard_rails.validity,
max_confidence_interval_multiplier,
&oracle_id.1,
true,
)?;
self.validity.insert(*oracle_id, oracle_validity);
Ok((oracle_price_data, oracle_validity))
}
pub fn get_price_data_and_guard_rails(
&mut self,
oracle_id: &OracleIdentifier,
) -> DriftResult<(&OraclePriceData, &ValidityGuardRails)> {
if self.should_get_quote_asset_price_data(&oracle_id.0) {
let validity_guard_rails = &self.oracle_guard_rails.validity;
return Ok((&self.quote_asset_price_data, validity_guard_rails));
}
if self.price_data.contains_key(oracle_id) {
let oracle_price_data = self.price_data.get(oracle_id).safe_unwrap()?;
let validity_guard_rails = &self.oracle_guard_rails.validity;
return Ok((oracle_price_data, validity_guard_rails));
}
let account_info = match self.oracles.get(&oracle_id.0) {
Some(account_info) => account_info,
None => {
msg!("oracle pubkey not found in oracle_map: {}", oracle_id.0);
return Err(ErrorCode::OracleNotFound);
}
};
let price_data = get_oracle_price(&oracle_id.1, account_info, self.slot)?;
self.price_data.insert(*oracle_id, price_data);
let oracle_price_data = self.price_data.get(oracle_id).safe_unwrap()?;
let validity_guard_rails = &self.oracle_guard_rails.validity;
Ok((oracle_price_data, validity_guard_rails))
}
pub fn load<'c>(
account_info_iter: &'c mut Peekable<Iter<AccountInfo<'a>>>,
slot: u64,
oracle_guard_rails: Option<OracleGuardRails>,
) -> DriftResult<OracleMap<'a>> {
let mut oracles: BTreeMap<Pubkey, AccountInfo<'a>> = BTreeMap::new();
while let Some(account_info) = account_info_iter.peek() {
if EXTERNAL_ORACLE_PROGRAM_IDS.contains(&account_info.owner) {
let account_info: &AccountInfo<'a> = account_info_iter.next().safe_unwrap()?;
let pubkey = account_info.key();
oracles.insert(pubkey, account_info.clone());
continue;
} else if account_info.owner == &crate::id() {
let data = account_info.try_borrow_data().map_err(|e| {
msg!("Failed to borrow data while loading oracle map {:?}", e);
UnableToLoadOracle
})?;
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator == &PrelaunchOracle::discriminator() {
let expected_data_len = PrelaunchOracle::SIZE;
if data.len() < expected_data_len {
break;
}
} else if account_discriminator == &PythLazerOracle::discriminator() {
let expected_data_len = PythLazerOracle::SIZE;
if data.len() < expected_data_len {
break;
}
} else {
break;
}
let account_info = account_info_iter.next().safe_unwrap()?;
let pubkey = account_info.key();
oracles.insert(pubkey, account_info.clone());
continue;
}
break;
}
let ogr: OracleGuardRails = if let Some(o) = oracle_guard_rails {
o
} else {
OracleGuardRails::default()
};
Ok(OracleMap {
oracles,
price_data: BTreeMap::new(),
validity: BTreeMap::new(),
slot,
oracle_guard_rails: ogr,
quote_asset_price_data: OraclePriceData {
price: PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
},
})
}
pub fn load_one<'c>(
account_info: &'c AccountInfo<'a>,
slot: u64,
oracle_guard_rails: Option<OracleGuardRails>,
) -> DriftResult<OracleMap<'a>> {
let mut oracles: BTreeMap<Pubkey, AccountInfo<'a>> = BTreeMap::new();
if EXTERNAL_ORACLE_PROGRAM_IDS.contains(&account_info.owner) {
let pubkey = account_info.key();
oracles.insert(pubkey, account_info.clone());
} else if account_info.owner == &crate::id() {
let data = account_info.try_borrow_data().map_err(|e| {
msg!("Failed to borrow data while loading oracle map {:?}", e);
UnableToLoadOracle
})?;
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator == &PrelaunchOracle::discriminator() {
let expected_data_len = PrelaunchOracle::SIZE;
if data.len() < expected_data_len {
msg!("Unexpected account data len loading oracle");
return Err(UnableToLoadOracle);
}
} else if account_discriminator == &PythLazerOracle::discriminator() {
let expected_data_len = PythLazerOracle::SIZE;
if data.len() < expected_data_len {
msg!("Unexpected account data len loading oracle");
return Err(UnableToLoadOracle);
}
} else {
msg!("Unexpected account discriminator");
return Err(UnableToLoadOracle);
}
let pubkey = account_info.key();
oracles.insert(pubkey, account_info.clone());
} else if account_info.key() != Pubkey::default() {
return Err(ErrorCode::InvalidOracle);
}
let ogr: OracleGuardRails = if let Some(o) = oracle_guard_rails {
o
} else {
OracleGuardRails::default()
};
Ok(OracleMap {
oracles,
price_data: BTreeMap::new(),
validity: BTreeMap::new(),
slot,
oracle_guard_rails: ogr,
quote_asset_price_data: OraclePriceData {
price: PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
},
})
}
pub fn validate_oracle_account_info<'c>(account_info: &'c AccountInfo<'a>) -> DriftResult {
if *account_info.key == Pubkey::default() {
return Ok(());
}
validate!(
OracleMap::load_one(account_info, 0, None)?.oracles.len() == 1,
ErrorCode::InvalidOracle,
"oracle owner not recognizable"
)
}
}
#[cfg(test)]
impl<'a> OracleMap<'a> {
pub fn empty() -> OracleMap<'a> {
OracleMap {
oracles: BTreeMap::new(),
validity: BTreeMap::new(),
price_data: BTreeMap::new(),
slot: 0,
oracle_guard_rails: OracleGuardRails::default(),
quote_asset_price_data: OraclePriceData {
price: PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
},
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/rfq_user.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::math::safe_unwrap::SafeUnwrap;
use crate::ID;
use anchor_lang::prelude::{AccountInfo, AccountLoader, Pubkey};
use anchor_lang::{account, zero_copy, Discriminator};
use arrayref::array_ref;
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::iter::Peekable;
use std::slice::Iter;
use crate::state::traits::Size;
pub const RFQ_PDA_SEED: &str = "RFQ";
#[zero_copy(unsafe)]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct RFQOrderId {
pub uuid: [u8; 8],
pub max_ts: i64,
}
impl RFQOrderId {
pub fn new(uuid: [u8; 8], max_ts: i64) -> Self {
Self { uuid, max_ts }
}
}
impl Size for RFQUser {
const SIZE: usize = 776;
}
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct RFQUser {
pub user_pubkey: Pubkey,
pub rfq_order_data: [RFQOrderId; 32],
}
impl RFQUser {
pub fn check_exists_and_prune_stale_rfq_order_ids(
&mut self,
rfq_order_id: RFQOrderId,
now: i64,
) -> DriftResult<bool> {
let mut uuid_exists = false;
for i in 0..self.rfq_order_data.len() {
let existing_rfq_order_id = &mut self.rfq_order_data[i];
if existing_rfq_order_id.uuid == rfq_order_id.uuid && existing_rfq_order_id.max_ts > now
{
uuid_exists = true;
} else {
if existing_rfq_order_id.max_ts < now {
existing_rfq_order_id.uuid = [0; 8];
existing_rfq_order_id.max_ts = 0;
}
}
}
Ok(uuid_exists)
}
pub fn add_rfq_order_id(&mut self, rfq_order_id: RFQOrderId) -> DriftResult {
for i in 0..self.rfq_order_data.len() {
if self.rfq_order_data[i].max_ts == 0 {
self.rfq_order_data[i] = rfq_order_id;
return Ok(());
}
}
Err(ErrorCode::RFQUserAccountFull.into())
}
}
pub fn derive_rfq_user_pda(user_account_pubkey: &Pubkey) -> DriftResult<Pubkey> {
let (rfq_pubkey, _) = Pubkey::find_program_address(
&[RFQ_PDA_SEED.as_bytes(), user_account_pubkey.as_ref()],
&ID,
);
Ok(rfq_pubkey)
}
pub fn load_rfq_user_account_map<'a: 'b, 'b>(
account_info_iter: &mut Peekable<Iter<'a, AccountInfo<'b>>>,
) -> DriftResult<BTreeMap<Pubkey, AccountLoader<'a, RFQUser>>> {
let mut rfq_user_account_map = BTreeMap::<Pubkey, AccountLoader<'a, RFQUser>>::new();
for account_info in account_info_iter {
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::InvalidRFQUserAccount))?;
let expected_data_len = RFQUser::SIZE;
if data.len() < expected_data_len {
break;
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &RFQUser::discriminator() {
break;
}
let user_pubkey_slice = array_ref![data, 8, 32];
let user_pubkey: Pubkey = Pubkey::try_from(*user_pubkey_slice).safe_unwrap()?;
let is_writable = account_info.is_writable;
if !is_writable {
return Err(ErrorCode::RFQUserAccountWrongMutability);
}
let account_loader: AccountLoader<'a, RFQUser> =
AccountLoader::try_from(account_info).or(Err(ErrorCode::InvalidRFQUserAccount))?;
rfq_user_account_map.insert(user_pubkey, account_loader);
}
Ok(rfq_user_account_map)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/protected_maker_mode_config.rs
|
use crate::error::DriftResult;
use crate::error::ErrorCode;
use crate::state::traits::Size;
use crate::validate;
use anchor_lang::prelude::*;
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct ProtectedMakerModeConfig {
pub max_users: u32,
pub current_users: u32,
pub reduce_only: u8,
pub padding: [u8; 31],
}
impl Size for ProtectedMakerModeConfig {
const SIZE: usize = 48;
}
impl ProtectedMakerModeConfig {
pub fn validate(&self) -> DriftResult {
validate!(
self.current_users <= self.max_users,
ErrorCode::InvalidProtectedMakerModeConfig,
"current users ({}) > max users ({})",
self.current_users,
self.max_users
)?;
Ok(())
}
pub fn is_reduce_only(&self) -> bool {
self.reduce_only > 0
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/high_leverage_mode_config.rs
|
use crate::error::DriftResult;
use crate::error::ErrorCode;
use crate::state::traits::Size;
use crate::validate;
use anchor_lang::prelude::*;
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct HighLeverageModeConfig {
pub max_users: u32,
pub current_users: u32,
pub reduce_only: u8,
pub padding: [u8; 31],
}
// implement SIZE const for ProtocolIfSharesTransferConfig
impl Size for HighLeverageModeConfig {
const SIZE: usize = 48;
}
impl HighLeverageModeConfig {
pub fn validate(&self) -> DriftResult {
validate!(
self.current_users <= self.max_users,
ErrorCode::InvalidHighLeverageModeConfig,
"current users ({}) > max users ({})",
self.current_users,
self.max_users
)?;
Ok(())
}
pub fn is_reduce_only(&self) -> bool {
self.reduce_only > 0
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/perp_market_map.rs
|
use anchor_lang::accounts::account_loader::AccountLoader;
use std::cell::{Ref, RefMut};
use std::collections::{BTreeMap, BTreeSet};
use std::iter::Peekable;
use std::slice::Iter;
use anchor_lang::prelude::AccountInfo;
use anchor_lang::Discriminator;
use arrayref::array_ref;
use crate::error::{DriftResult, ErrorCode};
use crate::state::perp_market::PerpMarket;
use crate::state::user::PerpPositions;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::traits::Size;
use solana_program::msg;
use std::panic::Location;
use super::user::SpotPosition;
pub struct PerpMarketMap<'a>(pub BTreeMap<u16, AccountLoader<'a, PerpMarket>>);
impl<'a> PerpMarketMap<'a> {
#[track_caller]
#[inline(always)]
pub fn get_ref(&self, market_index: &u16) -> DriftResult<Ref<PerpMarket>> {
let loader = match self.0.get(market_index) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find perp market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
return Err(ErrorCode::PerpMarketNotFound);
}
};
match loader.load() {
Ok(perp_market) => Ok(perp_market),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load perp market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadPerpMarketAccount)
}
}
}
#[track_caller]
#[inline(always)]
pub fn get_ref_mut(&self, market_index: &u16) -> DriftResult<RefMut<PerpMarket>> {
let loader = match self.0.get(market_index) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find perp market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
return Err(ErrorCode::PerpMarketNotFound);
}
};
match loader.load_mut() {
Ok(perp_market) => Ok(perp_market),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load perp market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadPerpMarketAccount)
}
}
}
pub fn load<'b, 'c>(
writable_markets: &'b MarketSet,
account_info_iter: &'c mut Peekable<Iter<'a, AccountInfo<'a>>>,
) -> DriftResult<PerpMarketMap<'a>> {
let mut perp_market_map: PerpMarketMap = PerpMarketMap(BTreeMap::new());
let market_discriminator: [u8; 8] = PerpMarket::discriminator();
while let Some(account_info) = account_info_iter.peek() {
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadMarketData))?;
let expected_data_len = PerpMarket::SIZE;
if data.len() < expected_data_len {
break;
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &market_discriminator {
break;
}
// market index 1160 bytes from front of account
let market_index = u16::from_le_bytes(*array_ref![data, 1160, 2]);
if perp_market_map.0.contains_key(&market_index) {
msg!("Can not include same market index twice {}", market_index);
return Err(ErrorCode::InvalidMarketAccount);
}
let account_info = account_info_iter.next().safe_unwrap()?;
let is_writable = account_info.is_writable;
if writable_markets.contains(&market_index) && !is_writable {
return Err(ErrorCode::MarketWrongMutability);
}
let account_loader: AccountLoader<PerpMarket> =
AccountLoader::try_from(account_info).or(Err(ErrorCode::InvalidMarketAccount))?;
perp_market_map.0.insert(market_index, account_loader);
}
Ok(perp_market_map)
}
}
#[cfg(test)]
impl<'a> PerpMarketMap<'a> {
pub fn load_one<'c: 'a>(
account_info: &'c AccountInfo<'a>,
must_be_writable: bool,
) -> DriftResult<PerpMarketMap<'a>> {
let mut perp_market_map: PerpMarketMap = PerpMarketMap(BTreeMap::new());
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadMarketData))?;
let expected_data_len = PerpMarket::SIZE;
if data.len() < expected_data_len {
return Err(ErrorCode::CouldNotLoadMarketData);
}
let market_discriminator: [u8; 8] = PerpMarket::discriminator();
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &market_discriminator {
return Err(ErrorCode::CouldNotLoadMarketData);
}
// market index 1160 bytes from front of account
let market_index = u16::from_le_bytes(*array_ref![data, 1160, 2]);
let is_writable = account_info.is_writable;
let account_loader: AccountLoader<PerpMarket> =
AccountLoader::try_from(account_info).or(Err(ErrorCode::InvalidMarketAccount))?;
if must_be_writable && !is_writable {
return Err(ErrorCode::MarketWrongMutability);
}
perp_market_map.0.insert(market_index, account_loader);
Ok(perp_market_map)
}
pub fn empty() -> Self {
PerpMarketMap(BTreeMap::new())
}
pub fn load_multiple<'c: 'a>(
account_infos: Vec<&'c AccountInfo<'a>>,
must_be_writable: bool,
) -> DriftResult<PerpMarketMap<'a>> {
let mut perp_market_map: PerpMarketMap = PerpMarketMap(BTreeMap::new());
for account_info in account_infos {
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadMarketData))?;
let expected_data_len = PerpMarket::SIZE;
if data.len() < expected_data_len {
return Err(ErrorCode::CouldNotLoadMarketData);
}
let market_discriminator: [u8; 8] = PerpMarket::discriminator();
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &market_discriminator {
return Err(ErrorCode::CouldNotLoadMarketData);
}
// market index 1160 bytes from front of account
let market_index = u16::from_le_bytes(*array_ref![data, 1160, 2]);
let is_writable = account_info.is_writable;
let account_loader: AccountLoader<PerpMarket> =
AccountLoader::try_from(account_info).or(Err(ErrorCode::InvalidMarketAccount))?;
if must_be_writable && !is_writable {
return Err(ErrorCode::MarketWrongMutability);
}
perp_market_map.0.insert(market_index, account_loader);
}
Ok(perp_market_map)
}
}
pub(crate) type MarketSet = BTreeSet<u16>;
pub fn get_writable_perp_market_set(market_index: u16) -> MarketSet {
let mut writable_markets = MarketSet::new();
writable_markets.insert(market_index);
writable_markets
}
pub fn get_writable_perp_market_set_from_vec(market_indexes: &[u16]) -> MarketSet {
let mut writable_markets = MarketSet::new();
for market_index in market_indexes.iter() {
writable_markets.insert(*market_index);
}
writable_markets
}
pub fn get_market_set_from_list(market_indexes: [u16; 5]) -> MarketSet {
let mut writable_markets = MarketSet::new();
for market_index in market_indexes.iter() {
if *market_index == 100 {
continue; // todo
}
writable_markets.insert(*market_index);
}
writable_markets
}
pub fn get_market_set_for_user_positions(user_positions: &PerpPositions) -> MarketSet {
let mut writable_markets = MarketSet::new();
for position in user_positions.iter() {
if !position.is_available() {
writable_markets.insert(position.market_index);
}
}
writable_markets
}
pub fn get_market_set_for_spot_positions(spot_positions: &[SpotPosition]) -> MarketSet {
let mut writable_markets = MarketSet::new();
for position in spot_positions.iter() {
if !position.is_available() {
writable_markets.insert(position.market_index);
}
}
writable_markets
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fill_mode.rs
|
use crate::error::DriftResult;
use crate::math::auction::calculate_auction_price;
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
use crate::state::user::Order;
#[cfg(test)]
mod tests;
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum FillMode {
Fill,
PlaceAndMake,
PlaceAndTake(bool, u8),
Liquidation,
RFQ,
}
impl FillMode {
pub fn get_limit_price(
&self,
order: &Order,
valid_oracle_price: Option<i64>,
slot: u64,
tick_size: u64,
is_prediction_market: bool,
) -> DriftResult<Option<u64>> {
match self {
FillMode::Fill | FillMode::PlaceAndMake | FillMode::Liquidation | FillMode::RFQ => {
order.get_limit_price(
valid_oracle_price,
None,
slot,
tick_size,
is_prediction_market,
)
}
FillMode::PlaceAndTake(_, auction_duration_percentage) => {
let auction_duration = order
.auction_duration
.cast::<u64>()?
.safe_mul(auction_duration_percentage.min(&100).cast()?)?
.safe_div(100)?
.cast::<u64>()?;
if order.has_auction() {
calculate_auction_price(
order,
order.slot.safe_add(auction_duration)?,
tick_size,
valid_oracle_price,
is_prediction_market,
)
.map(Some)
} else {
order.get_limit_price(
valid_oracle_price,
None,
slot,
tick_size,
is_prediction_market,
)
}
}
}
}
pub fn is_liquidation(&self) -> bool {
self == &FillMode::Liquidation
}
pub fn is_rfq(&self) -> bool {
self == &FillMode::RFQ
}
pub fn is_ioc(&self) -> bool {
matches!(self, FillMode::PlaceAndTake(true, _))
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/traits.rs
|
#[cfg(test)]
mod tests;
pub trait Size {
const SIZE: usize;
}
pub trait MarketIndexOffset {
const MARKET_INDEX_OFFSET: usize;
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/spot_market_map.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::state::spot_market::SpotMarket;
use anchor_lang::prelude::{AccountInfo, AccountLoader};
use std::cell::{Ref, RefMut};
use std::collections::{BTreeMap, BTreeSet};
use std::iter::Peekable;
use std::slice::Iter;
use crate::math::constants::QUOTE_SPOT_MARKET_INDEX;
use anchor_lang::Discriminator;
use arrayref::array_ref;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::traits::Size;
use solana_program::msg;
use std::panic::Location;
pub struct SpotMarketMap<'a>(
pub BTreeMap<u16, AccountLoader<'a, SpotMarket>>,
SpotMarketSet,
);
impl<'a> SpotMarketMap<'a> {
#[track_caller]
#[inline(always)]
pub fn get_ref(&self, market_index: &u16) -> DriftResult<Ref<SpotMarket>> {
let loader = match self.0.get(market_index) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find spot market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
return Err(ErrorCode::SpotMarketNotFound);
}
};
match loader.load() {
Ok(spot_market) => Ok(spot_market),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load spot market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadSpotMarketAccount)
}
}
}
#[track_caller]
#[inline(always)]
pub fn get_ref_mut(&self, market_index: &u16) -> DriftResult<RefMut<SpotMarket>> {
if !self.1.contains(market_index) {
let caller = Location::caller();
msg!(
"Spot market {} not expected to be mutable at {}:{}",
market_index,
caller.file(),
caller.line()
);
return Err(ErrorCode::SpotMarketWrongMutability);
}
let loader = match self.0.get(market_index) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find spot market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
return Err(ErrorCode::SpotMarketNotFound);
}
};
match loader.load_mut() {
Ok(spot_market) => Ok(spot_market),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load spot market {} at {}:{}",
market_index,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadSpotMarketAccount)
}
}
}
#[track_caller]
#[inline(always)]
pub fn get_quote_spot_market(&self) -> DriftResult<Ref<SpotMarket>> {
let loader = match self.0.get("E_SPOT_MARKET_INDEX) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find spot market {} at {}:{}",
QUOTE_SPOT_MARKET_INDEX,
caller.file(),
caller.line()
);
return Err(ErrorCode::SpotMarketNotFound);
}
};
match loader.load() {
Ok(spot_market) => Ok(spot_market),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load spot market {} at {}:{}",
QUOTE_SPOT_MARKET_INDEX,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadSpotMarketAccount)
}
}
}
#[track_caller]
#[inline(always)]
pub fn get_quote_spot_market_mut(&self) -> DriftResult<RefMut<SpotMarket>> {
if !self.1.contains("E_SPOT_MARKET_INDEX) {
let caller = Location::caller();
msg!(
"Spot market {} not expected to be mutable at {}:{}",
QUOTE_SPOT_MARKET_INDEX,
caller.file(),
caller.line()
);
return Err(ErrorCode::SpotMarketWrongMutability);
}
let loader = match self.0.get("E_SPOT_MARKET_INDEX) {
Some(loader) => loader,
None => {
let caller = Location::caller();
msg!(
"Could not find spot market {} at {}:{}",
QUOTE_SPOT_MARKET_INDEX,
caller.file(),
caller.line()
);
return Err(ErrorCode::SpotMarketNotFound);
}
};
match loader.load_mut() {
Ok(spot_market) => Ok(spot_market),
Err(e) => {
let caller = Location::caller();
msg!("{:?}", e);
msg!(
"Could not load spot market {} at {}:{}",
QUOTE_SPOT_MARKET_INDEX,
caller.file(),
caller.line()
);
Err(ErrorCode::UnableToLoadSpotMarketAccount)
}
}
}
pub fn load<'b, 'c>(
writable_spot_markets: &'b SpotMarketSet,
account_info_iter: &'c mut Peekable<Iter<'a, AccountInfo<'a>>>,
) -> DriftResult<SpotMarketMap<'a>> {
let mut spot_market_map: SpotMarketMap =
SpotMarketMap(BTreeMap::new(), writable_spot_markets.clone());
let spot_market_discriminator: [u8; 8] = SpotMarket::discriminator();
while let Some(account_info) = account_info_iter.peek() {
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadSpotMarketData))?;
let expected_data_len = SpotMarket::SIZE;
if data.len() < expected_data_len {
break;
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &spot_market_discriminator {
break;
}
let market_index = u16::from_le_bytes(*array_ref![data, 684, 2]);
if spot_market_map.0.contains_key(&market_index) {
msg!("Can not include same market index twice {}", market_index);
return Err(ErrorCode::InvalidSpotMarketAccount);
}
let account_info = account_info_iter.next().safe_unwrap()?;
let is_writable = account_info.is_writable;
let account_loader: AccountLoader<SpotMarket> =
AccountLoader::try_from(account_info)
.or(Err(ErrorCode::InvalidSpotMarketAccount))?;
if writable_spot_markets.contains(&market_index) && !is_writable {
return Err(ErrorCode::SpotMarketWrongMutability);
}
spot_market_map.0.insert(market_index, account_loader);
}
Ok(spot_market_map)
}
}
#[cfg(test)]
impl<'a> SpotMarketMap<'a> {
pub fn load_one<'c: 'a>(
account_info: &'c AccountInfo<'a>,
must_be_writable: bool,
) -> DriftResult<SpotMarketMap<'a>> {
let mut writable_markets = SpotMarketSet::new();
let mut map = BTreeMap::new();
let spot_market_discriminator: [u8; 8] = SpotMarket::discriminator();
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadSpotMarketData))?;
let expected_data_len = SpotMarket::SIZE;
if data.len() < expected_data_len {
return Err(ErrorCode::CouldNotLoadSpotMarketData);
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &spot_market_discriminator {
return Err(ErrorCode::CouldNotLoadSpotMarketData);
}
let market_index = u16::from_le_bytes(*array_ref![data, 684, 2]);
let is_writable = account_info.is_writable;
let account_loader: AccountLoader<SpotMarket> =
AccountLoader::try_from(account_info).or(Err(ErrorCode::InvalidSpotMarketAccount))?;
if must_be_writable && !is_writable {
return Err(ErrorCode::SpotMarketWrongMutability);
}
if must_be_writable {
writable_markets.insert(market_index);
}
if !must_be_writable && is_writable {
msg!("spot market {} not expected to be writeable", market_index);
return Err(ErrorCode::SpotMarketWrongMutability);
}
map.insert(market_index, account_loader);
Ok(SpotMarketMap(map, writable_markets))
}
pub fn empty() -> Self {
SpotMarketMap(BTreeMap::new(), BTreeSet::new())
}
pub fn load_multiple<'c: 'a>(
account_info: Vec<&'c AccountInfo<'a>>,
must_be_writable: bool,
) -> DriftResult<SpotMarketMap<'a>> {
let mut writable_markets = SpotMarketSet::new();
let mut map = BTreeMap::new();
let account_info_iter = account_info.into_iter();
for account_info in account_info_iter {
let spot_market_discriminator: [u8; 8] = SpotMarket::discriminator();
let data = account_info
.try_borrow_data()
.or(Err(ErrorCode::CouldNotLoadSpotMarketData))?;
let expected_data_len = SpotMarket::SIZE;
if data.len() < expected_data_len {
return Err(ErrorCode::CouldNotLoadSpotMarketData);
}
let account_discriminator = array_ref![data, 0, 8];
if account_discriminator != &spot_market_discriminator {
return Err(ErrorCode::CouldNotLoadSpotMarketData);
}
let market_index = u16::from_le_bytes(*array_ref![data, 684, 2]);
let is_writable = account_info.is_writable;
let account_loader: AccountLoader<SpotMarket> =
AccountLoader::try_from(account_info)
.or(Err(ErrorCode::InvalidSpotMarketAccount))?;
if must_be_writable {
writable_markets.insert(market_index);
}
if must_be_writable && !is_writable {
return Err(ErrorCode::SpotMarketWrongMutability);
}
map.insert(market_index, account_loader);
}
Ok(SpotMarketMap(map, writable_markets))
}
}
pub(crate) type SpotMarketSet = BTreeSet<u16>;
pub fn get_writable_spot_market_set(market_index: u16) -> SpotMarketSet {
let mut writable_markets = SpotMarketSet::new();
writable_markets.insert(market_index);
writable_markets
}
pub fn get_writable_spot_market_set_from_many(market_indexes: Vec<u16>) -> SpotMarketSet {
let mut writable_markets = SpotMarketSet::new();
for market_index in market_indexes {
writable_markets.insert(market_index);
}
writable_markets
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/pyth_lazer_oracle.rs
|
use crate::state::traits::Size;
use anchor_lang::prelude::*;
use solana_program::pubkey;
pub const PYTH_LAZER_ORACLE_SEED: &[u8] = b"pyth_lazer";
pub const PYTH_LAZER_STORAGE_ID: Pubkey = pubkey!("3rdJbqfnagQ4yx9HXJViD4zc4xpiSqmFsKpPuSCQVyQL");
impl Size for PythLazerOracle {
const SIZE: usize = 48;
}
#[account(zero_copy(unsafe))]
#[derive(Default, Eq, PartialEq, Debug)]
#[repr(C)]
pub struct PythLazerOracle {
pub price: i64,
pub publish_time: u64,
pub posted_slot: u64,
pub exponent: i32,
pub _padding: [u8; 4],
pub conf: u64,
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/insurance_fund_stake/tests.rs
|
mod transfer_config {
use crate::state::insurance_fund_stake::ProtocolIfSharesTransferConfig;
use solana_program::pubkey::Pubkey;
#[test]
fn validate_signer() {
let mut config = ProtocolIfSharesTransferConfig::default();
let signer = Pubkey::new_unique();
assert!(config.validate_signer(&signer).is_err());
let signer = Pubkey::default();
assert!(config.validate_signer(&signer).is_err());
let signer = Pubkey::new_unique();
config.whitelisted_signers[0] = signer;
assert!(config.validate_signer(&signer).is_ok());
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/paused_operations/tests.rs
|
mod test {
use crate::state::paused_operations::PerpOperation;
#[test]
fn test_is_operation_paused() {
// Test each variant individually
assert!(PerpOperation::is_operation_paused(
0b00000001,
PerpOperation::UpdateFunding
));
assert!(PerpOperation::is_operation_paused(
0b00000010,
PerpOperation::AmmFill
));
assert!(PerpOperation::is_operation_paused(
0b00000100,
PerpOperation::Fill
));
assert!(PerpOperation::is_operation_paused(
0b00001000,
PerpOperation::SettlePnl
));
// Test combinations
let all_operations = PerpOperation::UpdateFunding as u8
| PerpOperation::AmmFill as u8
| PerpOperation::Fill as u8
| PerpOperation::SettlePnl as u8;
assert!(PerpOperation::is_operation_paused(
all_operations,
PerpOperation::UpdateFunding
));
assert!(PerpOperation::is_operation_paused(
all_operations,
PerpOperation::AmmFill
));
assert!(PerpOperation::is_operation_paused(
all_operations,
PerpOperation::Fill
));
assert!(PerpOperation::is_operation_paused(
all_operations,
PerpOperation::SettlePnl
));
let no_operations = 0;
assert!(!PerpOperation::is_operation_paused(
no_operations,
PerpOperation::UpdateFunding
));
assert!(!PerpOperation::is_operation_paused(
no_operations,
PerpOperation::AmmFill
));
assert!(!PerpOperation::is_operation_paused(
no_operations,
PerpOperation::Fill
));
assert!(!PerpOperation::is_operation_paused(
no_operations,
PerpOperation::SettlePnl
));
// Test with multiple operations
let multiple_operations = PerpOperation::AmmFill as u8 | PerpOperation::SettlePnl as u8;
assert!(PerpOperation::is_operation_paused(
multiple_operations,
PerpOperation::AmmFill
));
assert!(PerpOperation::is_operation_paused(
multiple_operations,
PerpOperation::SettlePnl
));
assert!(!PerpOperation::is_operation_paused(
multiple_operations,
PerpOperation::Fill
));
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fulfillment_params/drift.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::math::spot_withdraw::validate_spot_market_vault_amount;
use crate::state::events::OrderActionExplanation;
use crate::state::spot_fulfillment_params::{ExternalSpotFill, SpotFulfillmentParams};
use crate::state::spot_market::SpotMarket;
use crate::{validate, PositionDirection};
use anchor_lang::prelude::InterfaceAccount;
use anchor_spl::token_interface::TokenAccount;
use arrayref::array_ref;
use solana_program::account_info::AccountInfo;
use solana_program::msg;
use std::cell::Ref;
pub struct MatchFulfillmentParams<'a> {
pub base_market_vault: Box<InterfaceAccount<'a, TokenAccount>>,
pub quote_market_vault: Box<InterfaceAccount<'a, TokenAccount>>,
}
impl<'a> MatchFulfillmentParams<'a> {
pub fn new<'b, 'c: 'a>(
account_info_iter: &'b mut std::iter::Peekable<std::slice::Iter<'c, AccountInfo<'a>>>,
base_market: &SpotMarket,
quote_market: &SpotMarket,
) -> DriftResult<MatchFulfillmentParams<'a>> {
let account_info_vec = account_info_iter.collect::<Vec<_>>();
let account_infos = array_ref![account_info_vec, 0, 2];
let [base_market_vault, quote_market_vault] = account_infos;
validate!(
&base_market.vault == base_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
"e_market.vault == quote_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
let base_market_vault: Box<InterfaceAccount<TokenAccount>> =
Box::new(InterfaceAccount::try_from(base_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
let quote_market_vault: Box<InterfaceAccount<TokenAccount>> =
Box::new(InterfaceAccount::try_from(quote_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
Ok(MatchFulfillmentParams {
base_market_vault,
quote_market_vault,
})
}
}
impl<'a> SpotFulfillmentParams for MatchFulfillmentParams<'a> {
fn is_external(&self) -> bool {
false
}
fn get_best_bid_and_ask(&self) -> DriftResult<(Option<u64>, Option<u64>)> {
Err(ErrorCode::InvalidSpotFulfillmentParams)
}
fn fulfill_order(
&mut self,
_taker_direction: PositionDirection,
_taker_price: u64,
_taker_base_asset_amount: u64,
_taker_max_quote_asset_amount: u64,
) -> DriftResult<ExternalSpotFill> {
Err(ErrorCode::InvalidSpotFulfillmentParams)
}
fn get_order_action_explanation(&self) -> DriftResult<OrderActionExplanation> {
Err(ErrorCode::InvalidSpotFulfillmentParams)
}
fn validate_vault_amounts(
&self,
base_market: &Ref<SpotMarket>,
quote_market: &Ref<SpotMarket>,
) -> DriftResult<()> {
validate_spot_market_vault_amount(base_market, self.base_market_vault.amount)?;
validate_spot_market_vault_amount(quote_market, self.quote_market_vault.amount)?;
Ok(())
}
fn validate_markets(
&self,
_base_market: &SpotMarket,
_quote_market: &SpotMarket,
) -> DriftResult<()> {
Ok(())
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fulfillment_params/openbook_v2.rs
|
#![allow(unused)] // unused when target_os is not solana
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode};
use crate::instructions::SpotFulfillmentType;
use crate::math::safe_math::SafeMath;
use crate::math::serum::{
calculate_price_from_serum_limit_price, calculate_serum_limit_price,
calculate_serum_max_coin_qty,
};
use crate::math::spot_withdraw::validate_spot_market_vault_amount;
use crate::signer::get_signer_seeds;
use crate::state::events::OrderActionExplanation;
use crate::state::load_ref::load_ref;
use crate::state::spot_fulfillment_params::{ExternalSpotFill, SpotFulfillmentParams};
use crate::state::spot_market::{SpotBalanceType, SpotFulfillmentConfigStatus, SpotMarket};
use crate::state::state::State;
use crate::state::traits::Size;
use crate::{load, validate};
use anchor_lang::prelude::*;
use anchor_lang::prelude::{Account, Program, System};
use anchor_lang::{account, InstructionData, Key};
use anchor_spl::token::{Token, TokenAccount};
use arrayref::array_ref;
use openbook_v2_light::instruction::PlaceTakeOrder;
use openbook_v2_light::{
BookSide, Market, PlaceOrderType, Side, OPEN_ORDERS_ACCOUNT_DISCRIMINATOR,
};
use solana_program::account_info::AccountInfo;
use solana_program::instruction::{AccountMeta, Instruction};
use solana_program::program::invoke_signed_unchecked;
use solana_program::pubkey::Pubkey;
use std::cell::Ref;
use std::convert::TryFrom;
#[account(zero_copy(unsafe))]
#[derive(Default, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct OpenbookV2FulfillmentConfig {
pub pubkey: Pubkey, //32
pub openbook_v2_program_id: Pubkey, // 64
pub openbook_v2_market: Pubkey, // 96
pub openbook_v2_market_authority: Pubkey, // 128
pub openbook_v2_event_heap: Pubkey, // 160
pub openbook_v2_bids: Pubkey, // 192
pub openbook_v2_asks: Pubkey, // 224
pub openbook_v2_base_vault: Pubkey, // 256
pub openbook_v2_quote_vault: Pubkey, // 288
pub market_index: u16, // 290
pub fulfillment_type: SpotFulfillmentType, // 291
pub status: SpotFulfillmentConfigStatus, // 292
pub padding: [u8; 4], // 296
}
impl Size for OpenbookV2FulfillmentConfig {
const SIZE: usize = 304;
}
pub struct OpenbookV2Context<'a, 'b> {
pub openbook_v2_program: &'a AccountInfo<'b>,
pub openbook_v2_market: &'a AccountInfo<'b>,
}
impl<'a, 'b> OpenbookV2Context<'a, 'b> {
pub fn load_openbook_v2_market(&self) -> DriftResult<Market> {
let market =
load_ref(self.openbook_v2_market).map_err(|_| ErrorCode::FailedOpenbookV2CPI)?;
Ok(*market)
}
pub fn to_openbook_v2_fulfillment_config(
&self,
openbook_v2_fulfillment_config_key: &Pubkey,
market_index: u16,
) -> DriftResult<OpenbookV2FulfillmentConfig> {
let market = self
.load_openbook_v2_market()
.map_err(|_| ErrorCode::FailedOpenbookV2CPI)?;
Ok(OpenbookV2FulfillmentConfig {
pubkey: *openbook_v2_fulfillment_config_key,
openbook_v2_program_id: *self.openbook_v2_program.key,
openbook_v2_market: *self.openbook_v2_market.key,
openbook_v2_market_authority: market.market_authority,
openbook_v2_event_heap: market.event_heap,
openbook_v2_bids: market.bids,
openbook_v2_asks: market.asks,
openbook_v2_base_vault: market.market_base_vault,
openbook_v2_quote_vault: market.market_quote_vault,
market_index,
fulfillment_type: SpotFulfillmentType::OpenbookV2,
status: SpotFulfillmentConfigStatus::Enabled,
padding: [0; 4],
})
}
}
pub struct OpenbookV2FulfillmentParams<'a, 'b> {
pub drift_signer: &'a AccountInfo<'b>, // same as penalty payer
pub openbook_v2_context: OpenbookV2Context<'a, 'b>,
pub openbook_v2_market_authority: &'a AccountInfo<'b>,
pub openbook_v2_event_heap: &'a AccountInfo<'b>,
pub openbook_v2_bids: &'a AccountInfo<'b>,
pub openbook_v2_asks: &'a AccountInfo<'b>,
pub openbook_v2_base_vault: &'a AccountInfo<'b>,
pub openbook_v2_quote_vault: &'a AccountInfo<'b>,
pub base_market_vault: Box<Account<'b, TokenAccount>>,
pub quote_market_vault: Box<Account<'b, TokenAccount>>,
pub token_program: Program<'b, Token>,
pub system_program: Program<'b, System>,
pub signer_nonce: u8,
pub now: i64,
pub remaining_ooa_accounts: Vec<UncheckedAccount<'b>>,
}
impl<'a, 'b> OpenbookV2FulfillmentParams<'a, 'b> {
#[allow(clippy::type_complexity)]
pub fn new<'c: 'b>(
account_info_iter: &'a mut std::iter::Peekable<std::slice::Iter<'c, AccountInfo<'b>>>,
state: &State,
base_market: &SpotMarket,
quote_market: &SpotMarket,
now: i64,
) -> DriftResult<Self> {
let account_info_vec = account_info_iter.collect::<Vec<_>>();
let mut remaining_ooa_accounts = account_info_vec
.iter()
.skip(14)
.filter(|acc| {
acc.data
.borrow()
.starts_with(&OPEN_ORDERS_ACCOUNT_DISCRIMINATOR)
})
.map(|acc| UncheckedAccount::try_from(*acc))
.collect::<Vec<_>>();
remaining_ooa_accounts.truncate(3);
let account_infos = array_ref![account_info_vec, 0, 14];
let [openbook_v2_fulfillment_config, drift_signer, openbook_v2_program, openbook_v2_market, openbook_v2_market_authority, openbook_v2_event_heap, openbook_v2_bids, openbook_v2_asks, openbook_v2_base_vault, openbook_v2_quote_vault, base_market_vault, quote_market_vault, token_program, system_program] =
account_infos;
let openbook_v2_fulfillment_config_loader: AccountLoader<OpenbookV2FulfillmentConfig> =
AccountLoader::try_from(openbook_v2_fulfillment_config).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?;
let openbook_v2_fulfillment_config = load!(openbook_v2_fulfillment_config_loader)?;
validate!(
openbook_v2_fulfillment_config.status == SpotFulfillmentConfigStatus::Enabled,
ErrorCode::SpotFulfillmentConfigDisabled
)?;
validate!(
&state.signer == drift_signer.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
openbook_v2_fulfillment_config.market_index == base_market.market_index,
ErrorCode::InvalidFulfillmentConfig,
"config market index {} does not equal base asset index {}",
openbook_v2_fulfillment_config.market_index,
base_market.market_index
)?;
validate!(
&base_market.vault == base_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
"e_market.vault == quote_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_program_id == openbook_v2_program.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_market_authority
== openbook_v2_market_authority.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_event_heap == openbook_v2_event_heap.key,
ErrorCode::InvalidFulfillmentConfig,
"Openbook V2 eventheap key does not match"
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_bids == openbook_v2_bids.key,
ErrorCode::InvalidFulfillmentConfig,
"Openbook V2 bids key does not match"
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_asks == openbook_v2_asks.key,
ErrorCode::InvalidFulfillmentConfig,
"Openbook V2 asks key does not match"
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_base_vault == openbook_v2_base_vault.key,
ErrorCode::InvalidFulfillmentConfig,
"OpenbookV2 quote vault key does not match"
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_quote_vault == openbook_v2_quote_vault.key,
ErrorCode::InvalidFulfillmentConfig,
"OpenbookV2 quote vault key does not match"
)?;
validate!(
&openbook_v2_fulfillment_config.openbook_v2_market == openbook_v2_market.key,
ErrorCode::InvalidFulfillmentConfig
)?;
let base_market_vault: Box<Account<TokenAccount>> =
Box::new(Account::try_from(base_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
let quote_market_vault: Box<Account<TokenAccount>> =
Box::new(Account::try_from(quote_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
let token_program: Program<Token> = Program::try_from(*token_program).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?;
let system_program: Program<System> = Program::try_from(*system_program).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?;
Ok(OpenbookV2FulfillmentParams {
drift_signer,
openbook_v2_context: OpenbookV2Context {
openbook_v2_program,
openbook_v2_market,
},
openbook_v2_market_authority,
openbook_v2_event_heap,
openbook_v2_bids,
openbook_v2_asks,
openbook_v2_base_vault,
openbook_v2_quote_vault,
base_market_vault,
quote_market_vault,
token_program,
system_program,
signer_nonce: state.signer_nonce,
now,
remaining_ooa_accounts,
})
}
}
impl<'a, 'b> OpenbookV2FulfillmentParams<'a, 'b> {
pub fn invoke_new_order(&self, data: Vec<u8>) -> DriftResult {
let mut accounts = vec![
AccountMeta::new(*self.drift_signer.key, true),
AccountMeta::new(*self.drift_signer.key, true),
AccountMeta::new(*self.openbook_v2_context.openbook_v2_market.key, false),
AccountMeta::new_readonly(*self.openbook_v2_market_authority.key, false),
AccountMeta::new(*self.openbook_v2_bids.key, false),
AccountMeta::new(*self.openbook_v2_asks.key, false),
AccountMeta::new(*self.openbook_v2_base_vault.key, false),
AccountMeta::new(*self.openbook_v2_quote_vault.key, false),
AccountMeta::new(*self.openbook_v2_event_heap.key, false),
AccountMeta::new(self.base_market_vault.key(), false),
AccountMeta::new(self.quote_market_vault.key(), false),
AccountMeta::new_readonly(*self.openbook_v2_context.openbook_v2_program.key, false),
AccountMeta::new_readonly(*self.openbook_v2_context.openbook_v2_program.key, false),
AccountMeta::new_readonly(*self.token_program.key, false),
AccountMeta::new_readonly(*self.system_program.key, false),
AccountMeta::new_readonly(*self.openbook_v2_context.openbook_v2_program.key, false),
];
let mut account_infos = vec![
self.openbook_v2_context.openbook_v2_program.clone(),
self.drift_signer.clone(),
self.drift_signer.clone(),
self.openbook_v2_context.openbook_v2_market.clone(),
self.openbook_v2_market_authority.clone(),
self.openbook_v2_bids.clone(),
self.openbook_v2_asks.clone(),
self.openbook_v2_base_vault.clone(),
self.openbook_v2_quote_vault.clone(),
self.openbook_v2_event_heap.clone(),
self.base_market_vault.to_account_info(),
self.quote_market_vault.to_account_info(),
self.openbook_v2_context.openbook_v2_program.clone(),
self.openbook_v2_context.openbook_v2_program.clone(),
self.token_program.to_account_info(),
self.system_program.to_account_info(),
self.openbook_v2_context.openbook_v2_program.clone(),
];
for unchecked_account in self.remaining_ooa_accounts.iter() {
accounts.push(AccountMeta::new(*unchecked_account.key, false));
account_infos.push(unchecked_account.to_account_info());
}
let new_place_take_order_instruction = Instruction {
program_id: *self.openbook_v2_context.openbook_v2_program.key,
accounts,
data,
};
let signer_seeds = get_signer_seeds(&self.signer_nonce);
let signers_seeds = &[&signer_seeds[..]];
invoke_signed_unchecked(
&new_place_take_order_instruction,
&account_infos,
signers_seeds,
)
.map_err(|e| {
msg!("{:?}", e);
ErrorCode::FailedOpenbookV2CPI
})?;
Ok(())
}
}
impl<'a, 'b> SpotFulfillmentParams for OpenbookV2FulfillmentParams<'a, 'b> {
fn is_external(&self) -> bool {
true
}
fn fulfill_order(
&mut self,
taker_direction: PositionDirection,
taker_price: u64,
taker_base_asset_amount: u64,
taker_max_quote_asset_amount: u64,
) -> DriftResult<ExternalSpotFill> {
// load openbook v2 market
let market = self.openbook_v2_context.load_openbook_v2_market()?;
// coin - base
// pc - quote
let serum_max_coin_qty =
calculate_serum_max_coin_qty(taker_base_asset_amount, market.base_lot_size as u64)?;
let price_lots = calculate_serum_limit_price(
taker_price,
market.quote_lot_size as u64,
market.base_decimals as u32,
market.base_lot_size as u64,
taker_direction,
)?;
let max_quote_lots_including_fees = (market.quote_lot_size as u64)
.safe_mul(price_lots)?
.safe_mul(serum_max_coin_qty)?
.min(taker_max_quote_asset_amount) as i64;
let max_base_lots = taker_base_asset_amount as i64 / market.base_lot_size;
// let max_quote_lots_including_fees = if taker_max_quote_asset_amount == u64::MAX { (price_lots as i64 * max_base_lots)/market.quote_lot_size } else {taker_max_quote_asset_amount as i64/market.quote_lot_size};
let openbook_v2_order_side = match taker_direction {
PositionDirection::Long => Side::Bid,
PositionDirection::Short => Side::Ask,
};
// the openbook v2 will take care of what is better if the price_lots or max_base or max_quote
let args = PlaceTakeOrder {
side: openbook_v2_order_side,
price_lots: price_lots as i64, // i64::MAX, // 8
// price_lots: i64::MAX,
max_base_lots, // 8
max_quote_lots_including_fees, // 8
order_type: PlaceOrderType::Market, // 1
limit: 20, // why 50?
// total - 27
};
let data = args.data();
let base_before = self.base_market_vault.amount;
let quote_before = self.quote_market_vault.amount;
self.invoke_new_order(data)?;
self.base_market_vault.reload().map_err(|_e| {
msg!("Failed to reload base_market_vault");
ErrorCode::FailedOpenbookV2CPI
})?;
self.quote_market_vault.reload().map_err(|_e| {
msg!("Failed to reload quote_market_vault");
ErrorCode::FailedOpenbookV2CPI
})?;
let base_after = self.base_market_vault.amount;
let quote_after = self.quote_market_vault.amount;
let (base_update_direction, base_asset_amount_filled) = if base_after > base_before {
(SpotBalanceType::Deposit, base_after.safe_sub(base_before)?)
} else {
(SpotBalanceType::Borrow, base_before.safe_sub(base_after)?)
};
if base_asset_amount_filled == 0 {
msg!("No base filled on openbook v2");
return Ok(ExternalSpotFill::empty());
}
let (quote_update_direction, quote_asset_amount_filled) =
if base_update_direction == SpotBalanceType::Borrow {
let quote_asset_amount_delta = quote_after.safe_sub(quote_before)?;
(SpotBalanceType::Deposit, quote_asset_amount_delta)
} else {
let quote_asset_amount_delta = quote_before.safe_sub(quote_after)?;
(SpotBalanceType::Borrow, quote_asset_amount_delta)
};
Ok(ExternalSpotFill {
base_asset_amount_filled,
quote_asset_amount_filled,
base_update_direction,
quote_update_direction,
fee: 0,
unsettled_referrer_rebate: 0,
settled_referrer_rebate: 0,
})
}
fn get_best_bid_and_ask(&self) -> DriftResult<(Option<u64>, Option<u64>)> {
let market = self.openbook_v2_context.load_openbook_v2_market()?;
let bid_data = self.openbook_v2_bids.data.borrow();
let bid = bytemuck::try_from_bytes::<BookSide>(&bid_data[8..]).map_err(|_| {
msg!("Failed to parse OpenbookV2 bids");
ErrorCode::FailedOpenbookV2CPI
})?;
let ask_data = self.openbook_v2_asks.data.borrow();
let ask = bytemuck::try_from_bytes::<BookSide>(&ask_data[8..]).map_err(|_| {
msg!("Failed to parse OpenbookV2 asks");
ErrorCode::FailedOpenbookV2CPI
})?;
let bid_price: Option<u64> = match bid.find_max() {
Some(bid) => {
let bid_price = calculate_price_from_serum_limit_price(
bid,
market.quote_lot_size as u64,
market.base_decimals as u32,
market.base_lot_size as u64,
)?;
Some(bid_price)
}
None => None,
};
let ask_price: Option<u64> = match ask.find_min() {
Some(ask) => {
let ask_price = calculate_price_from_serum_limit_price(
ask,
market.quote_lot_size as u64,
market.base_decimals as u32,
market.base_lot_size as u64,
)?;
Some(ask_price)
}
None => None,
};
Ok((bid_price, ask_price))
}
fn get_order_action_explanation(&self) -> DriftResult<OrderActionExplanation> {
Ok(OrderActionExplanation::OrderFilledWithOpenbookV2)
}
fn validate_vault_amounts(
&self,
base_market: &Ref<SpotMarket>,
quote_market: &Ref<SpotMarket>,
) -> DriftResult {
validate_spot_market_vault_amount(base_market, self.base_market_vault.amount)?;
validate_spot_market_vault_amount(quote_market, self.quote_market_vault.amount)?;
Ok(())
}
fn validate_markets(
&self,
base_market: &SpotMarket,
quote_market: &SpotMarket,
) -> DriftResult<()> {
validate!(
self.base_market_vault.mint == base_market.mint,
ErrorCode::DefaultError,
"base mints dont match"
)?;
validate!(
self.quote_market_vault.mint == quote_market.mint,
ErrorCode::DefaultError,
"base mints dont match"
)?;
Ok(())
}
}
#[cfg(test)]
mod openbook_v2_test {
use crate::math::serum::calculate_price_from_serum_limit_price;
#[test]
fn test_calculate_price_from_serum_limit_price() {
// price +- 6.6.2024 170.0
let openbook_v2_price = 170_000;
// values from https://solscan.io/account/CFSMrBssNG8Ud1edW59jNLnq2cwrQ9uY5cM3wXmqRJj3#anchorData
let price = calculate_price_from_serum_limit_price(
openbook_v2_price,
1, // quote_lot_size
9, // base decimals
1000000, // base_lot_size
)
.unwrap();
assert_eq!(170_000_000, price);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fulfillment_params/serum.rs
|
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode};
use crate::instructions::SpotFulfillmentType;
use crate::math::safe_math::SafeMath;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::math::serum::{
calculate_price_from_serum_limit_price, calculate_serum_limit_price,
calculate_serum_max_coin_qty, calculate_serum_max_native_pc_quantity,
};
use crate::math::spot_withdraw::validate_spot_market_vault_amount;
use crate::signer::get_signer_seeds;
use crate::state::events::OrderActionExplanation;
use crate::state::spot_fulfillment_params::{ExternalSpotFill, SpotFulfillmentParams};
use crate::state::spot_market::{SpotBalanceType, SpotFulfillmentConfigStatus, SpotMarket};
use crate::state::state::State;
use crate::state::traits::Size;
use crate::{load, validate};
use anchor_lang::accounts::account_loader::AccountLoader;
use anchor_lang::prelude::*;
use anchor_lang::{Key, ToAccountInfo};
use anchor_spl::token::{Token, TokenAccount};
use arrayref::array_ref;
use bytemuck::{cast_slice, from_bytes};
use serum_dex::critbit::SlabView;
use serum_dex::instruction::{NewOrderInstructionV3, SelfTradeBehavior};
use serum_dex::matching::{OrderBookState, Side};
use serum_dex::state::Market;
use solana_program::account_info::AccountInfo;
use solana_program::instruction::Instruction;
use solana_program::msg;
use std::cell::Ref;
use std::convert::TryFrom;
use std::num::NonZeroU64;
use std::ops::{Deref, DerefMut};
#[account(zero_copy(unsafe))]
#[derive(Default, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct SerumV3FulfillmentConfig {
pub pubkey: Pubkey,
pub serum_program_id: Pubkey,
pub serum_market: Pubkey,
pub serum_request_queue: Pubkey,
pub serum_event_queue: Pubkey,
pub serum_bids: Pubkey,
pub serum_asks: Pubkey,
pub serum_base_vault: Pubkey,
pub serum_quote_vault: Pubkey,
pub serum_open_orders: Pubkey,
pub serum_signer_nonce: u64,
pub market_index: u16,
pub fulfillment_type: SpotFulfillmentType,
pub status: SpotFulfillmentConfigStatus,
pub padding: [u8; 4],
}
impl Size for SerumV3FulfillmentConfig {
const SIZE: usize = 344;
}
pub struct SerumContext<'a, 'b> {
pub serum_program: &'a AccountInfo<'b>,
pub serum_market: &'a AccountInfo<'b>,
pub serum_open_orders: &'a AccountInfo<'b>,
}
impl<'a, 'b> SerumContext<'a, 'b> {
pub fn load_serum_market(&self) -> DriftResult<Market> {
Market::load(self.serum_market, self.serum_program.key, false).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidSerumMarket
})
}
pub fn load_open_orders(&self) -> DriftResult<Ref<'a, serum_dex::state::OpenOrders>> {
validate!(
self.serum_open_orders.data_len() >= 12,
ErrorCode::InvalidSerumOpenOrders
)?;
let unpadded_data: Ref<[u8]> = Ref::map(
self.serum_open_orders
.try_borrow_data()
.map_err(|_e| ErrorCode::InvalidSerumOpenOrders)?,
|data| {
let data_len = data.len() - 12;
let (_, rest) = data.split_at(5);
let (mid, _) = rest.split_at(data_len);
mid
},
);
Ok(Ref::map(unpadded_data, from_bytes))
}
pub fn invoke_init_open_orders(
&self,
authority: &'a AccountInfo<'b>,
rent: &Sysvar<'b, Rent>,
nonce: u8,
) -> DriftResult {
let signer_seeds = get_signer_seeds(&nonce);
let signers_seeds = &[&signer_seeds[..]];
let data = serum_dex::instruction::MarketInstruction::InitOpenOrders.pack();
let instruction = Instruction {
program_id: *self.serum_program.key,
data,
accounts: vec![
AccountMeta::new(*self.serum_open_orders.key, false),
AccountMeta::new_readonly(*authority.key, true),
AccountMeta::new_readonly(*self.serum_market.key, false),
AccountMeta::new_readonly(*rent.to_account_info().key, false),
],
};
let account_infos = [
self.serum_program.clone(),
self.serum_open_orders.clone(),
authority.clone(),
self.serum_market.clone(),
rent.to_account_info(),
];
solana_program::program::invoke_signed(&instruction, &account_infos, signers_seeds).map_err(
|e| {
msg!("{:?}", e);
ErrorCode::FailedSerumCPI
},
)
}
pub fn to_serum_v3_fulfillment_config(
&self,
serum_fulfillment_config_key: &Pubkey,
market_index: u16,
) -> DriftResult<SerumV3FulfillmentConfig> {
let market_state = self.load_serum_market()?;
let market_state_event_queue = market_state.event_q;
let serum_event_queue =
Pubkey::try_from_slice(cast_slice::<u64, u8>(&market_state_event_queue))
.map_err(|_| ErrorCode::InvalidSerumMarket)?;
let market_state_request_queue = market_state.req_q;
let serum_request_queue =
Pubkey::try_from_slice(cast_slice::<u64, u8>(&market_state_request_queue))
.map_err(|_| ErrorCode::InvalidSerumMarket)?;
let market_state_bids = market_state.bids;
let serum_bids = Pubkey::try_from_slice(cast_slice::<u64, u8>(&market_state_bids))
.map_err(|_| ErrorCode::InvalidSerumMarket)?;
let market_state_asks = market_state.asks;
let serum_asks = Pubkey::try_from_slice(cast_slice::<u64, u8>(&market_state_asks))
.map_err(|_| ErrorCode::InvalidSerumMarket)?;
let market_state_coin_vault = market_state.coin_vault;
let serum_base_vault =
Pubkey::try_from_slice(cast_slice::<u64, u8>(&market_state_coin_vault))
.map_err(|_| ErrorCode::InvalidSerumMarket)?;
let market_state_pc_vault = market_state.pc_vault;
let serum_quote_vault =
Pubkey::try_from_slice(cast_slice::<u64, u8>(&market_state_pc_vault))
.map_err(|_| ErrorCode::InvalidSerumMarket)?;
let serum_signer_nonce = market_state.vault_signer_nonce;
Ok(SerumV3FulfillmentConfig {
pubkey: *serum_fulfillment_config_key,
serum_program_id: *self.serum_program.key,
serum_market: *self.serum_market.key,
serum_request_queue,
serum_event_queue,
serum_bids,
serum_asks,
serum_base_vault,
serum_quote_vault,
serum_open_orders: *self.serum_open_orders.key,
serum_signer_nonce,
market_index,
fulfillment_type: SpotFulfillmentType::SerumV3,
status: SpotFulfillmentConfigStatus::Enabled,
padding: [0; 4],
})
}
}
pub struct SerumFulfillmentParams<'a, 'b> {
pub drift_signer: &'a AccountInfo<'b>,
pub serum_context: SerumContext<'a, 'b>,
pub serum_request_queue: &'a AccountInfo<'b>,
pub serum_event_queue: &'a AccountInfo<'b>,
pub serum_bids: &'a AccountInfo<'b>,
pub serum_asks: &'a AccountInfo<'b>,
pub serum_base_vault: &'a AccountInfo<'b>,
pub serum_quote_vault: &'a AccountInfo<'b>,
pub token_program: Program<'b, Token>,
pub base_market_vault: Box<Account<'b, TokenAccount>>,
pub quote_market_vault: Box<Account<'b, TokenAccount>>,
pub srm_vault: &'a AccountInfo<'b>,
pub serum_signer: &'a AccountInfo<'b>,
pub signer_nonce: u8,
pub base_mint_decimals: u32,
pub now: i64,
}
impl<'a, 'b> Deref for SerumFulfillmentParams<'a, 'b> {
type Target = SerumContext<'a, 'b>;
fn deref(&self) -> &Self::Target {
&self.serum_context
}
}
/// Constructor for SerumFulfillmentParams
impl<'a, 'b> SerumFulfillmentParams<'a, 'b> {
#[allow(clippy::type_complexity)]
pub fn new<'c: 'b>(
account_info_iter: &'a mut std::iter::Peekable<std::slice::Iter<'c, AccountInfo<'b>>>,
state: &State,
base_market: &SpotMarket,
quote_market: &SpotMarket,
now: i64,
) -> DriftResult<Self> {
let account_info_vec = account_info_iter.collect::<Vec<_>>();
let account_infos = array_ref![account_info_vec, 0, 16];
let [serum_fulfillment_config, serum_program, serum_market, serum_request_queue, serum_event_queue, serum_bids, serum_asks, serum_base_vault, serum_quote_vault, serum_open_orders, serum_signer, drift_signer, token_program, base_market_vault, quote_market_vault, srm_vault] =
account_infos;
let serum_fulfillment_config_loader: AccountLoader<SerumV3FulfillmentConfig> =
AccountLoader::try_from(serum_fulfillment_config).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?;
let serum_fulfillment_config = load!(serum_fulfillment_config_loader)?;
validate!(
serum_fulfillment_config.status == SpotFulfillmentConfigStatus::Enabled,
ErrorCode::SpotFulfillmentConfigDisabled
)?;
validate!(
&state.signer == drift_signer.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
serum_fulfillment_config.market_index == base_market.market_index,
ErrorCode::InvalidFulfillmentConfig,
"config market index {} does not equal base asset index {}",
serum_fulfillment_config.market_index,
base_market.market_index
)?;
validate!(
&base_market.vault == base_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
"e_market.vault == quote_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
&serum_fulfillment_config.serum_program_id == serum_program.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
&serum_fulfillment_config.serum_market == serum_market.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
&serum_fulfillment_config.serum_open_orders == serum_open_orders.key,
ErrorCode::InvalidFulfillmentConfig
)?;
let base_market_vault: Box<Account<TokenAccount>> =
Box::new(Account::try_from(base_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
let quote_market_vault: Box<Account<TokenAccount>> =
Box::new(Account::try_from(quote_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
let token_program: Program<Token> = Program::try_from(*token_program).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?;
validate!(
&state.srm_vault == srm_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
Ok(SerumFulfillmentParams {
drift_signer,
serum_context: SerumContext {
serum_program,
serum_market,
serum_open_orders,
},
serum_request_queue,
serum_event_queue,
serum_bids,
serum_asks,
serum_base_vault,
serum_quote_vault,
token_program,
base_market_vault,
quote_market_vault,
serum_signer,
srm_vault,
signer_nonce: state.signer_nonce,
base_mint_decimals: base_market.decimals,
now,
})
}
}
/// CPI Wrappers into Serum/Openbook
impl<'a, 'b> SerumFulfillmentParams<'a, 'b> {
pub fn invoke_new_order(
&self,
taker_direction: PositionDirection,
order: NewOrderInstructionV3,
) -> DriftResult {
let drift_vault = match taker_direction {
PositionDirection::Long => self.quote_market_vault.to_account_info(),
PositionDirection::Short => self.base_market_vault.to_account_info(),
};
let data = serum_dex::instruction::MarketInstruction::NewOrderV3(order).pack();
let mut instruction = Instruction {
program_id: *self.serum_program.key,
data,
accounts: vec![
AccountMeta::new(*self.serum_market.key, false),
AccountMeta::new(*self.serum_open_orders.key, false),
AccountMeta::new(*self.serum_request_queue.key, false),
AccountMeta::new(*self.serum_event_queue.key, false),
AccountMeta::new(*self.serum_bids.key, false),
AccountMeta::new(*self.serum_asks.key, false),
AccountMeta::new(*drift_vault.key, false),
AccountMeta::new_readonly(*self.drift_signer.key, true),
AccountMeta::new(*self.serum_base_vault.key, false),
AccountMeta::new(*self.serum_quote_vault.key, false),
AccountMeta::new_readonly(*self.token_program.key, false),
AccountMeta::new_readonly(*self.drift_signer.key, false),
],
};
if self.srm_vault.key != &Pubkey::default() {
instruction
.accounts
.push(AccountMeta::new_readonly(*self.srm_vault.key, false));
let account_infos = [
self.serum_program.clone(), // Have to add account of the program id
self.serum_market.clone(),
self.serum_open_orders.clone(),
self.serum_request_queue.clone(),
self.serum_event_queue.clone(),
self.serum_bids.clone(),
self.serum_asks.clone(),
drift_vault.clone(),
self.drift_signer.clone(),
self.serum_base_vault.clone(),
self.serum_quote_vault.clone(),
self.token_program.to_account_info(),
self.srm_vault.clone(),
];
let signer_seeds = get_signer_seeds(&self.signer_nonce);
let signers_seeds = &[&signer_seeds[..]];
solana_program::program::invoke_signed_unchecked(
&instruction,
&account_infos,
signers_seeds,
)
.map_err(|e| {
msg!("{:?}", e);
ErrorCode::FailedSerumCPI
})
} else {
let account_infos = [
self.serum_program.clone(), // Have to add account of the program id
self.serum_market.clone(),
self.serum_open_orders.clone(),
self.serum_request_queue.clone(),
self.serum_event_queue.clone(),
self.serum_bids.clone(),
self.serum_asks.clone(),
drift_vault.clone(),
self.drift_signer.clone(),
self.serum_base_vault.clone(),
self.serum_quote_vault.clone(),
self.token_program.to_account_info(),
];
let signer_seeds = get_signer_seeds(&self.signer_nonce);
let signers_seeds = &[&signer_seeds[..]];
solana_program::program::invoke_signed_unchecked(
&instruction,
&account_infos,
signers_seeds,
)
.map_err(|e| {
msg!("{:?}", e);
ErrorCode::FailedSerumCPI
})
}
}
pub fn invoke_settle_funds(&self) -> DriftResult {
let data = serum_dex::instruction::MarketInstruction::SettleFunds.pack();
let instruction = Instruction {
program_id: *self.serum_program.key,
data,
accounts: vec![
AccountMeta::new(*self.serum_market.key, false),
AccountMeta::new(*self.serum_open_orders.key, false),
AccountMeta::new_readonly(*self.drift_signer.key, true),
AccountMeta::new(*self.serum_base_vault.key, false),
AccountMeta::new(*self.serum_quote_vault.key, false),
AccountMeta::new(self.base_market_vault.key(), false),
AccountMeta::new(self.quote_market_vault.key(), false),
AccountMeta::new_readonly(*self.serum_signer.key, false),
AccountMeta::new_readonly(*self.token_program.key, false),
AccountMeta::new(self.quote_market_vault.key(), false),
],
};
let account_infos = [
self.serum_program.clone(),
self.serum_market.clone(),
self.serum_open_orders.clone(),
self.drift_signer.clone(),
self.serum_base_vault.clone(),
self.serum_quote_vault.clone(),
self.base_market_vault.to_account_info(),
self.quote_market_vault.to_account_info(),
self.serum_signer.clone(),
self.token_program.to_account_info(),
];
let signer_seeds = get_signer_seeds(&self.signer_nonce);
let signers_seeds = &[&signer_seeds[..]];
solana_program::program::invoke_signed_unchecked(
&instruction,
&account_infos,
signers_seeds,
)
.map_err(|e| {
msg!("{:?}", e);
ErrorCode::FailedSerumCPI
})
}
}
impl<'a, 'b> SpotFulfillmentParams for SerumFulfillmentParams<'a, 'b> {
fn is_external(&self) -> bool {
true
}
fn get_best_bid_and_ask(&self) -> DriftResult<(Option<u64>, Option<u64>)> {
let mut market = self.load_serum_market()?;
let mut bids = market.load_bids_mut(self.serum_bids).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidSerumBids
})?;
let mut asks = market.load_asks_mut(self.serum_asks).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidSerumAsks
})?;
let order_book_state = OrderBookState {
bids: bids.deref_mut(),
asks: asks.deref_mut(),
market_state: market.deref_mut(),
};
let best_bid = match order_book_state.bids.find_max() {
Some(best_bid_h) => {
let best_bid_ref = order_book_state
.bids
.get(best_bid_h)
.safe_unwrap()?
.as_leaf()
.safe_unwrap()?;
let price = calculate_price_from_serum_limit_price(
best_bid_ref.price().get(),
order_book_state.market_state.pc_lot_size,
self.base_mint_decimals,
order_book_state.market_state.coin_lot_size,
)?;
Some(price)
}
None => None,
};
let best_ask = match order_book_state.asks.find_min() {
Some(best_ask_h) => {
let best_ask_ref = order_book_state
.asks
.get(best_ask_h)
.safe_unwrap()?
.as_leaf()
.safe_unwrap()?;
let price = calculate_price_from_serum_limit_price(
best_ask_ref.price().get(),
order_book_state.market_state.pc_lot_size,
self.base_mint_decimals,
order_book_state.market_state.coin_lot_size,
)?;
Some(price)
}
None => None,
};
Ok((best_bid, best_ask))
}
fn fulfill_order(
&mut self,
taker_direction: PositionDirection,
taker_price: u64,
taker_base_asset_amount: u64,
taker_max_quote_asset_amount: u64,
) -> DriftResult<ExternalSpotFill> {
let market_state_before = self.load_serum_market()?;
let serum_order_side = match taker_direction {
PositionDirection::Long => Side::Bid,
PositionDirection::Short => Side::Ask,
};
let serum_max_coin_qty = calculate_serum_max_coin_qty(
taker_base_asset_amount,
market_state_before.coin_lot_size,
)?;
let serum_limit_price = calculate_serum_limit_price(
taker_price,
market_state_before.pc_lot_size,
self.base_mint_decimals,
market_state_before.coin_lot_size,
taker_direction,
)?;
let serum_max_native_pc_qty = calculate_serum_max_native_pc_quantity(
serum_limit_price,
serum_max_coin_qty,
market_state_before.pc_lot_size,
)?
.min(taker_max_quote_asset_amount);
if serum_max_coin_qty == 0 || serum_max_native_pc_qty == 0 {
return Ok(ExternalSpotFill::empty());
}
let serum_order = NewOrderInstructionV3 {
side: serum_order_side,
limit_price: NonZeroU64::new(serum_limit_price).safe_unwrap()?,
max_coin_qty: NonZeroU64::new(serum_max_coin_qty).safe_unwrap()?, // max base to deposit into serum
max_native_pc_qty_including_fees: NonZeroU64::new(serum_max_native_pc_qty)
.safe_unwrap()?, // max quote to deposit into serum
self_trade_behavior: SelfTradeBehavior::AbortTransaction,
order_type: serum_dex::matching::OrderType::ImmediateOrCancel,
client_order_id: 0,
limit: 10,
max_ts: self.now,
};
let _market_fees_accrued_before = market_state_before.pc_fees_accrued;
let base_before = self.base_market_vault.amount;
let quote_before = self.quote_market_vault.amount;
let market_rebates_accrued_before = market_state_before.referrer_rebates_accrued;
drop(market_state_before);
self.invoke_new_order(taker_direction, serum_order)?;
let market_state_after = self.load_serum_market()?;
let _market_fees_accrued_after = market_state_after.pc_fees_accrued;
let market_rebates_accrued_after = market_state_after.referrer_rebates_accrued;
drop(market_state_after);
let open_orders_before = self.load_open_orders()?;
let unsettled_referrer_rebate_before = open_orders_before.referrer_rebates_accrued;
drop(open_orders_before);
self.invoke_settle_funds()?;
self.base_market_vault.reload().map_err(|_e| {
msg!("Failed to reload base_market_vault");
ErrorCode::FailedSerumCPI
})?;
self.quote_market_vault.reload().map_err(|_e| {
msg!("Failed to reload quote_market_vault");
ErrorCode::FailedSerumCPI
})?;
let base_after = self.base_market_vault.amount;
let quote_after = self.quote_market_vault.amount;
let open_orders_after = self.load_open_orders()?;
let unsettled_referrer_rebate_after = open_orders_after.referrer_rebates_accrued;
drop(open_orders_after);
let settled_referred_rebate =
unsettled_referrer_rebate_before.safe_sub(unsettled_referrer_rebate_after)?;
let (base_update_direction, base_asset_amount_filled) = if base_after > base_before {
(SpotBalanceType::Deposit, base_after.safe_sub(base_before)?)
} else {
(SpotBalanceType::Borrow, base_before.safe_sub(base_after)?)
};
if base_asset_amount_filled == 0 {
msg!("No base filled on serum");
return Ok(ExternalSpotFill::empty());
}
let serum_referrer_rebate =
market_rebates_accrued_after.safe_sub(market_rebates_accrued_before)?;
// rebate is half of taker fee
let serum_fee = serum_referrer_rebate;
let (quote_update_direction, quote_asset_amount_filled) =
if base_update_direction == SpotBalanceType::Borrow {
let quote_asset_amount_delta = quote_after
.safe_sub(quote_before)?
.safe_sub(settled_referred_rebate)?;
(
SpotBalanceType::Deposit,
quote_asset_amount_delta
.safe_add(serum_fee)?
.safe_add(serum_referrer_rebate)?,
)
} else {
let quote_asset_amount_delta = quote_before
.safe_add(settled_referred_rebate)?
.safe_sub(quote_after)?;
(
SpotBalanceType::Borrow,
quote_asset_amount_delta
.safe_sub(serum_fee)?
.safe_sub(serum_referrer_rebate)?,
)
};
Ok(ExternalSpotFill {
base_asset_amount_filled,
quote_asset_amount_filled,
base_update_direction,
quote_update_direction,
fee: serum_fee,
unsettled_referrer_rebate: serum_referrer_rebate,
settled_referrer_rebate: settled_referred_rebate,
})
}
fn get_order_action_explanation(&self) -> DriftResult<OrderActionExplanation> {
Ok(OrderActionExplanation::OrderFillWithSerum)
}
fn validate_vault_amounts(
&self,
base_market: &Ref<SpotMarket>,
quote_market: &Ref<SpotMarket>,
) -> DriftResult {
validate_spot_market_vault_amount(base_market, self.base_market_vault.amount)?;
validate_spot_market_vault_amount(quote_market, self.quote_market_vault.amount)?;
Ok(())
}
fn validate_markets(
&self,
base_market: &SpotMarket,
quote_market: &SpotMarket,
) -> DriftResult<()> {
validate!(
self.base_market_vault.mint == base_market.mint,
ErrorCode::DefaultError,
"base mints dont match"
)?;
validate!(
self.quote_market_vault.mint == quote_market.mint,
ErrorCode::DefaultError,
"base mints dont match"
)?;
Ok(())
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fulfillment_params/mod.rs
|
pub mod drift;
pub mod openbook_v2;
pub mod phoenix;
pub mod serum;
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fulfillment_params/phoenix.rs
|
use anchor_lang::{prelude::*, ToAccountInfo};
use anchor_spl::token::{Token, TokenAccount};
use arrayref::array_ref;
use phoenix::{
program::{
create_new_order_instruction_with_custom_token_accounts, load_with_dispatch, MarketHeader,
},
quantities::{BaseLots, QuoteLots, Ticks, WrapperU64},
state::{OrderPacket, Side},
};
use solana_program::{msg, program::invoke_signed_unchecked};
use std::convert::TryFrom;
use std::{cell::Ref, convert::TryInto, mem::size_of, ops::Deref};
use crate::{
controller::position::PositionDirection,
error::{DriftResult, ErrorCode},
instructions::SpotFulfillmentType,
load,
math::{casting::Cast, safe_math::SafeMath, spot_withdraw::validate_spot_market_vault_amount},
signer::get_signer_seeds,
state::{
events::OrderActionExplanation,
spot_fulfillment_params::{ExternalSpotFill, SpotFulfillmentParams},
spot_market::{SpotBalanceType, SpotFulfillmentConfigStatus, SpotMarket},
state::State,
traits::Size,
},
validate,
};
pub const PHOENIX_MARKET_DISCRIMINANT: u64 = 8167313896524341111;
pub fn taker_price_to_phoenix_price_in_ticks_rounded_down(
taker_price: u64,
tick_size: u64,
header: &MarketHeader,
) -> DriftResult<Ticks> {
taker_price
.safe_mul(header.raw_base_units_per_base_unit as u64)?
.safe_div((header.get_quote_lot_size().as_u64().safe_mul(tick_size))?)
.map(Ticks::new)
}
pub fn taker_price_to_phoenix_price_in_ticks_rounded_up(
taker_price: u64,
tick_size: u64,
header: &MarketHeader,
) -> DriftResult<Ticks> {
taker_price
.safe_mul(header.raw_base_units_per_base_unit as u64)?
.safe_div_ceil((header.get_quote_lot_size().as_u64().safe_mul(tick_size))?)
.map(Ticks::new)
}
pub fn phoenix_price_in_ticks_to_taker_price(
price_in_ticks: u64,
tick_size: u64,
header: &MarketHeader,
) -> DriftResult<u64> {
price_in_ticks
.safe_mul(tick_size)?
.safe_mul(header.get_quote_lot_size().as_u64())?
.safe_div(header.raw_base_units_per_base_unit as u64)
}
pub fn compute_base_lot_size(
taker_base_asset_amount: u64,
taker_max_quote_asset_amount: u64,
taker_price: u64,
header: &MarketHeader,
) -> DriftResult<BaseLots> {
Ok(taker_base_asset_amount
.safe_div(header.get_base_lot_size().as_u64())
.map(BaseLots::new)?
.min(
// Conversion:
// taker_max_quote_asset_amount (QA) * base_atoms_per_raw_base_unit (BA/rBU) / taker_price (QA/rBU) / base_lot_size (BA/BL)
// Yields: num_base_lots (BL)
taker_max_quote_asset_amount
.cast::<u128>()?
.safe_mul(10_u128.pow(header.base_params.decimals))?
.safe_div(
taker_price
.cast::<u128>()?
.safe_mul(header.get_base_lot_size().as_u128())?,
)?
.cast::<u64>()
.map(BaseLots::new)?,
))
}
#[account(zero_copy(unsafe))]
#[derive(Default, PartialEq, Eq, Debug)]
#[repr(C)]
pub struct PhoenixV1FulfillmentConfig {
pub pubkey: Pubkey,
pub phoenix_program_id: Pubkey,
pub phoenix_log_authority: Pubkey,
pub phoenix_market: Pubkey,
pub phoenix_base_vault: Pubkey,
pub phoenix_quote_vault: Pubkey,
pub market_index: u16,
pub fulfillment_type: SpotFulfillmentType,
pub status: SpotFulfillmentConfigStatus,
pub padding: [u8; 4],
}
impl Size for PhoenixV1FulfillmentConfig {
const SIZE: usize = 208;
}
#[derive(Clone)]
pub struct PhoenixMarketContext<'a, 'b> {
pub phoenix_market: &'a AccountInfo<'b>,
pub header: MarketHeader,
}
impl<'a, 'b> PhoenixMarketContext<'a, 'b> {
pub fn new(info: &'a AccountInfo<'b>) -> DriftResult<PhoenixMarketContext<'a, 'b>> {
validate!(
info.owner == &phoenix::id(),
ErrorCode::InvalidPhoenixProgram,
"Market must be owned by the Phoenix program",
)?;
let data = info.data.borrow();
let header = bytemuck::try_from_bytes::<MarketHeader>(&data[..size_of::<MarketHeader>()])
.map_err(|_| {
msg!("Failed to parse Phoenix market header");
ErrorCode::FailedToDeserializePhoenixMarket
})?;
validate!(
header.discriminant == PHOENIX_MARKET_DISCRIMINANT,
ErrorCode::InvalidPhoenixProgram,
"Invalid market discriminant",
)?;
Ok(PhoenixMarketContext {
phoenix_market: info,
header: *header,
})
}
pub fn to_phoenix_v1_fulfillment_config(
&self,
config_key: &Pubkey,
market_index: u16,
) -> PhoenixV1FulfillmentConfig {
PhoenixV1FulfillmentConfig {
pubkey: *config_key,
phoenix_program_id: phoenix::id(),
phoenix_log_authority: phoenix::phoenix_log_authority::id(),
phoenix_market: *self.phoenix_market.key,
phoenix_base_vault: self.header.base_params.vault_key,
phoenix_quote_vault: self.header.quote_params.vault_key,
market_index,
fulfillment_type: SpotFulfillmentType::PhoenixV1,
status: SpotFulfillmentConfigStatus::Enabled,
padding: [0; 4],
}
}
}
impl<'a, 'b> Deref for PhoenixMarketContext<'a, 'b> {
type Target = AccountInfo<'b>;
fn deref(&self) -> &Self::Target {
self.phoenix_market
}
}
#[derive(Clone)]
pub struct PhoenixFulfillmentParams<'a, 'b> {
pub phoenix_program: &'a AccountInfo<'b>,
pub phoenix_log_authority: &'a AccountInfo<'b>,
pub phoenix_market: PhoenixMarketContext<'a, 'b>,
pub drift_signer: &'a AccountInfo<'b>,
pub phoenix_base_vault: &'a AccountInfo<'b>,
pub phoenix_quote_vault: &'a AccountInfo<'b>,
pub base_market_vault: Box<Account<'b, TokenAccount>>,
pub quote_market_vault: Box<Account<'b, TokenAccount>>,
pub token_program: Program<'b, Token>,
pub signer_nonce: u8,
}
/// Constructor for PhoenixFulfillmentParams
impl<'a, 'b> PhoenixFulfillmentParams<'a, 'b> {
#[allow(clippy::type_complexity)]
pub fn new<'c: 'b>(
account_info_iter: &'a mut std::iter::Peekable<std::slice::Iter<'c, AccountInfo<'b>>>,
state: &State,
base_market: &SpotMarket,
quote_market: &SpotMarket,
) -> DriftResult<Self> {
let account_info_vec = account_info_iter.collect::<Vec<_>>();
let account_infos = array_ref![account_info_vec, 0, 10];
let [phoenix_fulfillment_config, phoenix_program, phoenix_log_authority, phoenix_market, drift_signer, phoenix_base_vault, phoenix_quote_vault, base_market_vault, quote_market_vault, token_program] =
account_infos;
let phoenix_fulfillment_config_loader: AccountLoader<PhoenixV1FulfillmentConfig> =
AccountLoader::try_from(phoenix_fulfillment_config).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?;
let phoenix_fulfillment_config = load!(phoenix_fulfillment_config_loader)?;
validate!(
&phoenix_fulfillment_config.phoenix_program_id == phoenix_program.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
phoenix_log_authority.key == &phoenix::phoenix_log_authority::id(),
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
phoenix_fulfillment_config.status == SpotFulfillmentConfigStatus::Enabled,
ErrorCode::SpotFulfillmentConfigDisabled
)?;
validate!(
&state.signer == drift_signer.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
phoenix_fulfillment_config.market_index == base_market.market_index,
ErrorCode::InvalidFulfillmentConfig,
"config market index {} does not equal base asset index {}",
phoenix_fulfillment_config.market_index,
base_market.market_index
)?;
validate!(
&base_market.vault == base_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
validate!(
"e_market.vault == quote_market_vault.key,
ErrorCode::InvalidFulfillmentConfig
)?;
let phoenix_market_context = PhoenixMarketContext::new(phoenix_market)?;
validate!(
&phoenix_fulfillment_config.phoenix_base_vault == phoenix_base_vault.key,
ErrorCode::InvalidFulfillmentConfig,
"Phoenix base vault key does not match market header"
)?;
validate!(
&phoenix_fulfillment_config.phoenix_quote_vault == phoenix_quote_vault.key,
ErrorCode::InvalidFulfillmentConfig,
"Phoenix quote vault key does not match market header"
)?;
validate!(
&phoenix_fulfillment_config.phoenix_market == phoenix_market.key,
ErrorCode::InvalidFulfillmentConfig
)?;
let base_market_vault: Box<Account<TokenAccount>> =
Box::new(Account::try_from(base_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
let quote_market_vault: Box<Account<TokenAccount>> =
Box::new(Account::try_from(quote_market_vault).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?);
let token_program: Program<Token> = Program::try_from(*token_program).map_err(|e| {
msg!("{:?}", e);
ErrorCode::InvalidFulfillmentConfig
})?;
Ok(PhoenixFulfillmentParams {
drift_signer,
phoenix_program,
phoenix_market: phoenix_market_context,
phoenix_log_authority,
phoenix_base_vault,
phoenix_quote_vault,
token_program,
base_market_vault,
quote_market_vault,
signer_nonce: state.signer_nonce,
})
}
}
impl<'a, 'b> PhoenixFulfillmentParams<'a, 'b> {
pub fn to_account_infos(&self) -> [AccountInfo<'b>; 9] {
[
self.phoenix_program.clone(),
self.phoenix_log_authority.clone(),
self.phoenix_market.to_account_info(),
self.drift_signer.clone(),
self.base_market_vault.to_account_info(),
self.quote_market_vault.to_account_info(),
self.phoenix_base_vault.to_account_info(),
self.phoenix_quote_vault.to_account_info(),
self.token_program.to_account_info(),
]
}
}
impl<'a, 'b> PhoenixFulfillmentParams<'a, 'b> {
pub fn invoke_new_order(&self, order_packet: OrderPacket) -> DriftResult {
let base_mint = self.phoenix_market.header.base_params.mint_key;
let quote_mint = self.phoenix_market.header.quote_params.mint_key;
let new_order_instruction = create_new_order_instruction_with_custom_token_accounts(
self.phoenix_market.key,
self.drift_signer.key,
&self.base_market_vault.key(),
&self.quote_market_vault.key(),
&base_mint,
"e_mint,
&order_packet,
);
let signer_seeds = get_signer_seeds(&self.signer_nonce);
let signers_seeds = &[&signer_seeds[..]];
invoke_signed_unchecked(
&new_order_instruction,
&self.to_account_infos(),
signers_seeds,
)
.map_err(|e| {
msg!("{:?}", e);
ErrorCode::FailedPhoenixCPI
})?;
Ok(())
}
}
impl<'a, 'b> SpotFulfillmentParams for PhoenixFulfillmentParams<'a, 'b> {
fn is_external(&self) -> bool {
true
}
fn get_best_bid_and_ask(&self) -> DriftResult<(Option<u64>, Option<u64>)> {
let market_data = self.phoenix_market.data.borrow();
let (_, market_bytes) = market_data.split_at(size_of::<MarketHeader>());
let header = &self.phoenix_market.header;
if header.quote_params.decimals != 6 {
msg!("Quote decimals must be 6");
return Err(ErrorCode::InvalidPricePrecision);
}
let market = load_with_dispatch(&header.market_size_params, market_bytes)
.map_err(|_| {
msg!("Failed to deserialize market");
ErrorCode::FailedToDeserializePhoenixMarket
})?
.inner;
// Conversion: price_in_ticks (T) * tick_size (QL/(BU * T)) * quote_lot_size (QA/QL) / raw_base_units_per_base_unit (rBU/BU)
// Yields: price (QA/rBU)
let best_bid = market.get_book(Side::Bid).iter().next().and_then(|(o, _)| {
phoenix_price_in_ticks_to_taker_price(
o.price_in_ticks.as_u64(),
market.get_tick_size().as_u64(),
header,
)
.ok()
});
let best_ask = market.get_book(Side::Ask).iter().next().and_then(|(o, _)| {
phoenix_price_in_ticks_to_taker_price(
o.price_in_ticks.as_u64(),
market.get_tick_size().as_u64(),
header,
)
.ok()
});
Ok((best_bid, best_ask))
}
fn fulfill_order(
&mut self,
taker_direction: PositionDirection,
taker_price: u64,
taker_base_asset_amount: u64,
taker_max_quote_asset_amount: u64,
) -> DriftResult<ExternalSpotFill> {
let market_data = self.phoenix_market.data.borrow();
let (_, market_bytes) = market_data.split_at(size_of::<MarketHeader>());
let header = &self.phoenix_market.header;
let market_size_params = header.market_size_params;
let market = load_with_dispatch(&market_size_params, market_bytes)
.map_err(|_| {
msg!("Failed to deserialize market");
ErrorCode::FailedToDeserializePhoenixMarket
})?
.inner;
// The price in ticks is rounded down for longs and rounded up for shorts
let (side, price_in_ticks) = match taker_direction {
PositionDirection::Long => (
phoenix::state::Side::Bid,
taker_price_to_phoenix_price_in_ticks_rounded_down(
taker_price,
market.get_tick_size().as_u64(),
header,
)?,
),
PositionDirection::Short => (
phoenix::state::Side::Ask,
taker_price_to_phoenix_price_in_ticks_rounded_up(
taker_price,
market.get_tick_size().as_u64(),
header,
)?,
),
};
if price_in_ticks == Ticks::ZERO {
msg!("Price is too low");
return Ok(ExternalSpotFill::empty());
}
// This takes the minimum of
// 1. The number of base lots equivalent to the given base asset amount.
// 2. The number of base lots that can be bought with the max quote asset amount at the given taker price.
let num_base_lots = compute_base_lot_size(
taker_base_asset_amount,
taker_max_quote_asset_amount,
taker_price,
header,
)?;
if num_base_lots == 0 {
msg!("No base lots to fill");
return Ok(ExternalSpotFill::empty());
}
let phoenix_order = OrderPacket::ImmediateOrCancel {
side,
price_in_ticks: Some(price_in_ticks),
num_base_lots,
num_quote_lots: QuoteLots::ZERO,
min_base_lots_to_fill: BaseLots::ZERO,
min_quote_lots_to_fill: QuoteLots::ZERO,
self_trade_behavior: phoenix::state::SelfTradeBehavior::Abort,
match_limit: Some(64),
client_order_id: u128::from_le_bytes(
self.drift_signer.key.as_ref()[..16]
.try_into()
.map_err(|_| {
msg!("Failed to convert client order id");
ErrorCode::FailedPhoenixCPI
})?,
),
use_only_deposited_funds: false,
// TIF parameters
last_valid_slot: None,
last_valid_unix_timestamp_in_seconds: None,
};
let market_accrued_fees_before = market.get_uncollected_fee_amount().as_u64();
let base_before = self.base_market_vault.amount;
let quote_before = self.quote_market_vault.amount;
drop(market_data);
self.invoke_new_order(phoenix_order)?;
// Reload market data
let market_data = self.phoenix_market.data.borrow();
let (_, market_bytes) = market_data.split_at(size_of::<MarketHeader>());
self.base_market_vault.reload().map_err(|_e| {
msg!("Failed to reload base_market_vault");
ErrorCode::FailedPhoenixCPI
})?;
self.quote_market_vault.reload().map_err(|_e| {
msg!("Failed to reload quote_market_vault");
ErrorCode::FailedPhoenixCPI
})?;
let base_after = self.base_market_vault.amount;
let quote_after = self.quote_market_vault.amount;
let market_accrued_fees_after = load_with_dispatch(&market_size_params, market_bytes)
.map_err(|_| {
msg!("Failed to deserialize market");
ErrorCode::FailedToDeserializePhoenixMarket
})?
.inner
.get_uncollected_fee_amount()
.as_u64();
let (base_update_direction, base_asset_amount_filled) = if base_after > base_before {
(SpotBalanceType::Deposit, base_after.safe_sub(base_before)?)
} else {
(SpotBalanceType::Borrow, base_before.safe_sub(base_after)?)
};
if base_asset_amount_filled == 0 {
msg!("No base filled on phoenix");
return Ok(ExternalSpotFill::empty());
}
let phoenix_fee = market_accrued_fees_after.safe_sub(market_accrued_fees_before)?;
let (quote_update_direction, quote_asset_amount_filled) =
if base_update_direction == SpotBalanceType::Borrow {
let quote_asset_amount_delta = quote_after.safe_sub(quote_before)?;
(
SpotBalanceType::Deposit,
quote_asset_amount_delta.safe_add(phoenix_fee)?,
)
} else {
let quote_asset_amount_delta = quote_before.safe_sub(quote_after)?;
(
SpotBalanceType::Borrow,
quote_asset_amount_delta.safe_sub(phoenix_fee)?,
)
};
Ok(ExternalSpotFill {
base_asset_amount_filled,
quote_asset_amount_filled,
base_update_direction,
quote_update_direction,
fee: phoenix_fee,
unsettled_referrer_rebate: 0,
settled_referrer_rebate: 0,
})
}
fn get_order_action_explanation(&self) -> DriftResult<OrderActionExplanation> {
Ok(OrderActionExplanation::OrderFillWithPhoenix)
}
// Note: this trait method still feels a little out of place
fn validate_vault_amounts(
&self,
base_market: &Ref<SpotMarket>,
quote_market: &Ref<SpotMarket>,
) -> DriftResult {
validate_spot_market_vault_amount(base_market, self.base_market_vault.amount)?;
validate_spot_market_vault_amount(quote_market, self.quote_market_vault.amount)?;
Ok(())
}
fn validate_markets(
&self,
base_market: &SpotMarket,
quote_market: &SpotMarket,
) -> DriftResult<()> {
validate!(
self.base_market_vault.mint == base_market.mint,
ErrorCode::DefaultError,
"base mints dont match"
)?;
validate!(
self.quote_market_vault.mint == quote_market.mint,
ErrorCode::DefaultError,
"base mints dont match"
)?;
Ok(())
}
}
#[cfg(test)]
mod test {
use anchor_lang::prelude::Pubkey;
use phoenix::{
program::{MarketHeader, MarketSizeParams, TokenParams},
quantities::{
BaseAtomsPerBaseLot, QuoteAtomsPerBaseUnitPerTick, QuoteAtomsPerQuoteLot, Ticks,
WrapperU64,
},
};
use crate::state::fulfillment_params::phoenix::{
compute_base_lot_size, phoenix_price_in_ticks_to_taker_price,
taker_price_to_phoenix_price_in_ticks_rounded_down,
taker_price_to_phoenix_price_in_ticks_rounded_up,
};
fn setup() -> MarketHeader {
// Creates a market header with a similar configuration to the SOL/USDC mainnet-beta Phoenix market
MarketHeader::new(
MarketSizeParams {
bids_size: 2048,
asks_size: 2048,
num_seats: 4097,
},
TokenParams {
decimals: 9,
vault_bump: 255,
mint_key: Pubkey::new_unique(),
vault_key: Pubkey::new_unique(),
},
BaseAtomsPerBaseLot::new(1_000_000),
TokenParams {
decimals: 6,
vault_bump: 255,
mint_key: Pubkey::new_unique(),
vault_key: Pubkey::new_unique(),
},
QuoteAtomsPerQuoteLot::new(1),
QuoteAtomsPerBaseUnitPerTick::new(1000),
Pubkey::new_unique(),
Pubkey::new_unique(),
Pubkey::new_unique(),
1,
)
}
#[test]
fn test_tick_price_to_quote_atoms_per_raw_base_unit() {
let header = setup();
let tick_size = header.get_tick_size_in_quote_atoms_per_base_unit().as_u64()
/ header.get_quote_lot_size().as_u64();
// Tick is 0.001 USDC/SOL
assert_eq!(tick_size, 1000);
assert_eq!(
tick_size as f64 * 10.0_f64.powf(-(header.quote_params.decimals as f64)),
0.001
);
let target_price = 23.128;
let target_price_in_quote_atoms_per_raw_base_unit =
(target_price * 10.0_f64.powf(header.quote_params.decimals as f64)) as u64;
assert_eq!(target_price_in_quote_atoms_per_raw_base_unit, 23128000);
let target_price_in_ticks = target_price_in_quote_atoms_per_raw_base_unit / tick_size;
let converted_price =
phoenix_price_in_ticks_to_taker_price(target_price_in_ticks, tick_size, &header)
.unwrap();
assert_eq!(
converted_price,
target_price_in_quote_atoms_per_raw_base_unit
);
}
#[test]
fn test_price_in_quote_atoms_per_raw_base_unit_to_ticks() {
let header = setup();
let tick_size = header.get_tick_size_in_quote_atoms_per_base_unit().as_u64()
/ header.get_quote_lot_size().as_u64();
let taker_price = 23809812;
let sell_limit_price_in_ticks =
taker_price_to_phoenix_price_in_ticks_rounded_up(taker_price, tick_size, &header)
.unwrap();
let buy_limit_price_in_ticks =
taker_price_to_phoenix_price_in_ticks_rounded_down(taker_price, tick_size, &header)
.unwrap();
assert_eq!(
sell_limit_price_in_ticks,
buy_limit_price_in_ticks + Ticks::new(1)
);
assert_eq!(buy_limit_price_in_ticks, 23809);
// If the price is a multiple of the tick size, the buy and sell limit prices should be the same
let taker_price = 24123000;
let sell_limit_price_in_ticks =
taker_price_to_phoenix_price_in_ticks_rounded_up(taker_price, tick_size, &header)
.unwrap();
let buy_limit_price_in_ticks =
taker_price_to_phoenix_price_in_ticks_rounded_down(taker_price, tick_size, &header)
.unwrap();
assert_eq!(sell_limit_price_in_ticks, buy_limit_price_in_ticks);
assert_eq!(buy_limit_price_in_ticks, 24123);
}
#[test]
fn test_compute_base_lots() {
let header = setup();
let taker_price = 23809000;
// 55 SOL
let taker_base_asset_amount = 55 * 1_000_000_000;
let taker_max_quote_asset_amount = u64::MAX;
let num_base_lots = compute_base_lot_size(
taker_base_asset_amount,
taker_max_quote_asset_amount,
taker_price,
&header,
)
.unwrap();
assert_eq!(num_base_lots, 55000);
assert_eq!(
55000,
55 * 10_u64.pow(header.base_params.decimals) / header.get_base_lot_size().as_u64(),
);
let taker_base_asset_amount = u64::MAX;
// 2357.091 USDC
let taker_max_quote_asset_amount = 2357091000_u64;
let num_base_lots = compute_base_lot_size(
taker_base_asset_amount,
taker_max_quote_asset_amount,
taker_price,
&header,
)
.unwrap();
assert_eq!(num_base_lots, 99000);
assert_eq!(
99000,
99 * 10_u64.pow(header.base_params.decimals) / header.get_base_lot_size().as_u64(),
);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/fill_mode/tests.rs
|
use crate::state::fill_mode::FillMode;
use crate::state::user::{Order, OrderType};
use crate::{PositionDirection, PRICE_PRECISION_I64, PRICE_PRECISION_U64};
#[test]
fn test() {
let market_order = Order {
order_type: OrderType::Market,
direction: PositionDirection::Long,
auction_start_price: 100 * PRICE_PRECISION_I64,
auction_end_price: 110 * PRICE_PRECISION_I64,
price: 120 * PRICE_PRECISION_U64,
slot: 0,
auction_duration: 10,
..Order::default()
};
let fill_mode = FillMode::Fill;
let slot = 0;
let oracle_price = Some(100 * PRICE_PRECISION_I64);
let tick_size = 1;
let limit_price = fill_mode
.get_limit_price(&market_order, oracle_price, slot, tick_size, false)
.unwrap();
assert_eq!(limit_price, Some(100 * PRICE_PRECISION_U64));
let place_and_take_mode = FillMode::PlaceAndTake(false, 100);
let limit_price = place_and_take_mode
.get_limit_price(&market_order, oracle_price, slot, tick_size, false)
.unwrap();
assert_eq!(limit_price, Some(110 * PRICE_PRECISION_U64));
let limit_order = Order {
order_type: OrderType::Limit,
direction: PositionDirection::Long,
price: 120 * PRICE_PRECISION_U64,
slot: 0,
..Order::default()
};
let limit_price = place_and_take_mode
.get_limit_price(&limit_order, oracle_price, slot, tick_size, false)
.unwrap();
assert_eq!(limit_price, Some(120 * PRICE_PRECISION_U64));
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/traits/tests.rs
|
mod size {
use crate::state::events::OrderActionRecord;
use crate::state::fulfillment_params::serum::SerumV3FulfillmentConfig;
use crate::state::insurance_fund_stake::InsuranceFundStake;
use crate::state::perp_market::PerpMarket;
use crate::state::spot_market::SpotMarket;
use crate::state::state::State;
use crate::state::traits::Size;
use crate::state::user::{User, UserStats};
#[test]
fn order_action_records() {
let expected_size = std::mem::size_of::<OrderActionRecord>() + 8;
let actual_size = OrderActionRecord::SIZE;
assert_eq!(actual_size, expected_size);
}
#[test]
fn perp_market() {
let expected_size = std::mem::size_of::<PerpMarket>() + 8;
let actual_size = PerpMarket::SIZE;
assert_eq!(actual_size, expected_size);
}
#[test]
fn spot_market() {
let expected_size = std::mem::size_of::<SpotMarket>() + 8;
let actual_size = SpotMarket::SIZE;
assert_eq!(actual_size, expected_size);
}
#[test]
fn serum_config() {
let expected_size = std::mem::size_of::<SerumV3FulfillmentConfig>() + 8;
let actual_size = SerumV3FulfillmentConfig::SIZE;
assert_eq!(actual_size, expected_size);
}
#[test]
fn state() {
let expected_size = std::mem::size_of::<State>() + 8;
let actual_size = State::SIZE;
assert_eq!(actual_size, expected_size);
}
#[test]
fn user() {
let expected_size = std::mem::size_of::<User>() + 8;
let actual_size = User::SIZE;
assert_eq!(actual_size, expected_size);
}
#[test]
fn user_stats() {
let expected_size = std::mem::size_of::<UserStats>() + 8;
let actual_size = UserStats::SIZE;
assert_eq!(actual_size, expected_size);
}
#[test]
fn insurance_fund_stake() {
let expected_size = std::mem::size_of::<InsuranceFundStake>() + 8;
let actual_size = InsuranceFundStake::SIZE;
assert_eq!(actual_size, expected_size);
}
}
mod market_index_offset {
use crate::create_anchor_account_info;
use crate::state::perp_market::PerpMarket;
use crate::state::spot_market::SpotMarket;
use crate::state::traits::MarketIndexOffset;
use crate::test_utils::*;
use anchor_lang::prelude::*;
use arrayref::array_ref;
#[test]
fn spot_market() {
let mut spot_market = SpotMarket {
market_index: 11,
..SpotMarket::default()
};
create_anchor_account_info!(spot_market, SpotMarket, spot_market_account_info);
let data = spot_market_account_info.try_borrow_data().unwrap();
let market_index =
u16::from_le_bytes(*array_ref![data, SpotMarket::MARKET_INDEX_OFFSET, 2]);
assert_eq!(market_index, spot_market.market_index);
}
#[test]
fn perp_market() {
let mut perp_market = PerpMarket {
market_index: 11,
..PerpMarket::default()
};
create_anchor_account_info!(perp_market, PerpMarket, perp_market_account_info);
let data = perp_market_account_info.try_borrow_data().unwrap();
let market_index =
u16::from_le_bytes(*array_ref![data, PerpMarket::MARKET_INDEX_OFFSET, 2]);
assert_eq!(market_index, perp_market.market_index);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/oracle/tests.rs
|
use solana_program::pubkey::Pubkey;
use std::str::FromStr;
use crate::create_account_info;
use crate::state::oracle::{get_oracle_price, OracleSource};
use crate::state::oracle_map::OracleMap;
use crate::state::perp_market::AMM;
use crate::test_utils::*;
#[test]
fn pyth_1k() {
let mut oracle_price = get_hardcoded_pyth_price(8394, 10);
let oracle_price_key =
Pubkey::from_str("8ihFLu5FimgTQ1Unh4dVyEHUGodJ5gJQCrQf4KUVB9bN").unwrap();
let pyth_program = crate::ids::pyth_program::id();
create_account_info!(
oracle_price,
&oracle_price_key,
&pyth_program,
oracle_account_info
);
let oracle_price_data =
get_oracle_price(&OracleSource::Pyth1K, &oracle_account_info, 0).unwrap();
assert_eq!(oracle_price_data.price, 839);
let amm = AMM {
oracle_source: OracleSource::Pyth1K,
..AMM::default()
};
let twap = amm.get_oracle_twap(&oracle_account_info, 0).unwrap();
assert_eq!(twap, Some(839));
}
#[test]
fn pyth_1m() {
let mut oracle_price = get_hardcoded_pyth_price(8394, 10);
let oracle_price_key =
Pubkey::from_str("8ihFLu5FimgTQ1Unh4dVyEHUGodJ5gJQCrQf4KUVB9bN").unwrap();
let pyth_program = crate::ids::pyth_program::id();
create_account_info!(
oracle_price,
&oracle_price_key,
&pyth_program,
oracle_account_info
);
let oracle_price_data =
get_oracle_price(&OracleSource::Pyth1M, &oracle_account_info, 0).unwrap();
assert_eq!(oracle_price_data.price, 839400);
let amm = AMM {
oracle_source: OracleSource::Pyth1M,
..AMM::default()
};
let twap = amm.get_oracle_twap(&oracle_account_info, 0).unwrap();
assert_eq!(twap, Some(839400));
}
#[test]
fn pyth_pull_1m() {
let oracle_price_key =
Pubkey::from_str("DBE3N8uNjhKPRHfANdwGvCZghWXyLPdqdSbEW2XFwBiX").unwrap();
let oracle_market_str = String::from("IvEjY51+9M206svkAq6RZcKrffzb5QRNJ/KEEG+IqQv93vpfv/YMoAFysCEhfKP+aJIqGar5kBCcudhOmtAEtNICWtb1KTFEGbZFBQAAAAAABQIAAAAAAAD2////xXhYZgAAAADFeFhmAAAAAJMfBQAAAAAAnwEAAAAAAAAFMwYQAAAAAAA=");
let mut decoded_bytes = base64::decode(oracle_market_str).unwrap();
let oracle_market_bytes = decoded_bytes.as_mut_slice();
let mut lamports = 0;
let pyth_program = crate::ids::drift_oracle_receiver_program::id();
let bonk_market_account_info = create_account_info(
&oracle_price_key,
true,
&mut lamports,
oracle_market_bytes,
&pyth_program,
);
let oracle_price_data = get_oracle_price(
&OracleSource::Pyth1MPull,
&bonk_market_account_info,
234919073,
)
.unwrap();
assert_eq!(oracle_price_data.price, 34552600);
let amm = AMM {
oracle_source: OracleSource::Pyth1MPull,
..AMM::default()
};
let twap = amm.get_oracle_twap(&bonk_market_account_info, 0).unwrap();
assert_eq!(twap, Some(33576300));
}
#[test]
fn switchboard_on_demand() {
let oracle_price_key =
Pubkey::from_str("8an9aE6j4STjv1cNXaE7SJfqmfjgLUHpBKURjqcAQJbQ").unwrap();
let oracle_market_str = String::from("xBtsxArX2ygF5+9rNGznB5bCcRKtQrkPSKnB7SpgtyeGQM7FuE2KVlisPRQAAAAAAAAAAAAAAAA+UHpSRCo0IwwAAAAAAAAAJitDZKZoh6XepseJBXWe/lcspgoK5FkXhG/BewUorG5CqUEUAAAAAFqpQRQAAAAA8PzgMB6TfkcMAAAAAAAAAGjiSUNueeTftplz+u/z8VQ2hRIbsVfG2ikc8Oxa1OVTolooFAAAAAAAAAAAAAAAAEizjuOw8yicCgAAAAAAAAABXj3Y9l4yGBRFXaCetMwT6HpzMpca+kYR/MYh+j8EUB1uPhQAAAAAOG4+FAAAAAACiEe0ZUszUgwAAAAAAAAAkDfiD4Gn+CTbOnE8xYjATeEDBfMWFNY57v1LuujRnGZYrD0UAAAAAAAAAAAAAAAABl3I+mq45SMMAAAAAAAAACVOW/5bK8Btqmx4Vk6zcPIfXO8zAoD0jYfZl8sUISFEaSpxEwAAAAAAAAAAAAAAAMzgbc5nVjCoBwAAAAAAAABQtwZpTNT6DaYcbKn3fERJYIW+SUeHf96zTfeNM0KsnRRGqhMAAAAAAAAAAAAAAABIfPmsmN/hXwgAAAAAAAAAYJg3LYKk7K7VBmaP3CqKdDehOJ9w2BAdGN2ihbblBMLwyyEUAAAAAAAAAAAAAAAAxs9IiXhjQCcJAAAAAAAAACH5pdGZv3Zl4YGR/RkbyiM972/Y6TkFDRSOugqBX8R3pdatEwAAAAAAAAAAAAAAAATJSrig8pADCAAAAAAAAAB7gyHaEgJTUWoB03O2WP2y5wG0BQyy4DIW4QIX0Zm/LBCDrRMAAAAAAAAAAAAAAAD0QtXQ8ppmUwgAAAAAAAAAXKbf3SvboSeQoR1Uax14h2bo3XRZT6YDzVR04CCKI9OiWigUAAAAAAAAAAAAAAAAvDV3NgOBNZwKAAAAAAAAAOZ7GqcB2Y++LyL1s5nlJ5BPWiBqGufX9otlggY7+arpHW4+FAAAAAA4bj4UAAAAACId0nIlrSxSDAAAAAAAAACDlY3q65NTi3f76VZvIIwy9dPg2O22YgY8biVvXVbmRkKpQRQAAAAAWqlBFAAAAADw/OAwHpN+RwwAAAAAAAAA3MJlNs10pau942MW3ICzf2juvzF0+hdValrRUBcb0DpCqUEUAAAAAFqpQRQAAAAAgKcI0J26VkkMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWnepBOelBHznzx//7xQtA1OAt1Bx+exaGnlnqRII0HyUd7+1/xAShZ8zbPmHJWgOdwW6Kr7OFxiM+yjKZspbC8qNXh/AbUSNWMVBd3cJsl737xFECAru4/NmPaW4F85v6y5GYAAAAAAAAAAAAAAAAAlDV3AAAAAAEAAABkU09MAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFwNLEDVnAAAAAGeRaxMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADw/OAwHpN+RwwAAAAAAAAAEB9A716T3gAAAAAAAAAAAHTgmBCe9RtIDAAAAAAAAACQqieffyfYAQAAAAAAAAAA8PzgMB6TfkcMAAAAAAAAAICnCNCdulZJDAAAAAAAAAADDAAAAAAAAEKpQRQAAAAAQqlBFAAAAABCqUEUAAAAAJYAAAAAAAAAAAAAAAAAAABeHL43OGkgQ0jZpxMAAAAAuwZVOgV4IEP526cTAAAAAEBf4jv4GhxDij6qEwAAAABEt508DB4cQ5E+qhMAAAAARLedPAweHEOVPqoTAAAAAES3nTwMHhxDlj6qEwAAAABEt508DB4cQ5c+qhMAAAAA59KoPCNPG0MhQaoTAAAAADV9tzxZTRtDKUGqEwAAAAA2gsE8Ok4bQytBqhMAAAAAnJVNPGOFGkMHRqoTAAAAAJO/ozyxhBpDD0aqEwAAAACTv6M8sYQaQxBGqhMAAAAAk7+jPLGEGkMRRqoTAAAAAJO/ozyxhBpDEkaqEwAAAADKBrY8jnsaQxdGqhMAAAAA/9jKOLjfGENOV6sTAAAAAG5u7Tyn1hhDqVerEwAAAADm3FA7QJQZQxCDrRMAAAAAAAAAALfUE0Ol1q0TAAAAAAAAAABc2ShD8MshFAAAAACJzNU8PulfQ1isPRQAAAAAATRmOmlIY0Mdbj4UAAAAAF9OgD2UjmJDQqlBFAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==");
let mut decoded_bytes = base64::decode(oracle_market_str).unwrap();
let oracle_market_bytes = decoded_bytes.as_mut_slice();
let mut lamports = 0;
let sb_program = crate::ids::switchboard_on_demand::id();
let dsol_oracle_info = create_account_info(
&oracle_price_key,
true,
&mut lamports,
oracle_market_bytes,
&sb_program,
);
let oracle_price_data = get_oracle_price(
&OracleSource::SwitchboardOnDemand,
&dsol_oracle_info,
339848045,
)
.unwrap();
assert_eq!(oracle_price_data.price, 226556945);
let amm = AMM {
oracle_source: OracleSource::SwitchboardOnDemand,
..AMM::default()
};
let twap = amm.get_oracle_twap(&dsol_oracle_info, 0).unwrap();
assert_eq!(twap, Some(226556945));
}
#[test]
fn oracle_map_diff_oracle_source() {
let oracle_price_key =
Pubkey::from_str("DBE3N8uNjhKPRHfANdwGvCZghWXyLPdqdSbEW2XFwBiX").unwrap();
let oracle_market_str = String::from("IvEjY51+9M206svkAq6RZcKrffzb5QRNJ/KEEG+IqQv93vpfv/YMoAFysCEhfKP+aJIqGar5kBCcudhOmtAEtNICWtb1KTFEGbZFBQAAAAAABQIAAAAAAAD2////xXhYZgAAAADFeFhmAAAAAJMfBQAAAAAAnwEAAAAAAAAFMwYQAAAAAAA=");
let mut decoded_bytes = base64::decode(oracle_market_str).unwrap();
let oracle_market_bytes = decoded_bytes.as_mut_slice();
let mut lamports = 0;
let pyth_program = crate::ids::drift_oracle_receiver_program::id();
let bonk_market_account_info = create_account_info(
&oracle_price_key,
true,
&mut lamports,
oracle_market_bytes,
&pyth_program,
);
let mut oracle_map = OracleMap::load_one(&bonk_market_account_info, 0, None).unwrap();
let oracle_price_data = oracle_map
.get_price_data(&(oracle_price_key, OracleSource::Pyth1MPull))
.unwrap();
assert_eq!(oracle_price_data.price, 34552600);
let oracle_price_data = oracle_map
.get_price_data(&(oracle_price_key, OracleSource::PythPull))
.unwrap();
assert_eq!(oracle_price_data.price, 34);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/order_params/tests.rs
|
use crate::state::order_params::parse_optional_params;
mod get_auction_duration {
use crate::state::order_params::get_auction_duration;
use crate::{ContractTier, PRICE_PRECISION_U64};
#[test]
fn test() {
let price_diff = 0;
let price = 100 * PRICE_PRECISION_U64;
let contract_tier = ContractTier::C;
let duration = get_auction_duration(price_diff, price, contract_tier).unwrap();
assert_eq!(duration, 10);
let price_diff = PRICE_PRECISION_U64 / 10;
let price = 100 * PRICE_PRECISION_U64;
let duration = get_auction_duration(price_diff, price, contract_tier).unwrap();
assert_eq!(duration, 10);
let price_diff = PRICE_PRECISION_U64 / 2;
let price = 100 * PRICE_PRECISION_U64;
let duration = get_auction_duration(price_diff, price, contract_tier).unwrap();
assert_eq!(duration, 30);
let price_diff = PRICE_PRECISION_U64;
let price = 100 * PRICE_PRECISION_U64;
let duration = get_auction_duration(price_diff, price, contract_tier).unwrap();
assert_eq!(duration, 60);
let price_diff = 2 * PRICE_PRECISION_U64;
let price = 100 * PRICE_PRECISION_U64;
let duration = get_auction_duration(price_diff, price, contract_tier).unwrap();
assert_eq!(duration, 120);
}
}
mod update_perp_auction_params {
use crate::state::order_params::PostOnlyParam;
use crate::state::perp_market::{ContractTier, PerpMarket, AMM};
use crate::state::user::OrderType;
use crate::{
OracleSource, OrderParams, PositionDirection, AMM_RESERVE_PRECISION,
BID_ASK_SPREAD_PRECISION, PEG_PRECISION, PRICE_PRECISION_I64, PRICE_PRECISION_U64,
QUOTE_PRECISION_U64,
};
#[test]
fn test_extreme_sanitize_oracle_order() {
let oracle_price = 145 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.last_bid_price_twap = (oracle_price - 192988) as u64;
amm.last_mark_price_twap_5min = oracle_price as u64;
amm.last_ask_price_twap = (oracle_price + 192988) as u64;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap_5min = oracle_price;
amm.historical_oracle_data.last_oracle_price = oracle_price;
let perp_market = PerpMarket {
amm,
..PerpMarket::default()
};
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
auction_start_price: Some(amm.last_bid_price_twap as i64),
auction_end_price: Some((amm.last_bid_price_twap + 1000000) as i64),
auction_duration: Some(30),
direction: PositionDirection::Long,
..OrderParams::default()
};
assert_eq!(order_params_before.auction_start_price, Some(144_807_012));
assert_eq!(order_params_before.auction_end_price, Some(145_807_012));
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_after.auction_start_price, Some(-144807));
assert_eq!(order_params_after.auction_end_price, Some(3_092_988));
assert_eq!(order_params_after.auction_duration, Some(134));
let order_params_before2 = OrderParams {
order_type: OrderType::Oracle,
auction_start_price: Some(amm.last_ask_price_twap as i64),
auction_end_price: Some((amm.last_bid_price_twap - 1000000) as i64),
auction_duration: Some(30),
direction: PositionDirection::Short,
..OrderParams::default()
};
assert_eq!(order_params_before2.auction_start_price, Some(145192988));
assert_eq!(order_params_before2.auction_end_price, Some(143807012));
let mut order_params_after2 = order_params_before2;
order_params_after2
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_after2.auction_start_price, Some(145192988)); // will never fill kek
assert_eq!(order_params_after2.auction_end_price, Some(143807012));
assert_eq!(order_params_after2.auction_duration, Some(58));
// huge negative for short
let order_params_before3 = OrderParams {
order_type: OrderType::Oracle,
auction_start_price: Some(-(amm.last_ask_price_twap as i64)),
auction_end_price: Some(-((amm.last_bid_price_twap - 1000000) as i64)),
auction_duration: Some(30),
direction: PositionDirection::Short,
oracle_price_offset: Some(-((amm.last_bid_price_twap - 1000000) as i32)),
..OrderParams::default()
};
assert_eq!(order_params_before3.auction_start_price, Some(-145192988));
assert_eq!(order_params_before3.auction_end_price, Some(-143807012));
assert_eq!(order_params_before3.oracle_price_offset, Some(-143807012));
let mut order_params_after3 = order_params_before3;
order_params_after3
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_after3.auction_start_price, Some(145192));
assert_eq!(order_params_after3.auction_end_price, Some(-3092988));
assert_eq!(order_params_after3.oracle_price_offset, Some(-143807012));
assert_eq!(order_params_after3.auction_duration, Some(134));
}
#[test]
fn test_extreme_sanitize_oracle_order_huge_market_prem() {
let oracle_price = 145 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.last_bid_price_twap = (oracle_price * 15 / 10 - 192988) as u64;
amm.last_mark_price_twap_5min = (oracle_price * 16 / 10) as u64;
amm.last_ask_price_twap = (oracle_price * 16 / 10 + 192988) as u64;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap_5min = oracle_price;
amm.historical_oracle_data.last_oracle_price = oracle_price;
let perp_market = PerpMarket {
amm,
..PerpMarket::default()
};
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
auction_start_price: Some(amm.last_bid_price_twap as i64),
auction_end_price: Some((amm.last_bid_price_twap + 1000000) as i64),
auction_duration: Some(30),
..OrderParams::default()
};
assert_eq!(order_params_before.auction_start_price, Some(217_307_012));
assert_eq!(order_params_before.auction_end_price, Some(218_307_012));
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_after.auction_start_price, Some(72_524_319));
assert_eq!(order_params_after.auction_end_price, Some(90_092_988));
assert_eq!(order_params_after.auction_duration, Some(180));
}
#[test]
fn test_sanitize_limit() {
let oracle_price = 100 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.last_bid_price_twap = (oracle_price * 99 / 100) as u64;
amm.last_mark_price_twap_5min = oracle_price as u64;
amm.last_ask_price_twap = (oracle_price * 101 / 100) as u64;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap_5min = oracle_price;
amm.historical_oracle_data.last_oracle_price = oracle_price;
let perp_market = PerpMarket {
amm,
..PerpMarket::default()
};
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: Some(0),
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::MustPostOnly,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: true,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: Some(0),
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: None,
price: 0,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: None,
price: 100 * PRICE_PRECISION_U64,
direction: PositionDirection::Long,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: None,
price: 102 * PRICE_PRECISION_U64,
direction: PositionDirection::Long,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_duration, Some(175));
assert_eq!(
order_params_after.auction_start_price,
Some(100 * PRICE_PRECISION_I64 - 901000)
);
assert_eq!(
order_params_after.auction_end_price,
Some(102 * PRICE_PRECISION_I64)
);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: None,
price: 100 * PRICE_PRECISION_U64,
direction: PositionDirection::Short,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: None,
price: 98 * PRICE_PRECISION_U64,
direction: PositionDirection::Short,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_duration, Some(174));
assert_eq!(
order_params_after.auction_start_price,
Some(100 * PRICE_PRECISION_I64 + 899000) // %1 / 10 = 10 bps aggression
);
assert_eq!(
order_params_after.auction_end_price,
Some(98 * PRICE_PRECISION_I64)
);
}
#[test]
fn test_sanitize_oracle_limit() {
let oracle_price = 100 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 1000) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 1000) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.last_bid_price_twap = (oracle_price * 999 / 1000) as u64;
amm.last_mark_price_twap_5min = oracle_price as u64;
amm.last_ask_price_twap = (oracle_price * 1001 / 1000) as u64;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap_5min = oracle_price;
amm.historical_oracle_data.last_oracle_price = oracle_price;
let perp_market = PerpMarket {
amm,
..PerpMarket::default()
};
// test oracle offset long sanitize
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: Some((PRICE_PRECISION_I64 * 10) as i32),
price: 0,
direction: PositionDirection::Long,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
// assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price, Some(-90010));
assert_eq!(order_params_after.auction_end_price, Some(10000000));
assert_eq!(order_params_after.auction_duration, Some(180));
assert_eq!(order_params_after.price, 0);
assert_eq!(order_params_after.oracle_price_offset, Some(10000000));
// test oracle offset long no sanitize
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: Some((-PRICE_PRECISION_I64 * 2) as i32),
price: 0,
direction: PositionDirection::Long,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
// test oracle offset long no sanitize
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: Some((144) as i32),
price: 0,
direction: PositionDirection::Long,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(order_params_before, order_params_after);
// test oracle offset long sanitize threshold
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: Some((199003) as i32),
price: 0,
direction: PositionDirection::Long,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price, Some(-90010));
assert_eq!(order_params_after.auction_end_price, Some(199003));
assert_eq!(order_params_after.auction_duration, Some(18));
assert_eq!(order_params_after.price, 0);
assert_eq!(order_params_after.oracle_price_offset, Some(199003));
// test oracle offset short sanitize
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: Some((-PRICE_PRECISION_I64 * 10) as i32),
price: 0,
direction: PositionDirection::Short,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price, Some(89990));
assert_eq!(order_params_after.auction_end_price, Some(-10000000));
assert_eq!(order_params_after.auction_duration, Some(180));
assert_eq!(order_params_after.price, 0);
assert_eq!(order_params_after.oracle_price_offset, Some(-10000000));
// test oracle offset short sanitize threshold
let order_params_before = OrderParams {
order_type: OrderType::Limit,
auction_duration: None,
post_only: PostOnlyParam::None,
immediate_or_cancel: false,
oracle_price_offset: Some((-199003) as i32),
price: 0,
direction: PositionDirection::Short,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price, Some(89990));
assert_eq!(order_params_after.auction_end_price, Some(-199003));
assert_eq!(order_params_after.auction_duration, Some(18));
assert_eq!(order_params_after.price, 0);
assert_eq!(order_params_after.oracle_price_offset, Some(-199003));
}
#[test]
fn test_market_sanitize() {
let oracle_price = 99 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 99 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.historical_oracle_data.last_oracle_price = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price - 97238;
amm.last_ask_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + 217999;
amm.last_bid_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + 17238;
let mut perp_market = PerpMarket {
amm,
contract_tier: ContractTier::B,
..PerpMarket::default()
};
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Long,
auction_start_price: Some(103 * PRICE_PRECISION_I64),
auction_end_price: Some(104 * PRICE_PRECISION_I64),
price: 104 * PRICE_PRECISION_U64,
auction_duration: Some(1),
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price.unwrap(), 98901080);
let amm_bid_price = amm.bid_price(amm.reserve_price().unwrap()).unwrap();
assert_eq!(amm_bid_price, 98010000);
assert!(order_params_after.auction_start_price.unwrap() as u64 > amm_bid_price);
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Short,
auction_start_price: Some(98 * PRICE_PRECISION_I64),
auction_end_price: Some(95 * PRICE_PRECISION_I64),
price: 94 * PRICE_PRECISION_U64,
auction_duration: Some(11),
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price.unwrap(), 99118879);
// skip for prelaunch oracle
perp_market.amm.oracle_source = OracleSource::Prelaunch;
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price,
order_params_before.auction_start_price
);
assert_eq!(
order_params_after.auction_end_price,
order_params_before.auction_end_price
);
perp_market.contract_tier = ContractTier::B; // switch back
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Short,
auction_start_price: Some(103 * PRICE_PRECISION_I64),
auction_end_price: Some(104 * PRICE_PRECISION_I64),
price: 104 * PRICE_PRECISION_U64,
auction_duration: Some(1),
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_before.auction_start_price,
order_params_after.auction_start_price
);
assert_eq!(
Some(order_params_before.price as i64),
order_params_after.auction_end_price
);
assert_eq!(order_params_before.direction, order_params_after.direction);
assert_eq!(order_params_after.auction_duration, Some(102));
}
#[test]
fn test_oracle_market_sanitize() {
let oracle_price = 99 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.historical_oracle_data.last_oracle_price = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price - 97238;
amm.last_ask_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + 217999;
amm.last_bid_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + 17238;
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::B,
..PerpMarket::default()
};
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
direction: PositionDirection::Long,
auction_start_price: Some(4 * PRICE_PRECISION_I64),
auction_end_price: Some(5 * PRICE_PRECISION_I64),
price: 5 * PRICE_PRECISION_U64,
auction_duration: Some(8),
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price.unwrap(), -98920);
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
direction: PositionDirection::Short,
auction_start_price: Some(4 * PRICE_PRECISION_I64),
auction_end_price: Some(5 * PRICE_PRECISION_I64),
price: 5 * PRICE_PRECISION_U64,
auction_duration: Some(8),
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_before.auction_start_price,
order_params_after.auction_start_price
);
assert_eq!(
order_params_before.auction_end_price,
order_params_after.auction_end_price
);
assert_eq!(order_params_before.direction, order_params_after.direction);
assert_ne!(
order_params_before.auction_duration,
order_params_after.auction_duration
);
}
#[test]
fn test_market_sanatize_no_auction_params() {
let oracle_price = 99 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.historical_oracle_data.last_oracle_price = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price - 97238;
amm.last_ask_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + 217999;
amm.last_bid_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + 17238;
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Long,
auction_start_price: None,
auction_end_price: None,
price: 104 * PRICE_PRECISION_U64,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price.unwrap(), 98653580);
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Long,
auction_start_price: None,
auction_end_price: None,
price: 95 * PRICE_PRECISION_U64,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(
order_params_after.auction_start_price.unwrap(),
95 * PRICE_PRECISION_I64 - oracle_price / 400
);
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Short,
auction_start_price: None,
auction_end_price: None,
price: 94 * PRICE_PRECISION_U64,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(
order_params_after.auction_start_price.unwrap(),
99118879 + oracle_price / 400
);
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Short,
auction_start_price: None,
auction_end_price: None,
price: 100 * PRICE_PRECISION_U64,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(
order_params_after.auction_start_price.unwrap(),
100 * PRICE_PRECISION_I64 + oracle_price / 400
);
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Short,
auction_start_price: None,
auction_end_price: None,
price: 0,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price.unwrap(),
99118879 + oracle_price / 400
);
assert_eq!(order_params_after.auction_end_price.unwrap(), 98028211);
assert_eq!(order_params_after.auction_duration, Some(82));
let order_params_before = OrderParams {
order_type: OrderType::Market,
direction: PositionDirection::Long,
auction_start_price: None,
auction_end_price: None,
price: 0,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price.unwrap(),
98901080 - oracle_price / 400
);
assert_eq!(order_params_after.auction_end_price.unwrap(), 100207026);
assert_eq!(order_params_after.auction_duration, Some(95));
}
#[test]
fn test_oracle_market_sanitize_no_auction_params() {
let oracle_price = 99 * PRICE_PRECISION_I64;
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 100) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default()
};
amm.historical_oracle_data.last_oracle_price = oracle_price;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price - 97238;
amm.historical_oracle_data.last_oracle_price_twap_5min =
amm.historical_oracle_data.last_oracle_price_twap;
let ask_twap_offset = 217999;
amm.last_ask_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + ask_twap_offset;
let bid_twap_offset = 17238;
amm.last_bid_price_twap =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + bid_twap_offset;
amm.last_mark_price_twap_5min =
(amm.historical_oracle_data.last_oracle_price_twap as u64) + (17238 + 217999) / 2;
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
direction: PositionDirection::Long,
auction_start_price: None,
auction_end_price: None,
oracle_price_offset: Some(5 * PRICE_PRECISION_U64 as i32),
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(order_params_after.auction_start_price.unwrap(), -228802);
assert!(
order_params_after.auction_start_price.unwrap()
> (bid_twap_offset as i64) - oracle_price / 400
); // 25 bps buffer
assert_eq!(
order_params_after.auction_end_price.unwrap(),
order_params_before.oracle_price_offset.unwrap() as i64
);
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
direction: PositionDirection::Long,
auction_start_price: None,
auction_end_price: None,
oracle_price_offset: None,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_ne!(order_params_before, order_params_after);
assert_eq!(
order_params_after.auction_start_price.unwrap(),
18698 - oracle_price / 400
);
assert_eq!(order_params_after.auction_end_price.unwrap(), 1207026);
assert_eq!(order_params_after.oracle_price_offset, None);
// test sanitize laxing on stale/mismatched mark/oracle twap timestamps
// not too late, should be the same
amm.historical_oracle_data.last_oracle_price_twap_ts = 17000000;
amm.last_mark_price_twap_ts = 17000000 - 55;
let mut order_params_after_2 = order_params_before;
order_params_after_2
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price.unwrap(),
order_params_after_2.auction_start_price.unwrap()
);
assert_eq!(
order_params_after.auction_end_price.unwrap(),
order_params_after_2.auction_end_price.unwrap()
);
assert_eq!(
order_params_after.auction_duration.unwrap(),
order_params_after_2.auction_duration.unwrap()
);
// test sanitize skip on stale/mismatched mark/oracle twap timestamps
amm.historical_oracle_data.last_oracle_price_twap_ts = 17000000;
amm.last_mark_price_twap_ts = 17000000 - 65;
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price.unwrap(),
18698 - oracle_price / 400
);
assert_eq!(order_params_after.auction_end_price.unwrap(), 1207026);
// test sanitize skip on low volume
amm.historical_oracle_data.last_oracle_price_twap_ts = 17000000;
amm.last_mark_price_twap_ts = amm.historical_oracle_data.last_oracle_price_twap_ts;
amm.volume_24h = 183953; // under $1
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price.unwrap(),
18698 - oracle_price / 400
);
assert_eq!(order_params_after.auction_end_price.unwrap(), 1207026);
// test empty
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
direction: PositionDirection::Short,
auction_start_price: None,
auction_end_price: None,
oracle_price_offset: Some(-5 * PRICE_PRECISION_I64 as i32),
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price.unwrap(),
216738 + oracle_price / 400
);
assert!(
order_params_after.auction_start_price.unwrap()
< (ask_twap_offset as i64) + oracle_price / 400
);
assert_eq!(
order_params_after.auction_end_price.unwrap(),
order_params_before.oracle_price_offset.unwrap() as i64
);
assert_eq!(order_params_after.auction_duration.unwrap(), 180);
let order_params_before = OrderParams {
order_type: OrderType::Oracle,
direction: PositionDirection::Short,
auction_start_price: None,
auction_end_price: None,
oracle_price_offset: None,
auction_duration: None,
..OrderParams::default()
};
let mut order_params_after = order_params_before;
order_params_after
.update_perp_auction_params(&perp_market, oracle_price)
.unwrap();
assert_eq!(
order_params_after.auction_start_price.unwrap(),
216738 + oracle_price / 400
);
assert_eq!(order_params_after.auction_end_price.unwrap(), -971789);
assert_eq!(order_params_after.auction_duration.unwrap(), 88);
}
}
mod get_close_perp_params {
use crate::state::oracle::HistoricalOracleData;
use crate::state::order_params::PostOnlyParam;
use crate::state::perp_market::{PerpMarket, AMM};
use crate::{ContractTier, PRICE_PRECISION_U64};
use crate::state::user::{Order, OrderStatus};
use crate::test_utils::create_account_info;
use crate::validation::order::validate_order;
use crate::{
OrderParams, PositionDirection, BASE_PRECISION_U64, PRICE_PRECISION_I64,
QUOTE_PRECISION_U64,
};
use anchor_lang::prelude::AccountLoader;
use solana_program::pubkey::Pubkey;
use std::str::FromStr;
#[test]
fn bid() {
let oracle_price = 100 * PRICE_PRECISION_I64;
let slot = 1;
let amm = AMM {
last_ask_price_twap: 101 * PRICE_PRECISION_U64,
last_bid_price_twap: 99 * PRICE_PRECISION_U64,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 100 * PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
mark_std: PRICE_PRECISION_U64,
oracle_std: PRICE_PRECISION_U64,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default_test()
};
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let direction_to_close = PositionDirection::Long;
let base_asset_amount = BASE_PRECISION_U64;
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, -1000000);
assert_eq!(auction_end_price, 2 * PRICE_PRECISION_I64);
assert_eq!(oracle_price_offset, 2 * PRICE_PRECISION_I64 as i32);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
let amm = AMM {
last_ask_price_twap: 103 * PRICE_PRECISION_U64,
last_bid_price_twap: 101 * PRICE_PRECISION_U64,
last_mark_price_twap_5min: 102 * PRICE_PRECISION_U64,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 100 * PRICE_PRECISION_I64,
last_oracle_price_twap_5min: 100 * PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
mark_std: PRICE_PRECISION_U64,
oracle_std: PRICE_PRECISION_U64,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default_test()
};
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, PRICE_PRECISION_I64);
assert_eq!(auction_end_price, 4 * PRICE_PRECISION_I64);
assert_eq!(oracle_price_offset, 4 * PRICE_PRECISION_I64 as i32);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
let amm = AMM {
last_ask_price_twap: 99 * PRICE_PRECISION_U64,
last_bid_price_twap: 97 * PRICE_PRECISION_U64,
last_mark_price_twap_5min: 98 * PRICE_PRECISION_U64,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 100 * PRICE_PRECISION_I64,
last_oracle_price_twap_5min: 100 * PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
mark_std: PRICE_PRECISION_U64,
oracle_std: PRICE_PRECISION_U64,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default_test()
};
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, -3 * PRICE_PRECISION_I64);
assert_eq!(auction_end_price, 0);
assert_eq!(oracle_price_offset, 0);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
}
#[test]
fn ask() {
let oracle_price = 100 * PRICE_PRECISION_I64;
let slot = 1;
let amm = AMM {
last_ask_price_twap: 101 * PRICE_PRECISION_U64,
last_bid_price_twap: 99 * PRICE_PRECISION_U64,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 100 * PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
mark_std: PRICE_PRECISION_U64,
oracle_std: PRICE_PRECISION_U64,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default_test()
};
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let direction_to_close = PositionDirection::Short;
let base_asset_amount = BASE_PRECISION_U64;
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, 1000000);
assert_eq!(auction_end_price, -2 * PRICE_PRECISION_I64);
assert_eq!(oracle_price_offset, -2 * PRICE_PRECISION_I64 as i32);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
let amm = AMM {
last_ask_price_twap: 103 * PRICE_PRECISION_U64,
last_bid_price_twap: 101 * PRICE_PRECISION_U64,
last_mark_price_twap_5min: 102 * PRICE_PRECISION_U64,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 100 * PRICE_PRECISION_I64,
last_oracle_price_twap_5min: 100 * PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
mark_std: PRICE_PRECISION_U64,
oracle_std: PRICE_PRECISION_U64,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default_test()
};
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, 3 * PRICE_PRECISION_I64);
assert_eq!(auction_end_price, 0);
assert_eq!(oracle_price_offset, 0);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
let amm = AMM {
last_ask_price_twap: 99 * PRICE_PRECISION_U64,
last_mark_price_twap_5min: 98 * PRICE_PRECISION_U64,
last_bid_price_twap: 97 * PRICE_PRECISION_U64,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 100 * PRICE_PRECISION_I64,
last_oracle_price_twap_5min: 100 * PRICE_PRECISION_I64,
..HistoricalOracleData::default()
},
mark_std: PRICE_PRECISION_U64,
oracle_std: PRICE_PRECISION_U64,
volume_24h: 1_000_000 * QUOTE_PRECISION_U64,
..AMM::default_test()
};
let perp_market = PerpMarket {
amm,
contract_tier: ContractTier::Speculative,
..PerpMarket::default()
};
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, -PRICE_PRECISION_I64);
assert_eq!(auction_end_price, -4 * PRICE_PRECISION_I64);
assert_eq!(oracle_price_offset, -4 * PRICE_PRECISION_I64 as i32);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
}
#[test]
fn btc() {
let perp_market_str = String::from("Ct8MLGv1N/cV6vWLwJY+18dY2GsrmrNldgnISB7pmbcf7cn9S4FZ4OYt9si0qF/hpn20TcEt5dszD3rGa3LcZYr+3w9KQVtDd3+9kQoAAAAAAAAAAAAAAAEAAAAAAAAA2VkiggoAAAC/dZSICgAAACeqnmUAAAAAeCbW5P///////////////8J7Hv4BAAAAAAAAAAAAAAB7+rQtykoAAAAAAAAAAAAAAAAAAAAAAABlO/erzgEAAAAAAAAAAAAAVnP4srYEAAAAAAAAAAAAAJxiDwAAAAAAAAAAAAAAAAAy7nN6ywEAAAAAAAAAAAAA5ihcH9MBAAAAAAAAAAAAAK7izzLrAgAAAAAAAAAAAADs3G4NBAAAAAAAAAAAAAAAYIhJGrUEAAAAAAAAAAAAAKA0JMEnAAAAAAAAAAAAAADg/mJJ2f//////////////aJbnnAAAAAAAAAAAAAAAABidn20AAAAAAAAAAAAAAAAARCk1OgAAAAAAAAAAAAAA/U3ihP3//////////////0p/wecT+f////////////8elGWXkwYAAAAAAAAAAAAAbccyGPz4/////////////+ZmycPDBgAAAAAAAAAAAAAASI58awAAAAAAAAAAAAAArC2A7gAAAACsLYDuAAAAAKwtgO4AAAAApwxIKwEAAABrEoqhLAAAAAAAAAAAAAAAf+nRyBMAAAAAAAAAAAAAAIagdCkZAAAAAAAAAAAAAADQH9cHJgAAAAAAAAAAAAAAc132XBgAAAAAAAAAAAAAAATX1A4SAAAAAAAAAAAAAADSZHePVgcAAAAAAAAAAAAA99MFdFYHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACE4MmozQEAAAAAAAAAAAAAHWZqWLkEAAAAAAAAAAAAACdJh8HOAQAAAAAAAAAAAADzKL56tgQAAAAAAAAAAAAAd3+9kQoAAAAAAAAAAAAAALJBWoMKAAAAJf9eiwoAAABroFyHCgAAAIv2go0KAAAAPT5dDgAAAAAEAgAAAAAAAAFRgdb/////MqOeZQAAAAAQDgAAAAAAAKCGAQAAAAAAoIYBAAAAAAAgoQcAAAAAAAAAAAAAAAAAscrx5+8FAACIP1dQJgAAAEGRyqEnAAAAJ6qeZQAAAABr7TAQAAAAAJ4lmw8AAAAAJ6qeZQAAAAAUAAAALEwAACARAABsAQAAKhoAAAAAAADcBTIAZMgAAYCLLeUAAAAAKHVdAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFiluuwDJwEAAAAAAAAAAAAAAAAAAAAAAEJUQy1QRVJQICAgICAgICAgICAgICAgICAgICAgICAgWXIm/v////8AwusLAAAAAAB0O6QLAAAAvz8ZJAAAAACLqJ5lAAAAAADKmjsAAAAAAAAAAAAAAAAAAAAAAAAAAKcPDQAAAAAA8SQAAAAAAAC9AwAAAAAAAEAfAAAAAAAATB0AANQwAAD0AQAALAEAAAAAAAAQJwAApwUAABEJAAABAAEAAAAAALX/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==");
let mut decoded_bytes = base64::decode(perp_market_str).unwrap();
let perp_market_bytes = decoded_bytes.as_mut_slice();
let key = Pubkey::default();
let owner = Pubkey::from_str("dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH").unwrap();
let mut lamports = 0;
let perp_market_account_info =
create_account_info(&key, true, &mut lamports, perp_market_bytes, &owner);
let perp_market_loader: AccountLoader<PerpMarket> =
AccountLoader::try_from(&perp_market_account_info).unwrap();
let perp_market = perp_market_loader.load_mut().unwrap();
let oracle_price = perp_market.amm.historical_oracle_data.last_oracle_price;
let slot = 240991856_u64;
let direction_to_close = PositionDirection::Short;
let base_asset_amount = BASE_PRECISION_U64;
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, 153320940);
assert_eq!(auction_end_price, -251200914);
assert_eq!(oracle_price_offset, -251200914);
assert_eq!(params.auction_duration.unwrap_or(0), 80);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
}
#[test]
fn doge() {
let perp_market_str = String::from("Ct8MLGv1N/cueW7q94VBpwLPordbGCeLrp/R8owsajNEG7L2nvhZ8NzvUN0KTNLcwX5F3xZ23LM2oRphxp33oCmbAVDGctJc8y4BAAAAAAAAAAAAAAAAAAEAAAAAAAAAiC8BAAAAAABMLwEAAAAAACmrnmUAAAAAmSxi7CT8/////////////zgrThgAAAAAAAAAAAAAAADdzXKMUwsAAAAAAAAAAAAAAAAAAAAAAADP1HhexhXAAgAAAAAAAAAAdDGk8Gq1xwIAAAAAAAAAAAzkDwAAAAAAAAAAAAAAAAAply2wnkelAgAAAAAAAAAA4qQewS2M3gIAAAAAAAAAAInzGxP44sMCAAAAAAAAAAC0KwEAAAAAAAAAAAAAAAAABtbOzyJzxgIAAAAAAAAAAACcfFCu/wYAAAAAAAAAAAAAnFHtB0b6////////////9GoMAGU/AQAAAAAAAAAAAAzNwT1RBgAAAAAAAAAAAAAAAMFv8oYjAAAAAAAAAAAABhCDPfz//////////////6bEBnzX//////////////95+qpnJAAAAAAAAAAAAAAAwQyrjdX//////////////33ohvUnAAAAAAAAAAAAAAAA/As7QZ0VAAAAAAAAAAAA8iQAAAAAAADyJAAAAAAAAPIkAAAAAAAA1wYAAAAAAABg33mwCgAAAAAAAAAAAAAABY12UwkAAAAAAAAAAAAAALwqCWEBAAAAAAAAAAAAAACQMZk6EwAAAAAAAAAAAAAAnzjKCwEAAAAAAAAAAAAAAApzcx8BAAAAAAAAAAAAAADLvbQBAAAAAAAAAAAAAAAAy720AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACHhwa6WVC6AgAAAAAAAAAASl7rdy6XzQIAAAAAAAAAAPsDHiPPL8MCAAAAAAAAAACXfZpmTpbEAgAAAAAAAAAA8y4BAAAAAAD0/////////zIuAQAAAAAATTIBAAAAAAA/MAEAAAAAAGgwAQAAAAAAgEBdDgAAAAA3AgAAAAAAAGCTe/7/////66KeZQAAAAAQDgAAAAAAAACUNXcAAAAACgAAAAAAAAAAdDukCwAAAAAAAAAAAAAAc3fY9xsAAAD1rzWPAAAAABtgqEAAAAAAdKqeZQAAAAAlAAAAAAAAAJUAAAAAAAAAKaueZQAAAAAcJQAAgDgBAF1AAAAuIgAA1QEAAAAAAAD0ATIAZGQAAQAAAAAFAAAANbUVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADzUZfxOTwAAAAAAAAAAAAAAAAAAAAAAAERPR0UtUEVSUCAgICAgICAgICAgICAgICAgICAgICAg5Nyg//////+AlpgAAAAAAAAvaFkAAAAAMZviAQAAAABXpJ5lAAAAABAnAAAAAAAAAAAAAAAAAAAAAAAAAAAAABuUAAAAAAAAFRoAAAAAAAC+CgAAAAAAAMgAAADIAAAAECcAAKhhAADoAwAA9AEAAAAAAAAQJwAA2AAAAEkBAAAHAAEAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==");
let mut decoded_bytes = base64::decode(perp_market_str).unwrap();
let perp_market_bytes = decoded_bytes.as_mut_slice();
let key = Pubkey::default();
let owner = Pubkey::from_str("dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH").unwrap();
let mut lamports = 0;
let perp_market_account_info =
create_account_info(&key, true, &mut lamports, perp_market_bytes, &owner);
let perp_market_loader: AccountLoader<PerpMarket> =
AccountLoader::try_from(&perp_market_account_info).unwrap();
let perp_market = perp_market_loader.load_mut().unwrap();
let oracle_price = perp_market.amm.historical_oracle_data.last_oracle_price;
let slot = 240991856_u64;
let direction_to_close = PositionDirection::Short;
let base_asset_amount = 100 * BASE_PRECISION_U64;
let params =
OrderParams::get_close_perp_params(&perp_market, direction_to_close, base_asset_amount)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
assert_eq!(auction_start_price, 641);
assert_eq!(auction_end_price, -1021);
assert_eq!(oracle_price_offset, -1021);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
}
fn get_order(params: &OrderParams, slot: u64) -> Order {
Order {
status: OrderStatus::Open,
order_type: params.order_type,
market_type: params.market_type,
slot,
order_id: 1,
user_order_id: params.user_order_id,
market_index: params.market_index,
price: params.price,
existing_position_direction: PositionDirection::Long,
base_asset_amount: params.base_asset_amount,
base_asset_amount_filled: 0,
quote_asset_amount_filled: 0,
direction: params.direction,
reduce_only: params.reduce_only,
trigger_price: params.trigger_price.unwrap_or(0),
trigger_condition: params.trigger_condition,
post_only: params.post_only != PostOnlyParam::None,
oracle_price_offset: params.oracle_price_offset.unwrap_or(0),
immediate_or_cancel: params.immediate_or_cancel,
auction_start_price: params.auction_start_price.unwrap_or(0),
auction_end_price: params.auction_end_price.unwrap_or(0),
auction_duration: params.auction_duration.unwrap_or(0),
max_ts: 100,
padding: [0; 3],
}
}
#[test]
fn test_default_starts_on_perp_markets() {
// BTC style market
// ideally 60 above oracle is fill
let perp_market_str = String::from("Ct8MLGv1N/cV6vWLwJY+18dY2GsrmrNldgnISB7pmbcf7cn9S4FZ4OYt9si0qF/hpn20TcEt5dszD3rGa3LcZYr+3w9KQVtDQEK8LQwAAAAAAAAAAAAAAAIAAAAAAAAATR7OKQwAAACsuhItDAAAABqp1GUAAAAA/fzP2P///////////////99h9GQEAAAAAAAAAAAAAADXOjdJzWQAAAAAAAAAAAAAAAAAAAAAAAAuI6el0QEAAAAAAAAAAAAA9u9IVNEGAAAAAAAAAAAAAJxiDwAAAAAAAAAAAAAAAABVU808zgEAAAAAAAAAAAAACeF17dUBAAAAAAAAAAAAAM6XvYCFAwAAAAAAAAAAAACWxcs/AwAAAAAAAAAAAAAAN2QGws8GAAAAAAAAAAAAAMCk9S8+AAAAAAAAAAAAAADABV1mwv//////////////5QhrawAAAAAAAAAAAAAAAJuh5yoAAAAAAAAAAAAAAAAAoNshXQAAAAAAAAAAAAAAgruloUEAAAAAAAAAAAAAAIjHhpPh8//////////////C9GHQvgsAAAAAAAAAAAAApZ+7JMPz/////////////+Wma/v1CwAAAAAAAAAAAAAAMVw41QAAAAAAAAAAAAAAcUNyaAAAAABxQ3JoAAAAAHFDcmgAAAAArY7UlAAAAACt+g88fgAAAAAAAAAAAAAAznvNmTMAAAAAAAAAAAAAAPG3DURMAAAAAAAAAAAAAACBrvFTdAAAAAAAAAAAAAAA8tmZKi8AAAAAAAAAAAAAAHvRRkAjAAAAAAAAAAAAAADNFAJImwgAAAAAAAAAAAAA8oOQLJsIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA2eHJY0QEAAAAAAAAAAAAA+XzaddIGAAAAAAAAAAAAAOf5IqvRAQAAAAAAAAAAAACqVrs/0QYAAAAAAAAAAAAAQEK8LQwAAAAAAAAAAAAAAPDx7SoMAAAAnb+iLAwAAADGWMgrDAAAAIYLIy8MAAAA+dLcDgAAAABaAgAAAAAAALM+D/7/////VaLUZQAAAAAQDgAAAAAAAKCGAQAAAAAAoIYBAAAAAAAgoQcAAAAAAAAAAAAAAAAABeZ6i7gsAAAysGg95QAAAO7ctlC7AAAAGqnUZQAAAACpe6oBAAAAAPMj7gMAAAAAGqnUZQAAAAAyAAAAHCUAABAFAABcAAAAAAAAAK0DAADcBTIAZMgAAYCLLeUAAAAAvUntAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFaHyO66xAIAAAAAAAAAAAAAAAAAAAAAAEJUQy1QRVJQICAgICAgICAgICAgICAgICAgICAgICAggA8F/f////+A8PoCAAAAAABcsuwiAAAAXd8ZJAAAAAAMo9RlAAAAAADh9QUAAAAAAAAAAAAAAAAAAAAAAAAAALgnGAAAAAAAwygAAAAAAAD5AwAAAAAAAEAfAAAAAAAATB0AANQwAAD0AQAALAEAAAAAAAAQJwAArwwAAOgWAAABAAEAAAAAALX/AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==");
let mut decoded_bytes = base64::decode(perp_market_str).unwrap();
let perp_market_bytes = decoded_bytes.as_mut_slice();
let key = Pubkey::default();
let owner = Pubkey::from_str("dRiftyHA39MWEi3m9aunc5MzRF1JYuBsbn6VPcn33UH").unwrap();
let mut lamports = 0;
let perp_market_account_info =
create_account_info(&key, true, &mut lamports, perp_market_bytes, &owner);
let perp_market_loader: AccountLoader<PerpMarket> =
AccountLoader::try_from(&perp_market_account_info).unwrap();
let perp_market = perp_market_loader.load_mut().unwrap();
let oracle_price = perp_market.amm.historical_oracle_data.last_oracle_price;
let slot = 249352956_u64;
let base_asset_amount = 100 * BASE_PRECISION_U64;
let (long_start, long_end) = OrderParams::get_perp_baseline_start_end_price_offset(
&perp_market,
PositionDirection::Long,
1,
)
.unwrap();
assert_eq!(long_start, 25635886); // $25 above
assert_eq!(long_end, 115193672); //115
let (short_start, short_end) = OrderParams::get_perp_baseline_start_end_price_offset(
&perp_market,
PositionDirection::Short,
1,
)
.unwrap();
assert_eq!(short_start, 47008307);
assert_eq!(short_end, -47075408);
let params = OrderParams::get_close_perp_params(
&perp_market,
PositionDirection::Long,
base_asset_amount,
)
.unwrap();
let auction_start_price = params.auction_start_price.unwrap();
let auction_end_price = params.auction_end_price.unwrap();
let oracle_price_offset = params.oracle_price_offset.unwrap();
let auction_duration = params.auction_duration.unwrap();
assert_eq!(auction_start_price, long_start); // $25 above
assert_eq!(auction_end_price, long_end); // 115
assert_eq!(oracle_price_offset, long_end as i32);
assert_eq!(auction_duration, 80);
let order = get_order(¶ms, slot);
validate_order(&order, &perp_market, Some(oracle_price), slot).unwrap();
}
}
#[test]
fn test_parse_optional_params() {
let (success_condition, auction_duration_percentage) = parse_optional_params(Some(0x00001234));
assert_eq!(success_condition, 0x34);
assert_eq!(auction_duration_percentage, 0x12);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/user/tests.rs
|
mod get_claimable_pnl {
use crate::math::amm::calculate_net_user_pnl;
use crate::math::constants::{
AMM_RESERVE_PRECISION, BASE_PRECISION_I64, MAX_CONCENTRATION_COEFFICIENT,
PRICE_PRECISION_I64, QUOTE_PRECISION, QUOTE_PRECISION_I128, QUOTE_PRECISION_I64,
QUOTE_SPOT_MARKET_INDEX, SPOT_BALANCE_PRECISION, SPOT_CUMULATIVE_INTEREST_PRECISION,
SPOT_WEIGHT_PRECISION,
};
use crate::math::position::calculate_base_asset_value_and_pnl_with_oracle_price;
use crate::math::spot_balance::get_token_amount;
use crate::state::oracle::OracleSource;
use crate::state::perp_market::{PerpMarket, PoolBalance, AMM};
use crate::state::spot_market::{SpotBalance, SpotMarket};
use crate::state::user::{PerpPosition, User};
use crate::test_utils::get_positions;
#[test]
fn long_negative_unrealized_pnl() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -100 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
quote_break_even_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 50 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, -50 * QUOTE_PRECISION_I128);
}
#[test]
fn long_positive_unrealized_pnl_more_than_max_pnl_to_settle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -50 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 150 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, 50 * QUOTE_PRECISION_I128);
}
#[test]
fn long_positive_unrealized_pnl_more_than_max_pnl_and_pool_excess_to_settle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -50 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 150 * PRICE_PRECISION_I64;
let (base_asset_value, unrealized_pnl) =
calculate_base_asset_value_and_pnl_with_oracle_price(
&user.perp_positions[0],
oracle_price,
)
.unwrap();
assert_eq!(base_asset_value, 150 * QUOTE_PRECISION);
assert_eq!(unrealized_pnl, 100 * QUOTE_PRECISION_I128);
let excess_pnl_pool = 49 * QUOTE_PRECISION_I128;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, excess_pnl_pool)
.unwrap();
assert_eq!(unsettled_pnl, 99 * QUOTE_PRECISION_I128);
}
#[test]
fn long_positive_unrealized_pnl_less_than_max_pnl_to_settle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -50 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 75 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, 25 * QUOTE_PRECISION_I128);
}
#[test]
fn long_positive_unrealized_pnl_less_than_max_pnl_and_pool_excess_to_settle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -50 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 75 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, QUOTE_PRECISION_I128)
.unwrap();
assert_eq!(unsettled_pnl, 25 * QUOTE_PRECISION_I128);
}
#[test]
fn long_no_negative_pnl_if_already_settled_to_oracle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -150 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
quote_break_even_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 150 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, 0);
}
#[test]
fn short_negative_unrealized_pnl() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: -BASE_PRECISION_I64,
quote_asset_amount: 100 * QUOTE_PRECISION_I64,
quote_entry_amount: 100 * QUOTE_PRECISION_I64,
quote_break_even_amount: 100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 150 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, -50 * QUOTE_PRECISION_I128);
}
#[test]
fn short_positive_unrealized_pnl_more_than_max_pnl_to_settle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: -BASE_PRECISION_I64,
quote_asset_amount: 150 * QUOTE_PRECISION_I64,
quote_entry_amount: 100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 50 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, 50 * QUOTE_PRECISION_I128);
}
#[test]
fn short_positive_unrealized_pnl_less_than_max_pnl_to_settle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: -BASE_PRECISION_I64,
quote_asset_amount: 150 * QUOTE_PRECISION_I64,
quote_entry_amount: 100 * QUOTE_PRECISION_I64,
quote_break_even_amount: 100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 125 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, 25 * QUOTE_PRECISION_I128);
}
#[test]
fn short_no_negative_pnl_if_already_settled_to_oracle() {
let user = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: -BASE_PRECISION_I64,
quote_asset_amount: 150 * QUOTE_PRECISION_I64,
quote_entry_amount: 100 * QUOTE_PRECISION_I64,
quote_break_even_amount: 100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 150 * PRICE_PRECISION_I64;
let unsettled_pnl = user.perp_positions[0]
.get_claimable_pnl(oracle_price, 0)
.unwrap();
assert_eq!(unsettled_pnl, 0);
}
#[test]
fn multiple_users_test_no_claimable() {
let usdc_market = SpotMarket {
market_index: 0,
oracle_source: OracleSource::QuoteAsset,
cumulative_deposit_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
decimals: 6,
initial_asset_weight: SPOT_WEIGHT_PRECISION,
maintenance_asset_weight: SPOT_WEIGHT_PRECISION,
deposit_balance: 1000 * SPOT_BALANCE_PRECISION,
liquidator_fee: 0,
..SpotMarket::default()
};
let perp_market = PerpMarket {
amm: AMM {
base_asset_reserve: 99 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 101 * AMM_RESERVE_PRECISION,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 150_000,
concentration_coef: MAX_CONCENTRATION_COEFFICIENT,
total_fee_minus_distributions: 1000 * QUOTE_PRECISION_I128,
curve_update_intensity: 100,
base_asset_amount_with_amm: AMM_RESERVE_PRECISION as i128,
quote_asset_amount: -100 * QUOTE_PRECISION_I128,
..AMM::default()
},
pnl_pool: PoolBalance {
scaled_balance: (10 * SPOT_BALANCE_PRECISION),
market_index: QUOTE_SPOT_MARKET_INDEX,
..PoolBalance::default()
},
..PerpMarket::default()
};
let user1 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: -BASE_PRECISION_I64,
quote_asset_amount: 150 * QUOTE_PRECISION_I64,
quote_entry_amount: 100 * QUOTE_PRECISION_I64,
quote_break_even_amount: 100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let user2 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -150 * QUOTE_PRECISION_I64,
quote_entry_amount: -50 * QUOTE_PRECISION_I64,
quote_break_even_amount: -50 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let user3 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -100 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
quote_break_even_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 150 * PRICE_PRECISION_I64;
let pnl_pool_token_amount = get_token_amount(
perp_market.pnl_pool.scaled_balance,
&usdc_market,
perp_market.pnl_pool.balance_type(),
)
.unwrap() as i128;
assert_eq!(pnl_pool_token_amount, 10000000);
let net_user_pnl = calculate_net_user_pnl(&perp_market.amm, oracle_price).unwrap();
assert_eq!(net_user_pnl, 50000000);
let max_pnl_pool_excess = if net_user_pnl < pnl_pool_token_amount {
pnl_pool_token_amount
.checked_sub(net_user_pnl.max(0))
.unwrap()
} else {
0
};
assert_eq!(max_pnl_pool_excess, 0);
let unsettled_pnl1 = user1.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(unsettled_pnl1, 0);
let unsettled_pnl2 = user2.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(unsettled_pnl2, 0);
let unsettled_pnl3 = user3.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(unsettled_pnl3, 0);
}
#[test]
fn multiple_users_test_partially_claimable_from_pnl_pool_excess() {
let usdc_market = SpotMarket {
market_index: 0,
oracle_source: OracleSource::QuoteAsset,
cumulative_deposit_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
decimals: 6,
initial_asset_weight: SPOT_WEIGHT_PRECISION,
maintenance_asset_weight: SPOT_WEIGHT_PRECISION,
deposit_balance: 1000 * SPOT_BALANCE_PRECISION,
liquidator_fee: 0,
..SpotMarket::default()
};
let mut perp_market = PerpMarket {
amm: AMM {
base_asset_reserve: 99 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 101 * AMM_RESERVE_PRECISION,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 150_000,
concentration_coef: MAX_CONCENTRATION_COEFFICIENT,
total_fee_minus_distributions: 1000 * QUOTE_PRECISION_I128,
curve_update_intensity: 100,
base_asset_amount_with_amm: AMM_RESERVE_PRECISION as i128,
quote_asset_amount: -99 * QUOTE_PRECISION_I128,
..AMM::default()
},
pnl_pool: PoolBalance {
scaled_balance: (60 * SPOT_BALANCE_PRECISION),
market_index: QUOTE_SPOT_MARKET_INDEX,
..PoolBalance::default()
},
..PerpMarket::default()
};
let user1 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: -BASE_PRECISION_I64,
quote_asset_amount: 150 * QUOTE_PRECISION_I64,
quote_entry_amount: 100 * QUOTE_PRECISION_I64,
quote_break_even_amount: 100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let user2 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -149 * QUOTE_PRECISION_I64,
quote_entry_amount: -150 * QUOTE_PRECISION_I64,
quote_break_even_amount: -150 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let user3 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -100 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
quote_break_even_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 150 * PRICE_PRECISION_I64;
let pnl_pool_token_amount = get_token_amount(
perp_market.pnl_pool.scaled_balance,
&usdc_market,
perp_market.pnl_pool.balance_type(),
)
.unwrap() as i128;
assert_eq!(pnl_pool_token_amount, 60000000);
let net_user_pnl = calculate_net_user_pnl(&perp_market.amm, oracle_price).unwrap();
assert_eq!(net_user_pnl, 51000000);
let max_pnl_pool_excess = if net_user_pnl < pnl_pool_token_amount {
pnl_pool_token_amount
.checked_sub(net_user_pnl.max(0))
.unwrap()
} else {
0
};
assert_eq!(max_pnl_pool_excess, 9_000_000);
assert_eq!(max_pnl_pool_excess - net_user_pnl, -42_000_000);
let unsettled_pnl1 = user1.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(
user1.perp_positions[0]
.get_unrealized_pnl(oracle_price)
.unwrap(),
0
);
assert_eq!(unsettled_pnl1, 0);
let unsettled_pnl2 = user2.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(
user2.perp_positions[0]
.get_unrealized_pnl(oracle_price)
.unwrap(),
1_000_000
);
assert_eq!(unsettled_pnl2, 1_000_000);
let unsettled_pnl3 = user3.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(
user3.perp_positions[0]
.get_unrealized_pnl(oracle_price)
.unwrap(),
50_000_000
);
assert_eq!(unsettled_pnl3, 9_000_000);
perp_market.amm.quote_asset_amount = -100 * QUOTE_PRECISION_I128;
let net_user_pnl = calculate_net_user_pnl(&perp_market.amm, oracle_price).unwrap();
assert_eq!(net_user_pnl, 50000000);
let max_pnl_pool_excess = if net_user_pnl < pnl_pool_token_amount {
(pnl_pool_token_amount - QUOTE_PRECISION_I128)
.checked_sub(net_user_pnl.max(0))
.unwrap()
} else {
0
};
assert_eq!(max_pnl_pool_excess, 9_000_000);
let unsettled_pnl3 = user3.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(
user3.perp_positions[0]
.get_unrealized_pnl(oracle_price)
.unwrap(),
50_000_000
);
assert_eq!(unsettled_pnl3, 9_000_000);
}
#[test]
fn multiple_users_test_fully_claimable_from_pnl_pool_excess() {
let usdc_market = SpotMarket {
market_index: 0,
oracle_source: OracleSource::QuoteAsset,
cumulative_deposit_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
decimals: 6,
initial_asset_weight: SPOT_WEIGHT_PRECISION,
maintenance_asset_weight: SPOT_WEIGHT_PRECISION,
deposit_balance: 1000 * SPOT_BALANCE_PRECISION,
liquidator_fee: 0,
..SpotMarket::default()
};
let perp_market = PerpMarket {
amm: AMM {
base_asset_reserve: 99 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 101 * AMM_RESERVE_PRECISION,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 150_000,
concentration_coef: MAX_CONCENTRATION_COEFFICIENT,
total_fee_minus_distributions: 1000 * QUOTE_PRECISION_I128,
curve_update_intensity: 100,
base_asset_amount_with_amm: AMM_RESERVE_PRECISION as i128,
quote_asset_amount: -100 * QUOTE_PRECISION_I128,
..AMM::default()
},
pnl_pool: PoolBalance {
scaled_balance: (1000 * SPOT_BALANCE_PRECISION),
market_index: 0,
..PoolBalance::default()
},
..PerpMarket::default()
};
let user1 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: -BASE_PRECISION_I64,
quote_asset_amount: 150 * QUOTE_PRECISION_I64,
quote_entry_amount: 100 * QUOTE_PRECISION_I64,
quote_break_even_amount: 100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let user2 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -150 * QUOTE_PRECISION_I64,
quote_entry_amount: -160 * QUOTE_PRECISION_I64,
quote_break_even_amount: -160 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let user3 = User {
perp_positions: get_positions(PerpPosition {
base_asset_amount: BASE_PRECISION_I64,
quote_asset_amount: -100 * QUOTE_PRECISION_I64,
quote_entry_amount: -100 * QUOTE_PRECISION_I64,
quote_break_even_amount: -100 * QUOTE_PRECISION_I64,
..PerpPosition::default()
}),
..User::default()
};
let oracle_price = 160 * PRICE_PRECISION_I64;
let pnl_pool_token_amount = get_token_amount(
perp_market.pnl_pool.scaled_balance,
&usdc_market,
perp_market.pnl_pool.balance_type(),
)
.unwrap() as i128;
assert_eq!(pnl_pool_token_amount, 1000000000);
let net_user_pnl = calculate_net_user_pnl(&perp_market.amm, oracle_price).unwrap();
assert_eq!(net_user_pnl, 60000000);
let max_pnl_pool_excess = if net_user_pnl < pnl_pool_token_amount {
pnl_pool_token_amount
.checked_sub(net_user_pnl.max(0))
.unwrap()
} else {
0
};
assert_eq!(max_pnl_pool_excess, 940000000);
assert_eq!(max_pnl_pool_excess - net_user_pnl, 880000000);
let unsettled_pnl1 = user1.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(
user1.perp_positions[0]
.get_unrealized_pnl(oracle_price)
.unwrap(),
-10000000
);
assert_eq!(unsettled_pnl1, -10000000);
let unsettled_pnl2 = user2.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(
user2.perp_positions[0]
.get_unrealized_pnl(oracle_price)
.unwrap(),
10000000
);
assert_eq!(unsettled_pnl2, 10000000);
let unsettled_pnl3 = user3.perp_positions[0]
.get_claimable_pnl(oracle_price, max_pnl_pool_excess)
.unwrap();
assert_eq!(
user3.perp_positions[0]
.get_unrealized_pnl(oracle_price)
.unwrap(),
60000000
);
assert_eq!(unsettled_pnl3, 60000000);
}
}
mod get_worst_case_fill_simulation {
use crate::math::constants::{
PRICE_PRECISION_I64, QUOTE_PRECISION_I128, SPOT_BALANCE_PRECISION_U64,
};
use crate::math::margin::MarginRequirementType;
use crate::state::oracle::{OraclePriceData, StrictOraclePrice};
use crate::state::spot_market::{SpotBalanceType, SpotMarket};
use crate::state::user::{OrderFillSimulation, SpotPosition};
#[test]
fn no_token_open_bid() {
let spot_position = SpotPosition {
market_index: 1,
balance_type: SpotBalanceType::Deposit,
scaled_balance: 0,
open_orders: 1,
open_bids: 10_i64.pow(9),
open_asks: 0,
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 80 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -20 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -110 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 110 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 88 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -22 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 80 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -20 * QUOTE_PRECISION_I128);
}
#[test]
fn no_token_open_ask() {
let spot_position = SpotPosition {
market_index: 1,
balance_type: SpotBalanceType::Deposit,
scaled_balance: 0,
open_orders: 1,
open_bids: 0,
open_asks: -(10_i64.pow(9)),
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -(10_i128.pow(9)));
assert_eq!(worst_case_orders_value, 100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -120 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -20 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -(10_i128.pow(9)));
assert_eq!(worst_case_orders_value, 110 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -110 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -132 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -22 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -(10_i128.pow(9)));
assert_eq!(worst_case_orders_value, 100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -120 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -20 * QUOTE_PRECISION_I128);
}
#[test]
fn deposit_and_open_ask() {
let spot_position = SpotPosition {
market_index: 1,
balance_type: SpotBalanceType::Deposit,
scaled_balance: 2 * SPOT_BALANCE_PRECISION_U64,
open_orders: 1,
open_bids: 0,
open_asks: -(10_i64.pow(9)),
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 2 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 0);
assert_eq!(worst_case_token_value, 200 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 160 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 160 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 2 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 0);
assert_eq!(worst_case_token_value, 200 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 160 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 160 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 2 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 0);
assert_eq!(worst_case_token_value, 180 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 144 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 144 * QUOTE_PRECISION_I128);
}
#[test]
fn deposit_and_open_ask_flips_to_borrow() {
let spot_position = SpotPosition {
market_index: 1,
balance_type: SpotBalanceType::Deposit,
scaled_balance: SPOT_BALANCE_PRECISION_U64,
open_orders: 1,
open_bids: 0,
open_asks: -2 * 10_i64.pow(9),
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -(10_i128.pow(9)));
assert_eq!(worst_case_orders_value, 200 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -120 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 80 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -(10_i128.pow(9)));
assert_eq!(worst_case_orders_value, 220 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -120 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -144 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 76 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -(10_i128.pow(9)));
assert_eq!(worst_case_orders_value, 200 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -110 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -132 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 68 * QUOTE_PRECISION_I128);
}
#[test]
fn deposit_and_open_bid() {
let spot_position = SpotPosition {
market_index: 0,
balance_type: SpotBalanceType::Deposit,
scaled_balance: 2 * SPOT_BALANCE_PRECISION_U64,
open_orders: 1,
open_bids: 10_i64.pow(9),
open_asks: 0,
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 300 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 240 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 140 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -110 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 310 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 248 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 138 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 280 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 224 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, 124 * QUOTE_PRECISION_I128);
}
#[test]
fn borrow_and_open_bid() {
let spot_position = SpotPosition {
market_index: 1,
balance_type: SpotBalanceType::Borrow,
scaled_balance: 2 * SPOT_BALANCE_PRECISION_U64,
open_orders: 1,
open_bids: 10_i64.pow(9),
open_asks: 0,
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -2 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 0);
assert_eq!(worst_case_token_value, -200 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -240 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -240 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -2 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 0);
assert_eq!(worst_case_token_value, -220 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -264 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -264 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -2 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 0);
assert_eq!(worst_case_token_value, -200 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -240 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -240 * QUOTE_PRECISION_I128);
}
#[test]
fn borrow_and_open_bid_flips_to_deposit() {
let spot_position = SpotPosition {
market_index: 1,
balance_type: SpotBalanceType::Borrow,
scaled_balance: 2 * SPOT_BALANCE_PRECISION_U64,
open_orders: 1,
open_bids: 5 * 10_i64.pow(9),
open_asks: 0,
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -500 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 300 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 240 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -260 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -550 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 330 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 264 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -286 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, 3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, -500 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, 300 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, 240 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -260 * QUOTE_PRECISION_I128);
}
#[test]
fn borrow_and_open_ask() {
let spot_position = SpotPosition {
market_index: 1,
balance_type: SpotBalanceType::Borrow,
scaled_balance: 2 * SPOT_BALANCE_PRECISION_U64,
open_orders: 1,
open_bids: 0,
open_asks: -(10_i64.pow(9)),
..SpotPosition::default()
};
let spot_market = SpotMarket::default_base_market();
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
confidence: 1,
delay: 0,
has_sufficient_number_of_data_points: true,
};
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: None,
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -300 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -360 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -260 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(110 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 110 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -330 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -396 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -286 * QUOTE_PRECISION_I128);
let strict_price = StrictOraclePrice {
current: oracle_price_data.price,
twap_5min: Some(90 * PRICE_PRECISION_I64),
};
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: worst_case_weighted_token_value,
free_collateral_contribution,
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_price,
None,
MarginRequirementType::Initial,
)
.unwrap();
assert_eq!(worst_case_token_amount, -3 * 10_i128.pow(9));
assert_eq!(worst_case_orders_value, 100 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_token_value, -300 * QUOTE_PRECISION_I128);
assert_eq!(worst_case_weighted_token_value, -360 * QUOTE_PRECISION_I128);
assert_eq!(free_collateral_contribution, -260 * QUOTE_PRECISION_I128);
}
}
mod apply_user_custom_margin_ratio {
use crate::math::constants::{PRICE_PRECISION_I64, QUOTE_PRECISION_I128};
use crate::state::spot_market::SpotMarket;
use crate::state::user::OrderFillSimulation;
use crate::MARGIN_PRECISION;
#[test]
fn test() {
let sol = SpotMarket::default_base_market();
let oracle_price = 100 * PRICE_PRECISION_I64;
let custom_margin_ratio = MARGIN_PRECISION / 2; // 2x
let deposit = OrderFillSimulation {
token_value: 100 * QUOTE_PRECISION_I128,
weighted_token_value: 80 * QUOTE_PRECISION_I128,
free_collateral_contribution: 80 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let expected = OrderFillSimulation {
token_value: 100 * QUOTE_PRECISION_I128,
weighted_token_value: 50 * QUOTE_PRECISION_I128,
free_collateral_contribution: 50 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let actual = deposit
.apply_user_custom_margin_ratio(&sol, oracle_price, custom_margin_ratio)
.unwrap();
assert_eq!(actual, expected);
let borrow = OrderFillSimulation {
token_value: -100 * QUOTE_PRECISION_I128,
weighted_token_value: -120 * QUOTE_PRECISION_I128,
free_collateral_contribution: -120 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let expected = OrderFillSimulation {
token_value: -100 * QUOTE_PRECISION_I128,
weighted_token_value: -150 * QUOTE_PRECISION_I128,
free_collateral_contribution: -150 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let actual = borrow
.apply_user_custom_margin_ratio(&sol, oracle_price, custom_margin_ratio)
.unwrap();
assert_eq!(actual, expected);
let bid = OrderFillSimulation {
token_value: 100 * QUOTE_PRECISION_I128,
weighted_token_value: 80 * QUOTE_PRECISION_I128,
orders_value: -100 * QUOTE_PRECISION_I128,
free_collateral_contribution: -20 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let expected = OrderFillSimulation {
token_value: 100 * QUOTE_PRECISION_I128,
weighted_token_value: 50 * QUOTE_PRECISION_I128,
free_collateral_contribution: -50 * QUOTE_PRECISION_I128,
orders_value: -100 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let actual = bid
.apply_user_custom_margin_ratio(&sol, oracle_price, custom_margin_ratio)
.unwrap();
assert_eq!(actual, expected);
let ask = OrderFillSimulation {
token_value: -100 * QUOTE_PRECISION_I128,
weighted_token_value: -120 * QUOTE_PRECISION_I128,
free_collateral_contribution: -20 * QUOTE_PRECISION_I128,
orders_value: 100 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let expected = OrderFillSimulation {
token_value: -100 * QUOTE_PRECISION_I128,
weighted_token_value: -150 * QUOTE_PRECISION_I128,
free_collateral_contribution: -50 * QUOTE_PRECISION_I128,
orders_value: 100 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let actual = ask
.apply_user_custom_margin_ratio(&sol, oracle_price, custom_margin_ratio)
.unwrap();
assert_eq!(actual, expected);
let no_custom_margin_ratio = OrderFillSimulation {
token_value: -100 * QUOTE_PRECISION_I128,
weighted_token_value: -120 * QUOTE_PRECISION_I128,
free_collateral_contribution: -20 * QUOTE_PRECISION_I128,
orders_value: 100 * QUOTE_PRECISION_I128,
..OrderFillSimulation::default()
};
let expected = no_custom_margin_ratio;
let actual = no_custom_margin_ratio
.apply_user_custom_margin_ratio(&sol, oracle_price, 0)
.unwrap();
assert_eq!(actual, expected);
}
}
mod get_base_asset_amount_unfilled {
use crate::controller::position::PositionDirection;
use crate::state::user::Order;
#[test]
fn existing_position_is_none() {
let order = Order {
base_asset_amount: 1,
base_asset_amount_filled: 0,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(None).unwrap(), 1)
}
#[test]
fn order_is_not_reduce_only() {
let order = Order {
base_asset_amount: 1,
base_asset_amount_filled: 0,
reduce_only: false,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(1)).unwrap(), 1)
}
#[test]
fn order_is_reduce_only_and_post_only() {
let order = Order {
base_asset_amount: 1,
base_asset_amount_filled: 0,
reduce_only: true,
post_only: true,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(1)).unwrap(), 1)
}
#[test]
fn no_existing_position() {
let order = Order {
base_asset_amount: 1,
base_asset_amount_filled: 0,
reduce_only: true,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(0)).unwrap(), 0)
}
#[test]
fn bid_with_long_existing_position() {
let order = Order {
base_asset_amount: 1,
base_asset_amount_filled: 0,
reduce_only: true,
direction: PositionDirection::Long,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(1)).unwrap(), 0)
}
#[test]
fn bid_with_smaller_short_existing_position() {
let order = Order {
base_asset_amount: 5,
base_asset_amount_filled: 0,
reduce_only: true,
direction: PositionDirection::Long,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(-3)).unwrap(), 3)
}
#[test]
fn bid_with_larger_short_existing_position() {
let order = Order {
base_asset_amount: 5,
base_asset_amount_filled: 0,
reduce_only: true,
direction: PositionDirection::Long,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(-6)).unwrap(), 5)
}
#[test]
fn ask_with_short_existing_position() {
let order = Order {
base_asset_amount: 1,
base_asset_amount_filled: 0,
reduce_only: true,
direction: PositionDirection::Short,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(-1)).unwrap(), 0)
}
#[test]
fn ask_with_smaller_long_existing_position() {
let order = Order {
base_asset_amount: 5,
base_asset_amount_filled: 0,
reduce_only: true,
direction: PositionDirection::Short,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(3)).unwrap(), 3)
}
#[test]
fn ask_with_larger_long_existing_position() {
let order = Order {
base_asset_amount: 5,
base_asset_amount_filled: 0,
reduce_only: true,
direction: PositionDirection::Short,
..Order::default()
};
assert_eq!(order.get_base_asset_amount_unfilled(Some(6)).unwrap(), 5)
}
}
mod open_orders {
use crate::state::user::User;
#[test]
fn test() {
let mut user = User::default();
user.increment_open_orders(false);
assert_eq!(user.open_orders, 1);
assert!(user.has_open_order);
assert_eq!(user.open_auctions, 0);
assert!(!user.has_open_auction);
user.increment_open_orders(true);
assert_eq!(user.open_orders, 2);
assert!(user.has_open_order);
assert_eq!(user.open_auctions, 1);
assert!(user.has_open_auction);
user.decrement_open_orders(false);
assert_eq!(user.open_orders, 1);
assert!(user.has_open_order);
assert_eq!(user.open_auctions, 1);
assert!(user.has_open_auction);
user.decrement_open_orders(true);
assert_eq!(user.open_orders, 0);
assert!(!user.has_open_order);
assert_eq!(user.open_auctions, 0);
assert!(!user.has_open_auction);
}
}
mod update_user_status {
use crate::state::user::{User, UserStatus};
#[test]
fn test() {
let mut user = User::default();
assert_eq!(user.status, 0);
user.enter_liquidation(0).unwrap();
assert_eq!(user.status, UserStatus::BeingLiquidated as u8);
assert!(user.is_being_liquidated());
user.enter_bankruptcy();
assert_eq!(user.status, UserStatus::Bankrupt as u8);
assert!(user.is_being_liquidated());
assert!(user.is_bankrupt());
let mut user = User {
status: UserStatus::ReduceOnly as u8,
..User::default()
};
user.enter_liquidation(0).unwrap();
assert!(user.is_being_liquidated());
assert!(user.status & UserStatus::ReduceOnly as u8 > 0);
user.enter_bankruptcy();
assert!(user.is_being_liquidated());
assert!(user.is_bankrupt());
assert!(user.status & UserStatus::ReduceOnly as u8 > 0);
user.exit_liquidation();
assert!(!user.is_being_liquidated());
assert!(!user.is_bankrupt());
assert!(user.status & UserStatus::ReduceOnly as u8 > 0);
}
}
mod resting_limit_order {
use crate::state::user::{Order, OrderType};
use crate::PositionDirection;
#[test]
fn test() {
let order = Order {
order_type: OrderType::Market,
..Order::default()
};
let slot = 0;
assert!(!order.is_resting_limit_order(slot).unwrap());
let order = Order {
order_type: OrderType::TriggerMarket,
..Order::default()
};
assert!(!order.is_resting_limit_order(slot).unwrap());
let order = Order {
order_type: OrderType::Oracle,
..Order::default()
};
assert!(!order.is_resting_limit_order(slot).unwrap());
// limit order before end of auction
let order = Order {
order_type: OrderType::Limit,
post_only: false,
auction_duration: 10,
slot: 1,
..Order::default()
};
let slot = 2;
assert!(!order.is_resting_limit_order(slot).unwrap());
// limit order after end of auction
let order = Order {
order_type: OrderType::Limit,
post_only: false,
auction_duration: 10,
slot: 1,
..Order::default()
};
let slot = 12;
assert!(order.is_resting_limit_order(slot).unwrap());
// limit order post only
let order = Order {
order_type: OrderType::Limit,
post_only: true,
..Order::default()
};
let slot = 1;
assert!(order.is_resting_limit_order(slot).unwrap());
// trigger order long crosses trigger, auction complete
let order = Order {
order_type: OrderType::TriggerLimit,
direction: PositionDirection::Long,
trigger_price: 100,
price: 110,
slot: 1,
auction_duration: 10,
..Order::default()
};
let slot = 12;
assert!(order.is_resting_limit_order(slot).unwrap());
// trigger order long doesnt cross trigger, auction complete
let order = Order {
order_type: OrderType::TriggerLimit,
direction: PositionDirection::Long,
trigger_price: 100,
price: 90,
slot: 1,
auction_duration: 10,
..Order::default()
};
let slot = 12;
assert!(order.is_resting_limit_order(slot).unwrap());
// trigger order short crosses trigger, auction complete
let order = Order {
order_type: OrderType::TriggerLimit,
direction: PositionDirection::Short,
trigger_price: 100,
price: 90,
slot: 1,
auction_duration: 10,
..Order::default()
};
let slot = 12;
assert!(order.is_resting_limit_order(slot).unwrap());
// trigger order long doesnt cross trigger, auction complete
let order = Order {
order_type: OrderType::TriggerLimit,
direction: PositionDirection::Short,
trigger_price: 100,
price: 110,
slot: 1,
auction_duration: 10,
..Order::default()
};
let slot = 12;
assert!(order.is_resting_limit_order(slot).unwrap());
}
}
mod get_user_stats_age_ts {
use crate::state::user::UserStats;
#[test]
fn test() {
let user_stats = UserStats::default();
let now = 1;
let age = user_stats.get_age_ts(now);
assert_eq!(age, 1);
let user_stats = UserStats {
last_filler_volume_30d_ts: 2,
last_maker_volume_30d_ts: 3,
last_taker_volume_30d_ts: 4,
..UserStats::default()
};
let now = 5;
let age = user_stats.get_age_ts(now);
assert_eq!(age, 3);
let now = 1;
let age = user_stats.get_age_ts(now);
assert_eq!(age, 0);
}
}
mod fuel {
use crate::state::user::UserStats;
use crate::QUOTE_PRECISION_U64;
#[test]
fn test() {
let mut user_stats = UserStats::default();
user_stats
.update_fuel_maker_bonus(0, QUOTE_PRECISION_U64)
.unwrap();
assert_eq!(user_stats.fuel_maker, 0);
user_stats
.update_fuel_maker_bonus(1, QUOTE_PRECISION_U64)
.unwrap();
assert_eq!(user_stats.fuel_maker, 1);
user_stats
.update_fuel_taker_bonus(0, QUOTE_PRECISION_U64)
.unwrap();
assert_eq!(user_stats.fuel_taker, 0);
user_stats
.update_fuel_taker_bonus(1, QUOTE_PRECISION_U64)
.unwrap();
assert_eq!(user_stats.fuel_taker, 1);
}
}
mod worst_case_liability_value {
use crate::state::perp_market::ContractType;
use crate::state::user::PerpPosition;
use crate::{
BASE_PRECISION_I128, BASE_PRECISION_I64, MAX_PREDICTION_MARKET_PRICE_I64,
MAX_PREDICTION_MARKET_PRICE_U128, PRICE_PRECISION_I64, QUOTE_PRECISION,
};
#[test]
fn prediction() {
let contract_type = ContractType::Prediction;
let position = PerpPosition {
base_asset_amount: 0,
open_bids: BASE_PRECISION_I64,
open_asks: -BASE_PRECISION_I64,
..PerpPosition::default()
};
let price = MAX_PREDICTION_MARKET_PRICE_I64 * 3 / 4;
let (worst_case_base_asset_amount, worst_case_loss) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, BASE_PRECISION_I128);
assert_eq!(worst_case_loss, MAX_PREDICTION_MARKET_PRICE_U128 * 3 / 4);
let price = MAX_PREDICTION_MARKET_PRICE_I64 / 4;
let (worst_case_base_asset_amount, worst_case_loss) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, -BASE_PRECISION_I128);
assert_eq!(worst_case_loss, MAX_PREDICTION_MARKET_PRICE_U128 * 3 / 4);
let position = PerpPosition {
base_asset_amount: 98 * BASE_PRECISION_I64,
open_bids: 0,
open_asks: -99 * BASE_PRECISION_I64,
..PerpPosition::default()
};
let price = MAX_PREDICTION_MARKET_PRICE_I64 / 100;
let (worst_case_base_asset_amount, worst_case_loss) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, -BASE_PRECISION_I128);
assert_eq!(worst_case_loss, MAX_PREDICTION_MARKET_PRICE_U128 * 99 / 100);
let position = PerpPosition {
base_asset_amount: -98 * BASE_PRECISION_I64,
open_bids: 99 * BASE_PRECISION_I64,
open_asks: 0,
..PerpPosition::default()
};
let price = MAX_PREDICTION_MARKET_PRICE_I64 * 99 / 100;
let (worst_case_base_asset_amount, worst_case_loss) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, BASE_PRECISION_I128);
assert_eq!(worst_case_loss, MAX_PREDICTION_MARKET_PRICE_U128 * 99 / 100);
}
#[test]
fn perp() {
let contract_type = ContractType::Perpetual;
let position = PerpPosition {
base_asset_amount: 0,
open_bids: BASE_PRECISION_I64,
open_asks: -BASE_PRECISION_I64,
..PerpPosition::default()
};
let price = 100 * PRICE_PRECISION_I64;
let (worst_case_base_asset_amount, worst_case_liability) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, -BASE_PRECISION_I128);
assert_eq!(worst_case_liability, 100 * QUOTE_PRECISION);
let contract_type = ContractType::Perpetual;
let position = PerpPosition {
base_asset_amount: 0,
open_bids: 2 * BASE_PRECISION_I64,
open_asks: -BASE_PRECISION_I64,
..PerpPosition::default()
};
let price = 100 * PRICE_PRECISION_I64;
let (worst_case_base_asset_amount, worst_case_liability) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, 2 * BASE_PRECISION_I128);
assert_eq!(worst_case_liability, 200 * QUOTE_PRECISION);
let position = PerpPosition {
base_asset_amount: 98 * BASE_PRECISION_I64,
open_bids: 0,
open_asks: -99 * BASE_PRECISION_I64,
..PerpPosition::default()
};
let price = 100 * PRICE_PRECISION_I64;
let (worst_case_base_asset_amount, worst_case_loss) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, 98 * BASE_PRECISION_I128);
assert_eq!(worst_case_loss, 98 * 100 * QUOTE_PRECISION);
let position = PerpPosition {
base_asset_amount: -98 * BASE_PRECISION_I64,
open_bids: 99 * BASE_PRECISION_I64,
open_asks: 0,
..PerpPosition::default()
};
let price = 100 * PRICE_PRECISION_I64;
let (worst_case_base_asset_amount, worst_case_loss) = position
.worst_case_liability_value(price, contract_type)
.unwrap();
assert_eq!(worst_case_base_asset_amount, -98 * BASE_PRECISION_I128);
assert_eq!(worst_case_loss, 98 * 100 * QUOTE_PRECISION);
}
}
mod get_limit_price {
use crate::state::user::{Order, OrderType};
use crate::{PositionDirection, MAX_PREDICTION_MARKET_PRICE, MAX_PREDICTION_MARKET_PRICE_I64};
#[test]
fn prediction_market() {
let order = Order {
order_type: OrderType::Limit,
oracle_price_offset: MAX_PREDICTION_MARKET_PRICE as i32,
..Order::default()
};
let oracle_price = Some(MAX_PREDICTION_MARKET_PRICE_I64 / 2);
let limit_price = order
.get_limit_price(oracle_price, None, 0, 1, true)
.unwrap();
assert_eq!(limit_price, Some(MAX_PREDICTION_MARKET_PRICE));
let order = Order {
order_type: OrderType::Limit,
oracle_price_offset: -(MAX_PREDICTION_MARKET_PRICE as i32),
..Order::default()
};
let limit_price = order
.get_limit_price(oracle_price, None, 0, 1, true)
.unwrap();
assert_eq!(limit_price, Some(1));
let order = Order {
order_type: OrderType::Oracle,
auction_start_price: MAX_PREDICTION_MARKET_PRICE_I64,
auction_end_price: MAX_PREDICTION_MARKET_PRICE_I64,
oracle_price_offset: MAX_PREDICTION_MARKET_PRICE as i32,
slot: 1,
auction_duration: 10,
..Order::default()
};
let limit_price = order
.get_limit_price(oracle_price, None, 2, 1, true)
.unwrap();
assert_eq!(limit_price, Some(MAX_PREDICTION_MARKET_PRICE));
let order = Order {
order_type: OrderType::Oracle,
direction: PositionDirection::Short,
auction_start_price: -MAX_PREDICTION_MARKET_PRICE_I64,
auction_end_price: -MAX_PREDICTION_MARKET_PRICE_I64,
oracle_price_offset: -(MAX_PREDICTION_MARKET_PRICE as i32),
slot: 1,
auction_duration: 10,
..Order::default()
};
let limit_price = order
.get_limit_price(oracle_price, None, 2, 1, true)
.unwrap();
assert_eq!(limit_price, Some(1));
}
}
mod update_referrer_status {
use anchor_lang::prelude::Pubkey;
use crate::state::user::{ReferrerStatus, UserStats};
#[test]
fn test() {
let mut user_stats = UserStats {
referrer: Pubkey::new_unique(),
referrer_status: 0,
..UserStats::default()
};
user_stats.update_referrer_status();
assert_eq!(user_stats.referrer_status, ReferrerStatus::IsReferred as u8);
let mut user_stats = UserStats {
referrer: Pubkey::default(),
referrer_status: ReferrerStatus::IsReferred as u8,
..UserStats::default()
};
user_stats.update_referrer_status();
assert_eq!(user_stats.referrer_status, 0);
let mut user_stats = UserStats {
referrer: Pubkey::default(),
referrer_status: 3,
..UserStats::default()
};
user_stats.update_referrer_status();
assert_eq!(user_stats.referrer_status, 1);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/state/tests.rs
|
mod get_init_user_fee {
use crate::State;
#[test]
fn it_works() {
let state = State::default();
let init_user_fee = state.get_init_user_fee().unwrap();
assert_eq!(init_user_fee, 0);
let state = State {
max_initialize_user_fee: 1,
max_number_of_sub_accounts: 10,
number_of_sub_accounts: 800,
..State::default()
};
let max_number_of_sub_accounts = state.max_number_of_sub_accounts();
assert_eq!(max_number_of_sub_accounts, 1000);
let init_user_fee = state.get_init_user_fee().unwrap();
assert_eq!(init_user_fee, 0);
let state = State {
max_initialize_user_fee: 1,
max_number_of_sub_accounts: 10,
number_of_sub_accounts: 900,
..State::default()
};
let init_user_fee = state.get_init_user_fee().unwrap();
assert_eq!(init_user_fee, 5000000);
let state = State {
max_initialize_user_fee: 1,
max_number_of_sub_accounts: 10,
number_of_sub_accounts: 1000,
..State::default()
};
let init_user_fee = state.get_init_user_fee().unwrap();
assert_eq!(init_user_fee, 10000000);
let state = State {
max_initialize_user_fee: 100,
max_number_of_sub_accounts: 10,
number_of_sub_accounts: 1000,
..State::default()
};
let init_user_fee = state.get_init_user_fee().unwrap();
assert_eq!(init_user_fee, 1000000000);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/perp_market/tests.rs
|
mod amm {
use crate::state::perp_market::AMM;
use crate::{
AMM_RESERVE_PRECISION, BID_ASK_SPREAD_PRECISION, PEG_PRECISION, PRICE_PRECISION_I64,
};
#[test]
fn last_ask_premium() {
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 10) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 10) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
..AMM::default()
};
amm.historical_oracle_data.last_oracle_price = 100 * PRICE_PRECISION_I64;
let premium = amm.last_ask_premium().unwrap();
assert_eq!(premium, 10000000); // $1
}
#[test]
fn last_bid_discount() {
let mut amm = AMM {
base_asset_reserve: 100 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 100 * AMM_RESERVE_PRECISION,
short_spread: (BID_ASK_SPREAD_PRECISION / 10) as u32,
long_spread: (BID_ASK_SPREAD_PRECISION / 10) as u32,
sqrt_k: 100 * AMM_RESERVE_PRECISION,
peg_multiplier: 100 * PEG_PRECISION,
..AMM::default()
};
amm.historical_oracle_data.last_oracle_price = 100 * PRICE_PRECISION_I64;
let discount = amm.last_bid_discount().unwrap();
assert_eq!(discount, 10000000); // $1
}
}
mod get_margin_ratio {
use crate::math::margin::MarginRequirementType;
use crate::state::perp_market::PerpMarket;
use crate::state::user::MarginMode;
use crate::{BASE_PRECISION, MARGIN_PRECISION, MAX_MARGIN_RATIO};
#[test]
fn test() {
let perp_market = PerpMarket {
margin_ratio_initial: MARGIN_PRECISION / 10,
margin_ratio_maintenance: MARGIN_PRECISION / 20,
..PerpMarket::default()
};
let margin_ratio_initial = perp_market
.get_margin_ratio(BASE_PRECISION, MarginRequirementType::Initial, false)
.unwrap();
let margin_ratio_maintenance = perp_market
.get_margin_ratio(BASE_PRECISION, MarginRequirementType::Maintenance, false)
.unwrap();
let margin_ratio_fill = perp_market
.get_margin_ratio(BASE_PRECISION, MarginRequirementType::Fill, false)
.unwrap();
assert_eq!(margin_ratio_initial, MARGIN_PRECISION / 10);
assert_eq!(
margin_ratio_fill,
(MARGIN_PRECISION / 10 + MARGIN_PRECISION / 20) / 2
);
assert_eq!(margin_ratio_maintenance, MARGIN_PRECISION / 20);
let perp_market = PerpMarket {
margin_ratio_initial: MARGIN_PRECISION / 10,
margin_ratio_maintenance: MARGIN_PRECISION / 20,
high_leverage_margin_ratio_initial: MARGIN_PRECISION as u16 / 50,
high_leverage_margin_ratio_maintenance: MARGIN_PRECISION as u16 / 100,
..PerpMarket::default()
};
let margin_ratio_initial = perp_market
.get_margin_ratio(BASE_PRECISION, MarginRequirementType::Initial, true)
.unwrap();
let margin_ratio_maintenance = perp_market
.get_margin_ratio(BASE_PRECISION, MarginRequirementType::Maintenance, true)
.unwrap();
let margin_ratio_fill = perp_market
.get_margin_ratio(BASE_PRECISION, MarginRequirementType::Fill, true)
.unwrap();
assert_eq!(margin_ratio_initial, MARGIN_PRECISION / 50);
assert_eq!(
margin_ratio_fill,
(MARGIN_PRECISION / 50 + MARGIN_PRECISION / 100) / 2
);
assert_eq!(margin_ratio_maintenance, MARGIN_PRECISION / 100);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/swift_user/tests.rs
|
#[cfg(test)]
mod swift_order_id_eviction {
use std::cell::{Ref, RefCell};
use anchor_lang::prelude::Pubkey;
use borsh::BorshSerialize;
use crate::{
error::ErrorCode,
state::swift_user::{
SwiftOrderId, SwiftUserOrders, SwiftUserOrdersFixed, SwiftUserOrdersZeroCopy,
SwiftUserOrdersZeroCopyMut,
},
};
#[test]
fn swift_order_id_exists() {
let fixed = RefCell::new(SwiftUserOrdersFixed {
user_pubkey: Pubkey::default(),
padding: 0,
len: 32,
});
let data = RefCell::new([0u8; 768]);
let mut swift_user = SwiftUserOrdersZeroCopyMut {
fixed: fixed.borrow_mut(),
data: data.borrow_mut(),
};
let new_swift_order_id = SwiftOrderId::new([7; 8], 10, 2);
let add_result = swift_user.add_swift_order_id(new_swift_order_id);
assert!(add_result.is_ok());
assert_eq!(
swift_user.check_exists_and_prune_stale_swift_order_ids(new_swift_order_id, 11),
true
);
assert_eq!(
swift_user.check_exists_and_prune_stale_swift_order_ids(new_swift_order_id, 20),
true
);
assert_eq!(
swift_user.check_exists_and_prune_stale_swift_order_ids(new_swift_order_id, 30),
false
);
let mut count = 0;
for i in 0..32 {
if swift_user.get_mut(i).uuid == new_swift_order_id.uuid {
count += 1;
}
}
assert_eq!(count, 0);
}
#[test]
fn swift_user_order_account_full() {
let fixed = RefCell::new(SwiftUserOrdersFixed {
user_pubkey: Pubkey::default(),
padding: 0,
len: 32,
});
let swift_order_data: [SwiftOrderId; 32] = [SwiftOrderId::new([7; 8], 10, 1); 32];
let mut byte_array = [0u8; 768];
for (i, order) in swift_order_data.iter().enumerate() {
let start = i * 24;
let end = start + 24;
byte_array[start..end].copy_from_slice(&order.try_to_vec().unwrap());
}
let data = RefCell::new(byte_array);
let mut swift_user = SwiftUserOrdersZeroCopyMut {
fixed: fixed.borrow_mut(),
data: data.borrow_mut(),
};
let new_swift_order_id = SwiftOrderId::new([7; 8], 10, 2);
let add_result = swift_user.add_swift_order_id(new_swift_order_id);
assert!(add_result.is_err());
assert_eq!(
add_result.err().unwrap(),
ErrorCode::SwiftUserOrdersAccountFull
);
}
#[test]
fn bad_swift_order_ids() {
let fixed = RefCell::new(SwiftUserOrdersFixed {
user_pubkey: Pubkey::default(),
padding: 0,
len: 32,
});
let swift_order_data: [SwiftOrderId; 32] = [SwiftOrderId::new([7; 8], 10, 1); 32];
let mut byte_array = [0u8; 768];
for (i, order) in swift_order_data.iter().enumerate() {
let start = i * 24;
let end = start + 24;
byte_array[start..end].copy_from_slice(&order.try_to_vec().unwrap());
}
let data = RefCell::new(byte_array);
let mut swift_user = SwiftUserOrdersZeroCopyMut {
fixed: fixed.borrow_mut(),
data: data.borrow_mut(),
};
let new_swift_order_id = SwiftOrderId::new([7; 8], 10, 0);
let add_result = swift_user.add_swift_order_id(new_swift_order_id);
assert!(add_result.is_err());
assert_eq!(add_result.err().unwrap(), ErrorCode::InvalidSwiftOrderId);
let new_swift_order_id = SwiftOrderId::new([0; 8], 10, 10);
let add_result = swift_user.add_swift_order_id(new_swift_order_id);
assert!(add_result.is_err());
assert_eq!(add_result.err().unwrap(), ErrorCode::InvalidSwiftOrderId);
let new_swift_order_id = SwiftOrderId::new([7; 8], 0, 10);
let add_result = swift_user.add_swift_order_id(new_swift_order_id);
assert!(add_result.is_err());
assert_eq!(add_result.err().unwrap(), ErrorCode::InvalidSwiftOrderId);
}
}
#[cfg(test)]
mod zero_copy {
use std::cell::RefCell;
use crate::test_utils::create_account_info;
use crate::ID;
use anchor_lang::{prelude::Pubkey, Discriminator};
use borsh::BorshSerialize;
use crate::{
error::ErrorCode,
state::swift_user::{SwiftOrderId, SwiftUserOrders, SwiftUserOrdersLoader},
};
#[test]
fn zero_copy() {
let mut orders: SwiftUserOrders = SwiftUserOrders {
user_pubkey: Pubkey::default(),
padding: 0,
swift_order_data: Vec::with_capacity(100),
};
for i in 0..100 {
orders.swift_order_data.push(SwiftOrderId {
uuid: [0; 8],
max_slot: 0,
order_id: i as u32,
padding: 0,
});
}
let mut bytes = Vec::with_capacity(8 + orders.try_to_vec().unwrap().len());
bytes.extend_from_slice(&SwiftUserOrders::discriminator());
bytes.extend_from_slice(&orders.try_to_vec().unwrap());
let pubkey = Pubkey::default();
let mut lamports = 0;
let orders_account_info =
create_account_info(&pubkey, false, &mut lamports, &mut bytes, &ID);
let orders_zero_copy = orders_account_info.load().unwrap();
assert_eq!(orders_zero_copy.fixed.len, 100);
for i in 0..100 {
println!("i {}", i);
assert_eq!(
orders_zero_copy.get(i),
&SwiftOrderId {
uuid: [0; 8],
max_slot: 0,
order_id: i as u32,
padding: 0,
}
);
}
drop(orders_zero_copy);
// invalid owner
let random_pubkey = Pubkey::new_unique();
let orders_account_info = create_account_info(
&random_pubkey,
false,
&mut lamports,
&mut bytes,
&random_pubkey,
);
let result = orders_account_info.load();
assert!(result.is_err());
assert_eq!(result.err().unwrap(), ErrorCode::DefaultError);
// invalid discriminator
let mut bytes = Vec::with_capacity(8 + orders.try_to_vec().unwrap().len());
bytes.extend_from_slice(&orders.try_to_vec().unwrap());
bytes.extend_from_slice(&SwiftUserOrders::discriminator());
let orders_account_info =
create_account_info(&random_pubkey, false, &mut lamports, &mut bytes, &ID);
let result = orders_account_info.load();
assert!(result.is_err());
assert_eq!(result.err().unwrap(), ErrorCode::DefaultError);
}
#[test]
fn zero_copy_mut() {
let mut orders: SwiftUserOrders = SwiftUserOrders {
user_pubkey: Pubkey::default(),
padding: 0,
swift_order_data: Vec::with_capacity(100),
};
for i in 0..100 {
orders.swift_order_data.push(SwiftOrderId {
uuid: [0; 8],
max_slot: 0,
order_id: i as u32,
padding: 0,
});
}
let mut bytes = Vec::with_capacity(8 + orders.try_to_vec().unwrap().len());
bytes.extend_from_slice(&SwiftUserOrders::discriminator());
bytes.extend_from_slice(&orders.try_to_vec().unwrap());
let pubkey = Pubkey::default();
let mut lamports = 0;
let mut orders_account_info =
create_account_info(&pubkey, true, &mut lamports, &mut bytes, &ID);
let mut orders_zero_copy_mut = orders_account_info.load_mut().unwrap();
assert_eq!(orders_zero_copy_mut.fixed.len, 100);
for i in 0..100 {
println!("i {}", i);
assert_eq!(
orders_zero_copy_mut.get_mut(i),
&SwiftOrderId {
uuid: [0; 8],
max_slot: 0,
order_id: i as u32,
padding: 0,
}
);
}
drop(orders_zero_copy_mut);
// invalid owner
let random_pubkey = Pubkey::new_unique();
let mut orders_account_info = create_account_info(
&random_pubkey,
true,
&mut lamports,
&mut bytes,
&random_pubkey,
);
let result = orders_account_info.load_mut();
assert!(result.is_err());
assert_eq!(result.err().unwrap(), ErrorCode::DefaultError);
// invalid discriminator
let mut bytes = Vec::with_capacity(8 + orders.try_to_vec().unwrap().len());
bytes.extend_from_slice(&orders.try_to_vec().unwrap());
bytes.extend_from_slice(&SwiftUserOrders::discriminator());
let mut orders_account_info =
create_account_info(&random_pubkey, true, &mut lamports, &mut bytes, &ID);
let result = orders_account_info.load_mut();
assert!(result.is_err());
assert_eq!(result.err().unwrap(), ErrorCode::DefaultError);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/state/settle_pnl_mode/tests.rs
|
mod test {
use crate::error::ErrorCode;
use crate::SettlePnlMode;
#[test]
fn test_must_settle_returns_err() {
let mode = SettlePnlMode::MustSettle;
let result = mode.result(ErrorCode::DefaultError, 0, "Must settle error");
assert_eq!(result, Err(ErrorCode::DefaultError));
}
#[test]
fn test_try_settle_returns_ok() {
let mode = SettlePnlMode::TrySettle;
let result = mode.result(ErrorCode::DefaultError, 0, "Try settle error");
assert_eq!(result, Ok(()));
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/orders.rs
|
use std::cmp::min;
use std::ops::Sub;
use solana_program::msg;
use crate::controller::position::PositionDelta;
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode};
use crate::math::amm::calculate_amm_available_liquidity;
use crate::math::auction::is_amm_available_liquidity_source;
use crate::math::casting::Cast;
use crate::state::fill_mode::FillMode;
use crate::{
load, math, FeeTier, State, BASE_PRECISION_I128, FEE_ADJUSTMENT_MAX,
MAX_PREDICTION_MARKET_PRICE, MAX_PREDICTION_MARKET_PRICE_I64, OPEN_ORDER_MARGIN_REQUIREMENT,
PERCENTAGE_PRECISION, PERCENTAGE_PRECISION_U64, PRICE_PRECISION_I128, PRICE_PRECISION_U64,
QUOTE_PRECISION_I128, SPOT_WEIGHT_PRECISION, SPOT_WEIGHT_PRECISION_I128,
};
use crate::math::constants::MARGIN_PRECISION_U128;
use crate::math::margin::{
calculate_margin_requirement_and_total_collateral_and_liability_info, MarginRequirementType,
};
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::get_strict_token_value;
use crate::math::spot_withdraw::get_max_withdraw_for_market_with_token_amount;
use crate::math_error;
use crate::print_error;
use crate::state::margin_calculation::{MarginCalculation, MarginContext};
use crate::state::oracle::{OraclePriceData, StrictOraclePrice};
use crate::state::oracle_map::OracleMap;
use crate::state::order_params::PostOnlyParam;
use crate::state::perp_market::{PerpMarket, AMM};
use crate::state::perp_market_map::PerpMarketMap;
use crate::state::spot_market::SpotMarket;
use crate::state::spot_market_map::SpotMarketMap;
use crate::state::user::{
MarketType, Order, OrderFillSimulation, OrderStatus, OrderTriggerCondition, PerpPosition, User,
};
use crate::state::user_map::UserMap;
use crate::validate;
#[cfg(test)]
mod tests;
pub fn calculate_base_asset_amount_for_amm_to_fulfill(
order: &Order,
market: &PerpMarket,
limit_price: Option<u64>,
override_fill_price: Option<u64>,
existing_base_asset_amount: i64,
fee_tier: &FeeTier,
) -> DriftResult<(u64, Option<u64>)> {
let limit_price = if let Some(override_fill_price) = override_fill_price {
if let Some(limit_price) = limit_price {
validate!(
(limit_price >= override_fill_price && order.direction == PositionDirection::Long)
|| (limit_price <= override_fill_price
&& order.direction == PositionDirection::Short),
ErrorCode::InvalidAmmLimitPriceOverride,
"override_limit_price={} not better than order_limit_price={}",
override_fill_price,
limit_price
)?;
}
Some(override_fill_price)
} else {
limit_price
};
if order.must_be_triggered() && !order.triggered() {
return Ok((0, limit_price));
}
let limit_price_with_buffer =
calculate_limit_price_with_buffer(order, limit_price, fee_tier, market.fee_adjustment)?;
let base_asset_amount = calculate_base_asset_amount_to_fill_up_to_limit_price(
order,
market,
limit_price_with_buffer,
Some(existing_base_asset_amount),
)?;
let max_base_asset_amount = calculate_amm_available_liquidity(&market.amm, &order.direction)?;
Ok((min(base_asset_amount, max_base_asset_amount), limit_price))
}
fn calculate_limit_price_with_buffer(
order: &Order,
limit_price: Option<u64>,
fee_tier: &FeeTier,
fee_adjustment: i16,
) -> DriftResult<Option<u64>> {
if !order.post_only {
Ok(limit_price)
} else if let Some(limit_price) = limit_price {
let mut buffer = limit_price
.safe_mul(fee_tier.maker_rebate_numerator.cast()?)?
.safe_div(fee_tier.maker_rebate_denominator.cast()?)?;
if fee_adjustment < 0 {
let buffer_adjustment = buffer
.safe_mul(fee_adjustment.abs().cast()?)?
.safe_div(FEE_ADJUSTMENT_MAX)?;
buffer = buffer.saturating_sub(buffer_adjustment);
} else if fee_adjustment > 0 {
let buffer_adjustment = buffer
.safe_mul(fee_adjustment.cast()?)?
.safe_div(FEE_ADJUSTMENT_MAX)?;
buffer = buffer.saturating_add(buffer_adjustment);
}
match order.direction {
PositionDirection::Long => limit_price.safe_sub(buffer).map(Some),
PositionDirection::Short => limit_price.safe_add(buffer).map(Some),
}
} else {
Ok(None)
}
}
pub fn calculate_base_asset_amount_to_fill_up_to_limit_price(
order: &Order,
market: &PerpMarket,
limit_price: Option<u64>,
existing_base_asset_amount: Option<i64>,
) -> DriftResult<u64> {
let base_asset_amount_unfilled =
order.get_base_asset_amount_unfilled(existing_base_asset_amount)?;
let (max_trade_base_asset_amount, max_trade_direction) = if let Some(limit_price) = limit_price
{
// buy to right below or sell up right above the limit price
let adjusted_limit_price = match order.direction {
PositionDirection::Long => limit_price.safe_sub(market.amm.order_tick_size)?,
PositionDirection::Short => limit_price.safe_add(market.amm.order_tick_size)?,
};
math::amm_spread::calculate_base_asset_amount_to_trade_to_price(
&market.amm,
adjusted_limit_price,
order.direction,
)?
} else {
(base_asset_amount_unfilled, order.direction)
};
if max_trade_direction != order.direction || max_trade_base_asset_amount == 0 {
return Ok(0);
}
standardize_base_asset_amount(
min(base_asset_amount_unfilled, max_trade_base_asset_amount),
market.amm.order_step_size,
)
}
pub fn calculate_quote_asset_amount_for_maker_order(
base_asset_amount: u64,
fill_price: u64,
base_decimals: u32,
position_direction: PositionDirection,
) -> DriftResult<u64> {
let precision_decrease = 10_u128.pow(base_decimals);
match position_direction {
PositionDirection::Long => fill_price
.cast::<u128>()?
.safe_mul(base_asset_amount.cast()?)?
.safe_div(precision_decrease)?
.cast::<u64>(),
PositionDirection::Short => fill_price
.cast::<u128>()?
.safe_mul(base_asset_amount.cast()?)?
.safe_div_ceil(precision_decrease)?
.cast::<u64>(),
}
}
pub fn standardize_base_asset_amount_with_remainder_i128(
base_asset_amount: i128,
step_size: u128,
) -> DriftResult<(i128, i128)> {
let remainder = base_asset_amount
.unsigned_abs()
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?
.cast::<i128>()?
.safe_mul(base_asset_amount.signum())?;
let standardized_base_asset_amount = base_asset_amount.safe_sub(remainder)?;
Ok((standardized_base_asset_amount, remainder))
}
pub fn standardize_base_asset_amount(base_asset_amount: u64, step_size: u64) -> DriftResult<u64> {
let remainder = base_asset_amount
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?;
base_asset_amount.safe_sub(remainder)
}
pub fn standardize_base_asset_amount_ceil(
base_asset_amount: u64,
step_size: u64,
) -> DriftResult<u64> {
let remainder = base_asset_amount
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?;
if remainder == 0 {
Ok(base_asset_amount)
} else {
base_asset_amount.safe_add(step_size)?.safe_sub(remainder)
}
}
pub fn is_multiple_of_step_size(base_asset_amount: u64, step_size: u64) -> DriftResult<bool> {
let remainder = base_asset_amount
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?;
Ok(remainder == 0)
}
pub fn standardize_price(
price: u64,
tick_size: u64,
direction: PositionDirection,
) -> DriftResult<u64> {
if price == 0 {
return Ok(0);
}
let remainder = price
.checked_rem_euclid(tick_size)
.ok_or_else(math_error!())?;
if remainder == 0 {
return Ok(price);
}
match direction {
PositionDirection::Long => price.safe_sub(remainder),
PositionDirection::Short => price.safe_add(tick_size)?.safe_sub(remainder),
}
}
pub fn standardize_price_i64(
price: i64,
tick_size: i64,
direction: PositionDirection,
) -> DriftResult<i64> {
if price == 0 {
return Ok(0);
}
let remainder = price
.checked_rem_euclid(tick_size)
.ok_or_else(math_error!())?;
if remainder == 0 {
return Ok(price);
}
match direction {
PositionDirection::Long => price.safe_sub(remainder),
PositionDirection::Short => price.safe_add(tick_size)?.safe_sub(remainder),
}
}
pub fn get_price_for_perp_order(
price: u64,
direction: PositionDirection,
post_only: PostOnlyParam,
amm: &AMM,
) -> DriftResult<u64> {
let mut limit_price = standardize_price(price, amm.order_tick_size, direction)?;
if post_only == PostOnlyParam::Slide {
let reserve_price = amm.reserve_price()?;
match direction {
PositionDirection::Long => {
let amm_ask = amm.ask_price(reserve_price)?;
if limit_price >= amm_ask {
limit_price = amm_ask.safe_sub(amm.order_tick_size)?;
}
}
PositionDirection::Short => {
let amm_bid = amm.bid_price(reserve_price)?;
if limit_price <= amm_bid {
limit_price = amm_bid.safe_add(amm.order_tick_size)?;
}
}
}
}
Ok(limit_price)
}
pub fn get_position_delta_for_fill(
base_asset_amount: u64,
quote_asset_amount: u64,
direction: PositionDirection,
) -> DriftResult<PositionDelta> {
Ok(PositionDelta {
quote_asset_amount: match direction {
PositionDirection::Long => -quote_asset_amount.cast()?,
PositionDirection::Short => quote_asset_amount.cast()?,
},
base_asset_amount: match direction {
PositionDirection::Long => base_asset_amount.cast()?,
PositionDirection::Short => -base_asset_amount.cast()?,
},
remainder_base_asset_amount: None,
})
}
#[inline(always)]
pub fn validate_perp_fill_possible(
state: &State,
user: &User,
order_index: usize,
slot: u64,
num_makers: usize,
fill_mode: FillMode,
) -> DriftResult {
let amm_available = is_amm_available_liquidity_source(
&user.orders[order_index],
state.min_perp_auction_duration,
slot,
fill_mode,
)?;
if !amm_available && num_makers == 0 && user.orders[order_index].is_limit_order() {
msg!("invalid fill. order is limit order, amm is not available and no makers present");
return Err(ErrorCode::ImpossibleFill);
}
Ok(())
}
#[inline(always)]
pub fn should_expire_order_before_fill(
user: &User,
order_index: usize,
now: i64,
) -> DriftResult<bool> {
let should_order_be_expired = should_expire_order(user, order_index, now)?;
if should_order_be_expired && user.orders[order_index].is_limit_order() {
let now_sub_buffer = now.safe_sub(15)?;
if !should_expire_order(user, order_index, now_sub_buffer)? {
msg!("invalid fill. cant force expire limit order until 15s after max_ts. max ts {}, now {}, now plus buffer {}", user.orders[order_index].max_ts, now, now_sub_buffer);
return Err(ErrorCode::ImpossibleFill);
}
}
Ok(should_order_be_expired)
}
#[inline(always)]
pub fn should_expire_order(user: &User, user_order_index: usize, now: i64) -> DriftResult<bool> {
let order = &user.orders[user_order_index];
if order.status != OrderStatus::Open || order.max_ts == 0 || order.must_be_triggered() {
return Ok(false);
}
Ok(now > order.max_ts)
}
pub fn should_cancel_reduce_only_order(
order: &Order,
existing_base_asset_amount: i64,
step_size: u64,
) -> DriftResult<bool> {
let should_cancel = order.status == OrderStatus::Open
&& order.reduce_only
&& order.get_base_asset_amount_unfilled(Some(existing_base_asset_amount))? < step_size;
Ok(should_cancel)
}
pub fn order_breaches_maker_oracle_price_bands(
order: &Order,
oracle_price: i64,
slot: u64,
tick_size: u64,
margin_ratio_initial: u32,
is_prediction_market: bool,
) -> DriftResult<bool> {
let order_limit_price = order.force_get_limit_price(
Some(oracle_price),
None,
slot,
tick_size,
is_prediction_market,
)?;
limit_price_breaches_maker_oracle_price_bands(
order_limit_price,
order.direction,
oracle_price,
margin_ratio_initial,
)
}
/// Cancel maker order if there limit price cross the oracle price sufficiently
/// E.g. if initial margin ratio is .05 and oracle price is 100, then maker limit price must be
/// less than 105 to be valid
pub fn limit_price_breaches_maker_oracle_price_bands(
order_limit_price: u64,
order_direction: PositionDirection,
oracle_price: i64,
margin_ratio_initial: u32,
) -> DriftResult<bool> {
let oracle_price = oracle_price.unsigned_abs();
let max_percent_diff = margin_ratio_initial;
match order_direction {
PositionDirection::Long => {
if order_limit_price <= oracle_price {
return Ok(false);
}
let percent_diff = order_limit_price
.safe_sub(oracle_price)?
.cast::<u128>()?
.safe_mul(MARGIN_PRECISION_U128)?
.safe_div(oracle_price.cast()?)?;
if percent_diff >= max_percent_diff.cast()? {
// order cant be buying if oracle price is more than 5% below limit price
msg!(
"Limit Price Breaches Oracle for Long: {} >> {}",
order_limit_price,
oracle_price
);
return Ok(true);
}
Ok(false)
}
PositionDirection::Short => {
if order_limit_price >= oracle_price {
return Ok(false);
}
let percent_diff = oracle_price
.safe_sub(order_limit_price)?
.cast::<u128>()?
.safe_mul(MARGIN_PRECISION_U128)?
.safe_div(oracle_price.cast()?)?;
if percent_diff >= max_percent_diff.cast()? {
// order cant be selling if oracle price is more than 5% above limit price
msg!(
"Limit Price Breaches Oracle for Short: {} << {}",
order_limit_price,
oracle_price
);
return Ok(true);
}
Ok(false)
}
}
}
pub fn validate_fill_price_within_price_bands(
fill_price: u64,
direction: PositionDirection,
oracle_price: i64,
oracle_twap_5min: i64,
margin_ratio_initial: u32,
oracle_twap_5min_percent_divergence: u64,
is_prediction_market: bool,
) -> DriftResult {
if is_prediction_market {
validate!(
fill_price <= MAX_PREDICTION_MARKET_PRICE,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Prediction Market Price Bands: (fill: {} >= oracle: {})",
fill_price,
PRICE_PRECISION_U64
)?;
return Ok(());
}
let oracle_price = oracle_price.unsigned_abs();
let oracle_twap_5min = oracle_twap_5min.unsigned_abs();
let max_oracle_diff = margin_ratio_initial.cast::<u128>()?;
let max_oracle_twap_diff = oracle_twap_5min_percent_divergence.cast::<u128>()?; // 50%
if direction == PositionDirection::Long {
if fill_price < oracle_price && fill_price < oracle_twap_5min {
return Ok(());
}
let percent_diff: u128 = fill_price
.saturating_sub(oracle_price)
.cast::<u128>()?
.safe_mul(MARGIN_PRECISION_U128)?
.safe_div(oracle_price.cast()?)?;
validate!(
percent_diff < max_oracle_diff,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Oracle Price Bands: {} % <= {} % (fill: {} >= oracle: {})",
max_oracle_diff,
percent_diff,
fill_price,
oracle_price
)?;
let percent_diff = fill_price
.saturating_sub(oracle_twap_5min)
.cast::<u128>()?
.safe_mul(PERCENTAGE_PRECISION)?
.safe_div(oracle_twap_5min.cast()?)?;
validate!(
percent_diff < max_oracle_twap_diff,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Oracle TWAP Price Bands: {} % <= {} % (fill: {} >= twap: {})",
max_oracle_twap_diff,
percent_diff,
fill_price,
oracle_twap_5min
)?;
} else {
if fill_price > oracle_price && fill_price > oracle_twap_5min {
return Ok(());
}
let percent_diff: u128 = oracle_price
.saturating_sub(fill_price)
.cast::<u128>()?
.safe_mul(MARGIN_PRECISION_U128)?
.safe_div(oracle_price.cast()?)?;
validate!(
percent_diff < max_oracle_diff,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Oracle Price Bands: {} % <= {} % (fill: {} <= oracle: {})",
max_oracle_diff,
percent_diff,
fill_price,
oracle_price
)?;
let percent_diff = oracle_twap_5min
.saturating_sub(fill_price)
.cast::<u128>()?
.safe_mul(PERCENTAGE_PRECISION)?
.safe_div(oracle_twap_5min.cast()?)?;
validate!(
percent_diff < max_oracle_twap_diff,
ErrorCode::PriceBandsBreached,
"Fill Price Breaches Oracle TWAP Price Bands: {} % <= {} % (fill: {} <= twap: {})",
max_oracle_twap_diff,
percent_diff,
fill_price,
oracle_twap_5min
)?;
}
Ok(())
}
pub fn is_oracle_too_divergent_with_twap_5min(
oracle_price: i64,
oracle_twap_5min: i64,
max_divergence: i64,
) -> DriftResult<bool> {
let percent_diff = oracle_price
.safe_sub(oracle_twap_5min)?
.abs()
.safe_mul(PERCENTAGE_PRECISION_U64.cast::<i64>()?)?
.safe_div(oracle_twap_5min.abs())?;
let too_divergent = percent_diff >= max_divergence;
if too_divergent {
msg!("max divergence {}", max_divergence);
msg!(
"Oracle Price Too Divergent from TWAP 5min. oracle: {} twap: {}",
oracle_price,
oracle_twap_5min
);
}
Ok(too_divergent)
}
pub fn order_satisfies_trigger_condition(order: &Order, oracle_price: u64) -> DriftResult<bool> {
match order.trigger_condition {
OrderTriggerCondition::Above => Ok(oracle_price > order.trigger_price),
OrderTriggerCondition::Below => Ok(oracle_price < order.trigger_price),
_ => Err(print_error!(ErrorCode::InvalidTriggerOrderCondition)()),
}
}
pub fn is_new_order_risk_increasing(
order: &Order,
position_base_asset_amount: i64,
position_bids: i64,
position_asks: i64,
) -> DriftResult<bool> {
if order.reduce_only {
return Ok(false);
}
match order.direction {
PositionDirection::Long => {
if position_base_asset_amount >= 0 {
return Ok(true);
}
Ok(position_bids.safe_add(order.base_asset_amount.cast()?)?
> position_base_asset_amount.abs())
}
PositionDirection::Short => {
if position_base_asset_amount <= 0 {
return Ok(true);
}
Ok(position_asks
.safe_sub(order.base_asset_amount.cast()?)?
.abs()
> position_base_asset_amount)
}
}
}
pub fn is_order_position_reducing(
order_direction: &PositionDirection,
order_base_asset_amount: u64,
position_base_asset_amount: i64,
) -> DriftResult<bool> {
Ok(match order_direction {
// User is short and order is long
PositionDirection::Long if position_base_asset_amount < 0 => {
order_base_asset_amount <= position_base_asset_amount.unsigned_abs()
}
// User is long and order is short
PositionDirection::Short if position_base_asset_amount > 0 => {
order_base_asset_amount <= position_base_asset_amount.unsigned_abs()
}
_ => false,
})
}
pub fn validate_fill_price(
quote_asset_amount: u64,
base_asset_amount: u64,
base_precision: u64,
order_direction: PositionDirection,
order_limit_price: u64,
is_taker: bool,
) -> DriftResult {
let rounded_quote_asset_amount = if is_taker {
match order_direction {
PositionDirection::Long => quote_asset_amount.saturating_sub(1),
PositionDirection::Short => quote_asset_amount.saturating_add(1),
}
} else {
quote_asset_amount
};
let fill_price = calculate_fill_price(
rounded_quote_asset_amount,
base_asset_amount,
base_precision,
)?;
if order_direction == PositionDirection::Long && fill_price > order_limit_price {
msg!(
"long order fill price ({} = {}/{} * 1000) > limit price ({}) is_taker={}",
fill_price,
quote_asset_amount,
base_asset_amount,
order_limit_price,
is_taker
);
return Err(ErrorCode::InvalidOrderFillPrice);
}
if order_direction == PositionDirection::Short && fill_price < order_limit_price {
msg!(
"short order fill price ({} = {}/{} * 1000) < limit price ({}) is_taker={}",
fill_price,
quote_asset_amount,
base_asset_amount,
order_limit_price,
is_taker
);
return Err(ErrorCode::InvalidOrderFillPrice);
}
Ok(())
}
pub fn calculate_fill_price(
quote_asset_amount: u64,
base_asset_amount: u64,
base_precision: u64,
) -> DriftResult<u64> {
quote_asset_amount
.cast::<u128>()?
.safe_mul(base_precision as u128)?
.safe_div(base_asset_amount.cast()?)?
.cast::<u64>()
}
pub fn get_max_fill_amounts(
user: &User,
user_order_index: usize,
base_market: &SpotMarket,
quote_market: &SpotMarket,
is_leaving_drift: bool,
) -> DriftResult<(Option<u64>, Option<u64>)> {
let direction: PositionDirection = user.orders[user_order_index].direction;
match direction {
PositionDirection::Long => {
let max_quote = get_max_fill_amounts_for_market(user, quote_market, is_leaving_drift)?
.cast::<u64>()?;
Ok((None, Some(max_quote)))
}
PositionDirection::Short => {
let max_base = standardize_base_asset_amount(
get_max_fill_amounts_for_market(user, base_market, is_leaving_drift)?
.cast::<u64>()?,
base_market.order_step_size,
)?;
Ok((Some(max_base), None))
}
}
}
fn get_max_fill_amounts_for_market(
user: &User,
market: &SpotMarket,
is_leaving_drift: bool,
) -> DriftResult<u128> {
let position_index = user.get_spot_position_index(market.market_index)?;
let token_amount = user.spot_positions[position_index].get_signed_token_amount(market)?;
get_max_withdraw_for_market_with_token_amount(market, token_amount, is_leaving_drift)
}
pub fn find_maker_orders(
user: &User,
direction: &PositionDirection,
market_type: &MarketType,
market_index: u16,
valid_oracle_price: Option<i64>,
slot: u64,
tick_size: u64,
is_prediction_market: bool,
) -> DriftResult<Vec<(usize, u64)>> {
let mut orders: Vec<(usize, u64)> = Vec::with_capacity(32);
for (order_index, order) in user.orders.iter().enumerate() {
if order.status != OrderStatus::Open {
continue;
}
// if order direction is not same or market type is not same or market index is the same, skip
if order.direction != *direction
|| order.market_type != *market_type
|| order.market_index != market_index
{
continue;
}
// if order is not limit order or must be triggered and not triggered, skip
if !order.is_limit_order() || (order.must_be_triggered() && !order.triggered()) {
continue;
}
let limit_price = order.force_get_limit_price(
valid_oracle_price,
None,
slot,
tick_size,
is_prediction_market,
)?;
orders.push((order_index, limit_price));
}
Ok(orders)
}
pub fn calculate_max_perp_order_size(
user: &User,
position_index: usize,
market_index: u16,
direction: PositionDirection,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<u64> {
// calculate initial margin requirement
let MarginCalculation {
margin_requirement,
total_collateral,
..
} = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
MarginContext::standard(MarginRequirementType::Initial).strict(true),
)?;
let user_custom_margin_ratio = user.max_margin_ratio;
let user_high_leverage_mode = user.is_high_leverage_mode();
let free_collateral_before = total_collateral.safe_sub(margin_requirement.cast()?)?;
let perp_market = perp_market_map.get_ref(&market_index)?;
let oracle_price_data_price = oracle_map.get_price_data(&perp_market.oracle_id())?.price;
let quote_spot_market = spot_market_map.get_ref(&perp_market.quote_spot_market_index)?;
let quote_oracle_price = oracle_map
.get_price_data("e_spot_market.oracle_id())?
.price
.max(
quote_spot_market
.historical_oracle_data
.last_oracle_price_twap_5min,
);
drop(quote_spot_market);
let perp_position: &PerpPosition = &user.perp_positions[position_index];
let (worst_case_base_asset_amount, worst_case_liability_value) = perp_position
.worst_case_liability_value(oracle_price_data_price, perp_market.contract_type)?;
let margin_ratio = perp_market
.get_margin_ratio(
worst_case_base_asset_amount.unsigned_abs(),
MarginRequirementType::Initial,
user_high_leverage_mode,
)?
.max(user_custom_margin_ratio);
let mut order_size_to_reduce_position = 0_u64;
let mut free_collateral_released = 0_i128;
// account for order flipping worst case base asset amount
if worst_case_base_asset_amount < 0 && direction == PositionDirection::Long {
order_size_to_reduce_position = worst_case_base_asset_amount
.abs()
.cast::<i64>()?
.safe_sub(perp_position.open_bids)?
.max(0)
.unsigned_abs();
let existing_position_margin_requirement = worst_case_liability_value
.safe_mul(margin_ratio.cast()?)?
.safe_div(MARGIN_PRECISION_U128)?;
free_collateral_released = existing_position_margin_requirement.cast()?;
} else if worst_case_base_asset_amount > 0 && direction == PositionDirection::Short {
order_size_to_reduce_position = worst_case_base_asset_amount
.cast::<i64>()?
.safe_add(perp_position.open_asks)?
.max(0)
.unsigned_abs();
let existing_position_margin_requirement = worst_case_liability_value
.safe_mul(margin_ratio.cast()?)?
.safe_div(MARGIN_PRECISION_U128)?;
free_collateral_released = existing_position_margin_requirement.cast()?;
}
// if user has no free collateral, just return the order size to reduce position
if free_collateral_before <= 0 {
return standardize_base_asset_amount(
order_size_to_reduce_position,
perp_market.amm.order_step_size,
);
}
let oracle_price =
if !perp_market.is_prediction_market() || direction == PositionDirection::Long {
oracle_price_data_price
} else {
MAX_PREDICTION_MARKET_PRICE_I64.safe_sub(oracle_price_data_price)?
};
let calculate_order_size_and_margin_ratio = |margin_ratio: u32| {
let new_order_size = free_collateral_before
.safe_add(free_collateral_released)?
.safe_sub(OPEN_ORDER_MARGIN_REQUIREMENT.cast()?)?
.safe_mul(BASE_PRECISION_I128 / QUOTE_PRECISION_I128)?
.safe_mul(MARGIN_PRECISION_U128.cast()?)?
.safe_div(margin_ratio.cast()?)?
.safe_mul(PRICE_PRECISION_I128)?
.safe_div(oracle_price.cast()?)?
.safe_mul(PRICE_PRECISION_I128)?
.safe_div(quote_oracle_price.cast()?)?
.cast::<u64>()?;
let new_margin_ratio = perp_market
.get_margin_ratio(
worst_case_base_asset_amount
.unsigned_abs()
.safe_add(new_order_size.cast()?)?,
MarginRequirementType::Initial,
user_high_leverage_mode,
)?
.max(user_custom_margin_ratio);
Ok((new_order_size, new_margin_ratio))
};
let mut order_size = 0_u64;
let mut updated_margin_ratio = margin_ratio;
for _ in 0..6 {
let (new_order_size, new_margin_ratio) =
calculate_order_size_and_margin_ratio(updated_margin_ratio)?;
order_size = new_order_size;
updated_margin_ratio = new_margin_ratio;
if new_margin_ratio == margin_ratio {
break;
}
}
standardize_base_asset_amount(
order_size.safe_add(order_size_to_reduce_position)?,
perp_market.amm.order_step_size,
)
}
#[allow(clippy::unwrap_used)]
pub fn calculate_max_spot_order_size(
user: &User,
market_index: u16,
direction: PositionDirection,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<u64> {
// calculate initial margin requirement
let MarginCalculation {
margin_requirement,
total_collateral,
..
} = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
MarginContext::standard(MarginRequirementType::Initial).strict(true),
)?;
let user_custom_margin_ratio = user.max_margin_ratio;
let user_custom_liability_weight = user.max_margin_ratio.saturating_add(SPOT_WEIGHT_PRECISION);
let user_custom_asset_weight = SPOT_WEIGHT_PRECISION.saturating_sub(user_custom_margin_ratio);
let mut order_size_to_flip = 0_u64;
let free_collateral = total_collateral.safe_sub(margin_requirement.cast()?)?;
let spot_market = spot_market_map.get_ref(&market_index)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
let twap = spot_market
.historical_oracle_data
.last_oracle_price_twap_5min;
let strict_oracle_price = StrictOraclePrice::new(oracle_price_data.price, twap, true);
let max_oracle_price = strict_oracle_price.max();
let spot_position = user.get_spot_position(market_index)?;
let signed_token_amount = spot_position.get_signed_token_amount(&spot_market)?;
let [bid_simulation, ask_simulation] = spot_position
.simulate_fills_both_sides(
&spot_market,
&strict_oracle_price,
Some(signed_token_amount),
MarginRequirementType::Initial,
)?
.map(|simulation| {
simulation
.apply_user_custom_margin_ratio(
&spot_market,
strict_oracle_price.current,
user_custom_margin_ratio,
)
.unwrap()
});
let OrderFillSimulation {
token_amount: mut worst_case_token_amount,
..
} = OrderFillSimulation::riskier_side(ask_simulation, bid_simulation);
// account for order flipping worst case
if worst_case_token_amount < 0 && direction == PositionDirection::Long {
// to determine order size to flip direction, need to know diff in free collateral
let mut free_collateral_difference = bid_simulation
.free_collateral_contribution
.safe_sub(ask_simulation.free_collateral_contribution)?
.max(0)
.abs();
let mut token_amount = bid_simulation.token_amount;
// the free collateral delta is positive until the worst case hits 0
if token_amount < 0 {
let token_value =
get_strict_token_value(token_amount, spot_market.decimals, &strict_oracle_price)?;
let liability_weight = spot_market
.get_liability_weight(token_amount.unsigned_abs(), &MarginRequirementType::Initial)?
.max(user_custom_liability_weight);
let free_collateral_regained = token_value
.abs()
.safe_mul(liability_weight.safe_sub(SPOT_WEIGHT_PRECISION)?.cast()?)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)?;
free_collateral_difference =
free_collateral_difference.safe_add(free_collateral_regained)?;
order_size_to_flip = token_amount.abs().cast()?;
token_amount = 0;
}
// free collateral delta is negative as the worst case goes above 0
let weight = spot_market
.get_asset_weight(
token_amount.unsigned_abs(),
strict_oracle_price.current,
&MarginRequirementType::Initial,
)?
.min(user_custom_asset_weight);
let free_collateral_delta_per_order = weight
.cast::<i128>()?
.safe_sub(SPOT_WEIGHT_PRECISION_I128)?
.abs()
.safe_mul(max_oracle_price.cast()?)?
.safe_div(PRICE_PRECISION_I128)?
.safe_mul(QUOTE_PRECISION_I128)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)?;
order_size_to_flip = order_size_to_flip.safe_add(
free_collateral_difference
.safe_mul(spot_market.get_precision().cast()?)?
.safe_div(free_collateral_delta_per_order)?
.cast::<u64>()?,
)?;
worst_case_token_amount = token_amount.safe_sub(order_size_to_flip.cast()?)?;
} else if worst_case_token_amount > 0 && direction == PositionDirection::Short {
let mut free_collateral_difference = ask_simulation
.free_collateral_contribution
.safe_sub(bid_simulation.free_collateral_contribution)?
.max(0)
.abs();
let mut token_amount = ask_simulation.token_amount;
if token_amount > 0 {
let token_value =
get_strict_token_value(token_amount, spot_market.decimals, &strict_oracle_price)?;
let asset_weight = spot_market
.get_asset_weight(
token_amount.unsigned_abs(),
strict_oracle_price.current,
&MarginRequirementType::Initial,
)?
.min(user_custom_asset_weight);
let free_collateral_regained = token_value
.abs()
.safe_mul(SPOT_WEIGHT_PRECISION.safe_sub(asset_weight)?.cast()?)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)?;
free_collateral_difference =
free_collateral_difference.safe_add(free_collateral_regained)?;
order_size_to_flip = token_amount.abs().cast()?;
token_amount = 0;
}
let weight = spot_market
.get_liability_weight(token_amount.unsigned_abs(), &MarginRequirementType::Initial)?
.max(user_custom_liability_weight);
let free_collateral_delta_per_order = weight
.cast::<i128>()?
.safe_sub(SPOT_WEIGHT_PRECISION_I128)?
.abs()
.safe_mul(max_oracle_price.cast()?)?
.safe_div(PRICE_PRECISION_I128)?
.safe_mul(QUOTE_PRECISION_I128)?
.safe_div(SPOT_WEIGHT_PRECISION_I128)?;
order_size_to_flip = order_size_to_flip.safe_add(
free_collateral_difference
.safe_mul(spot_market.get_precision().cast()?)?
.safe_div(free_collateral_delta_per_order)?
.cast::<u64>()?,
)?;
worst_case_token_amount = token_amount.safe_sub(order_size_to_flip.cast()?)?;
}
if free_collateral <= 0 {
return standardize_base_asset_amount(order_size_to_flip, spot_market.order_step_size);
}
let free_collateral_delta = calculate_free_collateral_delta_for_spot(
&spot_market,
worst_case_token_amount.unsigned_abs(),
&strict_oracle_price,
direction,
user_custom_liability_weight,
user_custom_asset_weight,
)?;
let precision_increase = 10i128.pow(spot_market.decimals - 6);
let calculate_order_size_and_free_collateral_delta = |free_collateral_delta: u32| {
let new_order_size = free_collateral
.safe_sub(OPEN_ORDER_MARGIN_REQUIREMENT.cast()?)?
.safe_mul(precision_increase)?
.safe_mul(SPOT_WEIGHT_PRECISION.cast()?)?
.safe_div(free_collateral_delta.cast()?)?
.safe_mul(PRICE_PRECISION_I128)?
.safe_div(max_oracle_price.cast()?)?
.cast::<u64>()?;
// increasing the worst case token amount with new order size may increase margin ratio,
// so need to recalculate free collateral delta with updated margin ratio
let new_free_collateral_delta = calculate_free_collateral_delta_for_spot(
&spot_market,
worst_case_token_amount
.unsigned_abs()
.safe_add(new_order_size.cast()?)?,
&strict_oracle_price,
direction,
user_custom_liability_weight,
user_custom_asset_weight,
)?;
Ok((new_order_size, new_free_collateral_delta))
};
let mut order_size = 0_u64;
let mut updated_free_collateral_delta = free_collateral_delta;
for _ in 0..6 {
let (new_order_size, new_free_collateral_delta) =
calculate_order_size_and_free_collateral_delta(updated_free_collateral_delta)?;
order_size = new_order_size;
updated_free_collateral_delta = new_free_collateral_delta;
if updated_free_collateral_delta == free_collateral_delta {
break;
}
}
standardize_base_asset_amount(
order_size.safe_add(order_size_to_flip)?,
spot_market.order_step_size,
)
}
fn calculate_free_collateral_delta_for_spot(
spot_market: &SpotMarket,
worst_case_token_amount: u128,
strict_oracle_price: &StrictOraclePrice,
order_direction: PositionDirection,
user_custom_liability_weight: u32,
user_custom_asset_weight: u32,
) -> DriftResult<u32> {
Ok(if order_direction == PositionDirection::Long {
SPOT_WEIGHT_PRECISION.sub(
spot_market
.get_asset_weight(
worst_case_token_amount,
strict_oracle_price.current,
&MarginRequirementType::Initial,
)?
.min(user_custom_asset_weight),
)
} else {
spot_market
.get_liability_weight(worst_case_token_amount, &MarginRequirementType::Initial)?
.max(user_custom_liability_weight)
.sub(SPOT_WEIGHT_PRECISION)
})
}
#[derive(Eq, PartialEq, Debug)]
pub struct Level {
pub price: u64,
pub base_asset_amount: u64,
}
pub fn find_bids_and_asks_from_users(
perp_market: &PerpMarket,
oracle_price_date: &OraclePriceData,
users: &UserMap,
slot: u64,
now: i64,
) -> DriftResult<(Vec<Level>, Vec<Level>)> {
let mut bids: Vec<Level> = Vec::with_capacity(32);
let mut asks: Vec<Level> = Vec::with_capacity(32);
let market_index = perp_market.market_index;
let tick_size = perp_market.amm.order_tick_size;
let oracle_price = Some(oracle_price_date.price);
let mut insert_order = |base_asset_amount: u64, price: u64, direction: PositionDirection| {
let orders = match direction {
PositionDirection::Long => &mut bids,
PositionDirection::Short => &mut asks,
};
let index = match orders.binary_search_by(|level| match direction {
PositionDirection::Long => price.cmp(&level.price),
PositionDirection::Short => level.price.cmp(&price),
}) {
Ok(index) => index,
Err(index) => index,
};
if index < orders.capacity() {
if orders.len() == orders.capacity() {
orders.pop();
}
orders.insert(
index,
Level {
price,
base_asset_amount,
},
);
}
};
for account_loader in users.0.values() {
let user = load!(account_loader)?;
for (_, order) in user.orders.iter().enumerate() {
if order.status != OrderStatus::Open {
continue;
}
if order.market_type != MarketType::Perp || order.market_index != market_index {
continue;
}
// if order is not limit order or must be triggered and not triggered, skip
if !order.is_limit_order() || (order.must_be_triggered() && !order.triggered()) {
continue;
}
if !order.is_resting_limit_order(slot)? {
continue;
}
if now > order.max_ts && order.max_ts != 0 {
continue;
}
let existing_position = user.get_perp_position(market_index)?.base_asset_amount;
let base_amount = order.get_base_asset_amount_unfilled(Some(existing_position))?;
let limit_price = order.force_get_limit_price(
oracle_price,
None,
slot,
tick_size,
perp_market.is_prediction_market(),
)?;
insert_order(base_amount, limit_price, order.direction);
}
}
Ok((bids, asks))
}
pub fn estimate_price_from_side(side: &Vec<Level>, depth: u64) -> DriftResult<Option<u64>> {
let mut depth_remaining = depth;
let mut cumulative_base = 0_u64;
let mut cumulative_quote = 0_u128;
for level in side {
let base_delta = level.base_asset_amount.min(depth_remaining);
let quote_delta = level.price.cast::<u128>()?.safe_mul(base_delta.cast()?)?;
cumulative_base = cumulative_base.safe_add(base_delta)?;
depth_remaining = depth_remaining.safe_sub(base_delta)?;
cumulative_quote = cumulative_quote.safe_add(quote_delta)?;
if depth_remaining == 0 {
break;
}
}
let price = if depth_remaining == 0 {
Some(
cumulative_quote
.safe_div(cumulative_base.cast()?)?
.cast::<u64>()?,
)
} else {
None
};
Ok(price)
}
pub fn select_margin_type_for_perp_maker(
maker: &User,
base_asset_amount_filled: i64,
market_index: u16,
) -> DriftResult<MarginRequirementType> {
let position_after_fill = maker
.get_perp_position(market_index)
.map_or(0, |p| p.base_asset_amount);
let position_before = position_after_fill.safe_sub(base_asset_amount_filled)?;
if position_after_fill == 0 {
return Ok(MarginRequirementType::Maintenance);
}
if position_after_fill.signum() == position_before.signum()
&& position_after_fill.abs() < position_before.abs()
{
return Ok(MarginRequirementType::Maintenance);
}
Ok(MarginRequirementType::Fill)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/bankruptcy.rs
|
use crate::state::spot_market::SpotBalanceType;
use crate::state::user::User;
#[cfg(test)]
mod tests;
pub fn is_user_bankrupt(user: &User) -> bool {
// user is bankrupt iff they have spot liabilities, no spot assets, and no perp exposure
let mut has_liability = false;
for spot_position in user.spot_positions.iter() {
if spot_position.scaled_balance > 0 {
match spot_position.balance_type {
SpotBalanceType::Deposit => return false,
SpotBalanceType::Borrow => has_liability = true,
}
}
}
for perp_position in user.perp_positions.iter() {
if perp_position.base_asset_amount != 0
|| perp_position.quote_asset_amount > 0
|| perp_position.has_open_order()
|| perp_position.is_lp()
{
return false;
}
if perp_position.quote_asset_amount < 0 {
has_liability = true;
}
}
has_liability
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/amm_spread.rs
|
use std::cmp::{max, min};
use solana_program::msg;
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode};
use crate::math::amm::_calculate_market_open_bids_asks;
use crate::math::bn::U192;
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO_I128, AMM_TO_QUOTE_PRECISION_RATIO_I128,
BID_ASK_SPREAD_PRECISION, BID_ASK_SPREAD_PRECISION_I128, DEFAULT_LARGE_BID_ASK_FACTOR,
DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT, FUNDING_RATE_BUFFER,
MAX_BID_ASK_INVENTORY_SKEW_FACTOR, PEG_PRECISION, PERCENTAGE_PRECISION,
PERCENTAGE_PRECISION_I128, PERCENTAGE_PRECISION_U64, PRICE_PRECISION, PRICE_PRECISION_I128,
PRICE_PRECISION_I64,
};
use crate::math::safe_math::SafeMath;
use crate::state::perp_market::{ContractType, PerpMarket, AMM};
use crate::validate;
#[cfg(test)]
mod tests;
pub fn calculate_base_asset_amount_to_trade_to_price(
amm: &AMM,
limit_price: u64,
direction: PositionDirection,
) -> DriftResult<(u64, PositionDirection)> {
let invariant_sqrt_u192 = U192::from(amm.sqrt_k);
let invariant = invariant_sqrt_u192.safe_mul(invariant_sqrt_u192)?;
validate!(
limit_price > 0,
ErrorCode::InvalidOrderLimitPrice,
"limit_price <= 0"
)?;
let new_base_asset_reserve_squared = invariant
.safe_mul(U192::from(PRICE_PRECISION))?
.safe_div(U192::from(limit_price))?
.safe_mul(U192::from(amm.peg_multiplier))?
.safe_div(U192::from(PEG_PRECISION))?;
let new_base_asset_reserve = new_base_asset_reserve_squared
.integer_sqrt()
.try_to_u128()?;
let base_asset_reserve_before = if amm.base_spread > 0 {
let (spread_base_asset_reserve, _) = get_spread_reserves(amm, direction)?;
spread_base_asset_reserve
} else {
amm.base_asset_reserve
};
if new_base_asset_reserve > base_asset_reserve_before {
let max_trade_amount = new_base_asset_reserve
.safe_sub(base_asset_reserve_before)?
.cast::<u64>()
.unwrap_or(u64::MAX);
Ok((max_trade_amount, PositionDirection::Short))
} else {
let max_trade_amount = base_asset_reserve_before
.safe_sub(new_base_asset_reserve)?
.cast::<u64>()
.unwrap_or(u64::MAX);
Ok((max_trade_amount, PositionDirection::Long))
}
}
pub fn cap_to_max_spread(
mut long_spread: u64,
mut short_spread: u64,
max_spread: u64,
) -> DriftResult<(u64, u64)> {
let total_spread = long_spread.safe_add(short_spread)?;
if total_spread > max_spread {
if long_spread > short_spread {
long_spread = long_spread
.saturating_mul(max_spread)
.safe_div_ceil(total_spread)?;
short_spread = max_spread.safe_sub(long_spread)?;
} else {
short_spread = short_spread
.saturating_mul(max_spread)
.safe_div_ceil(total_spread)?;
long_spread = max_spread.safe_sub(short_spread)?;
}
}
let new_total_spread = long_spread.safe_add(short_spread)?;
validate!(
new_total_spread <= max_spread,
ErrorCode::InvalidAmmMaxSpreadDetected,
"new_total_spread({}) > max_spread({})",
new_total_spread,
max_spread
)?;
Ok((long_spread, short_spread))
}
pub fn calculate_long_short_vol_spread(
last_oracle_conf_pct: u64,
reserve_price: u64,
mark_std: u64,
oracle_std: u64,
long_intensity_volume: u64,
short_intensity_volume: u64,
volume_24h: u64,
) -> DriftResult<(u64, u64)> {
// 1.6 * std
let market_avg_std_pct: u128 = oracle_std
.safe_add(mark_std)?
.cast::<u128>()?
.safe_mul(PERCENTAGE_PRECISION)?
.safe_div(reserve_price.cast::<u128>()?)?
.safe_div(2)?;
let vol_spread: u128 = last_oracle_conf_pct
.cast::<u128>()?
.max(market_avg_std_pct.safe_div(2)?);
let factor_clamp_min: u128 = PERCENTAGE_PRECISION / 100; // .01
let factor_clamp_max: u128 = 16 * PERCENTAGE_PRECISION / 10; // 1.6
let long_vol_spread_factor: u128 = long_intensity_volume
.cast::<u128>()?
.safe_mul(PERCENTAGE_PRECISION)?
.safe_div(max(volume_24h.cast::<u128>()?, 1))?
.clamp(factor_clamp_min, factor_clamp_max);
let short_vol_spread_factor: u128 = short_intensity_volume
.cast::<u128>()?
.safe_mul(PERCENTAGE_PRECISION)?
.safe_div(max(volume_24h.cast::<u128>()?, 1))?
.clamp(factor_clamp_min, factor_clamp_max);
// only consider confidence interval at full value when above 25 bps
let conf_component = if last_oracle_conf_pct > PERCENTAGE_PRECISION_U64 / 400 {
last_oracle_conf_pct
} else {
last_oracle_conf_pct.safe_div(10)?
};
Ok((
max(
conf_component,
vol_spread
.safe_mul(long_vol_spread_factor)?
.safe_div(PERCENTAGE_PRECISION)?
.cast::<u64>()?,
),
max(
conf_component,
vol_spread
.safe_mul(short_vol_spread_factor)?
.safe_div(PERCENTAGE_PRECISION)?
.cast::<u64>()?,
),
))
}
pub fn calculate_inventory_liquidity_ratio(
base_asset_amount_with_amm: i128,
base_asset_reserve: u128,
min_base_asset_reserve: u128,
max_base_asset_reserve: u128,
) -> DriftResult<i128> {
// computes min(1, x/(1-x)) for 0 < x < 1
// inventory scale
let (max_bids, max_asks) = _calculate_market_open_bids_asks(
base_asset_reserve,
min_base_asset_reserve,
max_base_asset_reserve,
)?;
let min_side_liquidity = max_bids.min(max_asks.abs());
let amm_inventory_pct = if base_asset_amount_with_amm.abs() < min_side_liquidity {
base_asset_amount_with_amm
.abs()
.safe_mul(PERCENTAGE_PRECISION_I128)
.unwrap_or(i128::MAX)
.safe_div(min_side_liquidity.max(1))?
.min(PERCENTAGE_PRECISION_I128)
} else {
PERCENTAGE_PRECISION_I128 // 100%
};
Ok(amm_inventory_pct)
}
pub fn calculate_spread_inventory_scale(
base_asset_amount_with_amm: i128,
base_asset_reserve: u128,
min_base_asset_reserve: u128,
max_base_asset_reserve: u128,
directional_spread: u64,
max_spread: u64,
) -> DriftResult<u64> {
if base_asset_amount_with_amm == 0 {
return Ok(BID_ASK_SPREAD_PRECISION);
}
let amm_inventory_pct = calculate_inventory_liquidity_ratio(
base_asset_amount_with_amm,
base_asset_reserve,
min_base_asset_reserve,
max_base_asset_reserve,
)?;
// only allow up to scale up of larger of MAX_BID_ASK_INVENTORY_SKEW_FACTOR or max spread
let inventory_scale_max = MAX_BID_ASK_INVENTORY_SKEW_FACTOR.max(
max_spread
.safe_mul(BID_ASK_SPREAD_PRECISION)?
.safe_div(max(directional_spread, 1))?,
);
let inventory_scale_capped = min(
inventory_scale_max,
BID_ASK_SPREAD_PRECISION
.safe_add(
inventory_scale_max
.safe_mul(amm_inventory_pct.unsigned_abs().cast()?)
.unwrap_or(u64::MAX)
.safe_div(PERCENTAGE_PRECISION_I128.cast()?)?,
)
.unwrap_or(u64::MAX),
);
Ok(inventory_scale_capped)
}
pub fn calculate_spread_leverage_scale(
quote_asset_reserve: u128,
terminal_quote_asset_reserve: u128,
peg_multiplier: u128,
base_asset_amount_with_amm: i128,
reserve_price: u64,
total_fee_minus_distributions: i128,
) -> DriftResult<u64> {
let net_base_asset_value = quote_asset_reserve
.cast::<i128>()?
.safe_sub(terminal_quote_asset_reserve.cast::<i128>()?)?
.safe_mul(peg_multiplier.cast::<i128>()?)?
.safe_div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO_I128)?;
let local_base_asset_value = base_asset_amount_with_amm
.safe_mul(reserve_price.cast::<i128>()?)?
.safe_div(AMM_TO_QUOTE_PRECISION_RATIO_I128 * PRICE_PRECISION_I128)?;
let effective_leverage = max(0, local_base_asset_value.safe_sub(net_base_asset_value)?)
.safe_mul(BID_ASK_SPREAD_PRECISION_I128)?
.safe_div(max(0, total_fee_minus_distributions) + 1)?;
let effective_leverage_capped = min(
MAX_BID_ASK_INVENTORY_SKEW_FACTOR,
BID_ASK_SPREAD_PRECISION.safe_add(max(0, effective_leverage).cast::<u64>()? + 1)?,
);
Ok(effective_leverage_capped)
}
pub fn calculate_spread_revenue_retreat_amount(
base_spread: u32,
max_spread: u64,
net_revenue_since_last_funding: i64,
) -> DriftResult<u64> {
// on-the-hour revenue scale
let revenue_retreat_amount = if net_revenue_since_last_funding
< DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT
{
let max_retreat = max_spread.safe_div(10)?;
if net_revenue_since_last_funding
>= DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT * 1000
{
min(
max_retreat,
base_spread
.cast::<u64>()?
.safe_mul(net_revenue_since_last_funding.unsigned_abs())?
.safe_div(DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT.unsigned_abs())?,
)
} else {
max_retreat
}
} else {
0
};
Ok(revenue_retreat_amount)
}
pub fn calculate_max_target_spread(
reserve_price: u64,
last_oracle_reserve_price_spread_pct: i64,
last_oracle_conf_pct: u64,
mark_std: u64,
oracle_std: u64,
max_spread: u32,
) -> DriftResult<u64> {
let max_spread_baseline = last_oracle_reserve_price_spread_pct.unsigned_abs().max(
last_oracle_conf_pct
.safe_mul(2)?
.max(
mark_std
.max(oracle_std)
.safe_mul(PERCENTAGE_PRECISION_U64)?
.safe_div(reserve_price)?,
)
.min(BID_ASK_SPREAD_PRECISION),
);
let max_target_spread = max_spread.cast::<u64>()?.max(max_spread_baseline);
Ok(max_target_spread)
}
#[allow(clippy::comparison_chain)]
pub fn calculate_spread(
base_spread: u32,
last_oracle_reserve_price_spread_pct: i64,
last_oracle_conf_pct: u64,
max_spread: u32,
quote_asset_reserve: u128,
terminal_quote_asset_reserve: u128,
peg_multiplier: u128,
base_asset_amount_with_amm: i128,
reserve_price: u64,
total_fee_minus_distributions: i128,
net_revenue_since_last_funding: i64,
base_asset_reserve: u128,
min_base_asset_reserve: u128,
max_base_asset_reserve: u128,
mark_std: u64,
oracle_std: u64,
long_intensity_volume: u64,
short_intensity_volume: u64,
volume_24h: u64,
) -> DriftResult<(u32, u32)> {
let (long_vol_spread, short_vol_spread) = calculate_long_short_vol_spread(
last_oracle_conf_pct,
reserve_price,
mark_std,
oracle_std,
long_intensity_volume,
short_intensity_volume,
volume_24h,
)?;
let half_base_spread_u64 = (base_spread / 2) as u64;
let mut long_spread = max(half_base_spread_u64, long_vol_spread);
let mut short_spread = max(half_base_spread_u64, short_vol_spread);
let max_target_spread = calculate_max_target_spread(
reserve_price,
last_oracle_reserve_price_spread_pct,
last_oracle_conf_pct,
mark_std,
oracle_std,
max_spread,
)?;
// oracle retreat
// if mark - oracle < 0 (mark below oracle) and user going long then increase spread
if last_oracle_reserve_price_spread_pct < 0 {
long_spread = max(
long_spread,
last_oracle_reserve_price_spread_pct
.unsigned_abs()
.safe_add(long_vol_spread)?,
);
} else if last_oracle_reserve_price_spread_pct > 0 {
short_spread = max(
short_spread,
last_oracle_reserve_price_spread_pct
.unsigned_abs()
.safe_add(short_vol_spread)?,
);
}
// inventory scale
let inventory_scale_capped = calculate_spread_inventory_scale(
base_asset_amount_with_amm,
base_asset_reserve,
min_base_asset_reserve,
max_base_asset_reserve,
if base_asset_amount_with_amm > 0 {
long_spread
} else {
short_spread
},
max_target_spread,
)?;
if base_asset_amount_with_amm > 0 {
long_spread = long_spread
.safe_mul(inventory_scale_capped)?
.safe_div(BID_ASK_SPREAD_PRECISION)?;
} else if base_asset_amount_with_amm < 0 {
short_spread = short_spread
.safe_mul(inventory_scale_capped)?
.safe_div(BID_ASK_SPREAD_PRECISION)?;
}
if total_fee_minus_distributions <= 0 {
long_spread = long_spread
.saturating_mul(DEFAULT_LARGE_BID_ASK_FACTOR)
.safe_div(BID_ASK_SPREAD_PRECISION)?;
short_spread = short_spread
.saturating_mul(DEFAULT_LARGE_BID_ASK_FACTOR)
.safe_div(BID_ASK_SPREAD_PRECISION)?;
} else {
// effective leverage scale
let effective_leverage_capped = calculate_spread_leverage_scale(
quote_asset_reserve,
terminal_quote_asset_reserve,
peg_multiplier,
base_asset_amount_with_amm,
reserve_price,
total_fee_minus_distributions,
)?;
if base_asset_amount_with_amm > 0 {
long_spread = long_spread
.safe_mul(effective_leverage_capped)?
.safe_div(BID_ASK_SPREAD_PRECISION)?;
} else if base_asset_amount_with_amm < 0 {
short_spread = short_spread
.safe_mul(effective_leverage_capped)?
.safe_div(BID_ASK_SPREAD_PRECISION)?;
}
}
let revenue_retreat_amount = calculate_spread_revenue_retreat_amount(
base_spread,
max_target_spread,
net_revenue_since_last_funding,
)?;
if revenue_retreat_amount != 0 {
if base_asset_amount_with_amm > 0 {
long_spread = long_spread.safe_add(revenue_retreat_amount)?;
short_spread = short_spread.safe_add(revenue_retreat_amount.safe_div(2)?)?;
} else if base_asset_amount_with_amm < 0 {
long_spread = long_spread.safe_add(revenue_retreat_amount.safe_div(2)?)?;
short_spread = short_spread.safe_add(revenue_retreat_amount)?;
} else {
long_spread = long_spread.safe_add(revenue_retreat_amount.safe_div(2)?)?;
short_spread = short_spread.safe_add(revenue_retreat_amount.safe_div(2)?)?;
}
}
let (long_spread, short_spread) =
cap_to_max_spread(long_spread, short_spread, max_target_spread)?;
Ok((long_spread.cast::<u32>()?, short_spread.cast::<u32>()?))
}
pub fn get_spread_reserves(amm: &AMM, direction: PositionDirection) -> DriftResult<(u128, u128)> {
let (base_asset_reserve, quote_asset_reserve) = match direction {
PositionDirection::Long => (amm.ask_base_asset_reserve, amm.ask_quote_asset_reserve),
PositionDirection::Short => (amm.bid_base_asset_reserve, amm.bid_quote_asset_reserve),
};
Ok((base_asset_reserve, quote_asset_reserve))
}
pub fn calculate_spread_reserves(
market: &PerpMarket,
direction: PositionDirection,
) -> DriftResult<(u128, u128)> {
let spread = match direction {
PositionDirection::Long => market.amm.long_spread,
PositionDirection::Short => market.amm.short_spread,
};
let spread_with_offset: i32 = if direction == PositionDirection::Short {
(-spread.cast::<i32>()?).safe_add(market.amm.reference_price_offset)?
} else {
spread
.cast::<i32>()?
.safe_add(market.amm.reference_price_offset)?
};
let quote_asset_reserve_delta = if spread_with_offset.abs() > 1 {
let quote_reserve_divisor =
BID_ASK_SPREAD_PRECISION_I128 / (spread_with_offset / 2).cast::<i128>()?;
market
.amm
.quote_asset_reserve
.cast::<i128>()?
.safe_div(quote_reserve_divisor)?
} else {
0_i128
};
let mut quote_asset_reserve = if quote_asset_reserve_delta > 0 {
market
.amm
.quote_asset_reserve
.safe_add(quote_asset_reserve_delta.unsigned_abs())?
} else {
market
.amm
.quote_asset_reserve
.safe_sub(quote_asset_reserve_delta.unsigned_abs())?
};
if market.contract_type == ContractType::Prediction {
let (quote_asset_reserve_lower_bound, quote_asset_reserve_upper_bound) =
market.get_quote_asset_reserve_prediction_market_bounds(direction)?;
quote_asset_reserve = quote_asset_reserve.clamp(
quote_asset_reserve_lower_bound,
quote_asset_reserve_upper_bound,
);
}
let invariant_sqrt_u192 = U192::from(market.amm.sqrt_k);
let invariant = invariant_sqrt_u192.safe_mul(invariant_sqrt_u192)?;
let base_asset_reserve = invariant
.safe_div(U192::from(quote_asset_reserve))?
.try_to_u128()?;
Ok((base_asset_reserve, quote_asset_reserve))
}
#[allow(clippy::comparison_chain)]
pub fn calculate_reference_price_offset(
reserve_price: u64,
last_24h_avg_funding_rate: i64,
liquidity_fraction: i128,
_min_order_size: u64,
oracle_twap_fast: i64,
mark_twap_fast: u64,
oracle_twap_slow: i64,
mark_twap_slow: u64,
max_offset_pct: i64,
) -> DriftResult<i32> {
if last_24h_avg_funding_rate == 0 {
return Ok(0);
}
let max_offset_in_price = max_offset_pct
.safe_mul(reserve_price.cast()?)?
.safe_div(PERCENTAGE_PRECISION.cast()?)?;
// calculate quote denominated market premium
let mark_premium_minute: i64 = mark_twap_fast
.cast::<i64>()?
.safe_sub(oracle_twap_fast)?
.clamp(-max_offset_in_price, max_offset_in_price);
let mark_premium_hour: i64 = mark_twap_slow
.cast::<i64>()?
.safe_sub(oracle_twap_slow)?
.clamp(-max_offset_in_price, max_offset_in_price);
// convert last_24h_avg_funding_rate to quote denominated premium
let mark_premium_day: i64 = last_24h_avg_funding_rate
.safe_div(FUNDING_RATE_BUFFER.cast()?)?
.safe_mul(24)?
.clamp(-max_offset_in_price, max_offset_in_price); // todo: look at how 24h funding is calc w.r.t. the funding_period
// take average clamped premium as the price-based offset
let mark_premium_avg = mark_premium_minute
.safe_add(mark_premium_hour)?
.safe_add(mark_premium_day)?
.safe_div(3_i64)?;
let mark_premium_avg_pct: i64 = mark_premium_avg
.safe_mul(PRICE_PRECISION_I64)?
.safe_div(reserve_price.cast()?)?;
let inventory_pct = liquidity_fraction
.cast::<i64>()?
.safe_mul(max_offset_pct)?
.safe_div(PERCENTAGE_PRECISION.cast::<i64>()?)?
.clamp(-max_offset_pct, max_offset_pct);
// only apply when inventory is consistent with recent and 24h market premium
let offset_pct = if (mark_premium_avg_pct >= 0 && inventory_pct >= 0)
|| (mark_premium_avg_pct <= 0 && inventory_pct <= 0)
{
mark_premium_avg_pct.safe_add(inventory_pct)?
} else {
0
};
let clamped_offset_pct = offset_pct.clamp(-max_offset_pct, max_offset_pct);
validate!(
clamped_offset_pct.abs() <= max_offset_pct,
ErrorCode::InvalidAmmDetected,
"clamp offset pct failed {}",
clamped_offset_pct
)?;
clamped_offset_pct.cast()
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/margin.rs
|
use crate::error::DriftResult;
use crate::error::ErrorCode;
use crate::math::constants::{
MARGIN_PRECISION_U128, MAX_POSITIVE_UPNL_FOR_INITIAL_MARGIN, PRICE_PRECISION,
SPOT_IMF_PRECISION_U128, SPOT_WEIGHT_PRECISION, SPOT_WEIGHT_PRECISION_U128,
};
use crate::math::position::calculate_base_asset_value_and_pnl_with_oracle_price;
use crate::{validate, PRICE_PRECISION_I128};
use crate::{validation, PRICE_PRECISION_I64};
use crate::math::casting::Cast;
use crate::math::funding::calculate_funding_payment;
use crate::math::oracle::{is_oracle_valid_for_action, DriftAction};
use crate::math::spot_balance::{get_strict_token_value, get_token_value};
use crate::math::safe_math::SafeMath;
use crate::state::margin_calculation::{MarginCalculation, MarginContext, MarketIdentifier};
use crate::state::oracle::{OraclePriceData, StrictOraclePrice};
use crate::state::oracle_map::OracleMap;
use crate::state::perp_market::{ContractTier, MarketStatus, PerpMarket};
use crate::state::perp_market_map::PerpMarketMap;
use crate::state::spot_market::{AssetTier, SpotBalanceType};
use crate::state::spot_market_map::SpotMarketMap;
use crate::state::user::{MarketType, OrderFillSimulation, PerpPosition, User};
use num_integer::Roots;
use solana_program::msg;
use std::cmp::{max, min, Ordering};
#[cfg(test)]
mod tests;
#[derive(Clone, Copy, PartialEq, Debug, Eq)]
pub enum MarginRequirementType {
Initial,
Fill,
Maintenance,
}
pub fn calculate_size_premium_liability_weight(
size: u128, // AMM_RESERVE_PRECISION
imf_factor: u32,
liability_weight: u32,
precision: u128,
) -> DriftResult<u32> {
if imf_factor == 0 {
return Ok(liability_weight);
}
let size_sqrt = ((size * 10) + 1).nth_root(2); //1e9 -> 1e10 -> 1e5
let imf_factor_u128 = imf_factor.cast::<u128>()?;
let liability_weight_u128 = liability_weight.cast::<u128>()?;
let liability_weight_numerator =
liability_weight_u128.safe_sub(liability_weight_u128.safe_div(5)?)?;
// increases
let size_premium_liability_weight = liability_weight_numerator
.safe_add(
size_sqrt // 1e5
.safe_mul(imf_factor_u128)?
.safe_div(100_000 * SPOT_IMF_PRECISION_U128 / precision)?, // 1e5 * 1e2
)?
.cast::<u32>()?;
let max_liability_weight = max(liability_weight, size_premium_liability_weight);
Ok(max_liability_weight)
}
pub fn calculate_size_discount_asset_weight(
size: u128, // AMM_RESERVE_PRECISION
imf_factor: u32,
asset_weight: u32,
) -> DriftResult<u32> {
if imf_factor == 0 {
return Ok(asset_weight);
}
let size_sqrt = ((size * 10) + 1).nth_root(2); //1e9 -> 1e10 -> 1e5
let imf_numerator = SPOT_IMF_PRECISION_U128 + SPOT_IMF_PRECISION_U128 / 10;
let size_discount_asset_weight = imf_numerator
.safe_mul(SPOT_WEIGHT_PRECISION_U128)?
.safe_div(
SPOT_IMF_PRECISION_U128
.safe_add(size_sqrt.safe_mul(imf_factor.cast()?)?.safe_div(100_000)?)?,
)?
.cast::<u32>()?;
let min_asset_weight = min(asset_weight, size_discount_asset_weight);
Ok(min_asset_weight)
}
pub fn calculate_perp_position_value_and_pnl(
market_position: &PerpPosition,
market: &PerpMarket,
oracle_price_data: &OraclePriceData,
strict_quote_price: &StrictOraclePrice,
margin_requirement_type: MarginRequirementType,
user_custom_margin_ratio: u32,
user_high_leverage_mode: bool,
track_open_order_fraction: bool,
) -> DriftResult<(u128, i128, u128, u128, u128)> {
let valuation_price = if market.status == MarketStatus::Settlement {
market.expiry_price
} else {
oracle_price_data.price
};
// the funding must be calculated before calculated the unrealized pnl w simulated lp position
let unrealized_funding = calculate_funding_payment(
if market_position.base_asset_amount > 0 {
market.amm.cumulative_funding_rate_long
} else {
market.amm.cumulative_funding_rate_short
},
market_position,
)?;
let market_position = market_position.simulate_settled_lp_position(market, valuation_price)?;
let (base_asset_value, unrealized_pnl) =
calculate_base_asset_value_and_pnl_with_oracle_price(&market_position, valuation_price)?;
let total_unrealized_pnl = unrealized_pnl.safe_add(unrealized_funding.cast()?)?;
let (worst_case_base_asset_amount, worse_case_liability_value) = market_position
.worst_case_liability_value(oracle_price_data.price, market.contract_type)?;
// for calculating the perps value, since it's a liability, use the large of twap and quote oracle price
let worse_case_liability_value = worse_case_liability_value
.safe_mul(strict_quote_price.max().cast()?)?
.safe_div(PRICE_PRECISION)?;
let mut margin_requirement = if market.status == MarketStatus::Settlement {
0
} else {
let margin_ratio = user_custom_margin_ratio.max(market.get_margin_ratio(
worst_case_base_asset_amount.unsigned_abs(),
margin_requirement_type,
user_high_leverage_mode,
)?);
worse_case_liability_value
.safe_mul(margin_ratio.cast()?)?
.safe_div(MARGIN_PRECISION_U128)?
};
// add small margin requirement for every open order
margin_requirement = margin_requirement
.safe_add(market_position.margin_requirement_for_open_orders()?)?
.safe_add(
market_position
.margin_requirement_for_lp_shares(market.amm.order_step_size, valuation_price)?,
)?;
let unrealized_asset_weight =
market.get_unrealized_asset_weight(total_unrealized_pnl, margin_requirement_type)?;
let quote_price = if total_unrealized_pnl > 0 {
strict_quote_price.min()
} else if total_unrealized_pnl < 0 {
strict_quote_price.max()
} else {
strict_quote_price.current
};
let mut weighted_unrealized_pnl = total_unrealized_pnl;
if unrealized_asset_weight != SPOT_WEIGHT_PRECISION {
weighted_unrealized_pnl = weighted_unrealized_pnl
.safe_mul(unrealized_asset_weight.cast()?)?
.safe_div(SPOT_WEIGHT_PRECISION.cast()?)?;
}
if quote_price != PRICE_PRECISION_I64 {
weighted_unrealized_pnl = weighted_unrealized_pnl
.safe_mul(quote_price.cast()?)?
.safe_div(PRICE_PRECISION_I128)?;
}
if margin_requirement_type == MarginRequirementType::Initial {
// safety guard for dangerously configured perp market
weighted_unrealized_pnl = weighted_unrealized_pnl.min(MAX_POSITIVE_UPNL_FOR_INITIAL_MARGIN);
}
let open_order_margin_requirement =
if track_open_order_fraction && worst_case_base_asset_amount != 0 {
let worst_case_base_asset_amount = worst_case_base_asset_amount.unsigned_abs();
worst_case_base_asset_amount
.safe_sub(market_position.base_asset_amount.unsigned_abs().cast()?)?
.safe_mul(margin_requirement)?
.safe_div(worst_case_base_asset_amount)?
} else {
0_u128
};
Ok((
margin_requirement,
weighted_unrealized_pnl,
worse_case_liability_value,
open_order_margin_requirement,
base_asset_value,
))
}
pub fn calculate_user_safest_position_tiers(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
) -> DriftResult<(AssetTier, ContractTier)> {
let mut safest_tier_spot_liablity: AssetTier = AssetTier::default();
let mut safest_tier_perp_liablity: ContractTier = ContractTier::default();
for spot_position in user.spot_positions.iter() {
if spot_position.is_available() || spot_position.balance_type == SpotBalanceType::Deposit {
continue;
}
let spot_market = spot_market_map.get_ref(&spot_position.market_index)?;
safest_tier_spot_liablity = min(safest_tier_spot_liablity, spot_market.asset_tier);
}
for market_position in user.perp_positions.iter() {
if market_position.is_available() {
continue;
}
let market = &perp_market_map.get_ref(&market_position.market_index)?;
safest_tier_perp_liablity = min(safest_tier_perp_liablity, market.contract_tier);
}
Ok((safest_tier_spot_liablity, safest_tier_perp_liablity))
}
pub fn calculate_margin_requirement_and_total_collateral_and_liability_info(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
context: MarginContext,
) -> DriftResult<MarginCalculation> {
let mut calculation = MarginCalculation::new(context);
let user_custom_margin_ratio = if context.margin_type == MarginRequirementType::Initial {
user.max_margin_ratio
} else {
0_u32
};
let user_pool_id = user.pool_id;
let user_high_leverage_mode = user.is_high_leverage_mode();
for spot_position in user.spot_positions.iter() {
validation::position::validate_spot_position(spot_position)?;
if spot_position.is_available() {
continue;
}
let spot_market = spot_market_map.get_ref(&spot_position.market_index)?;
let (oracle_price_data, oracle_validity) = oracle_map.get_price_data_and_validity(
MarketType::Spot,
spot_market.market_index,
&spot_market.oracle_id(),
spot_market.historical_oracle_data.last_oracle_price_twap,
spot_market.get_max_confidence_interval_multiplier()?,
)?;
validate!(
user_pool_id == spot_market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) == spot market pool id ({})",
user_pool_id,
spot_market.pool_id,
)?;
let oracle_valid =
is_oracle_valid_for_action(oracle_validity, Some(DriftAction::MarginCalc))?;
let strict_oracle_price = StrictOraclePrice::new(
oracle_price_data.price,
spot_market
.historical_oracle_data
.last_oracle_price_twap_5min,
calculation.context.strict,
);
strict_oracle_price.validate()?;
if spot_market.market_index == 0 {
let token_amount = spot_position.get_signed_token_amount(&spot_market)?;
if token_amount == 0 {
validate!(
spot_position.scaled_balance == 0,
ErrorCode::InvalidMarginRatio,
"spot_position.scaled_balance={} when token_amount={}",
spot_position.scaled_balance,
token_amount,
)?;
}
calculation.update_fuel_spot_bonus(&spot_market, token_amount, &strict_oracle_price)?;
let mut token_value =
get_strict_token_value(token_amount, spot_market.decimals, &strict_oracle_price)?;
match spot_position.balance_type {
SpotBalanceType::Deposit => {
if calculation.context.ignore_invalid_deposit_oracles && !oracle_valid {
msg!(
"token_value set to 0 for market_index={}",
spot_market.market_index
);
token_value = 0;
}
calculation.add_total_collateral(token_value)?;
calculation.update_all_deposit_oracles_valid(oracle_valid);
#[cfg(feature = "drift-rs")]
calculation.add_spot_asset_value(token_value)?;
}
SpotBalanceType::Borrow => {
let token_value = token_value.unsigned_abs();
validate!(
token_value != 0,
ErrorCode::InvalidMarginRatio,
"token_value=0 for token_amount={} in spot market_index={}",
token_amount,
spot_market.market_index,
)?;
calculation.add_margin_requirement(
token_value,
token_value,
MarketIdentifier::spot(0),
)?;
calculation.add_spot_liability()?;
calculation.update_all_liability_oracles_valid(oracle_valid);
#[cfg(feature = "drift-rs")]
calculation.add_spot_liability_value(token_value)?;
}
}
} else {
let signed_token_amount = spot_position.get_signed_token_amount(&spot_market)?;
calculation.update_fuel_spot_bonus(
&spot_market,
signed_token_amount,
&strict_oracle_price,
)?;
let OrderFillSimulation {
token_amount: worst_case_token_amount,
orders_value: mut worst_case_orders_value,
token_value: worst_case_token_value,
weighted_token_value: mut worst_case_weighted_token_value,
..
} = spot_position
.get_worst_case_fill_simulation(
&spot_market,
&strict_oracle_price,
Some(signed_token_amount),
context.margin_type,
)?
.apply_user_custom_margin_ratio(
&spot_market,
strict_oracle_price.current,
user_custom_margin_ratio,
)?;
if worst_case_token_amount == 0 {
validate!(
spot_position.scaled_balance == 0,
ErrorCode::InvalidMarginRatio,
"spot_position.scaled_balance={} when worst_case_token_amount={} market_index={}",
spot_position.scaled_balance,
worst_case_token_amount,
spot_market.market_index,
)?;
}
calculation.add_margin_requirement(
spot_position.margin_requirement_for_open_orders()?,
0,
MarketIdentifier::spot(spot_market.market_index),
)?;
match worst_case_token_value.cmp(&0) {
Ordering::Greater => {
if calculation.context.ignore_invalid_deposit_oracles && !oracle_valid {
msg!(
"worst_case_weighted_token_value set to 0 for market_index={}",
spot_market.market_index
);
worst_case_weighted_token_value = 0;
}
calculation
.add_total_collateral(worst_case_weighted_token_value.cast::<i128>()?)?;
calculation.update_all_deposit_oracles_valid(oracle_valid);
#[cfg(feature = "drift-rs")]
calculation.add_spot_asset_value(worst_case_token_value)?;
}
Ordering::Less => {
validate!(
worst_case_weighted_token_value.unsigned_abs() >= worst_case_token_value.unsigned_abs(),
ErrorCode::InvalidMarginRatio,
"weighted_token_value < abs(worst_case_token_value) in spot market_index={}",
spot_market.market_index,
)?;
validate!(
worst_case_weighted_token_value != 0,
ErrorCode::InvalidOracle,
"weighted_token_value=0 for worst_case_token_amount={} in spot market_index={}",
worst_case_token_amount,
spot_market.market_index,
)?;
calculation.add_margin_requirement(
worst_case_weighted_token_value.unsigned_abs(),
worst_case_token_value.unsigned_abs(),
MarketIdentifier::spot(spot_market.market_index),
)?;
calculation.add_spot_liability()?;
calculation.update_with_spot_isolated_liability(
spot_market.asset_tier == AssetTier::Isolated,
);
calculation.update_all_liability_oracles_valid(oracle_valid);
#[cfg(feature = "drift-rs")]
calculation.add_spot_liability_value(worst_case_token_value.unsigned_abs())?;
}
Ordering::Equal => {
if spot_position.has_open_order() {
calculation.add_spot_liability()?;
calculation.update_all_liability_oracles_valid(oracle_valid);
calculation.update_with_spot_isolated_liability(
spot_market.asset_tier == AssetTier::Isolated,
);
}
}
}
match worst_case_orders_value.cmp(&0) {
Ordering::Greater => {
if calculation.context.ignore_invalid_deposit_oracles && !oracle_valid {
msg!(
"worst_case_orders_value set to 0 for market_index={}",
spot_market.market_index
);
worst_case_orders_value = 0;
}
calculation.add_total_collateral(worst_case_orders_value.cast::<i128>()?)?;
#[cfg(feature = "drift-rs")]
calculation.add_spot_asset_value(worst_case_orders_value)?;
}
Ordering::Less => {
calculation.add_margin_requirement(
worst_case_orders_value.unsigned_abs(),
worst_case_orders_value.unsigned_abs(),
MarketIdentifier::spot(0),
)?;
#[cfg(feature = "drift-rs")]
calculation.add_spot_liability_value(worst_case_orders_value.unsigned_abs())?;
}
Ordering::Equal => {}
}
}
}
for market_position in user.perp_positions.iter() {
if market_position.is_available() {
continue;
}
let market = &perp_market_map.get_ref(&market_position.market_index)?;
validate!(
user_pool_id == market.pool_id,
ErrorCode::InvalidPoolId,
"user pool id ({}) == perp market pool id ({})",
user_pool_id,
market.pool_id,
)?;
let quote_spot_market = spot_market_map.get_ref(&market.quote_spot_market_index)?;
let (quote_oracle_price_data, quote_oracle_validity) = oracle_map
.get_price_data_and_validity(
MarketType::Spot,
quote_spot_market.market_index,
"e_spot_market.oracle_id(),
quote_spot_market
.historical_oracle_data
.last_oracle_price_twap,
quote_spot_market.get_max_confidence_interval_multiplier()?,
)?;
let strict_quote_price = StrictOraclePrice::new(
quote_oracle_price_data.price,
quote_spot_market
.historical_oracle_data
.last_oracle_price_twap_5min,
calculation.context.strict,
);
drop(quote_spot_market);
let (oracle_price_data, oracle_validity) = oracle_map.get_price_data_and_validity(
MarketType::Perp,
market.market_index,
&market.oracle_id(),
market.amm.historical_oracle_data.last_oracle_price_twap,
market.get_max_confidence_interval_multiplier()?,
)?;
let (
perp_margin_requirement,
weighted_pnl,
worst_case_liability_value,
open_order_margin_requirement,
base_asset_value,
) = calculate_perp_position_value_and_pnl(
market_position,
market,
oracle_price_data,
&strict_quote_price,
context.margin_type,
user_custom_margin_ratio,
user_high_leverage_mode,
calculation.track_open_orders_fraction(),
)?;
calculation.update_fuel_perp_bonus(
market,
market_position,
base_asset_value,
oracle_price_data.price,
)?;
calculation.add_margin_requirement(
perp_margin_requirement,
worst_case_liability_value,
MarketIdentifier::perp(market.market_index),
)?;
if calculation.track_open_orders_fraction() {
calculation.add_open_orders_margin_requirement(open_order_margin_requirement)?;
}
calculation.add_total_collateral(weighted_pnl)?;
#[cfg(feature = "drift-rs")]
calculation.add_perp_liability_value(worst_case_liability_value)?;
#[cfg(feature = "drift-rs")]
calculation.add_perp_pnl(weighted_pnl)?;
let has_perp_liability = market_position.base_asset_amount != 0
|| market_position.quote_asset_amount < 0
|| market_position.has_open_order()
|| market_position.is_lp();
if has_perp_liability {
calculation.add_perp_liability()?;
calculation.update_with_perp_isolated_liability(
market.contract_tier == ContractTier::Isolated,
);
}
if has_perp_liability || calculation.context.margin_type != MarginRequirementType::Initial {
calculation.update_all_liability_oracles_valid(is_oracle_valid_for_action(
quote_oracle_validity,
Some(DriftAction::MarginCalc),
)?);
calculation.update_all_liability_oracles_valid(is_oracle_valid_for_action(
oracle_validity,
Some(DriftAction::MarginCalc),
)?);
}
}
calculation.validate_num_spot_liabilities()?;
Ok(calculation)
}
pub fn validate_any_isolated_tier_requirements(
user: &User,
calculation: MarginCalculation,
) -> DriftResult {
if calculation.with_perp_isolated_liability && !user.is_reduce_only() {
validate!(
calculation.num_perp_liabilities <= 1,
ErrorCode::IsolatedAssetTierViolation,
"User attempting to increase perp liabilities above 1 with a isolated tier liability"
)?;
validate!(
!user.is_margin_trading_enabled,
ErrorCode::IsolatedAssetTierViolation,
"User attempting isolated tier liability with margin trading enabled"
)?;
if calculation.num_spot_liabilities > 0 {
let quote_spot_position = user.get_quote_spot_position();
validate!(
(calculation.num_spot_liabilities == 1 && quote_spot_position.is_borrow()
),
ErrorCode::IsolatedAssetTierViolation,
"User attempting to increase spot liabilities beyond usdc with a isolated tier liability"
)?;
}
}
if calculation.with_spot_isolated_liability && !user.is_reduce_only() {
validate!(
calculation.num_perp_liabilities == 0 && calculation.num_spot_liabilities == 1,
ErrorCode::IsolatedAssetTierViolation,
"User attempting to increase perp liabilities above 0 with a isolated tier liability"
)?;
}
Ok(())
}
pub fn meets_withdraw_margin_requirement(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
margin_requirement_type: MarginRequirementType,
) -> DriftResult<bool> {
let strict = margin_requirement_type == MarginRequirementType::Initial;
let context = MarginContext::standard(margin_requirement_type)
.strict(strict)
.ignore_invalid_deposit_oracles(true);
let calculation = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
context,
)?;
if calculation.margin_requirement > 0 || calculation.get_num_of_liabilities()? > 0 {
validate!(
calculation.all_liability_oracles_valid,
ErrorCode::InvalidOracle,
"User attempting to withdraw with outstanding liabilities when a liability oracle is invalid"
)?;
}
validate_any_isolated_tier_requirements(user, calculation)?;
validate!(
calculation.meets_margin_requirement(),
ErrorCode::InsufficientCollateral,
"User attempting to withdraw where total_collateral {} is below initial_margin_requirement {}",
calculation.total_collateral,
calculation.margin_requirement
)?;
Ok(true)
}
pub fn meets_place_order_margin_requirement(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
risk_increasing: bool,
) -> DriftResult {
let margin_type = if risk_increasing {
MarginRequirementType::Initial
} else {
MarginRequirementType::Maintenance
};
let context = MarginContext::standard(margin_type).strict(true);
let calculation = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
context,
)?;
if !calculation.meets_margin_requirement() {
msg!(
"total_collateral={}, margin_requirement={} margin type = {:?}",
calculation.total_collateral,
calculation.margin_requirement,
margin_type
);
return Err(ErrorCode::InsufficientCollateral);
}
validate_any_isolated_tier_requirements(user, calculation)?;
Ok(())
}
pub fn meets_initial_margin_requirement(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<bool> {
calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
MarginContext::standard(MarginRequirementType::Initial),
)
.map(|calc| calc.meets_margin_requirement())
}
pub fn meets_settle_pnl_maintenance_margin_requirement(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<bool> {
calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
MarginContext::standard(MarginRequirementType::Maintenance).strict(true),
)
.map(|calc| calc.meets_margin_requirement())
}
pub fn meets_maintenance_margin_requirement(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<bool> {
calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
MarginContext::standard(MarginRequirementType::Maintenance),
)
.map(|calc| calc.meets_margin_requirement())
}
pub fn calculate_max_withdrawable_amount(
market_index: u16,
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<u64> {
let calculation = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
perp_market_map,
spot_market_map,
oracle_map,
MarginContext::standard(MarginRequirementType::Initial),
)?;
let spot_market = &mut spot_market_map.get_ref(&market_index)?;
let token_amount = user
.get_spot_position(market_index)?
.get_token_amount(spot_market)?;
let oracle_price = oracle_map.get_price_data(&spot_market.oracle_id())?.price;
let asset_weight = spot_market.get_asset_weight(
token_amount,
oracle_price,
&MarginRequirementType::Initial,
)?;
if asset_weight == 0 {
return Ok(u64::MAX);
}
if calculation.get_num_of_liabilities()? == 0 {
// user has small dust deposit and no liabilities
// so return early with user tokens amount
return token_amount.cast();
}
let free_collateral = calculation.get_free_collateral()?;
let precision_increase = 10u128.pow(spot_market.decimals - 6);
free_collateral
.safe_mul(MARGIN_PRECISION_U128)?
.safe_div(asset_weight.cast()?)?
.safe_mul(PRICE_PRECISION)?
.safe_div(oracle_price.cast()?)?
.safe_mul(precision_increase)?
.cast()
}
pub fn validate_spot_margin_trading(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult {
if user.is_margin_trading_enabled {
for perp_position in &user.perp_positions {
if !perp_position.is_available() {
let perp_market = perp_market_map.get_ref(&perp_position.market_index)?;
validate!(
perp_market.contract_tier != ContractTier::Isolated,
ErrorCode::IsolatedAssetTierViolation,
"Isolated perpetual market = {} doesn't allow margin trading",
perp_market.market_index
)?;
}
}
return Ok(());
}
let mut total_open_bids_value = 0_i128;
for spot_position in &user.spot_positions {
let asks = spot_position.open_asks;
if asks < 0 {
let spot_market = spot_market_map.get_ref(&spot_position.market_index)?;
let signed_token_amount = spot_position.get_signed_token_amount(&spot_market)?;
// The user can have:
// 1. no open asks with an existing short
// 2. open asks with a larger existing long
validate!(
signed_token_amount.safe_add(asks.cast()?)? >= 0,
ErrorCode::MarginTradingDisabled,
"Open asks can lead to increased borrow in spot market {}",
spot_position.market_index
)?;
}
let bids = spot_position.open_bids;
if bids > 0 {
let spot_market = spot_market_map.get_ref(&spot_position.market_index)?;
let oracle_price_data = oracle_map.get_price_data(&spot_market.oracle_id())?;
let open_bids_value =
get_token_value(-bids as i128, spot_market.decimals, oracle_price_data.price)?;
total_open_bids_value = total_open_bids_value.safe_add(open_bids_value)?;
}
}
let mut quote_token_amount = 0_i128;
let quote_spot_position = user.get_quote_spot_position();
if !quote_spot_position.is_available() {
let quote_spot_market = spot_market_map.get_quote_spot_market()?;
quote_token_amount = quote_spot_position.get_signed_token_amount("e_spot_market)?;
}
// The user can have open bids if their value is less than existing quote token amount
validate!(
total_open_bids_value == 0 || quote_token_amount.safe_add(total_open_bids_value)? >= 0,
ErrorCode::MarginTradingDisabled,
"Open bids leads to increased borrow for spot market 0"
)?;
Ok(())
}
pub fn calculate_user_equity(
user: &User,
perp_market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
) -> DriftResult<(i128, bool)> {
let mut net_usd_value: i128 = 0;
let mut all_oracles_valid = true;
for spot_position in user.spot_positions.iter() {
if spot_position.is_available() {
continue;
}
let spot_market = spot_market_map.get_ref(&spot_position.market_index)?;
let (oracle_price_data, oracle_validity) = oracle_map.get_price_data_and_validity(
MarketType::Spot,
spot_market.market_index,
&spot_market.oracle_id(),
spot_market.historical_oracle_data.last_oracle_price_twap,
spot_market.get_max_confidence_interval_multiplier()?,
)?;
all_oracles_valid &=
is_oracle_valid_for_action(oracle_validity, Some(DriftAction::MarginCalc))?;
let token_amount = spot_position.get_signed_token_amount(&spot_market)?;
let oracle_price = oracle_price_data.price;
let token_value = get_token_value(token_amount, spot_market.decimals, oracle_price)?;
net_usd_value = net_usd_value.safe_add(token_value)?;
}
for market_position in user.perp_positions.iter() {
if market_position.is_available() {
continue;
}
let market = &perp_market_map.get_ref(&market_position.market_index)?;
let quote_oracle_price = {
let quote_spot_market = spot_market_map.get_ref(&market.quote_spot_market_index)?;
let (quote_oracle_price_data, quote_oracle_validity) = oracle_map
.get_price_data_and_validity(
MarketType::Spot,
quote_spot_market.market_index,
"e_spot_market.oracle_id(),
quote_spot_market
.historical_oracle_data
.last_oracle_price_twap,
quote_spot_market.get_max_confidence_interval_multiplier()?,
)?;
all_oracles_valid &=
is_oracle_valid_for_action(quote_oracle_validity, Some(DriftAction::MarginCalc))?;
quote_oracle_price_data.price
};
let (oracle_price_data, oracle_validity) = oracle_map.get_price_data_and_validity(
MarketType::Perp,
market.market_index,
&market.oracle_id(),
market.amm.historical_oracle_data.last_oracle_price_twap,
market.get_max_confidence_interval_multiplier()?,
)?;
all_oracles_valid &=
is_oracle_valid_for_action(oracle_validity, Some(DriftAction::MarginCalc))?;
let valuation_price = if market.status == MarketStatus::Settlement {
market.expiry_price
} else {
oracle_price_data.price
};
let unrealized_funding = calculate_funding_payment(
if market_position.base_asset_amount > 0 {
market.amm.cumulative_funding_rate_long
} else {
market.amm.cumulative_funding_rate_short
},
market_position,
)?;
let market_position =
market_position.simulate_settled_lp_position(market, valuation_price)?;
let (_, unrealized_pnl) = calculate_base_asset_value_and_pnl_with_oracle_price(
&market_position,
valuation_price,
)?;
let pnl = unrealized_pnl.safe_add(unrealized_funding.cast()?)?;
let pnl_value = pnl
.safe_mul(quote_oracle_price.cast()?)?
.safe_div(PRICE_PRECISION_I128)?;
net_usd_value = net_usd_value.safe_add(pnl_value)?;
}
Ok((net_usd_value, all_oracles_valid))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/fulfillment.rs
|
use crate::controller::position::PositionDirection;
use crate::error::DriftResult;
use crate::math::auction::can_fill_with_amm;
use crate::math::casting::Cast;
use crate::math::matching::do_orders_cross;
use crate::math::safe_unwrap::SafeUnwrap;
use crate::state::fill_mode::FillMode;
use crate::state::fulfillment::{PerpFulfillmentMethod, SpotFulfillmentMethod};
use crate::state::perp_market::{AMMAvailability, AMM};
use crate::state::user::Order;
use solana_program::pubkey::Pubkey;
#[cfg(test)]
mod tests;
pub fn determine_perp_fulfillment_methods(
order: &Order,
maker_orders_info: &[(Pubkey, usize, u64)],
amm: &AMM,
amm_reserve_price: u64,
valid_oracle_price: Option<i64>,
limit_price: Option<u64>,
amm_availability: AMMAvailability,
slot: u64,
min_auction_duration: u8,
fill_mode: FillMode,
) -> DriftResult<Vec<PerpFulfillmentMethod>> {
if order.post_only {
return determine_perp_fulfillment_methods_for_maker(
order,
amm,
amm_reserve_price,
valid_oracle_price,
limit_price,
amm_availability,
slot,
min_auction_duration,
fill_mode,
);
}
let mut fulfillment_methods = Vec::with_capacity(8);
let can_fill_with_amm = can_fill_with_amm(
amm_availability,
valid_oracle_price,
order,
min_auction_duration,
slot,
fill_mode,
)?;
let maker_direction = order.direction.opposite();
let mut amm_price = match maker_direction {
PositionDirection::Long => amm.bid_price(amm_reserve_price)?,
PositionDirection::Short => amm.ask_price(amm_reserve_price)?,
};
for (maker_key, maker_order_index, maker_price) in maker_orders_info.iter() {
let taker_crosses_maker = match limit_price {
Some(taker_price) => do_orders_cross(maker_direction, *maker_price, taker_price),
None => true,
};
if !taker_crosses_maker {
break;
}
if can_fill_with_amm {
let maker_better_than_amm = match order.direction {
PositionDirection::Long => *maker_price <= amm_price,
PositionDirection::Short => *maker_price >= amm_price,
};
if !maker_better_than_amm {
fulfillment_methods.push(PerpFulfillmentMethod::AMM(Some(*maker_price)));
amm_price = *maker_price;
}
}
fulfillment_methods.push(PerpFulfillmentMethod::Match(
*maker_key,
maker_order_index.cast()?,
));
if fulfillment_methods.len() > 6 {
break;
}
}
if can_fill_with_amm {
let taker_crosses_amm = match limit_price {
Some(taker_price) => do_orders_cross(maker_direction, amm_price, taker_price),
None => true,
};
if taker_crosses_amm {
fulfillment_methods.push(PerpFulfillmentMethod::AMM(None));
}
}
Ok(fulfillment_methods)
}
fn determine_perp_fulfillment_methods_for_maker(
order: &Order,
amm: &AMM,
amm_reserve_price: u64,
valid_oracle_price: Option<i64>,
limit_price: Option<u64>,
amm_availability: AMMAvailability,
slot: u64,
min_auction_duration: u8,
fill_mode: FillMode,
) -> DriftResult<Vec<PerpFulfillmentMethod>> {
let maker_direction = order.direction;
let can_fill_with_amm = can_fill_with_amm(
amm_availability,
valid_oracle_price,
order,
min_auction_duration,
slot,
fill_mode,
)?;
if !can_fill_with_amm {
return Ok(vec![]);
}
let amm_price = match maker_direction {
PositionDirection::Long => amm.ask_price(amm_reserve_price)?,
PositionDirection::Short => amm.bid_price(amm_reserve_price)?,
};
let maker_price = limit_price.safe_unwrap()?;
let amm_crosses_maker = do_orders_cross(maker_direction, maker_price, amm_price);
if amm_crosses_maker {
Ok(vec![PerpFulfillmentMethod::AMM(None)])
} else {
Ok(vec![])
}
}
pub fn determine_spot_fulfillment_methods(
order: &Order,
maker_orders_info: &[(Pubkey, usize, u64)],
limit_price: Option<u64>,
external_fulfillment_params_available: bool,
) -> DriftResult<Vec<SpotFulfillmentMethod>> {
let mut fulfillment_methods = Vec::with_capacity(8);
if !order.post_only && external_fulfillment_params_available {
fulfillment_methods.push(SpotFulfillmentMethod::ExternalMarket);
return Ok(fulfillment_methods);
}
let maker_direction = order.direction.opposite();
for (maker_key, maker_order_index, maker_price) in maker_orders_info.iter() {
let taker_crosses_maker = match limit_price {
Some(taker_price) => do_orders_cross(maker_direction, *maker_price, taker_price),
// todo come up with fallback price
None => false,
};
if !taker_crosses_maker {
break;
}
fulfillment_methods.push(SpotFulfillmentMethod::Match(
*maker_key,
*maker_order_index as u16,
));
if fulfillment_methods.len() > 6 {
break;
}
}
Ok(fulfillment_methods)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/ceil_div.rs
|
use crate::math::bn::{U192, U256};
use num_traits::{One, Zero};
pub trait CheckedCeilDiv: Sized {
/// Perform ceiling division
fn checked_ceil_div(&self, rhs: Self) -> Option<Self>;
}
macro_rules! checked_impl {
($t:ty) => {
impl CheckedCeilDiv for $t {
#[track_caller]
#[inline]
fn checked_ceil_div(&self, rhs: $t) -> Option<$t> {
let quotient = self.checked_div(rhs)?;
let remainder = self.checked_rem(rhs)?;
if remainder > <$t>::zero() {
quotient.checked_add(<$t>::one())
} else {
Some(quotient)
}
}
}
};
}
checked_impl!(U256);
checked_impl!(U192);
checked_impl!(u128);
checked_impl!(u64);
checked_impl!(u32);
checked_impl!(u16);
checked_impl!(u8);
checked_impl!(i128);
checked_impl!(i64);
checked_impl!(i32);
checked_impl!(i16);
checked_impl!(i8);
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/amm.rs
|
use std::cmp::{max, min};
use solana_program::msg;
use crate::controller::amm::SwapDirection;
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode};
use crate::math::bn::U192;
use crate::math::casting::Cast;
use crate::math::constants::{
BID_ASK_SPREAD_PRECISION_I128, CONCENTRATION_PRECISION,
DEFAULT_MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR, FIVE_MINUTE, ONE_HOUR, ONE_MINUTE,
PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO, PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO_I128,
PRICE_TO_PEG_PRECISION_RATIO, QUOTE_PRECISION_I64,
};
use crate::math::orders::standardize_base_asset_amount;
use crate::math::quote_asset::reserve_to_asset_amount;
use crate::math::stats::{calculate_new_twap, calculate_rolling_sum, calculate_weighted_average};
use crate::state::oracle::OraclePriceData;
use crate::state::perp_market::AMM;
use crate::state::state::PriceDivergenceGuardRails;
use crate::{validate, PERCENTAGE_PRECISION_U64};
use super::helpers::get_proportion_u128;
use crate::math::safe_math::SafeMath;
#[cfg(test)]
mod tests;
pub fn calculate_price(
quote_asset_reserve: u128,
base_asset_reserve: u128,
peg_multiplier: u128,
) -> DriftResult<u64> {
let peg_quote_asset_amount = quote_asset_reserve.safe_mul(peg_multiplier)?;
U192::from(peg_quote_asset_amount)
.safe_mul(U192::from(PRICE_TO_PEG_PRECISION_RATIO))?
.safe_div(U192::from(base_asset_reserve))?
.try_to_u64()
}
pub fn calculate_bid_ask_bounds(
concentration_coef: u128,
sqrt_k: u128,
) -> DriftResult<(u128, u128)> {
validate!(
concentration_coef > CONCENTRATION_PRECISION,
ErrorCode::InvalidConcentrationCoef,
"concentration_coef={} <= CONCENTRATION_PRECISION={}",
concentration_coef,
CONCENTRATION_PRECISION
)?;
// worse case if all asks are filled (max reserve)
let ask_bounded_base =
get_proportion_u128(sqrt_k, concentration_coef, CONCENTRATION_PRECISION)?;
// worse case if all bids are filled (min reserve)
let bid_bounded_base =
get_proportion_u128(sqrt_k, CONCENTRATION_PRECISION, concentration_coef)?;
Ok((bid_bounded_base, ask_bounded_base))
}
pub fn calculate_market_open_bids_asks(amm: &AMM) -> DriftResult<(i128, i128)> {
let base_asset_reserve = amm.base_asset_reserve;
let min_base_asset_reserve = amm.min_base_asset_reserve;
let max_base_asset_reserve = amm.max_base_asset_reserve;
let (max_bids, max_asks) = _calculate_market_open_bids_asks(
base_asset_reserve,
min_base_asset_reserve,
max_base_asset_reserve,
)?;
Ok((max_bids, max_asks))
}
pub fn _calculate_market_open_bids_asks(
base_asset_reserve: u128,
min_base_asset_reserve: u128,
max_base_asset_reserve: u128,
) -> DriftResult<(i128, i128)> {
// worse case if all asks are filled
let max_asks = if base_asset_reserve < max_base_asset_reserve {
-max_base_asset_reserve
.safe_sub(base_asset_reserve)?
.cast::<i128>()?
} else {
0
};
// worst case if all bids are filled
let max_bids = if base_asset_reserve > min_base_asset_reserve {
base_asset_reserve
.safe_sub(min_base_asset_reserve)?
.cast::<i128>()?
} else {
0
};
Ok((max_bids, max_asks))
}
pub fn update_mark_twap_crank(
amm: &mut AMM,
now: i64,
oracle_price_data: &OraclePriceData,
best_dlob_bid_price: Option<u64>,
best_dlob_ask_price: Option<u64>,
sanitize_clamp: Option<i64>,
) -> DriftResult {
let amm_reserve_price = amm.reserve_price()?;
let (amm_bid_price, amm_ask_price) = amm.bid_ask_price(amm_reserve_price)?;
let mut best_bid_price = match best_dlob_bid_price {
Some(best_dlob_bid_price) => best_dlob_bid_price.max(amm_bid_price),
None => amm_bid_price,
};
let mut best_ask_price = match best_dlob_ask_price {
Some(best_dlob_ask_price) => best_dlob_ask_price.min(amm_ask_price),
None => amm_ask_price,
};
// handle crossing bid/ask
if best_bid_price > best_ask_price {
if best_bid_price >= oracle_price_data.price.cast()? {
best_bid_price = best_ask_price;
} else {
best_ask_price = best_bid_price;
}
}
update_mark_twap(
amm,
now,
best_bid_price,
best_ask_price,
None,
sanitize_clamp,
)?;
Ok(())
}
pub fn estimate_best_bid_ask_price(
amm: &mut AMM,
precomputed_trade_price: Option<u64>,
direction: Option<PositionDirection>,
) -> DriftResult<(u64, u64)> {
let base_spread_u64 = amm.base_spread.cast::<u64>()?;
let last_oracle_price_u64 = amm.historical_oracle_data.last_oracle_price.cast::<u64>()?;
let trade_price: u64 = match precomputed_trade_price {
Some(trade_price) => trade_price,
None => last_oracle_price_u64,
};
let trade_premium: i64 = trade_price
.cast::<i64>()?
.safe_sub(amm.historical_oracle_data.last_oracle_price)?;
validate!(
amm.historical_oracle_data.last_oracle_price > 0,
ErrorCode::InvalidOracle,
"amm.historical_oracle_data.last_oracle_price <= 0"
)?;
let amm_reserve_price = amm.reserve_price()?;
let (amm_bid_price, amm_ask_price) = amm.bid_ask_price(amm_reserve_price)?;
// estimation of bid/ask by looking at execution premium
// trade is a long
let best_bid_estimate = if trade_premium > 0 {
let discount = min(base_spread_u64, amm.short_spread.cast::<u64>()? / 2);
last_oracle_price_u64
.saturating_sub(discount.min(trade_premium.unsigned_abs()))
.max(amm.order_tick_size)
} else {
trade_price
}
.max(amm_bid_price);
// trade is a short
let best_ask_estimate = if trade_premium < 0 {
let premium: u64 = min(base_spread_u64, amm.long_spread.cast::<u64>()? / 2);
last_oracle_price_u64.safe_add(premium.min(trade_premium.unsigned_abs()))?
} else {
trade_price
}
.min(amm_ask_price);
let (bid_price, ask_price) = match direction {
Some(direction) => match direction {
PositionDirection::Long => (best_bid_estimate, trade_price.max(best_bid_estimate)),
PositionDirection::Short => (trade_price.min(best_ask_estimate), best_ask_estimate),
},
None => (
trade_price.max(amm_bid_price).min(amm_ask_price),
trade_price.max(amm_bid_price).min(amm_ask_price),
),
};
validate!(
bid_price <= ask_price,
ErrorCode::InvalidMarkTwapUpdateDetected,
"bid_price({}, {}) not <= ask_price({}, {}),",
best_bid_estimate,
bid_price,
ask_price,
best_ask_estimate,
)?;
Ok((bid_price, ask_price))
}
pub fn update_mark_twap(
amm: &mut AMM,
now: i64,
bid_price: u64,
ask_price: u64,
precomputed_trade_price: Option<u64>,
sanitize_clamp: Option<i64>,
) -> DriftResult<u64> {
let (bid_price_capped_update, ask_price_capped_update) = (
sanitize_new_price(
bid_price.cast()?,
amm.last_bid_price_twap.cast()?,
sanitize_clamp,
)?,
sanitize_new_price(
ask_price.cast()?,
amm.last_ask_price_twap.cast()?,
sanitize_clamp,
)?,
);
validate!(
bid_price_capped_update <= ask_price_capped_update,
ErrorCode::InvalidMarkTwapUpdateDetected,
"bid_price_capped_update not <= ask_price_capped_update,"
)?;
let last_valid_trade_since_oracle_twap_update = amm
.historical_oracle_data
.last_oracle_price_twap_ts
.safe_sub(amm.last_mark_price_twap_ts)?;
// if an delayed more than ONE_MINUTE or 60th of funding period, shrink toward oracle_twap
let (last_bid_price_twap, last_ask_price_twap) = if last_valid_trade_since_oracle_twap_update
> amm.funding_period.safe_div(60)?.max(ONE_MINUTE.cast()?)
{
msg!(
"correcting mark twap update (oracle previously invalid for {:?} seconds)",
last_valid_trade_since_oracle_twap_update
);
let from_start_valid = max(
0,
amm.funding_period
.safe_sub(last_valid_trade_since_oracle_twap_update)?,
);
(
calculate_weighted_average(
amm.historical_oracle_data
.last_oracle_price_twap
.cast::<i64>()?,
amm.last_bid_price_twap.cast()?,
last_valid_trade_since_oracle_twap_update,
from_start_valid,
)?,
calculate_weighted_average(
amm.historical_oracle_data
.last_oracle_price_twap
.cast::<i64>()?,
amm.last_ask_price_twap.cast()?,
last_valid_trade_since_oracle_twap_update,
from_start_valid,
)?,
)
} else {
(
amm.last_bid_price_twap.cast()?,
amm.last_ask_price_twap.cast()?,
)
};
// update bid and ask twaps
let bid_twap = calculate_new_twap(
bid_price_capped_update,
now,
last_bid_price_twap,
amm.last_mark_price_twap_ts,
amm.funding_period,
)?;
amm.last_bid_price_twap = bid_twap.cast()?;
let ask_twap = calculate_new_twap(
ask_price_capped_update,
now,
last_ask_price_twap,
amm.last_mark_price_twap_ts,
amm.funding_period,
)?;
amm.last_ask_price_twap = ask_twap.cast()?;
let mid_twap = bid_twap.safe_add(ask_twap)? / 2;
// update std stat
let trade_price: u64 = match precomputed_trade_price {
Some(trade_price) => trade_price,
None => bid_price.safe_add(ask_price)?.safe_div(2)?,
};
update_amm_mark_std(amm, now, trade_price, amm.last_mark_price_twap)?;
amm.last_mark_price_twap = mid_twap.cast()?;
amm.last_mark_price_twap_5min = calculate_new_twap(
bid_price_capped_update
.safe_add(ask_price_capped_update)?
.safe_div(2)?
.cast()?,
now,
amm.last_mark_price_twap_5min.cast()?,
amm.last_mark_price_twap_ts,
FIVE_MINUTE as i64,
)?
.cast()?;
amm.last_mark_price_twap_ts = now;
mid_twap.cast()
}
pub fn update_mark_twap_from_estimates(
amm: &mut AMM,
now: i64,
precomputed_trade_price: Option<u64>,
direction: Option<PositionDirection>,
sanitize_clamp: Option<i64>,
) -> DriftResult<u64> {
let (bid_price, ask_price) =
estimate_best_bid_ask_price(amm, precomputed_trade_price, direction)?;
update_mark_twap(
amm,
now,
bid_price,
ask_price,
precomputed_trade_price,
sanitize_clamp,
)
}
pub fn sanitize_new_price(
new_price: i64,
last_price_twap: i64,
sanitize_clamp_denominator: Option<i64>,
) -> DriftResult<i64> {
// when/if twap is 0, dont try to normalize new_price
if last_price_twap == 0 {
return Ok(new_price);
}
let new_price_spread = new_price.safe_sub(last_price_twap)?;
// cap new oracle update to 100/MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR% delta from twap
let sanitize_clamp_denominator =
if let Some(sanitize_clamp_denominator) = sanitize_clamp_denominator {
sanitize_clamp_denominator
} else {
DEFAULT_MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR
};
if sanitize_clamp_denominator == 0 {
// no need to use price band check
return Ok(new_price);
}
let price_twap_price_band = last_price_twap.safe_div(sanitize_clamp_denominator)?;
let capped_update_price =
if new_price_spread.unsigned_abs() > price_twap_price_band.unsigned_abs() {
if new_price > last_price_twap {
last_price_twap.safe_add(price_twap_price_band)?
} else {
last_price_twap.safe_sub(price_twap_price_band)?
}
} else {
new_price
};
Ok(capped_update_price)
}
pub fn update_oracle_price_twap(
amm: &mut AMM,
now: i64,
oracle_price_data: &OraclePriceData,
precomputed_reserve_price: Option<u64>,
sanitize_clamp: Option<i64>,
) -> DriftResult<i64> {
let reserve_price = match precomputed_reserve_price {
Some(reserve_price) => reserve_price,
None => amm.reserve_price()?,
};
let oracle_price = normalise_oracle_price(amm, oracle_price_data, Some(reserve_price))?;
let capped_oracle_update_price = sanitize_new_price(
oracle_price,
amm.historical_oracle_data.last_oracle_price_twap,
sanitize_clamp,
)?;
// sanity check
let oracle_price_twap: i64;
if capped_oracle_update_price > 0 && oracle_price > 0 {
oracle_price_twap = calculate_new_oracle_price_twap(
amm,
now,
capped_oracle_update_price,
TwapPeriod::FundingPeriod,
)?;
let oracle_price_twap_5min = calculate_new_oracle_price_twap(
amm,
now,
capped_oracle_update_price,
TwapPeriod::FiveMin,
)?;
amm.last_oracle_normalised_price = capped_oracle_update_price;
amm.historical_oracle_data.last_oracle_price = oracle_price_data.price;
// use decayed last_oracle_conf_pct as lower bound
amm.last_oracle_conf_pct =
amm.get_new_oracle_conf_pct(oracle_price_data.confidence, reserve_price, now)?;
amm.historical_oracle_data.last_oracle_delay = oracle_price_data.delay;
amm.last_oracle_reserve_price_spread_pct =
calculate_oracle_reserve_price_spread_pct(amm, oracle_price_data, Some(reserve_price))?;
amm.historical_oracle_data.last_oracle_price_twap_5min = oracle_price_twap_5min;
amm.historical_oracle_data.last_oracle_price_twap = oracle_price_twap;
// update std stat
update_amm_oracle_std(
amm,
now,
oracle_price.cast()?,
amm.historical_oracle_data.last_oracle_price_twap.cast()?,
)?;
amm.historical_oracle_data.last_oracle_price_twap_ts = now;
} else {
oracle_price_twap = amm.historical_oracle_data.last_oracle_price_twap
}
Ok(oracle_price_twap)
}
pub enum TwapPeriod {
FundingPeriod,
FiveMin,
}
pub fn calculate_new_oracle_price_twap(
amm: &AMM,
now: i64,
oracle_price: i64,
twap_period: TwapPeriod,
) -> DriftResult<i64> {
let (last_mark_twap, last_oracle_twap) = match twap_period {
TwapPeriod::FundingPeriod => (
amm.last_mark_price_twap,
amm.historical_oracle_data.last_oracle_price_twap,
),
TwapPeriod::FiveMin => (
amm.last_mark_price_twap_5min,
amm.historical_oracle_data.last_oracle_price_twap_5min,
),
};
let period: i64 = match twap_period {
TwapPeriod::FundingPeriod => amm.funding_period,
TwapPeriod::FiveMin => FIVE_MINUTE as i64,
};
let since_last = max(
if period == 0 { 1_i64 } else { 0_i64 },
now.safe_sub(amm.historical_oracle_data.last_oracle_price_twap_ts)?,
);
let from_start = max(0_i64, period.safe_sub(since_last)?);
// if an oracle delay impacted last oracle_twap, shrink toward mark_twap
let interpolated_oracle_price =
if amm.last_mark_price_twap_ts > amm.historical_oracle_data.last_oracle_price_twap_ts {
let since_last_valid = amm
.last_mark_price_twap_ts
.safe_sub(amm.historical_oracle_data.last_oracle_price_twap_ts)?;
msg!(
"correcting oracle twap update (oracle previously invalid for {:?} seconds)",
since_last_valid
);
let from_start_valid = max(1, period.safe_sub(since_last_valid)?);
calculate_weighted_average(
last_mark_twap.cast::<i64>()?,
oracle_price,
since_last_valid,
from_start_valid,
)?
} else {
oracle_price
};
calculate_weighted_average(
interpolated_oracle_price,
last_oracle_twap.cast()?,
since_last,
from_start,
)
}
pub fn update_amm_mark_std(amm: &mut AMM, now: i64, price: u64, ewma: u64) -> DriftResult<bool> {
let since_last = max(1_i64, now.safe_sub(amm.last_mark_price_twap_ts)?);
let price_change = price.cast::<i64>()?.safe_sub(ewma.cast::<i64>()?)?;
amm.mark_std = calculate_rolling_sum(
amm.mark_std,
price_change.unsigned_abs(),
max(ONE_HOUR, since_last),
ONE_HOUR,
)?;
Ok(true)
}
pub fn update_amm_oracle_std(amm: &mut AMM, now: i64, price: u64, ewma: u64) -> DriftResult<bool> {
let since_last = max(
1_i64,
now.safe_sub(amm.historical_oracle_data.last_oracle_price_twap_ts)?,
);
let price_change = price.cast::<i64>()?.safe_sub(ewma.cast::<i64>()?)?;
amm.oracle_std = calculate_rolling_sum(
amm.oracle_std,
price_change.unsigned_abs(),
max(ONE_HOUR, since_last),
ONE_HOUR,
)?;
Ok(true)
}
pub fn update_amm_long_short_intensity(
amm: &mut AMM,
now: i64,
quote_asset_amount: u64,
direction: PositionDirection,
) -> DriftResult<bool> {
let since_last = max(1, now.safe_sub(amm.last_trade_ts)?);
let (long_quote_amount, short_quote_amount) = if direction == PositionDirection::Long {
(quote_asset_amount, 0_u64)
} else {
(0_u64, quote_asset_amount)
};
amm.long_intensity_count = calculate_weighted_average(
amm.long_intensity_count.cast()?,
long_quote_amount
.cast::<i64>()?
.safe_div(QUOTE_PRECISION_I64)?,
since_last,
ONE_HOUR,
)?
.cast()?;
amm.long_intensity_volume = calculate_rolling_sum(
amm.long_intensity_volume,
long_quote_amount,
since_last,
ONE_HOUR,
)?;
amm.short_intensity_count = calculate_weighted_average(
amm.short_intensity_count.cast()?,
short_quote_amount
.cast::<i64>()?
.safe_div(QUOTE_PRECISION_I64)?,
since_last,
ONE_HOUR,
)?
.cast()?;
amm.short_intensity_volume = calculate_rolling_sum(
amm.short_intensity_volume,
short_quote_amount,
since_last,
ONE_HOUR,
)?;
Ok(true)
}
pub fn calculate_swap_output(
swap_amount: u128,
input_asset_reserve: u128,
direction: SwapDirection,
invariant_sqrt: u128,
) -> DriftResult<(u128, u128)> {
let invariant_sqrt_u192 = U192::from(invariant_sqrt);
let invariant = invariant_sqrt_u192.safe_mul(invariant_sqrt_u192)?;
if direction == SwapDirection::Remove && swap_amount > input_asset_reserve {
msg!("{:?} > {:?}", swap_amount, input_asset_reserve);
return Err(ErrorCode::TradeSizeTooLarge);
}
let new_input_asset_reserve = if let SwapDirection::Add = direction {
input_asset_reserve.safe_add(swap_amount)?
} else {
input_asset_reserve.safe_sub(swap_amount)?
};
let new_input_amount_u192 = U192::from(new_input_asset_reserve);
let new_output_asset_reserve = invariant.safe_div(new_input_amount_u192)?.try_to_u128()?;
Ok((new_output_asset_reserve, new_input_asset_reserve))
}
pub fn calculate_quote_asset_amount_swapped(
quote_asset_reserve_before: u128,
quote_asset_reserve_after: u128,
swap_direction: SwapDirection,
peg_multiplier: u128,
) -> DriftResult<u128> {
let mut quote_asset_reserve_change = match swap_direction {
SwapDirection::Add => quote_asset_reserve_before.safe_sub(quote_asset_reserve_after)?,
SwapDirection::Remove => quote_asset_reserve_after.safe_sub(quote_asset_reserve_before)?,
};
// when a user goes long base asset, make the base asset slightly more expensive
// by adding one unit of quote asset
if swap_direction == SwapDirection::Remove {
quote_asset_reserve_change = quote_asset_reserve_change.safe_add(1)?;
}
let mut quote_asset_amount =
reserve_to_asset_amount(quote_asset_reserve_change, peg_multiplier)?;
// when a user goes long base asset, make the base asset slightly more expensive
// by adding one unit of quote asset
if swap_direction == SwapDirection::Remove {
quote_asset_amount = quote_asset_amount.safe_add(1)?;
}
Ok(quote_asset_amount)
}
pub fn calculate_terminal_reserves(amm: &AMM) -> DriftResult<(u128, u128)> {
let swap_direction = if amm.base_asset_amount_with_amm > 0 {
SwapDirection::Add
} else {
SwapDirection::Remove
};
let (new_quote_asset_amount, new_base_asset_amount) = calculate_swap_output(
amm.base_asset_amount_with_amm.unsigned_abs(),
amm.base_asset_reserve,
swap_direction,
amm.sqrt_k,
)?;
Ok((new_quote_asset_amount, new_base_asset_amount))
}
pub fn calculate_terminal_price_and_reserves(amm: &AMM) -> DriftResult<(u64, u128, u128)> {
let (new_quote_asset_amount, new_base_asset_amount) = calculate_terminal_reserves(amm)?;
let terminal_price = calculate_price(
new_quote_asset_amount,
new_base_asset_amount,
amm.peg_multiplier,
)?;
Ok((
terminal_price,
new_quote_asset_amount,
new_base_asset_amount,
))
}
pub fn calculate_oracle_reserve_price_spread(
amm: &AMM,
oracle_price_data: &OraclePriceData,
precomputed_reserve_price: Option<u64>,
) -> DriftResult<(i64, i64)> {
let reserve_price = match precomputed_reserve_price {
Some(reserve_price) => reserve_price.cast::<i64>()?,
None => amm.reserve_price()?.cast::<i64>()?,
};
let oracle_price = oracle_price_data.price;
let price_spread = reserve_price.safe_sub(oracle_price)?;
Ok((oracle_price, price_spread))
}
pub fn normalise_oracle_price(
amm: &AMM,
oracle_price: &OraclePriceData,
precomputed_reserve_price: Option<u64>,
) -> DriftResult<i64> {
let OraclePriceData {
price: oracle_price,
confidence: oracle_conf,
..
} = *oracle_price;
let reserve_price = match precomputed_reserve_price {
Some(reserve_price) => reserve_price.cast::<i64>()?,
None => amm.reserve_price()?.cast::<i64>()?,
};
// 2.5 bps of the mark price
let reserve_price_2p5_bps = reserve_price.safe_div(4000)?;
let conf_int = oracle_conf.cast::<i64>()?;
// normalises oracle toward mark price based on the oracle’s confidence interval
// if mark above oracle: use oracle+conf unless it exceeds .99975 * mark price
// if mark below oracle: use oracle-conf unless it less than 1.00025 * mark price
// (this guarantees more reasonable funding rates in volatile periods)
let normalised_price = if reserve_price > oracle_price {
min(
max(reserve_price.safe_sub(reserve_price_2p5_bps)?, oracle_price),
oracle_price.safe_add(conf_int)?,
)
} else {
max(
min(reserve_price.safe_add(reserve_price_2p5_bps)?, oracle_price),
oracle_price.safe_sub(conf_int)?,
)
};
Ok(normalised_price)
}
pub fn calculate_oracle_reserve_price_spread_pct(
amm: &AMM,
oracle_price_data: &OraclePriceData,
precomputed_reserve_price: Option<u64>,
) -> DriftResult<i64> {
let reserve_price = match precomputed_reserve_price {
Some(reserve_price) => reserve_price,
None => amm.reserve_price()?,
};
let (_oracle_price, price_spread) =
calculate_oracle_reserve_price_spread(amm, oracle_price_data, Some(reserve_price))?;
price_spread
.cast::<i128>()?
.safe_mul(BID_ASK_SPREAD_PRECISION_I128)?
.safe_div(reserve_price.cast::<i128>()?)? // todo? better for spread logic
.cast()
}
pub fn calculate_oracle_twap_5min_price_spread_pct(
amm: &AMM,
other_price: u64,
) -> DriftResult<i64> {
let price_spread = other_price
.cast::<i64>()?
.safe_sub(amm.historical_oracle_data.last_oracle_price_twap_5min)?;
// price_spread_pct
price_spread
.cast::<i128>()?
.safe_mul(BID_ASK_SPREAD_PRECISION_I128)?
.safe_div(other_price.cast::<i128>()?)? // todo? better for spread logic
.cast()
}
pub fn is_oracle_mark_too_divergent(
price_spread_pct: i64,
oracle_guard_rails: &PriceDivergenceGuardRails,
) -> DriftResult<bool> {
let max_divergence = oracle_guard_rails
.mark_oracle_percent_divergence
.max(PERCENTAGE_PRECISION_U64 / 10);
Ok(price_spread_pct.unsigned_abs() > max_divergence)
}
pub fn calculate_amm_available_liquidity(
amm: &AMM,
order_direction: &PositionDirection,
) -> DriftResult<u64> {
let max_fill_size: u64 = (amm.base_asset_reserve / amm.max_fill_reserve_fraction as u128)
.min(u64::MAX as u128)
.cast()?;
// one fill can only take up to half of side's liquidity
let max_base_asset_amount_on_side = match order_direction {
PositionDirection::Long => {
amm.base_asset_reserve
.saturating_sub(amm.min_base_asset_reserve)
/ 2
}
PositionDirection::Short => {
amm.max_base_asset_reserve
.saturating_sub(amm.base_asset_reserve)
/ 2
}
}
.cast::<u64>()?;
standardize_base_asset_amount(
max_fill_size.min(max_base_asset_amount_on_side),
amm.order_step_size,
)
}
pub fn calculate_net_user_cost_basis(amm: &AMM) -> DriftResult<i128> {
amm.quote_asset_amount
.safe_add(amm.quote_asset_amount_with_unsettled_lp.cast()?)?
.safe_add(amm.net_unsettled_funding_pnl.cast()?)
}
pub fn calculate_net_user_pnl(amm: &AMM, oracle_price: i64) -> DriftResult<i128> {
validate!(
oracle_price > 0,
ErrorCode::InvalidOracle,
"oracle_price <= 0",
)?;
let net_user_base_asset_value = amm
.base_asset_amount_with_amm
.safe_add(amm.base_asset_amount_with_unsettled_lp)?
.safe_mul(oracle_price.cast()?)?
.safe_div(PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO.cast()?)?;
net_user_base_asset_value.safe_add(calculate_net_user_cost_basis(amm)?)
}
pub fn calculate_expiry_price(
amm: &AMM,
target_price: i64,
total_excess_balance: i128,
) -> DriftResult<i64> {
if amm.base_asset_amount_with_amm.abs() < amm.order_step_size.cast::<i128>()? {
return Ok(target_price);
}
// net_baa * price + net_quote <= 0
// net_quote/net_baa <= -price
// net_user_unrealized_pnl negative = surplus in market
// net_user_unrealized_pnl positive = expiry price needs to differ from oracle
let best_expiry_price = -(amm
.quote_asset_amount
.safe_sub(total_excess_balance.cast::<i128>()?)?
.safe_mul(PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO_I128)?
.safe_div(amm.base_asset_amount_with_amm)?)
.cast::<i64>()?;
let expiry_price = if amm.base_asset_amount_with_amm >= 0 {
// net longs only get as high as oracle_price
best_expiry_price.min(target_price).saturating_sub(1)
} else {
// net shorts only get as low as oracle price
best_expiry_price.max(target_price).saturating_add(1)
};
Ok(expiry_price)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/fuel.rs
|
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
use crate::state::perp_market::PerpMarket;
use crate::state::spot_market::SpotMarket;
use crate::{FUEL_WINDOW_U128, QUOTE_PRECISION, QUOTE_PRECISION_U64};
#[cfg(test)]
mod tests;
pub fn calculate_perp_fuel_bonus(
perp_market: &PerpMarket,
base_asset_value: i128,
fuel_bonus_numerator: i64,
) -> DriftResult<u64> {
let result: u64 = if base_asset_value.unsigned_abs() < QUOTE_PRECISION {
0_u64
} else {
base_asset_value
.unsigned_abs()
.safe_mul(fuel_bonus_numerator.cast()?)?
.safe_mul(perp_market.fuel_boost_position.cast()?)?
.safe_div(FUEL_WINDOW_U128)?
.cast::<u64>()?
/ (QUOTE_PRECISION_U64 / 10)
};
Ok(result)
}
pub fn calculate_spot_fuel_bonus(
spot_market: &SpotMarket,
signed_token_value: i128,
fuel_bonus_numerator: i64,
) -> DriftResult<u64> {
let result: u64 = if signed_token_value.unsigned_abs() < QUOTE_PRECISION {
0_u64
} else if signed_token_value > 0 {
signed_token_value
.unsigned_abs()
.safe_mul(fuel_bonus_numerator.cast()?)?
.safe_mul(spot_market.fuel_boost_deposits.cast()?)?
.safe_div(FUEL_WINDOW_U128)?
.cast::<u64>()?
/ (QUOTE_PRECISION_U64 / 10)
} else {
signed_token_value
.unsigned_abs()
.safe_mul(fuel_bonus_numerator.cast()?)?
.safe_mul(spot_market.fuel_boost_borrows.cast()?)?
.safe_div(FUEL_WINDOW_U128)?
.cast::<u64>()?
/ (QUOTE_PRECISION_U64 / 10)
};
Ok(result)
}
pub fn calculate_insurance_fuel_bonus(
spot_market: &SpotMarket,
stake_amount: u64,
stake_amount_delta: i64,
fuel_bonus_numerator: u32,
) -> DriftResult<u64> {
Ok(stake_amount
.saturating_sub(stake_amount_delta.unsigned_abs())
.cast::<u128>()?
.safe_mul(fuel_bonus_numerator.cast()?)?
.safe_mul(spot_market.fuel_boost_insurance.cast()?)?
.safe_div(FUEL_WINDOW_U128)?
.cast::<u64>()?
/ (QUOTE_PRECISION_U64 / 10))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/constants.rs
|
use solana_program::native_token::LAMPORTS_PER_SOL; // expo 9
pub const LAMPORTS_PER_SOL_U64: u64 = LAMPORTS_PER_SOL;
pub const LAMPORTS_PER_SOL_I64: i64 = LAMPORTS_PER_SOL as i64;
// SPOT MARKET CONSTANTS
pub const QUOTE_SPOT_MARKET_INDEX: u16 = 0;
pub const GOV_SPOT_MARKET_INDEX: u16 = 15;
// USER ACCOUNT CONSTANTS
pub const MAX_SPOT_POSITIONS: u8 = 8;
pub const MAX_PERP_POSITIONS: u8 = 8;
pub const MAX_OPEN_ORDERS: u8 = 32;
// PRECISIONS
pub const AMM_RESERVE_PRECISION: u128 = 1_000_000_000; //expo = -9;
pub const AMM_RESERVE_PRECISION_I128: i128 = (AMM_RESERVE_PRECISION) as i128;
pub const BASE_PRECISION: u128 = AMM_RESERVE_PRECISION; //expo = -9;
pub const BASE_PRECISION_I128: i128 = AMM_RESERVE_PRECISION_I128;
pub const BASE_PRECISION_U64: u64 = AMM_RESERVE_PRECISION as u64; //expo = -9;
pub const BASE_PRECISION_I64: i64 = AMM_RESERVE_PRECISION_I128 as i64; //expo = -9;
pub const PERP_DECIMALS: u32 = 9;
pub const PRICE_PRECISION: u128 = 1_000_000; //expo = -6;
pub const PRICE_PRECISION_I128: i128 = PRICE_PRECISION as i128;
pub const PRICE_PRECISION_U64: u64 = 1_000_000; //expo = -6;
pub const PRICE_PRECISION_I64: i64 = 1_000_000; //expo = -6;
pub const PEG_PRECISION: u128 = 1_000_000; //expo = -6
pub const PEG_PRECISION_I128: i128 = PEG_PRECISION as i128; //expo = -6
pub const QUOTE_PRECISION: u128 = 1_000_000; // expo = -6
pub const QUOTE_PRECISION_I128: i128 = 1_000_000; // expo = -6
pub const QUOTE_PRECISION_I64: i64 = 1_000_000; // expo = -6
pub const QUOTE_PRECISION_U64: u64 = 1_000_000; // expo = -6
pub const FUNDING_RATE_BUFFER: u128 = 1_000; // expo = -3
pub const FUNDING_RATE_BUFFER_I128: i128 = FUNDING_RATE_BUFFER as i128; // expo = -3
pub const MARGIN_PRECISION: u32 = 10_000; // expo = -4
pub const MARGIN_PRECISION_U128: u128 = 10_000; // expo = -4
pub const SPOT_WEIGHT_PRECISION: u32 = MARGIN_PRECISION; // expo = -4
pub const SPOT_WEIGHT_PRECISION_U128: u128 = SPOT_WEIGHT_PRECISION as u128; // expo = -4
pub const SPOT_WEIGHT_PRECISION_I128: i128 = SPOT_WEIGHT_PRECISION as i128; // expo = -4
pub const LIQUIDATION_PCT_PRECISION: u128 = 10_000;
pub const SPOT_BALANCE_PRECISION: u128 = 1_000_000_000; // expo = -9
pub const SPOT_BALANCE_PRECISION_U64: u64 = 1_000_000_000; // expo = -9
pub const SPOT_CUMULATIVE_INTEREST_PRECISION: u128 = 10_000_000_000; // expo = -10
pub const PERCENTAGE_PRECISION: u128 = 1_000_000; // expo -6 (represents 100%)
pub const PERCENTAGE_PRECISION_I128: i128 = PERCENTAGE_PRECISION as i128;
pub const PERCENTAGE_PRECISION_U64: u64 = PERCENTAGE_PRECISION as u64;
pub const PERCENTAGE_PRECISION_I64: i64 = PERCENTAGE_PRECISION as i64;
pub const TEN_BPS: i128 = PERCENTAGE_PRECISION_I128 / 1000;
pub const TEN_BPS_I64: i64 = TEN_BPS as i64;
pub const TWO_PT_TWO_PCT: i128 = 22_000;
pub const BID_ASK_SPREAD_PRECISION: u64 = PERCENTAGE_PRECISION as u64; // expo = -6
pub const BID_ASK_SPREAD_PRECISION_I64: i64 = (BID_ASK_SPREAD_PRECISION) as i64;
pub const BID_ASK_SPREAD_PRECISION_U128: u128 = BID_ASK_SPREAD_PRECISION as u128; // expo = -6
pub const BID_ASK_SPREAD_PRECISION_I128: i128 = BID_ASK_SPREAD_PRECISION as i128; // expo = -6
pub const CONCENTRATION_PRECISION: u128 = PERCENTAGE_PRECISION; // expo 6
pub const IF_FACTOR_PRECISION: u128 = PERCENTAGE_PRECISION; // expo 6
pub const SPOT_UTILIZATION_PRECISION: u128 = PERCENTAGE_PRECISION; // expo = -6
pub const SPOT_UTILIZATION_PRECISION_U32: u32 = PERCENTAGE_PRECISION as u32; // expo = -6
pub const SPOT_RATE_PRECISION: u128 = PERCENTAGE_PRECISION; // expo = -6
pub const SPOT_RATE_PRECISION_U32: u32 = PERCENTAGE_PRECISION as u32; // expo = -6
pub const LIQUIDATION_FEE_PRECISION: u32 = PERCENTAGE_PRECISION as u32; // expo = -6
pub const LIQUIDATION_FEE_PRECISION_U128: u128 = LIQUIDATION_FEE_PRECISION as u128; // expo = -6
pub const SPOT_IMF_PRECISION: u32 = PERCENTAGE_PRECISION as u32; // expo = -6
pub const SPOT_IMF_PRECISION_U128: u128 = SPOT_IMF_PRECISION as u128; // expo = -6
// FORMULAIC REPEG / K
pub const K_BPS_UPDATE_SCALE: i128 = PERCENTAGE_PRECISION_I128;
pub const PEG_BPS_UPDATE_SCALE: u128 = PERCENTAGE_PRECISION; // expo = -6 (represents 100%)
// PRECISION CONVERSIONS
pub const PRICE_TO_PEG_PRECISION_RATIO: u128 = PRICE_PRECISION / PEG_PRECISION; // expo: 1 (Delete if we keep peg/price as 1e6)
pub const AMM_TO_QUOTE_PRECISION_RATIO: u128 = AMM_RESERVE_PRECISION / QUOTE_PRECISION; // expo: 3
pub const AMM_TO_QUOTE_PRECISION_RATIO_I128: i128 =
(AMM_RESERVE_PRECISION / QUOTE_PRECISION) as i128; // expo: 3
pub const AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO: u128 =
AMM_RESERVE_PRECISION * PEG_PRECISION / QUOTE_PRECISION; // expo: 9
pub const QUOTE_TO_BASE_AMT_FUNDING_PRECISION: i128 =
AMM_RESERVE_PRECISION_I128 * FUNDING_RATE_PRECISION_I128 / QUOTE_PRECISION_I128; // expo: 12
pub const PRICE_TO_QUOTE_PRECISION_RATIO: u128 = PRICE_PRECISION / QUOTE_PRECISION; // expo: 1
pub const PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO: u128 =
PRICE_PRECISION * AMM_TO_QUOTE_PRECISION_RATIO; // expo 9
pub const LIQUIDATION_FEE_TO_MARGIN_PRECISION_RATIO: u32 = // expo 2
LIQUIDATION_FEE_PRECISION / MARGIN_PRECISION;
pub const LIQUIDATION_FEE_TO_MARGIN_PRECISION_RATIO_U128: u128 = // expo 2
LIQUIDATION_FEE_TO_MARGIN_PRECISION_RATIO as u128;
pub const FUNDING_RATE_TO_QUOTE_PRECISION_PRECISION_RATIO: u128 = // expo 3
FUNDING_RATE_PRECISION / QUOTE_PRECISION;
pub const FUNDING_RATE_PRECISION: u128 = PRICE_PRECISION * FUNDING_RATE_BUFFER; // expo: 9
pub const FUNDING_RATE_PRECISION_I128: i128 = PRICE_PRECISION_I128 * FUNDING_RATE_BUFFER_I128; // expo: 9
pub const FUNDING_RATE_PRECISION_I64: i64 = FUNDING_RATE_PRECISION_I128 as i64; // expo: 9
pub const AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO_I128: i128 =
AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO as i128;
pub const PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO_I128: i128 =
PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO as i128; // expo 9
// FEE REBATES
pub const SHARE_OF_FEES_ALLOCATED_TO_DRIFT_NUMERATOR: u128 = 1;
pub const SHARE_OF_FEES_ALLOCATED_TO_DRIFT_DENOMINATOR: u128 = 2;
pub const SHARE_OF_IF_ESCROW_ALLOCATED_TO_PROTOCOL_NUMERATOR: u128 = 1;
pub const SHARE_OF_IF_ESCROW_ALLOCATED_TO_PROTOCOL_DENOMINATOR: u128 = 2;
pub const SHARE_OF_REVENUE_ALLOCATED_TO_INSURANCE_FUND_VAULT_NUMERATOR: u128 = 1;
pub const SHARE_OF_REVENUE_ALLOCATED_TO_INSURANCE_FUND_VAULT_DENOMINATOR: u128 = 1;
// TIME PERIODS
pub const ONE_MINUTE: i128 = 60_i128;
pub const FIVE_MINUTE: i128 = (60 * 5) as i128;
pub const ONE_HOUR: i64 = 3600;
pub const ONE_HOUR_I128: i128 = ONE_HOUR as i128;
pub const TWENTY_FOUR_HOUR: i64 = 3600 * 24;
pub const THIRTEEN_DAY: i64 = TWENTY_FOUR_HOUR * 13; // IF unstake default
pub const EPOCH_DURATION: i64 = TWENTY_FOUR_HOUR * 28;
pub const THIRTY_DAY: i64 = TWENTY_FOUR_HOUR * 30;
pub const THIRTY_DAY_I128: i128 = (TWENTY_FOUR_HOUR * 30) as i128;
pub const ONE_YEAR: u128 = 31536000;
// QUOTE AMOUNTS
pub const ONE_HUNDRED_MILLION_QUOTE: u64 = 100_000_000_u64 * QUOTE_PRECISION_U64;
pub const FIFTY_MILLION_QUOTE: u64 = 50_000_000_u64 * QUOTE_PRECISION_U64;
pub const TEN_MILLION_QUOTE: u64 = 10_000_000_u64 * QUOTE_PRECISION_U64;
pub const FIVE_MILLION_QUOTE: u64 = 5_000_000_u64 * QUOTE_PRECISION_U64;
pub const ONE_MILLION_QUOTE: u64 = 1_000_000_u64 * QUOTE_PRECISION_U64;
pub const TWO_HUNDRED_FIFTY_THOUSAND_QUOTE: u64 = 250_000_u64 * QUOTE_PRECISION_U64;
pub const ONE_HUNDRED_THOUSAND_QUOTE: u64 = 100_000_u64 * QUOTE_PRECISION_U64;
pub const TWENTY_FIVE_THOUSAND_QUOTE: u64 = 25_000_u64 * QUOTE_PRECISION_U64;
pub const TEN_THOUSAND_QUOTE: u64 = 10_000_u64 * QUOTE_PRECISION_U64;
pub const ONE_THOUSAND_QUOTE: u64 = 1_000_u64 * QUOTE_PRECISION_U64;
pub const TWO_HUNDRED_FIFTY_QUOTE: u64 = 250_u64 * QUOTE_PRECISION_U64;
// INSURANCE TIERS
pub const INSURANCE_A_MAX: u64 = ONE_HUNDRED_MILLION_QUOTE;
pub const INSURANCE_B_MAX: u64 = ONE_MILLION_QUOTE;
pub const INSURANCE_C_MAX: u64 = ONE_HUNDRED_THOUSAND_QUOTE;
pub const INSURANCE_SPECULATIVE_MAX: u64 = 0;
// QUOTE THRESHOLDS
pub const FEE_POOL_TO_REVENUE_POOL_THRESHOLD: u128 = TWO_HUNDRED_FIFTY_QUOTE as u128;
// FEES
pub const ONE_BPS_DENOMINATOR: u32 = 10000;
pub const MAX_REFERRER_REWARD_EPOCH_UPPER_BOUND: u64 = (4000 * QUOTE_PRECISION) as u64;
pub const LP_FEE_SLICE_NUMERATOR: u128 = 8;
pub const LP_FEE_SLICE_DENOMINATOR: u128 = 10;
pub const FEE_DENOMINATOR: u32 = 10 * ONE_BPS_DENOMINATOR;
pub const FEE_PERCENTAGE_DENOMINATOR: u32 = 100;
pub const OPEN_ORDER_MARGIN_REQUIREMENT: u128 = QUOTE_PRECISION / 100;
pub const FEE_ADJUSTMENT_MAX: u64 = 100;
pub const FEE_ADJUSTMENT_MAX_I16: i16 = FEE_ADJUSTMENT_MAX as i16;
// PRICE AMOUNTS
pub const HUNDRENTH_OF_CENT: u128 = PRICE_PRECISION / 10_000; //.0001
// CONSTRAINTS
pub const MAX_K_BPS_INCREASE: i128 = TEN_BPS;
pub const MAX_K_BPS_DECREASE: i128 = TWO_PT_TWO_PCT;
pub const MAX_UPDATE_K_PRICE_CHANGE: u128 = HUNDRENTH_OF_CENT;
pub const MAX_SQRT_K: u128 = 1000000000000000000000; // 1e21 (count 'em!)
pub const MAX_BASE_ASSET_AMOUNT_WITH_AMM: u128 = 100000000000000000; // 1e17 (count 'em!)
pub const MAX_PEG_BPS_INCREASE: u128 = TEN_BPS as u128; // 10 bps increase
pub const MAX_PEG_BPS_DECREASE: u128 = TEN_BPS as u128; // 10 bps decrease
pub const MAX_APR_PER_REVENUE_SETTLE_TO_INSURANCE_FUND_VAULT: u64 = 10 * PERCENTAGE_PRECISION_U64; // 1000% APR
pub const MAX_CONCENTRATION_COEFFICIENT: u128 = 1_414_200;
pub const MAX_LIQUIDATION_MULTIPLIER: u32 = 3;
pub const LIQUIDATION_FEE_INCREASE_PER_SLOT: u32 = LIQUIDATION_FEE_PRECISION / 1_000_000; // .01 bps per slot
pub const MAX_LIQUIDATION_SLIPPAGE: i128 = 10_000; // expo = -2
pub const MAX_LIQUIDATION_SLIPPAGE_U128: u128 = 10_000; // expo = -2
pub const MAX_MARK_TWAP_DIVERGENCE: u128 = 500_000; // expo = -3
pub const MAX_MARGIN_RATIO: u32 = MARGIN_PRECISION; // 1x leverage
pub const MIN_MARGIN_RATIO: u32 = MARGIN_PRECISION / 50; // 50x leverage
pub const HIGH_LEVERAGE_MIN_MARGIN_RATIO: u32 = MARGIN_PRECISION / 200; // 200x leverage
pub const MAX_BID_ASK_INVENTORY_SKEW_FACTOR: u64 = 10 * BID_ASK_SPREAD_PRECISION;
pub const MAX_POSITIVE_UPNL_FOR_INITIAL_MARGIN: i128 = 100 * QUOTE_PRECISION_I128; // max upnl for initial margin calc
pub const DEFAULT_MAX_TWAP_UPDATE_PRICE_BAND_DENOMINATOR: i64 = 3; // '3' here means clamp new data point to 33% (1/3) divergence from current twap (if twap > 0)
// DEFAULTS
pub const DEFAULT_REVENUE_SINCE_LAST_FUNDING_SPREAD_RETREAT: i64 = -25 * QUOTE_PRECISION_I64; //$25 loss
pub const DEFAULT_LARGE_BID_ASK_FACTOR: u64 = 10 * BID_ASK_SPREAD_PRECISION;
pub const DEFAULT_LIQUIDATION_MARGIN_BUFFER_RATIO: u32 = MARGIN_PRECISION / 50; // 2%
pub const DEFAULT_BASE_ASSET_AMOUNT_STEP_SIZE: u64 = BASE_PRECISION_U64 / 10000; // 1e-4;
pub const DEFAULT_QUOTE_ASSET_AMOUNT_TICK_SIZE: u64 =
PRICE_PRECISION_U64 / DEFAULT_BASE_ASSET_AMOUNT_STEP_SIZE; // 1e-2
// FUNDING
pub const FUNDING_RATE_OFFSET_DENOMINATOR: i64 = 5000; // 5000 => 7.3% annualized rate for hourly funding
// ORDERS
pub const AUCTION_DERIVE_PRICE_FRACTION: i64 = 200;
// WITHDRAWS
pub const SPOT_MARKET_TOKEN_TWAP_WINDOW: i64 = TWENTY_FOUR_HOUR;
// FUEL
pub const FUEL_WINDOW_U128: u128 = EPOCH_DURATION as u128;
pub const FUEL_START_TS: i64 = 1723147200_i64; // August 8 2024 UTC
// PREDICTION
pub const MAX_PREDICTION_MARKET_PRICE: u64 = PRICE_PRECISION_U64;
pub const MAX_PREDICTION_MARKET_PRICE_I64: i64 = PRICE_PRECISION_U64 as i64;
pub const MAX_PREDICTION_MARKET_PRICE_U128: u128 = PRICE_PRECISION_U64 as u128;
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/insurance.rs
|
use solana_program::msg;
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
use crate::math::helpers::{get_proportion_u128, log10_iter};
use crate::math::safe_math::SafeMath;
use crate::state::insurance_fund_stake::InsuranceFundStake;
use crate::state::spot_market::SpotMarket;
use crate::validate;
#[cfg(test)]
mod tests;
pub fn vault_amount_to_if_shares(
amount: u64,
total_if_shares: u128,
insurance_fund_vault_balance: u64,
) -> DriftResult<u128> {
// relative to the entire pool + total amount minted
let n_shares = if insurance_fund_vault_balance > 0 {
// assumes total_if_shares != 0 (in most cases) for nice result for user
get_proportion_u128(
amount.cast::<u128>()?,
total_if_shares,
insurance_fund_vault_balance.cast::<u128>()?,
)?
} else {
// must be case that total_if_shares == 0 for nice result for user
validate!(
total_if_shares == 0,
ErrorCode::InvalidIFSharesDetected,
"assumes total_if_shares == 0",
)?;
amount.cast::<u128>()?
};
Ok(n_shares)
}
pub fn if_shares_to_vault_amount(
n_shares: u128,
total_if_shares: u128,
insurance_fund_vault_balance: u64,
) -> DriftResult<u64> {
validate!(
n_shares <= total_if_shares,
ErrorCode::InvalidIFSharesDetected,
"n_shares({}) > total_if_shares({})",
n_shares,
total_if_shares
)?;
let amount = if total_if_shares > 0 {
get_proportion_u128(
insurance_fund_vault_balance as u128,
n_shares,
total_if_shares,
)?
.cast::<u64>()?
} else {
0
};
Ok(amount)
}
pub fn calculate_rebase_info(
total_if_shares: u128,
insurance_fund_vault_balance: u64,
) -> DriftResult<(u32, u128)> {
let rebase_divisor_full = total_if_shares
.safe_div(10)?
.safe_div(insurance_fund_vault_balance.cast::<u128>()?)?;
let expo_diff = log10_iter(rebase_divisor_full).cast::<u32>()?;
let rebase_divisor = 10_u128.pow(expo_diff);
Ok((expo_diff, rebase_divisor))
}
pub fn calculate_if_shares_lost(
insurance_fund_stake: &InsuranceFundStake,
spot_market: &SpotMarket,
insurance_fund_vault_balance: u64,
) -> DriftResult<u128> {
let n_shares = insurance_fund_stake.last_withdraw_request_shares;
let amount = if_shares_to_vault_amount(
n_shares,
spot_market.insurance_fund.total_shares,
insurance_fund_vault_balance,
)?;
let if_shares_lost = if amount > insurance_fund_stake.last_withdraw_request_value {
let new_n_shares = vault_amount_to_if_shares(
insurance_fund_stake.last_withdraw_request_value,
spot_market.insurance_fund.total_shares.safe_sub(n_shares)?,
insurance_fund_vault_balance
.safe_sub(insurance_fund_stake.last_withdraw_request_value)?,
)?;
validate!(
new_n_shares <= n_shares,
ErrorCode::InvalidIFSharesDetected,
"Issue calculating delta if_shares after canceling request {} < {}",
new_n_shares,
n_shares
)?;
n_shares.safe_sub(new_n_shares)?
} else {
0
};
Ok(if_shares_lost)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/floor_div.rs
|
use num_traits::{One, Zero};
pub trait CheckedFloorDiv: Sized {
/// Perform floor division
fn checked_floor_div(&self, rhs: Self) -> Option<Self>;
}
macro_rules! checked_impl {
($t:ty) => {
impl CheckedFloorDiv for $t {
#[track_caller]
#[inline]
fn checked_floor_div(&self, rhs: $t) -> Option<$t> {
let quotient = self.checked_div(rhs)?;
let remainder = self.checked_rem(rhs)?;
if remainder != <$t>::zero() {
quotient.checked_sub(<$t>::one())
} else {
Some(quotient)
}
}
}
};
}
checked_impl!(i128);
checked_impl!(i64);
checked_impl!(i32);
checked_impl!(i16);
checked_impl!(i8);
#[cfg(test)]
mod test {
use crate::math::floor_div::CheckedFloorDiv;
#[test]
fn test() {
let x = -3_i128;
assert_eq!(x.checked_floor_div(2), Some(-2));
assert_eq!(x.checked_floor_div(0), None);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/safe_unwrap.rs
|
use crate::error::{DriftResult, ErrorCode};
use solana_program::msg;
use std::panic::Location;
pub trait SafeUnwrap {
type Item;
fn safe_unwrap(self) -> DriftResult<Self::Item>;
}
impl<T> SafeUnwrap for Option<T> {
type Item = T;
#[track_caller]
#[inline(always)]
fn safe_unwrap(self) -> DriftResult<T> {
match self {
Some(v) => Ok(v),
None => {
let caller = Location::caller();
msg!("Unwrap error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::FailedUnwrap)
}
}
}
}
impl<T, U> SafeUnwrap for Result<T, U> {
type Item = T;
#[track_caller]
#[inline(always)]
fn safe_unwrap(self) -> DriftResult<T> {
match self {
Ok(v) => Ok(v),
Err(_) => {
let caller = Location::caller();
msg!("Unwrap error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::FailedUnwrap)
}
}
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/funding.rs
|
use std::cmp::max;
use solana_program::msg;
use crate::error::{DriftResult, ErrorCode};
use crate::math::bn;
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_TO_QUOTE_PRECISION_RATIO, AMM_TO_QUOTE_PRECISION_RATIO_I128, FUNDING_RATE_BUFFER,
PRICE_PRECISION, QUOTE_TO_BASE_AMT_FUNDING_PRECISION,
};
use crate::math::repeg::{calculate_fee_pool, get_total_fee_lower_bound};
use crate::math::safe_math::SafeMath;
use crate::state::perp_market::PerpMarket;
use crate::state::user::PerpPosition;
#[cfg(test)]
mod tests;
/// With a virtual AMM, there can be an imbalance between longs and shorts and thus funding can be asymmetric.
/// To account for this, amm keeps track of the cumulative funding rate for both longs and shorts.
/// When there is a period with asymmetric funding, the protocol will pay/receive funding from/to it's collected fees.
pub fn calculate_funding_rate_long_short(
market: &mut PerpMarket,
funding_rate: i128,
) -> DriftResult<(i128, i128, i128)> {
// Calculate the funding payment owed by the net_market_position if funding is not capped
// If the net market position owes funding payment, the protocol receives payment
let settled_net_market_position = market
.amm
.base_asset_amount_with_amm
.safe_add(market.amm.base_asset_amount_with_unsettled_lp)?;
let net_market_position_funding_payment =
calculate_funding_payment_in_quote_precision(funding_rate, settled_net_market_position)?;
let uncapped_funding_pnl = -net_market_position_funding_payment;
// If the uncapped_funding_pnl is positive, the protocol receives money.
if uncapped_funding_pnl >= 0 {
market.amm.total_fee_minus_distributions = market
.amm
.total_fee_minus_distributions
.safe_add(uncapped_funding_pnl)?;
market.amm.net_revenue_since_last_funding = market
.amm
.net_revenue_since_last_funding
.safe_add(uncapped_funding_pnl as i64)?;
return Ok((funding_rate, funding_rate, uncapped_funding_pnl));
}
let (capped_funding_rate, capped_funding_pnl) =
calculate_capped_funding_rate(market, uncapped_funding_pnl, funding_rate)?;
let new_total_fee_minus_distributions = market
.amm
.total_fee_minus_distributions
.safe_add(capped_funding_pnl)?;
// protocol is paying part of funding imbalance
if capped_funding_pnl != 0 {
let total_fee_minus_distributions_lower_bound =
get_total_fee_lower_bound(market)?.cast::<i128>()?;
// makes sure the protocol doesn't pay more than the share of fees allocated to `distributions`
if new_total_fee_minus_distributions < total_fee_minus_distributions_lower_bound {
msg!("new_total_fee_minus_distributions={} < total_fee_minus_distributions_lower_bound={}", new_total_fee_minus_distributions, total_fee_minus_distributions_lower_bound);
return Err(ErrorCode::InvalidFundingProfitability);
}
}
market.amm.total_fee_minus_distributions = new_total_fee_minus_distributions;
market.amm.net_revenue_since_last_funding = market
.amm
.net_revenue_since_last_funding
.safe_sub(capped_funding_pnl.unsigned_abs() as i64)?;
let funding_rate_long = if funding_rate < 0 {
capped_funding_rate
} else {
funding_rate
};
let funding_rate_short = if funding_rate > 0 {
capped_funding_rate
} else {
funding_rate
};
Ok((funding_rate_long, funding_rate_short, uncapped_funding_pnl))
}
fn calculate_capped_funding_rate(
market: &PerpMarket,
uncapped_funding_pnl: i128, // if negative, users would net receive from protocol
funding_rate: i128,
) -> DriftResult<(i128, i128)> {
// The funding_rate_pnl_limit is the amount of fees the protocol can use before it hits it's lower bound
let fee_pool = calculate_fee_pool(market)?;
// limit to 1/3 of current fee pool per funding period
let funding_rate_pnl_limit = -fee_pool.cast::<i128>()?.safe_div(3)?;
// if theres enough in fees, give user's uncapped funding
// if theres a little/nothing in fees, give the user's capped outflow funding
let capped_funding_pnl = max(uncapped_funding_pnl, funding_rate_pnl_limit);
let capped_funding_rate = if uncapped_funding_pnl < funding_rate_pnl_limit {
// Calculate how much funding payment is already available from users
let funding_payment_from_users = calculate_funding_payment_in_quote_precision(
funding_rate,
if funding_rate > 0 {
market.amm.base_asset_amount_long
} else {
market.amm.base_asset_amount_short
},
)?;
// increase the funding_rate_pnl_limit by accounting for the funding payment already being made by users
// this makes it so that the capped rate includes funding payments from users and protocol collected fees
let funding_rate_pnl_limit =
funding_rate_pnl_limit.safe_sub(funding_payment_from_users.abs())?;
if funding_rate < 0 {
// longs receive
calculate_funding_rate_from_pnl_limit(
funding_rate_pnl_limit,
market.amm.base_asset_amount_long,
)?
} else {
// shorts receive
calculate_funding_rate_from_pnl_limit(
funding_rate_pnl_limit,
market.amm.base_asset_amount_short,
)?
}
} else {
funding_rate
};
Ok((capped_funding_rate, capped_funding_pnl))
}
pub fn calculate_funding_payment(
amm_cumulative_funding_rate: i128,
market_position: &PerpPosition,
) -> DriftResult<i64> {
let funding_rate_delta = amm_cumulative_funding_rate
.safe_sub(market_position.last_cumulative_funding_rate.cast()?)?;
if funding_rate_delta == 0 {
return Ok(0);
}
_calculate_funding_payment(
funding_rate_delta,
market_position.base_asset_amount.cast()?,
)?
.safe_div(AMM_TO_QUOTE_PRECISION_RATIO_I128)?
.cast()
}
fn _calculate_funding_payment(
funding_rate_delta: i128,
base_asset_amount: i128,
) -> DriftResult<i128> {
let funding_rate_delta_sign: i128 = if funding_rate_delta > 0 { 1 } else { -1 };
let funding_rate_payment_magnitude = bn::U192::from(funding_rate_delta.unsigned_abs())
.safe_mul(bn::U192::from(base_asset_amount.unsigned_abs()))?
.safe_div(bn::U192::from(PRICE_PRECISION))?
.safe_div(bn::U192::from(FUNDING_RATE_BUFFER))?
.try_to_u128()?
.cast::<i128>()?;
// funding_rate: longs pay shorts
let funding_rate_payment_sign: i128 = if base_asset_amount > 0 { -1 } else { 1 };
let funding_rate_payment = (funding_rate_payment_magnitude)
.safe_mul(funding_rate_payment_sign)?
.safe_mul(funding_rate_delta_sign)?;
Ok(funding_rate_payment)
}
fn calculate_funding_rate_from_pnl_limit(
pnl_limit: i128,
base_asset_amount: i128,
) -> DriftResult<i128> {
if base_asset_amount == 0 {
return Ok(0);
}
let pnl_limit_biased = if pnl_limit < 0 {
pnl_limit.safe_add(1)?
} else {
pnl_limit
};
pnl_limit_biased
.safe_mul(QUOTE_TO_BASE_AMT_FUNDING_PRECISION)?
.safe_div(base_asset_amount)
}
pub fn calculate_funding_payment_in_quote_precision(
funding_rate_delta: i128,
base_asset_amount: i128,
) -> DriftResult<i128> {
let funding_payment = _calculate_funding_payment(funding_rate_delta, base_asset_amount)?;
let funding_payment_collateral =
funding_payment.safe_div(AMM_TO_QUOTE_PRECISION_RATIO.cast::<i128>()?)?;
Ok(funding_payment_collateral)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/fees.rs
|
use std::cmp::{max, min};
use num_integer::Roots;
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::constants::{
FIFTY_MILLION_QUOTE, FIVE_MILLION_QUOTE, ONE_HUNDRED_MILLION_QUOTE, ONE_HUNDRED_THOUSAND_QUOTE,
ONE_MILLION_QUOTE, ONE_THOUSAND_QUOTE, TEN_BPS, TEN_MILLION_QUOTE, TEN_THOUSAND_QUOTE,
TWENTY_FIVE_THOUSAND_QUOTE,
};
use crate::math::helpers::get_proportion_u128;
use crate::math::safe_math::SafeMath;
use crate::state::state::{FeeStructure, FeeTier, OrderFillerRewardStructure};
use crate::state::user::{MarketType, UserStats};
use crate::{FEE_ADJUSTMENT_MAX, QUOTE_PRECISION_U64};
use solana_program::msg;
#[cfg(test)]
mod tests;
pub struct FillFees {
pub user_fee: u64,
pub maker_rebate: u64,
pub fee_to_market: i64,
pub fee_to_market_for_lp: i64,
pub filler_reward: u64,
pub referrer_reward: u64,
pub referee_discount: u64,
}
pub fn calculate_fee_for_fulfillment_with_amm(
user_stats: &UserStats,
quote_asset_amount: u64,
fee_structure: &FeeStructure,
order_slot: u64,
clock_slot: u64,
reward_filler: bool,
reward_referrer: bool,
referrer_stats: &Option<&mut UserStats>,
quote_asset_amount_surplus: i64,
is_post_only: bool,
fee_adjustment: i16,
user_high_leverage_mode: bool,
) -> DriftResult<FillFees> {
let fee_tier = determine_user_fee_tier(
user_stats,
fee_structure,
&MarketType::Perp,
user_high_leverage_mode,
)?;
// if there was a quote_asset_amount_surplus, the order was a maker order and fee_to_market comes from surplus
if is_post_only {
let maker_rebate = calculate_maker_rebate(quote_asset_amount, fee_tier, fee_adjustment)?;
let fee = quote_asset_amount_surplus
.cast::<u64>()?
.safe_sub(maker_rebate)
.map_err(|e| {
msg!(
"quote_asset_amount_surplus {} quote_asset_amount {} maker_rebate {}",
quote_asset_amount_surplus,
quote_asset_amount,
maker_rebate
);
e
})?;
let filler_reward = if !reward_filler {
0_u64
} else {
calculate_filler_reward(
fee,
order_slot,
clock_slot,
0,
&fee_structure.filler_reward_structure,
)?
};
let fee_to_market = fee.safe_sub(filler_reward)?.cast::<i64>()?;
let user_fee = 0_u64;
Ok(FillFees {
user_fee,
maker_rebate,
fee_to_market,
fee_to_market_for_lp: 0,
filler_reward,
referrer_reward: 0,
referee_discount: 0,
})
} else {
let mut fee = calculate_taker_fee(quote_asset_amount, fee_tier, fee_adjustment)?;
if user_high_leverage_mode {
fee = fee.safe_mul(2)?;
}
let (fee, referee_discount, referrer_reward) = if reward_referrer {
calculate_referee_fee_and_referrer_reward(
fee,
fee_tier,
fee_structure.referrer_reward_epoch_upper_bound,
referrer_stats,
)?
} else {
(fee, 0, 0)
};
let filler_reward = if !reward_filler {
0_u64
} else {
calculate_filler_reward(
fee,
order_slot,
clock_slot,
0,
&fee_structure.filler_reward_structure,
)?
};
let fee_to_market = fee
.safe_sub(filler_reward)?
.safe_sub(referrer_reward)?
.cast::<i64>()?
.safe_add(quote_asset_amount_surplus)?;
let fee_to_market_for_lp = fee_to_market.safe_sub(quote_asset_amount_surplus)?;
// must be non-negative
Ok(FillFees {
user_fee: fee,
maker_rebate: 0,
fee_to_market,
fee_to_market_for_lp,
filler_reward,
referrer_reward,
referee_discount,
})
}
}
fn calculate_taker_fee(
quote_asset_amount: u64,
fee_tier: &FeeTier,
fee_adjustment: i16,
) -> DriftResult<u64> {
let mut taker_fee = quote_asset_amount
.cast::<u128>()?
.safe_mul(fee_tier.fee_numerator.cast::<u128>()?)?
.safe_div_ceil(fee_tier.fee_denominator.cast::<u128>()?)?
.cast::<u64>()?;
if fee_adjustment < 0 {
taker_fee = taker_fee.saturating_sub(
taker_fee
.safe_mul(fee_adjustment.unsigned_abs().cast()?)?
.safe_div(FEE_ADJUSTMENT_MAX)?,
);
} else if fee_adjustment > 0 {
taker_fee = taker_fee.saturating_add(
taker_fee
.safe_mul(fee_adjustment.cast()?)?
.safe_div_ceil(FEE_ADJUSTMENT_MAX)?,
);
}
Ok(taker_fee)
}
fn calculate_maker_rebate(
quote_asset_amount: u64,
fee_tier: &FeeTier,
fee_adjustment: i16,
) -> DriftResult<u64> {
let mut maker_fee = quote_asset_amount
.cast::<u128>()?
.safe_mul(fee_tier.maker_rebate_numerator as u128)?
.safe_div(fee_tier.maker_rebate_denominator as u128)?
.cast::<u64>()?;
if fee_adjustment < 0 {
maker_fee = maker_fee.saturating_sub(
maker_fee
.safe_mul(fee_adjustment.unsigned_abs().cast()?)?
.safe_div_ceil(FEE_ADJUSTMENT_MAX)?,
);
} else if fee_adjustment > 0 {
maker_fee = maker_fee.saturating_add(
maker_fee
.safe_mul(fee_adjustment.cast()?)?
.safe_div(FEE_ADJUSTMENT_MAX)?,
);
}
Ok(maker_fee)
}
fn calculate_referee_fee_and_referrer_reward(
fee: u64,
fee_tier: &FeeTier,
referrer_reward_epoch_upper_bound: u64,
referrer_stats: &Option<&mut UserStats>,
) -> DriftResult<(u64, u64, u64)> {
let referee_discount = get_proportion_u128(
fee as u128,
fee_tier.referee_fee_numerator as u128,
fee_tier.referee_fee_denominator as u128,
)?
.cast::<u64>()?;
let max_referrer_reward_from_fee = get_proportion_u128(
fee as u128,
fee_tier.referrer_reward_numerator as u128,
fee_tier.referrer_reward_denominator as u128,
)?
.cast::<u64>()?;
let referee_fee = fee.safe_sub(referee_discount)?;
let referrer_reward = match referrer_stats {
Some(referrer_stats) => {
let max_referrer_reward_in_epoch = referrer_reward_epoch_upper_bound
.saturating_sub(referrer_stats.fees.current_epoch_referrer_reward);
max_referrer_reward_from_fee.min(max_referrer_reward_in_epoch)
}
None => max_referrer_reward_from_fee,
};
Ok((referee_fee, referee_discount, referrer_reward))
}
fn calculate_filler_reward(
fee: u64,
order_slot: u64,
clock_slot: u64,
multiplier: u64,
filler_reward_structure: &OrderFillerRewardStructure,
) -> DriftResult<u64> {
// incentivize keepers to prioritize filling older orders (rather than just largest orders)
// for sufficiently small-sized order, reward based on fraction of fee paid
let size_filler_reward = fee
.safe_mul(filler_reward_structure.reward_numerator as u64)?
.safe_div(filler_reward_structure.reward_denominator as u64)?;
let multiplier_precision = TEN_BPS.cast::<u128>()?;
let min_time_filler_reward = filler_reward_structure
.time_based_reward_lower_bound
.safe_mul(
multiplier
.cast::<u128>()?
.max(multiplier_precision)
.min(multiplier_precision * 100),
)?
.safe_div(multiplier_precision)?;
let slots_since_order = max(1, clock_slot.safe_sub(order_slot)?.cast::<u128>()?);
let time_filler_reward = slots_since_order
.safe_mul(100_000_000)? // 1e8
.nth_root(4)
.safe_mul(min_time_filler_reward)?
.safe_div(100)? // 1e2 = sqrt(sqrt(1e8))
.cast::<u64>()?;
// lesser of size-based and time-based reward
let fee = min(size_filler_reward, time_filler_reward);
Ok(fee)
}
pub fn calculate_fee_for_fulfillment_with_match(
taker_stats: &UserStats,
maker_stats: &Option<&mut UserStats>,
quote_asset_amount: u64,
fee_structure: &FeeStructure,
order_slot: u64,
clock_slot: u64,
filler_multiplier: u64,
reward_referrer: bool,
referrer_stats: &Option<&mut UserStats>,
market_type: &MarketType,
fee_adjustment: i16,
user_high_leverage_mode: bool,
) -> DriftResult<FillFees> {
let taker_fee_tier = determine_user_fee_tier(
taker_stats,
fee_structure,
market_type,
user_high_leverage_mode,
)?;
let maker_fee_tier = if let Some(maker_stats) = maker_stats {
determine_user_fee_tier(maker_stats, fee_structure, market_type, false)?
} else {
determine_user_fee_tier(taker_stats, fee_structure, market_type, false)?
};
let mut taker_fee = calculate_taker_fee(quote_asset_amount, taker_fee_tier, fee_adjustment)?;
if user_high_leverage_mode {
taker_fee = taker_fee.safe_mul(2)?;
}
let (taker_fee, referee_discount, referrer_reward) = if reward_referrer {
calculate_referee_fee_and_referrer_reward(
taker_fee,
taker_fee_tier,
fee_structure.referrer_reward_epoch_upper_bound,
referrer_stats,
)?
} else {
(taker_fee, 0, 0)
};
let maker_rebate = calculate_maker_rebate(quote_asset_amount, maker_fee_tier, fee_adjustment)?;
let filler_reward = if filler_multiplier == 0 {
0_u64
} else {
calculate_filler_reward(
taker_fee,
order_slot,
clock_slot,
filler_multiplier,
&fee_structure.filler_reward_structure,
)?
};
// must be non-negative
let fee_to_market = taker_fee
.safe_sub(filler_reward)?
.safe_sub(referrer_reward)?
.safe_sub(maker_rebate)?
.cast::<i64>()?;
Ok(FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referrer_reward,
fee_to_market_for_lp: 0,
referee_discount,
})
}
pub struct ExternalFillFees {
pub user_fee: u64,
pub fee_to_market: u64,
pub fee_pool_delta: i64,
pub filler_reward: u64,
}
pub fn calculate_fee_for_fulfillment_with_external_market(
user_stats: &UserStats,
quote_asset_amount: u64,
fee_structure: &FeeStructure,
order_slot: u64,
clock_slot: u64,
reward_filler: bool,
external_market_fee: u64,
unsettled_referrer_rebate: u64,
fee_pool_amount: u64,
fee_adjustment: i16,
) -> DriftResult<ExternalFillFees> {
let taker_fee_tier =
determine_user_fee_tier(user_stats, fee_structure, &MarketType::Spot, false)?;
let fee = calculate_taker_fee(quote_asset_amount, taker_fee_tier, fee_adjustment)?;
let fee_plus_referrer_rebate = external_market_fee.safe_add(unsettled_referrer_rebate)?;
let user_fee = fee.max(fee_plus_referrer_rebate);
let filler_reward = if reward_filler {
let immediately_available_fee = user_fee.safe_sub(fee_plus_referrer_rebate)?;
let eventual_available_fee = user_fee.safe_sub(external_market_fee)?;
// can only pay the filler immediately if
// 1. there are fees already in the fee pool
// 2. the user_fee is greater than the serum_fee_plus_referrer_rebate
let available_fee =
eventual_available_fee.min(fee_pool_amount.max(immediately_available_fee));
calculate_filler_reward(
quote_asset_amount,
order_slot,
clock_slot,
0,
&fee_structure.filler_reward_structure,
)?
.min(available_fee)
} else {
0
};
let fee_to_market = user_fee
.safe_sub(external_market_fee)?
.safe_sub(filler_reward)?;
let fee_pool_delta = fee_to_market
.cast::<i64>()?
.safe_sub(unsettled_referrer_rebate.cast()?)?;
Ok(ExternalFillFees {
user_fee,
fee_to_market,
filler_reward,
fee_pool_delta,
})
}
pub fn determine_user_fee_tier<'a>(
user_stats: &UserStats,
fee_structure: &'a FeeStructure,
market_type: &MarketType,
user_high_leverage_mode: bool,
) -> DriftResult<&'a FeeTier> {
match market_type {
MarketType::Perp if user_high_leverage_mode => Ok(&fee_structure.fee_tiers[0]),
MarketType::Perp => determine_perp_fee_tier(user_stats, fee_structure),
MarketType::Spot => determine_spot_fee_tier(user_stats, fee_structure),
}
}
fn determine_perp_fee_tier<'a>(
user_stats: &UserStats,
fee_structure: &'a FeeStructure,
) -> DriftResult<&'a FeeTier> {
let total_30d_volume = user_stats.get_total_30d_volume()?;
let staked_gov_token_amount = user_stats.if_staked_gov_token_amount;
if total_30d_volume >= ONE_HUNDRED_MILLION_QUOTE
|| staked_gov_token_amount >= ONE_HUNDRED_THOUSAND_QUOTE + 19_500 * QUOTE_PRECISION_U64
{
return Ok(&fee_structure.fee_tiers[5]);
}
if total_30d_volume >= FIFTY_MILLION_QUOTE
|| staked_gov_token_amount >= ONE_HUNDRED_THOUSAND_QUOTE - QUOTE_PRECISION_U64
{
return Ok(&fee_structure.fee_tiers[4]);
}
if total_30d_volume >= TEN_MILLION_QUOTE
|| staked_gov_token_amount >= TWENTY_FIVE_THOUSAND_QUOTE * 2 - QUOTE_PRECISION_U64
{
return Ok(&fee_structure.fee_tiers[3]);
}
if total_30d_volume >= FIVE_MILLION_QUOTE
|| staked_gov_token_amount >= TEN_THOUSAND_QUOTE - QUOTE_PRECISION_U64
{
return Ok(&fee_structure.fee_tiers[2]);
}
if total_30d_volume >= ONE_MILLION_QUOTE
|| staked_gov_token_amount >= ONE_THOUSAND_QUOTE - QUOTE_PRECISION_U64
{
return Ok(&fee_structure.fee_tiers[1]);
}
Ok(&fee_structure.fee_tiers[0])
}
fn determine_spot_fee_tier<'a>(
_user_stats: &UserStats,
fee_structure: &'a FeeStructure,
) -> DriftResult<&'a FeeTier> {
Ok(&fee_structure.fee_tiers[0])
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/serum.rs
|
#[cfg(test)]
mod tests;
use crate::controller::position::PositionDirection;
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::constants::PRICE_TO_QUOTE_PRECISION_RATIO;
use crate::math::safe_math::SafeMath;
// Max amount of base to put deposit into serum
pub fn calculate_serum_max_coin_qty(
base_asset_amount: u64,
coin_lot_size: u64,
) -> DriftResult<u64> {
base_asset_amount.safe_div(coin_lot_size)
}
// calculate limit price in serum lot sizes
pub fn calculate_serum_limit_price(
limit_price: u64,
pc_lot_size: u64,
coin_decimals: u32,
coin_lot_size: u64,
direction: PositionDirection,
) -> DriftResult<u64> {
let coin_precision = 10_u128.pow(coin_decimals);
match direction {
PositionDirection::Long => limit_price
.cast::<u128>()?
.safe_div(PRICE_TO_QUOTE_PRECISION_RATIO)?
.safe_mul(coin_lot_size.cast()?)?
.safe_div(pc_lot_size.cast::<u128>()?.safe_mul(coin_precision)?)?
.cast(),
PositionDirection::Short => limit_price
.cast::<u128>()?
.safe_div(PRICE_TO_QUOTE_PRECISION_RATIO)?
.safe_mul(coin_lot_size.cast()?)?
.safe_div_ceil(pc_lot_size.cast::<u128>()?.safe_mul(coin_precision)?)?
.cast(),
}
}
// Max amount of quote to put deposit into serum
pub fn calculate_serum_max_native_pc_quantity(
serum_limit_price: u64,
serum_coin_qty: u64,
pc_lot_size: u64,
) -> DriftResult<u64> {
pc_lot_size
.safe_add(pc_lot_size / 2500)? // max 4bps
.safe_mul(serum_limit_price)?
.safe_mul(serum_coin_qty)?
.safe_mul(10004)?
.safe_div(10000)
}
pub fn calculate_price_from_serum_limit_price(
limit_price: u64,
pc_lot_size: u64,
coin_decimals: u32,
coin_lot_size: u64,
) -> DriftResult<u64> {
let coin_precision = 10_u128.pow(coin_decimals);
limit_price
.cast::<u128>()?
.safe_mul(pc_lot_size.cast::<u128>()?.safe_mul(coin_precision)?)?
.safe_mul(PRICE_TO_QUOTE_PRECISION_RATIO)?
.safe_div(coin_lot_size.cast()?)?
.cast()
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/cp_curve.rs
|
use solana_program::msg;
use crate::error::{DriftResult, ErrorCode};
use crate::math::amm;
use crate::math::bn;
use crate::math::bn::U192;
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_RESERVE_PRECISION, AMM_TO_QUOTE_PRECISION_RATIO_I128, K_BPS_UPDATE_SCALE,
MAX_K_BPS_DECREASE, MAX_SQRT_K, PEG_PRECISION, PERCENTAGE_PRECISION_I128, QUOTE_PRECISION,
};
use crate::math::position::{calculate_base_asset_value, calculate_base_asset_value_and_pnl};
use crate::math::safe_math::SafeMath;
use crate::state::perp_market::{MarketStatus, PerpMarket};
use crate::validate;
#[cfg(test)]
mod tests;
pub fn calculate_budgeted_k_scale(
market: &mut PerpMarket,
budget: i128,
k_pct_upper_bound: i128,
k_pct_lower_bound: i128,
) -> DriftResult<(u128, u128)> {
validate!(
k_pct_upper_bound >= K_BPS_UPDATE_SCALE,
ErrorCode::InvalidUpdateK,
"invalid k_pct_upper_bound={} > {}",
k_pct_upper_bound,
K_BPS_UPDATE_SCALE
)?;
validate!(
(K_BPS_UPDATE_SCALE - MAX_K_BPS_DECREASE..=K_BPS_UPDATE_SCALE).contains(&k_pct_lower_bound),
ErrorCode::InvalidUpdateK,
"invalid k_pct_lower_bound={} vs {}",
k_pct_lower_bound,
K_BPS_UPDATE_SCALE - MAX_K_BPS_DECREASE
)?;
let (numerator, denominator) = _calculate_budgeted_k_scale(
market.amm.base_asset_reserve,
market.amm.quote_asset_reserve,
budget,
market.amm.peg_multiplier,
market.amm.base_asset_amount_with_amm,
k_pct_upper_bound,
k_pct_lower_bound,
)?;
Ok((numerator, denominator))
}
pub fn _calculate_budgeted_k_scale(
x: u128,
y: u128,
budget: i128,
q: u128,
d: i128,
k_pct_upper_bound: i128,
k_pct_lower_bound: i128,
) -> DriftResult<(u128, u128)> {
// let curve_update_intensity = curve_update_intensity as i128;
let c = -budget;
let q = q.cast::<i128>()?;
let c_sign: i128 = if c > 0 { 1 } else { -1 };
let d_sign: i128 = if d > 0 { 1 } else { -1 };
let rounding_bias: i128 = c_sign.safe_mul(d_sign)?;
let x_d = x.cast::<i128>()?.safe_add(d)?;
let amm_reserve_precision_u192 = U192::from(AMM_RESERVE_PRECISION);
let x_times_x_d_u192 = U192::from(x)
.safe_mul(U192::from(x_d))?
.safe_div(amm_reserve_precision_u192)?;
let quote_precision_u192 = U192::from(QUOTE_PRECISION);
let x_times_x_d_c = x_times_x_d_u192
.safe_mul(U192::from(c.unsigned_abs()))?
.safe_div(quote_precision_u192)?
.try_to_u128()?;
let c_times_x_d_d = U192::from(c.unsigned_abs())
.safe_mul(U192::from(x_d.unsigned_abs()))?
.safe_div(quote_precision_u192)?
.safe_mul(U192::from(d.unsigned_abs()))?
.safe_div(amm_reserve_precision_u192)?
.try_to_u128()?;
let pegged_quote_times_dd = U192::from(y)
.safe_mul(U192::from(d.unsigned_abs()))?
.safe_div(amm_reserve_precision_u192)?
.safe_mul(U192::from(d.unsigned_abs()))?
.safe_div(amm_reserve_precision_u192)?
.safe_mul(U192::from(q))?
.safe_div(U192::from(PEG_PRECISION))?
.try_to_u128()?
.cast::<i128>()?;
let numer1 = pegged_quote_times_dd;
let numer2 = c_times_x_d_d.cast::<i128>()?.safe_mul(rounding_bias)?;
let denom1 = x_times_x_d_c.cast::<i128>()?.safe_mul(c_sign)?;
let denom2 = pegged_quote_times_dd;
// protocol is spending to increase k
if c_sign < 0 {
// thus denom1 is negative and solution is unstable
if x_times_x_d_c > pegged_quote_times_dd.unsigned_abs() {
msg!("cost exceeds possible amount to spend");
msg!("k * {:?}/{:?}", k_pct_upper_bound, K_BPS_UPDATE_SCALE);
return Ok((
k_pct_upper_bound.cast::<u128>()?,
K_BPS_UPDATE_SCALE.cast::<u128>()?,
));
}
}
let mut numerator = (numer1.safe_sub(numer2)?).safe_div(AMM_TO_QUOTE_PRECISION_RATIO_I128)?;
let mut denominator = denom1
.safe_add(denom2)?
.safe_div(AMM_TO_QUOTE_PRECISION_RATIO_I128)?;
if numerator < 0 && denominator < 0 {
numerator = numerator.abs();
denominator = denominator.abs();
}
assert!((numerator > 0 && denominator > 0));
let (numerator, denominator) = if numerator > denominator {
let current_pct_change = numerator
.safe_mul(PERCENTAGE_PRECISION_I128)?
.safe_div(denominator)?;
let maximum_pct_change = k_pct_upper_bound
.safe_mul(PERCENTAGE_PRECISION_I128)?
.safe_div(K_BPS_UPDATE_SCALE)?;
if current_pct_change > maximum_pct_change {
(k_pct_upper_bound, K_BPS_UPDATE_SCALE)
} else {
(current_pct_change, K_BPS_UPDATE_SCALE)
}
} else {
let current_pct_change = numerator
.safe_mul(PERCENTAGE_PRECISION_I128)?
.safe_div(denominator)?;
let maximum_pct_change = k_pct_lower_bound
.safe_mul(PERCENTAGE_PRECISION_I128)?
.safe_div(K_BPS_UPDATE_SCALE)?;
if current_pct_change < maximum_pct_change {
(k_pct_lower_bound, K_BPS_UPDATE_SCALE)
} else {
(current_pct_change, K_BPS_UPDATE_SCALE)
}
};
Ok((numerator.cast::<u128>()?, denominator.cast::<u128>()?))
}
/// To find the cost of adjusting k, compare the net market value before and after adjusting k
/// Increasing k costs the protocol terminal money because it reduces slippage and improves the exit price for net market position
/// Decreasing k relieves the protocol terminal money because it increases slippage and hurts the exit price for net market position
pub fn adjust_k_cost(
market: &mut PerpMarket,
update_k_result: &UpdateKResult,
) -> DriftResult<i128> {
let mut market_clone = *market;
// Find the net market value before adjusting k
let (current_net_market_value, _) = calculate_base_asset_value_and_pnl(
market_clone.amm.base_asset_amount_with_amm,
0,
&market_clone.amm,
)?;
update_k(&mut market_clone, update_k_result)?;
let (_new_net_market_value, cost) = calculate_base_asset_value_and_pnl(
market_clone.amm.base_asset_amount_with_amm,
current_net_market_value,
&market_clone.amm,
)?;
Ok(cost)
}
/// To find the cost of adjusting k, compare the net market value before and after adjusting k
/// Increasing k costs the protocol money because it reduces slippage and improves the exit price for net market position
/// Decreasing k costs the protocol money because it increases slippage and hurts the exit price for net market position
pub fn adjust_k_cost_and_update(
market: &mut PerpMarket,
update_k_result: &UpdateKResult,
) -> DriftResult<i128> {
// Find the net market value before adjusting k
let current_net_market_value =
calculate_base_asset_value(market.amm.base_asset_amount_with_amm, &market.amm)?;
update_k(market, update_k_result)?;
let (_new_net_market_value, cost) = calculate_base_asset_value_and_pnl(
market.amm.base_asset_amount_with_amm,
current_net_market_value,
&market.amm,
)?;
Ok(cost)
}
pub struct UpdateKResult {
pub sqrt_k: u128,
pub base_asset_reserve: u128,
pub quote_asset_reserve: u128,
}
pub fn get_update_k_result(
market: &PerpMarket,
new_sqrt_k: bn::U192,
bound_update: bool,
) -> DriftResult<UpdateKResult> {
let sqrt_k_ratio_precision = bn::U192::from(AMM_RESERVE_PRECISION);
let old_sqrt_k = bn::U192::from(market.amm.sqrt_k);
let mut sqrt_k_ratio = new_sqrt_k
.safe_mul(sqrt_k_ratio_precision)?
.safe_div(old_sqrt_k)?;
// if decreasing k, max decrease ratio for single transaction is 50%
if bound_update && sqrt_k_ratio < U192::from(500_000_000_u128) {
return Err(ErrorCode::InvalidUpdateK);
}
if sqrt_k_ratio < sqrt_k_ratio_precision {
sqrt_k_ratio = sqrt_k_ratio + 1;
}
let sqrt_k = new_sqrt_k.try_to_u128()?;
validate!(
sqrt_k_ratio < sqrt_k_ratio_precision || sqrt_k <= MAX_SQRT_K,
ErrorCode::InvalidUpdateK,
"cannot increase sqrt_k={} past MAX_SQRT_K",
sqrt_k
)?;
// only allow too small when market is in reduce only mode
if market.status != MarketStatus::ReduceOnly
&& new_sqrt_k < old_sqrt_k
&& market.amm.base_asset_amount_with_amm.unsigned_abs() > sqrt_k
{
// todo, check less lp_tokens as well
msg!("new_sqrt_k too small relative to market imbalance");
return Err(ErrorCode::InvalidUpdateK);
}
let base_asset_reserve = bn::U192::from(market.amm.base_asset_reserve)
.safe_mul(sqrt_k_ratio)?
.safe_div(sqrt_k_ratio_precision)?
.try_to_u128()?;
let invariant_sqrt_u192 = U192::from(sqrt_k);
let invariant = invariant_sqrt_u192.safe_mul(invariant_sqrt_u192)?;
let quote_asset_reserve = invariant
.safe_div(U192::from(base_asset_reserve))?
.try_to_u128()?;
Ok(UpdateKResult {
sqrt_k,
base_asset_reserve,
quote_asset_reserve,
})
}
pub fn update_k(market: &mut PerpMarket, update_k_result: &UpdateKResult) -> DriftResult {
market.amm.base_asset_reserve = update_k_result.base_asset_reserve;
market.amm.quote_asset_reserve = update_k_result.quote_asset_reserve;
market.amm.sqrt_k = update_k_result.sqrt_k;
let (new_terminal_quote_reserve, new_terminal_base_reserve) =
amm::calculate_terminal_reserves(&market.amm)?;
market.amm.terminal_quote_asset_reserve = new_terminal_quote_reserve;
let (min_base_asset_reserve, max_base_asset_reserve) =
amm::calculate_bid_ask_bounds(market.amm.concentration_coef, new_terminal_base_reserve)?;
market.amm.min_base_asset_reserve = min_base_asset_reserve;
market.amm.max_base_asset_reserve = max_base_asset_reserve;
let reserve_price_after = market.amm.reserve_price()?;
crate::controller::amm::update_spreads(market, reserve_price_after)?;
Ok(())
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/spot_balance.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
#[cfg(feature = "drift-rs")]
use crate::math::constants::PERCENTAGE_PRECISION;
use crate::math::constants::{ONE_YEAR, SPOT_RATE_PRECISION, SPOT_UTILIZATION_PRECISION};
use crate::math::safe_math::{SafeDivFloor, SafeMath};
use crate::state::oracle::{OraclePriceData, StrictOraclePrice};
use crate::state::spot_market::{SpotBalanceType, SpotMarket};
use crate::state::user::SpotPosition;
#[cfg(test)]
mod tests;
pub fn get_spot_balance(
token_amount: u128,
spot_market: &SpotMarket,
balance_type: &SpotBalanceType,
round_up: bool,
) -> DriftResult<u128> {
let precision_increase = 10_u128.pow(19_u32.safe_sub(spot_market.decimals)?);
let cumulative_interest = match balance_type {
SpotBalanceType::Deposit => spot_market.cumulative_deposit_interest,
SpotBalanceType::Borrow => spot_market.cumulative_borrow_interest,
};
let mut balance = token_amount
.safe_mul(precision_increase)?
.safe_div(cumulative_interest)?;
if round_up && balance != 0 {
balance = balance.safe_add(1)?;
}
Ok(balance)
}
pub fn get_token_amount(
balance: u128,
spot_market: &SpotMarket,
balance_type: &SpotBalanceType,
) -> DriftResult<u128> {
let precision_decrease = 10_u128.pow(19_u32.safe_sub(spot_market.decimals)?);
let cumulative_interest = match balance_type {
SpotBalanceType::Deposit => spot_market.cumulative_deposit_interest,
SpotBalanceType::Borrow => spot_market.cumulative_borrow_interest,
};
let token_amount = match balance_type {
SpotBalanceType::Deposit => balance
.safe_mul(cumulative_interest)?
.safe_div(precision_decrease)?,
SpotBalanceType::Borrow => balance
.safe_mul(cumulative_interest)?
.safe_div_ceil(precision_decrease)?,
};
Ok(token_amount)
}
pub fn get_signed_token_amount(
token_amount: u128,
balance_type: &SpotBalanceType,
) -> DriftResult<i128> {
match balance_type {
SpotBalanceType::Deposit => token_amount.cast(),
SpotBalanceType::Borrow => token_amount
.cast::<i128>()
.map(|token_amount| -token_amount),
}
}
pub fn get_interest_token_amount(
balance: u128,
spot_market: &SpotMarket,
interest: u128,
) -> DriftResult<u128> {
let precision_decrease = 10_u128.pow(19_u32.safe_sub(spot_market.decimals)?);
let token_amount = balance.safe_mul(interest)?.safe_div(precision_decrease)?;
Ok(token_amount)
}
pub struct InterestAccumulated {
pub borrow_interest: u128,
pub deposit_interest: u128,
}
pub fn calculate_utilization(
deposit_token_amount: u128,
borrow_token_amount: u128,
) -> DriftResult<u128> {
let utilization = borrow_token_amount
.safe_mul(SPOT_UTILIZATION_PRECISION)?
.checked_div(deposit_token_amount)
.unwrap_or({
if deposit_token_amount == 0 && borrow_token_amount == 0 {
0_u128
} else {
// if there are borrows without deposits, default to maximum utilization rate
SPOT_UTILIZATION_PRECISION
}
});
Ok(utilization)
}
pub fn calculate_spot_market_utilization(spot_market: &SpotMarket) -> DriftResult<u128> {
let deposit_token_amount = get_token_amount(
spot_market.deposit_balance,
spot_market,
&SpotBalanceType::Deposit,
)?;
let borrow_token_amount = get_token_amount(
spot_market.borrow_balance,
spot_market,
&SpotBalanceType::Borrow,
)?;
let utilization = calculate_utilization(deposit_token_amount, borrow_token_amount)?;
Ok(utilization)
}
pub fn calculate_accumulated_interest(
spot_market: &SpotMarket,
now: i64,
) -> DriftResult<InterestAccumulated> {
if now <= spot_market.last_interest_ts.cast()? {
return Ok(InterestAccumulated {
borrow_interest: 0,
deposit_interest: 0,
});
}
let utilization = calculate_spot_market_utilization(spot_market)?;
if utilization == 0 {
return Ok(InterestAccumulated {
borrow_interest: 0,
deposit_interest: 0,
});
}
let borrow_rate = calculate_borrow_rate(spot_market, utilization)?;
let time_since_last_update = now
.cast::<u64>()
.or(Err(ErrorCode::UnableToCastUnixTime))?
.safe_sub(spot_market.last_interest_ts)?;
// To save some compute units, have to multiply the rate by the `time_since_last_update` here
// and then divide out by ONE_YEAR when calculating interest accumulated below
let modified_borrow_rate = borrow_rate.safe_mul(time_since_last_update as u128)?;
let modified_deposit_rate = modified_borrow_rate
.safe_mul(utilization)?
.safe_div(SPOT_UTILIZATION_PRECISION)?;
let borrow_interest = spot_market
.cumulative_borrow_interest
.safe_mul(modified_borrow_rate)?
.safe_div(ONE_YEAR)?
.safe_div(SPOT_RATE_PRECISION)?
.safe_add(1)?;
let deposit_interest = spot_market
.cumulative_deposit_interest
.safe_mul(modified_deposit_rate)?
.safe_div(ONE_YEAR)?
.safe_div(SPOT_RATE_PRECISION)?;
Ok(InterestAccumulated {
borrow_interest,
deposit_interest,
})
}
#[inline(always)]
pub fn calculate_borrow_rate(spot_market: &SpotMarket, utilization: u128) -> DriftResult<u128> {
let borrow_rate = if utilization > spot_market.optimal_utilization.cast()? {
let surplus_utilization = utilization.safe_sub(spot_market.optimal_utilization.cast()?)?;
let borrow_rate_slope = spot_market
.max_borrow_rate
.cast::<u128>()?
.safe_sub(spot_market.optimal_borrow_rate.cast()?)?
.safe_mul(SPOT_UTILIZATION_PRECISION)?
.safe_div(
SPOT_UTILIZATION_PRECISION.safe_sub(spot_market.optimal_utilization.cast()?)?,
)?;
spot_market.optimal_borrow_rate.cast::<u128>()?.safe_add(
surplus_utilization
.safe_mul(borrow_rate_slope)?
.safe_div(SPOT_UTILIZATION_PRECISION)?,
)?
} else {
let borrow_rate_slope = spot_market
.optimal_borrow_rate
.cast::<u128>()?
.safe_mul(SPOT_UTILIZATION_PRECISION)?
.safe_div(spot_market.optimal_utilization.cast()?)?;
utilization
.safe_mul(borrow_rate_slope)?
.safe_div(SPOT_UTILIZATION_PRECISION)?
}
.max(spot_market.get_min_borrow_rate()?.cast()?);
Ok(borrow_rate)
}
#[cfg(feature = "drift-rs")]
pub fn calculate_deposit_rate(
spot_market: &SpotMarket,
utilization: u128,
borrow_rate: u128,
) -> DriftResult<u128> {
borrow_rate
.safe_mul(PERCENTAGE_PRECISION.safe_sub(spot_market.insurance_fund.total_factor.cast()?)?)?
.safe_mul(utilization)?
.safe_div(SPOT_UTILIZATION_PRECISION)?
.safe_div(PERCENTAGE_PRECISION)
}
pub fn get_balance_value_and_token_amount(
spot_position: &SpotPosition,
spot_market: &SpotMarket,
oracle_price_data: &OraclePriceData,
) -> DriftResult<(u128, u128)> {
let token_amount = spot_position.get_token_amount(spot_market)?;
let precision_decrease = 10_u128.pow(spot_market.decimals);
let value = token_amount
.safe_mul(oracle_price_data.price.cast()?)?
.safe_div(precision_decrease)?;
Ok((value, token_amount))
}
pub fn get_strict_token_value(
token_amount: i128,
spot_decimals: u32,
strict_price: &StrictOraclePrice,
) -> DriftResult<i128> {
if token_amount == 0 {
return Ok(0);
}
let precision_decrease = 10_i128.pow(spot_decimals);
let price = if token_amount > 0 {
strict_price.min()
} else {
strict_price.max()
};
let token_with_price = token_amount.safe_mul(price.cast()?)?;
if token_with_price < 0 {
token_with_price.safe_div_floor(precision_decrease)
} else {
token_with_price.safe_div(precision_decrease)
}
}
pub fn get_token_value(
token_amount: i128,
spot_decimals: u32,
oracle_price: i64,
) -> DriftResult<i128> {
if token_amount == 0 {
return Ok(0);
}
let precision_decrease = 10_i128.pow(spot_decimals);
let token_with_oracle = token_amount.safe_mul(oracle_price.cast()?)?;
if token_with_oracle < 0 {
token_with_oracle.safe_div_floor(precision_decrease.abs())
} else {
token_with_oracle.safe_div(precision_decrease)
}
}
pub fn get_balance_value(
spot_position: &SpotPosition,
spot_market: &SpotMarket,
oracle_price_data: &OraclePriceData,
) -> DriftResult<u128> {
let (value, _) =
get_balance_value_and_token_amount(spot_position, spot_market, oracle_price_data)?;
Ok(value)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/helpers.rs
|
use solana_program::msg;
use crate::error::DriftResult;
use crate::math::bn::U192;
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
use crate::math_error;
#[cfg(test)]
mod tests;
pub fn standardize_value_with_remainder_i128(
value: i128,
step_size: u128,
) -> DriftResult<(i128, i128)> {
let remainder = value
.unsigned_abs()
.checked_rem_euclid(step_size)
.ok_or_else(math_error!())?
.cast::<i128>()?
.safe_mul(value.signum())?;
let standardized_value = value.safe_sub(remainder)?;
Ok((standardized_value, remainder))
}
pub fn get_proportion_i128(value: i128, numerator: u128, denominator: u128) -> DriftResult<i128> {
let proportional_u128 = get_proportion_u128(value.unsigned_abs(), numerator, denominator)?;
let proportional_value = proportional_u128.cast::<i128>()?.safe_mul(value.signum())?;
Ok(proportional_value)
}
pub fn get_proportion_u128(value: u128, numerator: u128, denominator: u128) -> DriftResult<u128> {
// we use u128::max.sqrt() here
let large_constant = u64::MAX.cast::<u128>()?;
let proportional_value = if numerator == denominator {
value
} else if value >= large_constant || numerator >= large_constant {
let value = U192::from(value)
.safe_mul(U192::from(numerator))?
.safe_div(U192::from(denominator))?;
value.cast::<u128>()?
} else if numerator > denominator / 2 && denominator > numerator {
// get values to ensure a ceiling division
let (std_value, r) = standardize_value_with_remainder_i128(
value
.safe_mul(denominator.safe_sub(numerator)?)?
.cast::<i128>()?,
denominator,
)?;
// perform ceiling division by subtracting one if there is a remainder
value
.safe_sub(std_value.cast::<u128>()?.safe_div(denominator)?)?
.safe_sub(r.signum().cast::<u128>()?)?
} else {
value.safe_mul(numerator)?.safe_div(denominator)?
};
Ok(proportional_value)
}
pub fn on_the_hour_update(now: i64, last_update_ts: i64, update_period: i64) -> DriftResult<i64> {
let time_since_last_update = now.safe_sub(last_update_ts)?;
// round next update time to be available on the hour
let mut next_update_wait = update_period;
if update_period > 1 {
let last_update_delay = last_update_ts.rem_euclid(update_period);
if last_update_delay != 0 {
let max_delay_for_next_period = update_period.safe_div(3)?;
let two_funding_periods = update_period.safe_mul(2)?;
if last_update_delay > max_delay_for_next_period {
// too late for on the hour next period, delay to following period
next_update_wait = two_funding_periods.safe_sub(last_update_delay)?;
} else {
// allow update on the hour
next_update_wait = update_period.safe_sub(last_update_delay)?;
}
if next_update_wait > two_funding_periods {
next_update_wait = next_update_wait.safe_sub(update_period)?;
}
}
}
let time_remaining_until_update = next_update_wait.safe_sub(time_since_last_update)?.max(0);
Ok(time_remaining_until_update)
}
#[cfg(test)]
#[allow(clippy::comparison_chain)]
pub fn log10(n: u128) -> u128 {
if n < 10 {
0
} else if n == 10 {
1
} else {
log10(n / 10) + 1
}
}
pub fn log10_iter(n: u128) -> u128 {
let mut result = 0;
let mut n_copy = n;
while n_copy >= 10 {
result += 1;
n_copy /= 10;
}
result
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/mod.rs
|
pub mod amm;
pub mod amm_jit;
pub mod amm_spread;
pub mod auction;
pub mod bankruptcy;
pub mod bn;
pub mod casting;
pub mod ceil_div;
pub mod constants;
pub mod cp_curve;
pub mod fees;
mod floor_div;
pub mod fuel;
pub mod fulfillment;
pub mod funding;
pub mod helpers;
pub mod insurance;
pub mod liquidation;
pub mod lp;
pub mod margin;
pub mod matching;
pub mod oracle;
pub mod orders;
pub mod pnl;
pub mod position;
pub mod quote_asset;
pub mod repeg;
pub mod safe_math;
pub mod safe_unwrap;
pub mod serum;
pub mod spot_balance;
pub mod spot_swap;
pub mod spot_withdraw;
pub mod stats;
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/pnl.rs
|
use crate::controller::amm::SwapDirection;
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
pub fn calculate_pnl(
exit_value: u128,
entry_value: u128,
swap_direction_to_close: SwapDirection,
) -> DriftResult<i128> {
match swap_direction_to_close {
SwapDirection::Add => exit_value.cast::<i128>()?.safe_sub(entry_value.cast()?),
SwapDirection::Remove => entry_value.cast::<i128>()?.safe_sub(exit_value.cast()?),
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/safe_math.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::math::bn::{U192, U256};
use crate::math::ceil_div::CheckedCeilDiv;
use crate::math::floor_div::CheckedFloorDiv;
use solana_program::msg;
use std::panic::Location;
pub trait SafeMath: Sized {
fn safe_add(self, rhs: Self) -> DriftResult<Self>;
fn safe_sub(self, rhs: Self) -> DriftResult<Self>;
fn safe_mul(self, rhs: Self) -> DriftResult<Self>;
fn safe_div(self, rhs: Self) -> DriftResult<Self>;
fn safe_div_ceil(self, rhs: Self) -> DriftResult<Self>;
}
macro_rules! checked_impl {
($t:ty) => {
impl SafeMath for $t {
#[track_caller]
#[inline(always)]
fn safe_add(self, v: $t) -> DriftResult<$t> {
match self.checked_add(v) {
Some(result) => Ok(result),
None => {
let caller = Location::caller();
msg!("Math error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::MathError)
}
}
}
#[track_caller]
#[inline(always)]
fn safe_sub(self, v: $t) -> DriftResult<$t> {
match self.checked_sub(v) {
Some(result) => Ok(result),
None => {
let caller = Location::caller();
msg!("Math error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::MathError)
}
}
}
#[track_caller]
#[inline(always)]
fn safe_mul(self, v: $t) -> DriftResult<$t> {
match self.checked_mul(v) {
Some(result) => Ok(result),
None => {
let caller = Location::caller();
msg!("Math error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::MathError)
}
}
}
#[track_caller]
#[inline(always)]
fn safe_div(self, v: $t) -> DriftResult<$t> {
match self.checked_div(v) {
Some(result) => Ok(result),
None => {
let caller = Location::caller();
msg!("Math error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::MathError)
}
}
}
#[track_caller]
#[inline(always)]
fn safe_div_ceil(self, v: $t) -> DriftResult<$t> {
match self.checked_ceil_div(v) {
Some(result) => Ok(result),
None => {
let caller = Location::caller();
msg!("Math error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::MathError)
}
}
}
}
};
}
checked_impl!(U256);
checked_impl!(U192);
checked_impl!(u128);
checked_impl!(u64);
checked_impl!(u32);
checked_impl!(u16);
checked_impl!(u8);
checked_impl!(i128);
checked_impl!(i64);
checked_impl!(i32);
checked_impl!(i16);
checked_impl!(i8);
pub trait SafeDivFloor: Sized {
/// Perform floor division
fn safe_div_floor(self, rhs: Self) -> DriftResult<Self>;
}
macro_rules! div_floor_impl {
($t:ty) => {
impl SafeDivFloor for $t {
#[track_caller]
#[inline(always)]
fn safe_div_floor(self, v: $t) -> DriftResult<$t> {
match self.checked_floor_div(v) {
Some(result) => Ok(result),
None => {
let caller = Location::caller();
msg!("Math error thrown at {}:{}", caller.file(), caller.line());
Err(ErrorCode::MathError)
}
}
}
}
};
}
div_floor_impl!(i128);
div_floor_impl!(i64);
div_floor_impl!(i32);
div_floor_impl!(i16);
div_floor_impl!(i8);
#[cfg(test)]
mod test {
use crate::error::ErrorCode;
use crate::math::safe_math::{SafeDivFloor, SafeMath};
#[test]
fn safe_add() {
assert_eq!(1_u128.safe_add(1).unwrap(), 2);
assert_eq!(1_u128.safe_add(u128::MAX), Err(ErrorCode::MathError));
}
#[test]
fn safe_sub() {
assert_eq!(1_u128.safe_sub(1).unwrap(), 0);
assert_eq!(0_u128.safe_sub(1), Err(ErrorCode::MathError));
}
#[test]
fn safe_mul() {
assert_eq!(8_u128.safe_mul(80).unwrap(), 640);
assert_eq!(1_u128.safe_mul(1).unwrap(), 1);
assert_eq!(2_u128.safe_mul(u128::MAX), Err(ErrorCode::MathError));
}
#[test]
fn safe_div() {
assert_eq!(155_u128.safe_div(8).unwrap(), 19);
assert_eq!(159_u128.safe_div(8).unwrap(), 19);
assert_eq!(160_u128.safe_div(8).unwrap(), 20);
assert_eq!(1_u128.safe_div(1).unwrap(), 1);
assert_eq!(1_u128.safe_div(100).unwrap(), 0);
assert_eq!(1_u128.safe_div(0), Err(ErrorCode::MathError));
}
#[test]
fn safe_div_floor() {
assert_eq!((-155_i128).safe_div_floor(8).unwrap(), -20);
assert_eq!((-159_i128).safe_div_floor(8).unwrap(), -20);
assert_eq!((-160_i128).safe_div_floor(8).unwrap(), -20);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/oracle.rs
|
use std::cmp::max;
use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::msg;
use crate::error::{DriftResult, ErrorCode};
use crate::math::amm;
use crate::math::casting::Cast;
use crate::math::constants::BID_ASK_SPREAD_PRECISION;
use crate::math::safe_math::SafeMath;
use crate::state::oracle::{OraclePriceData, OracleSource};
use crate::state::paused_operations::PerpOperation;
use crate::state::perp_market::PerpMarket;
use crate::state::state::{OracleGuardRails, ValidityGuardRails};
use crate::state::user::MarketType;
use std::fmt;
#[cfg(test)]
mod tests;
// ordered by "severity"
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq, Default)]
pub enum OracleValidity {
NonPositive,
TooVolatile,
TooUncertain,
StaleForMargin,
InsufficientDataPoints,
StaleForAMM,
#[default]
Valid,
}
impl OracleValidity {
pub fn get_error_code(&self) -> ErrorCode {
match self {
OracleValidity::NonPositive => ErrorCode::OracleNonPositive,
OracleValidity::TooVolatile => ErrorCode::OracleTooVolatile,
OracleValidity::TooUncertain => ErrorCode::OracleTooUncertain,
OracleValidity::StaleForMargin => ErrorCode::OracleStaleForMargin,
OracleValidity::InsufficientDataPoints => ErrorCode::OracleInsufficientDataPoints,
OracleValidity::StaleForAMM => ErrorCode::OracleStaleForAMM,
OracleValidity::Valid => unreachable!(),
}
}
}
impl fmt::Display for OracleValidity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
OracleValidity::NonPositive => write!(f, "NonPositive"),
OracleValidity::TooVolatile => write!(f, "TooVolatile"),
OracleValidity::TooUncertain => write!(f, "TooUncertain"),
OracleValidity::StaleForMargin => write!(f, "StaleForMargin"),
OracleValidity::InsufficientDataPoints => write!(f, "InsufficientDataPoints"),
OracleValidity::StaleForAMM => write!(f, "StaleForAMM"),
OracleValidity::Valid => write!(f, "Valid"),
}
}
}
#[derive(Clone, Copy, BorshSerialize, BorshDeserialize, PartialEq, Debug, Eq)]
pub enum DriftAction {
UpdateFunding,
SettlePnl,
TriggerOrder,
FillOrderMatch,
FillOrderAmm,
Liquidate,
MarginCalc,
UpdateTwap,
UpdateAMMCurve,
OracleOrderPrice,
}
pub fn is_oracle_valid_for_action(
oracle_validity: OracleValidity,
action: Option<DriftAction>,
) -> DriftResult<bool> {
let is_ok = match action {
Some(action) => match action {
DriftAction::FillOrderAmm => {
matches!(oracle_validity, OracleValidity::Valid)
}
// relax oracle staleness, later checks for sufficiently recent amm slot update for funding update
DriftAction::UpdateFunding => {
matches!(
oracle_validity,
OracleValidity::Valid
| OracleValidity::StaleForAMM
| OracleValidity::InsufficientDataPoints
| OracleValidity::StaleForMargin
)
}
DriftAction::OracleOrderPrice => {
matches!(
oracle_validity,
OracleValidity::Valid
| OracleValidity::StaleForAMM
| OracleValidity::InsufficientDataPoints
)
}
DriftAction::MarginCalc => !matches!(
oracle_validity,
OracleValidity::NonPositive
| OracleValidity::TooVolatile
| OracleValidity::TooUncertain
| OracleValidity::StaleForMargin
),
DriftAction::TriggerOrder => !matches!(
oracle_validity,
OracleValidity::NonPositive | OracleValidity::TooVolatile
),
DriftAction::SettlePnl => matches!(
oracle_validity,
OracleValidity::Valid
| OracleValidity::StaleForAMM
| OracleValidity::InsufficientDataPoints
| OracleValidity::StaleForMargin
),
DriftAction::FillOrderMatch => !matches!(
oracle_validity,
OracleValidity::NonPositive
| OracleValidity::TooVolatile
| OracleValidity::TooUncertain
),
DriftAction::Liquidate => !matches!(
oracle_validity,
OracleValidity::NonPositive | OracleValidity::TooVolatile
),
DriftAction::UpdateTwap => !matches!(oracle_validity, OracleValidity::NonPositive),
DriftAction::UpdateAMMCurve => !matches!(oracle_validity, OracleValidity::NonPositive),
},
None => {
matches!(oracle_validity, OracleValidity::Valid)
}
};
Ok(is_ok)
}
pub fn block_operation(
market: &PerpMarket,
oracle_price_data: &OraclePriceData,
guard_rails: &OracleGuardRails,
reserve_price: u64,
slot: u64,
) -> DriftResult<bool> {
let OracleStatus {
oracle_validity,
mark_too_divergent: is_oracle_mark_too_divergent,
oracle_reserve_price_spread_pct: _,
..
} = get_oracle_status(market, oracle_price_data, guard_rails, reserve_price)?;
let is_oracle_valid =
is_oracle_valid_for_action(oracle_validity, Some(DriftAction::UpdateFunding))?;
let slots_since_amm_update = slot.saturating_sub(market.amm.last_update_slot);
let funding_paused_on_market = market.is_operation_paused(PerpOperation::UpdateFunding);
// block if amm hasnt been updated since over half the funding period (assuming slot ~= 500ms)
let block = slots_since_amm_update > market.amm.funding_period.cast()?
|| !is_oracle_valid
|| is_oracle_mark_too_divergent
|| funding_paused_on_market;
Ok(block)
}
#[derive(Default, Clone, Copy, Debug)]
pub struct OracleStatus {
pub price_data: OraclePriceData,
pub oracle_reserve_price_spread_pct: i64,
pub mark_too_divergent: bool,
pub oracle_validity: OracleValidity,
}
pub fn get_oracle_status(
market: &PerpMarket,
oracle_price_data: &OraclePriceData,
guard_rails: &OracleGuardRails,
reserve_price: u64,
) -> DriftResult<OracleStatus> {
let oracle_validity = oracle_validity(
MarketType::Perp,
market.market_index,
market.amm.historical_oracle_data.last_oracle_price_twap,
oracle_price_data,
&guard_rails.validity,
market.get_max_confidence_interval_multiplier()?,
&market.amm.oracle_source,
false,
)?;
let oracle_reserve_price_spread_pct =
amm::calculate_oracle_twap_5min_price_spread_pct(&market.amm, reserve_price)?;
let is_oracle_mark_too_divergent = amm::is_oracle_mark_too_divergent(
oracle_reserve_price_spread_pct,
&guard_rails.price_divergence,
)?;
Ok(OracleStatus {
price_data: *oracle_price_data,
oracle_reserve_price_spread_pct,
mark_too_divergent: is_oracle_mark_too_divergent,
oracle_validity,
})
}
pub fn oracle_validity(
market_type: MarketType,
market_index: u16,
last_oracle_twap: i64,
oracle_price_data: &OraclePriceData,
valid_oracle_guard_rails: &ValidityGuardRails,
max_confidence_interval_multiplier: u64,
oracle_source: &OracleSource,
log_validity: bool,
) -> DriftResult<OracleValidity> {
let OraclePriceData {
price: oracle_price,
confidence: oracle_conf,
delay: oracle_delay,
has_sufficient_number_of_data_points,
..
} = *oracle_price_data;
let is_oracle_price_nonpositive = oracle_price <= 0;
let is_oracle_price_too_volatile = (oracle_price.max(last_oracle_twap))
.safe_div(last_oracle_twap.min(oracle_price).max(1))?
.gt(&valid_oracle_guard_rails.too_volatile_ratio);
let conf_pct_of_price = max(1, oracle_conf)
.safe_mul(BID_ASK_SPREAD_PRECISION)?
.safe_div(oracle_price.cast()?)?;
// TooUncertain
let is_conf_too_large = conf_pct_of_price.gt(&valid_oracle_guard_rails
.confidence_interval_max_size
.safe_mul(max_confidence_interval_multiplier)?);
let is_stale_for_amm = oracle_delay.gt(&valid_oracle_guard_rails.slots_before_stale_for_amm);
let is_stale_for_margin = if matches!(
oracle_source,
OracleSource::PythStableCoinPull | OracleSource::PythStableCoin
) {
oracle_delay.gt(&(valid_oracle_guard_rails
.slots_before_stale_for_margin
.saturating_mul(3)))
} else {
oracle_delay.gt(&valid_oracle_guard_rails.slots_before_stale_for_margin)
};
let oracle_validity = if is_oracle_price_nonpositive {
OracleValidity::NonPositive
} else if is_oracle_price_too_volatile {
OracleValidity::TooVolatile
} else if is_conf_too_large {
OracleValidity::TooUncertain
} else if is_stale_for_margin {
OracleValidity::StaleForMargin
} else if !has_sufficient_number_of_data_points {
OracleValidity::InsufficientDataPoints
} else if is_stale_for_amm {
OracleValidity::StaleForAMM
} else {
OracleValidity::Valid
};
if log_validity {
if !has_sufficient_number_of_data_points {
msg!(
"Invalid {} {} Oracle: Insufficient Data Points",
market_type,
market_index
);
}
if is_oracle_price_nonpositive {
msg!(
"Invalid {} {} Oracle: Non-positive (oracle_price <=0)",
market_type,
market_index
);
}
if is_oracle_price_too_volatile {
msg!(
"Invalid {} {} Oracle: Too Volatile (last_oracle_price_twap={:?} vs oracle_price={:?})",
market_type,
market_index,
last_oracle_twap,
oracle_price,
);
}
if is_conf_too_large {
msg!(
"Invalid {} {} Oracle: Confidence Too Large (is_conf_too_large={:?})",
market_type,
market_index,
conf_pct_of_price
);
}
if is_stale_for_amm || is_stale_for_margin {
msg!(
"Invalid {} {} Oracle: Stale (oracle_delay={:?})",
market_type,
market_index,
oracle_delay
);
}
}
Ok(oracle_validity)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/auction.rs
|
use crate::controller::position::PositionDirection;
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
use crate::math::constants::AUCTION_DERIVE_PRICE_FRACTION;
use crate::math::orders::standardize_price;
use crate::math::safe_math::SafeMath;
use crate::state::oracle::OraclePriceData;
use crate::state::user::{Order, OrderType};
use solana_program::msg;
use crate::state::fill_mode::FillMode;
use crate::state::perp_market::{AMMAvailability, PerpMarket};
use crate::{OrderParams, MAX_PREDICTION_MARKET_PRICE};
use std::cmp::min;
#[cfg(test)]
mod tests;
pub fn calculate_auction_prices(
oracle_price_data: &OraclePriceData,
direction: PositionDirection,
limit_price: u64,
) -> DriftResult<(i64, i64)> {
let oracle_price = oracle_price_data.price;
let limit_price = limit_price.cast::<i64>()?;
if limit_price > 0 {
let (auction_start_price, auction_end_price) = match direction {
// Long and limit price is better than oracle price
PositionDirection::Long if limit_price < oracle_price => {
let limit_derive_start_price =
limit_price.safe_sub(limit_price / AUCTION_DERIVE_PRICE_FRACTION)?;
let oracle_derive_start_price =
oracle_price.safe_sub(oracle_price / AUCTION_DERIVE_PRICE_FRACTION)?;
(
limit_derive_start_price.min(oracle_derive_start_price),
limit_price,
)
}
// Long and limit price is worse than oracle price
PositionDirection::Long if limit_price >= oracle_price => {
let oracle_derive_end_price =
oracle_price.safe_add(oracle_price / AUCTION_DERIVE_PRICE_FRACTION)?;
(oracle_price, limit_price.min(oracle_derive_end_price))
}
// Short and limit price is better than oracle price
PositionDirection::Short if limit_price > oracle_price => {
let limit_derive_start_price =
limit_price.safe_add(limit_price / AUCTION_DERIVE_PRICE_FRACTION)?;
let oracle_derive_start_price =
oracle_price.safe_add(oracle_price / AUCTION_DERIVE_PRICE_FRACTION)?;
(
limit_derive_start_price.max(oracle_derive_start_price),
limit_price,
)
}
// Short and limit price is worse than oracle price
PositionDirection::Short if limit_price <= oracle_price => {
let oracle_derive_end_price =
oracle_price.safe_sub(oracle_price / AUCTION_DERIVE_PRICE_FRACTION)?;
(oracle_price, limit_price.max(oracle_derive_end_price))
}
_ => unreachable!(),
};
return Ok((auction_start_price, auction_end_price));
}
let auction_end_price = match direction {
PositionDirection::Long => {
oracle_price.safe_add(oracle_price / AUCTION_DERIVE_PRICE_FRACTION)?
}
PositionDirection::Short => {
oracle_price.safe_sub(oracle_price / AUCTION_DERIVE_PRICE_FRACTION)?
}
};
Ok((oracle_price, auction_end_price))
}
pub fn calculate_auction_price(
order: &Order,
slot: u64,
tick_size: u64,
valid_oracle_price: Option<i64>,
is_prediction_market: bool,
) -> DriftResult<u64> {
match order.order_type {
OrderType::Market | OrderType::TriggerMarket | OrderType::TriggerLimit => {
calculate_auction_price_for_fixed_auction(order, slot, tick_size)
}
OrderType::Limit => {
if order.has_oracle_price_offset() {
calculate_auction_price_for_oracle_offset_auction(
order,
slot,
tick_size,
valid_oracle_price,
is_prediction_market,
)
} else {
calculate_auction_price_for_fixed_auction(order, slot, tick_size)
}
}
OrderType::Oracle => calculate_auction_price_for_oracle_offset_auction(
order,
slot,
tick_size,
valid_oracle_price,
is_prediction_market,
),
}
}
fn calculate_auction_price_for_fixed_auction(
order: &Order,
slot: u64,
tick_size: u64,
) -> DriftResult<u64> {
let slots_elapsed = slot.safe_sub(order.slot)?;
let delta_numerator = min(slots_elapsed, order.auction_duration.cast()?);
let delta_denominator = order.auction_duration;
let auction_start_price = order.auction_start_price.cast::<u64>()?;
let auction_end_price = order.auction_end_price.cast::<u64>()?;
if delta_denominator == 0 {
return standardize_price(auction_end_price, tick_size, order.direction);
}
let price_delta = match order.direction {
PositionDirection::Long => auction_end_price
.safe_sub(auction_start_price)?
.safe_mul(delta_numerator.cast()?)?
.safe_div(delta_denominator.cast()?)?,
PositionDirection::Short => auction_start_price
.safe_sub(auction_end_price)?
.safe_mul(delta_numerator.cast()?)?
.safe_div(delta_denominator.cast()?)?,
};
let price = match order.direction {
PositionDirection::Long => auction_start_price.safe_add(price_delta)?,
PositionDirection::Short => auction_start_price.safe_sub(price_delta)?,
};
standardize_price(price, tick_size, order.direction)
}
fn calculate_auction_price_for_oracle_offset_auction(
order: &Order,
slot: u64,
tick_size: u64,
valid_oracle_price: Option<i64>,
is_prediction_market: bool,
) -> DriftResult<u64> {
let oracle_price = valid_oracle_price.ok_or_else(|| {
msg!("Could not find oracle too calculate oracle offset auction price");
ErrorCode::OracleNotFound
})?;
let slots_elapsed = slot.safe_sub(order.slot)?;
let delta_numerator = min(slots_elapsed, order.auction_duration.cast()?);
let delta_denominator = order.auction_duration;
let auction_start_price_offset = order.auction_start_price;
let auction_end_price_offset = order.auction_end_price;
if delta_denominator == 0 {
let mut price = oracle_price
.safe_add(auction_end_price_offset)?
.max(tick_size.cast()?)
.cast::<u64>()?;
if is_prediction_market {
price = price.min(MAX_PREDICTION_MARKET_PRICE);
}
return standardize_price(price, tick_size, order.direction);
}
let price_offset_delta = match order.direction {
PositionDirection::Long => auction_end_price_offset
.safe_sub(auction_start_price_offset)?
.safe_mul(delta_numerator.cast()?)?
.safe_div(delta_denominator.cast()?)?,
PositionDirection::Short => auction_start_price_offset
.safe_sub(auction_end_price_offset)?
.safe_mul(delta_numerator.cast()?)?
.safe_div(delta_denominator.cast()?)?,
};
let price_offset = match order.direction {
PositionDirection::Long => auction_start_price_offset.safe_add(price_offset_delta)?,
PositionDirection::Short => auction_start_price_offset.safe_sub(price_offset_delta)?,
};
let mut price = oracle_price
.safe_add(price_offset)?
.max(tick_size.cast()?)
.cast::<u64>()?;
if is_prediction_market {
price = price.min(MAX_PREDICTION_MARKET_PRICE);
}
standardize_price(price, tick_size, order.direction)
}
pub fn is_auction_complete(order_slot: u64, auction_duration: u8, slot: u64) -> DriftResult<bool> {
if auction_duration == 0 {
return Ok(true);
}
let slots_elapsed = slot.safe_sub(order_slot)?;
Ok(slots_elapsed > auction_duration.cast()?)
}
pub fn can_fill_with_amm(
amm_availability: AMMAvailability,
valid_oracle_price: Option<i64>,
order: &Order,
min_auction_duration: u8,
slot: u64,
fill_mode: FillMode,
) -> DriftResult<bool> {
Ok(amm_availability != AMMAvailability::Unavailable
&& valid_oracle_price.is_some()
&& (amm_availability == AMMAvailability::Immediate
|| is_amm_available_liquidity_source(order, min_auction_duration, slot, fill_mode)?))
}
pub fn is_amm_available_liquidity_source(
order: &Order,
min_auction_duration: u8,
slot: u64,
fill_mode: FillMode,
) -> DriftResult<bool> {
Ok(is_auction_complete(order.slot, min_auction_duration, slot)? || fill_mode.is_liquidation())
}
pub fn calculate_auction_params_for_trigger_order(
order: &Order,
oracle_price_data: &OraclePriceData,
min_auction_duration: u8,
perp_market: Option<&PerpMarket>,
) -> DriftResult<(u8, i64, i64)> {
let auction_duration = min_auction_duration;
if let Some(perp_market) = perp_market {
let (auction_start_price, auction_end_price, derived_auction_duration) =
OrderParams::derive_market_order_auction_params(
perp_market,
order.direction,
oracle_price_data.price,
order.price,
0,
)?;
let auction_duration = auction_duration.max(derived_auction_duration);
Ok((auction_duration, auction_start_price, auction_end_price))
} else {
let (auction_start_price, auction_end_price) =
calculate_auction_prices(oracle_price_data, order.direction, order.price)?;
Ok((auction_duration, auction_start_price, auction_end_price))
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/liquidation.rs
|
use std::u32;
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_RESERVE_PRECISION_I128, FUNDING_RATE_TO_QUOTE_PRECISION_PRECISION_RATIO,
LIQUIDATION_FEE_PRECISION, LIQUIDATION_FEE_PRECISION_U128,
LIQUIDATION_FEE_TO_MARGIN_PRECISION_RATIO, LIQUIDATION_PCT_PRECISION, PRICE_PRECISION,
PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO, QUOTE_PRECISION, SPOT_WEIGHT_PRECISION_U128,
};
use crate::math::margin::calculate_margin_requirement_and_total_collateral_and_liability_info;
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::get_token_amount;
use crate::math::spot_swap::calculate_swap_price;
use crate::state::margin_calculation::MarginContext;
use crate::state::oracle_map::OracleMap;
use crate::state::perp_market::PerpMarket;
use crate::state::perp_market_map::PerpMarketMap;
use crate::state::spot_market::{SpotBalanceType, SpotMarket};
use crate::state::spot_market_map::SpotMarketMap;
use crate::state::user::{OrderType, User};
use crate::{
validate, MarketType, OrderParams, PositionDirection, BASE_PRECISION,
LIQUIDATION_FEE_INCREASE_PER_SLOT,
};
use solana_program::msg;
pub const LIQUIDATION_FEE_ADJUST_GRACE_PERIOD_SLOTS: u64 = 1_500; // ~10 minutes
#[cfg(test)]
mod tests;
pub fn calculate_base_asset_amount_to_cover_margin_shortage(
margin_shortage: u128,
margin_ratio: u32,
liquidation_fee: u32,
if_liquidation_fee: u32,
oracle_price: i64,
quote_oracle_price: i64,
) -> DriftResult<u64> {
let margin_ratio = margin_ratio.safe_mul(LIQUIDATION_FEE_TO_MARGIN_PRECISION_RATIO)?;
if oracle_price == 0 || margin_ratio <= liquidation_fee {
return Ok(u64::MAX);
}
margin_shortage
.safe_mul(PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO)?
.safe_div(
oracle_price
.cast::<u128>()?
.safe_mul(quote_oracle_price.cast()?)?
.safe_div(PRICE_PRECISION)?
.safe_mul(margin_ratio.safe_sub(liquidation_fee)?.cast()?)?
.safe_div(LIQUIDATION_FEE_PRECISION_U128)?
.safe_sub(
oracle_price
.cast::<u128>()?
.safe_mul(if_liquidation_fee.cast()?)?
.safe_div(LIQUIDATION_FEE_PRECISION_U128)?,
)?,
)?
.cast()
}
pub fn calculate_liability_transfer_to_cover_margin_shortage(
margin_shortage: u128,
asset_weight: u32,
asset_liquidation_multiplier: u32,
liability_weight: u32,
liability_liquidation_multiplier: u32,
liability_decimals: u32,
liability_price: i64,
if_liquidation_fee: u32,
) -> DriftResult<u128> {
// If unsettled pnl asset weight is 1 and quote asset is 1, this calculation breaks
if asset_weight >= liability_weight {
return Ok(u128::MAX);
}
let (numerator_scale, denominator_scale) = if liability_decimals > 6 {
(10_u128.pow(liability_decimals - 6), 1)
} else {
(1, 10_u128.pow(6 - liability_decimals))
};
let liability_weight_component = liability_weight.cast::<u128>()?.safe_mul(10)?; // multiply market weights by extra 10 to increase precision
let asset_weight_component = asset_weight
.cast::<u128>()?
.safe_mul(10)?
.safe_mul(asset_liquidation_multiplier.cast()?)?
.safe_div(liability_liquidation_multiplier.cast()?)?;
if asset_weight_component >= liability_weight_component {
return Ok(u128::MAX);
}
margin_shortage
.safe_mul(numerator_scale)?
.safe_mul(PRICE_PRECISION * SPOT_WEIGHT_PRECISION_U128 * 10)?
.safe_div(
liability_price
.cast::<u128>()?
.safe_mul(liability_weight_component.safe_sub(asset_weight_component)?)?
.safe_sub(
liability_price
.cast::<u128>()?
.safe_mul(if_liquidation_fee.cast()?)?
.safe_div(LIQUIDATION_FEE_PRECISION_U128)?
.safe_mul(liability_weight.cast()?)?
.safe_mul(10)?,
)?,
)?
.safe_div(denominator_scale)
}
pub fn calculate_liability_transfer_implied_by_asset_amount(
asset_amount: u128,
asset_liquidation_multiplier: u32,
asset_decimals: u32,
asset_price: i64,
liability_liquidation_multiplier: u32,
liability_decimals: u32,
liability_price: i64,
) -> DriftResult<u128> {
let (numerator_scale, denominator_scale) = if liability_decimals > asset_decimals {
(10_u128.pow(liability_decimals - asset_decimals), 1)
} else {
(1, 10_u128.pow(asset_decimals - liability_decimals))
};
asset_amount
.safe_mul(numerator_scale)?
.safe_mul(asset_price.cast()?)?
.safe_mul(liability_liquidation_multiplier.cast()?)?
.safe_div_ceil(
liability_price
.cast::<u128>()?
.safe_mul(asset_liquidation_multiplier.cast()?)?,
)?
.safe_div_ceil(denominator_scale)
}
pub fn calculate_asset_transfer_for_liability_transfer(
asset_amount: u128,
asset_liquidation_multiplier: u32,
asset_decimals: u32,
asset_price: i64,
liability_amount: u128,
liability_liquidation_multiplier: u32,
liability_decimals: u32,
liability_price: i64,
) -> DriftResult<u128> {
let (numerator_scale, denominator_scale) = if asset_decimals > liability_decimals {
(10_u128.pow(asset_decimals - liability_decimals), 1)
} else {
(1, 10_u128.pow(liability_decimals - asset_decimals))
};
let mut asset_transfer = liability_amount
.safe_mul(numerator_scale)?
.safe_mul(liability_price.cast()?)?
.safe_mul(asset_liquidation_multiplier.cast()?)?
.safe_div(
asset_price
.cast::<u128>()?
.safe_mul(liability_liquidation_multiplier.cast()?)?,
)?
.safe_div(denominator_scale)?
.max(1);
// Need to check if asset_transfer should be rounded to asset amount
let (asset_value_numerator_scale, asset_value_denominator_scale) = if asset_decimals > 6 {
(10_u128.pow(asset_decimals - 6), 1)
} else {
(1, 10_u128.pow(asset_decimals - 6))
};
let asset_delta = if asset_transfer > asset_amount {
asset_transfer - asset_amount
} else {
asset_amount - asset_transfer
};
let asset_value_delta = asset_delta
.safe_mul(asset_price.cast()?)?
.safe_div(PRICE_PRECISION)?
.safe_mul(asset_value_numerator_scale)?
.safe_div(asset_value_denominator_scale)?;
if asset_value_delta < QUOTE_PRECISION {
asset_transfer = asset_amount;
}
Ok(asset_transfer)
}
pub fn is_user_being_liquidated(
user: &User,
market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
liquidation_margin_buffer_ratio: u32,
) -> DriftResult<bool> {
let margin_calculation = calculate_margin_requirement_and_total_collateral_and_liability_info(
user,
market_map,
spot_market_map,
oracle_map,
MarginContext::liquidation(liquidation_margin_buffer_ratio),
)?;
let is_being_liquidated = !margin_calculation.can_exit_liquidation()?;
Ok(is_being_liquidated)
}
pub fn validate_user_not_being_liquidated(
user: &mut User,
market_map: &PerpMarketMap,
spot_market_map: &SpotMarketMap,
oracle_map: &mut OracleMap,
liquidation_margin_buffer_ratio: u32,
) -> DriftResult {
if !user.is_being_liquidated() {
return Ok(());
}
let is_still_being_liquidated = is_user_being_liquidated(
user,
market_map,
spot_market_map,
oracle_map,
liquidation_margin_buffer_ratio,
)?;
if is_still_being_liquidated {
return Err(ErrorCode::UserIsBeingLiquidated);
} else {
user.exit_liquidation()
}
Ok(())
}
pub enum LiquidationMultiplierType {
Discount,
Premium,
}
pub fn calculate_liquidation_multiplier(
liquidation_fee: u32,
multiplier_type: LiquidationMultiplierType,
) -> DriftResult<u32> {
match multiplier_type {
LiquidationMultiplierType::Premium => LIQUIDATION_FEE_PRECISION.safe_add(liquidation_fee),
LiquidationMultiplierType::Discount => LIQUIDATION_FEE_PRECISION.safe_sub(liquidation_fee),
}
}
pub fn calculate_funding_rate_deltas_to_resolve_bankruptcy(
loss: i128,
market: &PerpMarket,
) -> DriftResult<i128> {
let total_base_asset_amount = market
.amm
.base_asset_amount_long
.abs()
.safe_add(market.amm.base_asset_amount_short.abs())?;
validate!(
total_base_asset_amount != 0,
ErrorCode::CantResolvePerpBankruptcy,
"Cant resolve perp bankruptcy when total base asset amount is 0"
)?;
loss.abs()
.safe_mul(AMM_RESERVE_PRECISION_I128)?
.safe_div_ceil(total_base_asset_amount)?
.safe_mul(FUNDING_RATE_TO_QUOTE_PRECISION_PRECISION_RATIO.cast()?)
}
pub fn calculate_cumulative_deposit_interest_delta_to_resolve_bankruptcy(
borrow: u128,
spot_market: &SpotMarket,
) -> DriftResult<u128> {
let total_deposits = get_token_amount(
spot_market.deposit_balance,
spot_market,
&SpotBalanceType::Deposit,
)?;
spot_market
.cumulative_deposit_interest
.safe_mul(borrow)?
.safe_div_ceil(total_deposits)
.or(Ok(0))
}
pub fn validate_transfer_satisfies_limit_price(
asset_transfer: u128,
liability_transfer: u128,
asset_decimals: u32,
liability_decimals: u32,
limit_price: Option<u64>,
) -> DriftResult {
let limit_price = match limit_price {
Some(limit_price) => limit_price,
None => return Ok(()),
};
let swap_price = calculate_swap_price(
asset_transfer,
liability_transfer,
asset_decimals,
liability_decimals,
)?;
validate!(
swap_price >= limit_price.cast()?,
ErrorCode::LiquidationDoesntSatisfyLimitPrice,
"transfer price transfer_price ({}/1000000) < limit price ({}/1000000)",
swap_price,
limit_price
)
}
pub fn calculate_max_pct_to_liquidate(
user: &User,
margin_shortage: u128,
slot: u64,
initial_pct_to_liquidate: u128,
liquidation_duration: u128,
) -> DriftResult<u128> {
// if margin shortage is tiny, accelerate liquidation
if margin_shortage < 50 * QUOTE_PRECISION {
return Ok(LIQUIDATION_PCT_PRECISION);
}
let slots_elapsed = slot.safe_sub(user.last_active_slot)?;
let pct_freeable = slots_elapsed
.cast::<u128>()?
.safe_mul(LIQUIDATION_PCT_PRECISION)?
.safe_div(liquidation_duration) // ~ 1 minute if per slot is 400ms
.unwrap_or(LIQUIDATION_PCT_PRECISION) // if divide by zero, default to 100%
.safe_add(initial_pct_to_liquidate)?
.min(LIQUIDATION_PCT_PRECISION);
let total_margin_shortage = margin_shortage.safe_add(user.liquidation_margin_freed.cast()?)?;
let max_margin_freed = total_margin_shortage
.safe_mul(pct_freeable)?
.safe_div(LIQUIDATION_PCT_PRECISION)?;
let margin_freeable = max_margin_freed.saturating_sub(user.liquidation_margin_freed.cast()?);
margin_freeable
.safe_mul(LIQUIDATION_PCT_PRECISION)?
.safe_div(margin_shortage)
}
pub fn calculate_perp_if_fee(
margin_shortage: u128,
user_base_asset_amount: u64,
margin_ratio: u32,
liquidator_fee: u32,
oracle_price: i64,
quote_oracle_price: i64,
max_if_liquidation_fee: u32,
) -> DriftResult<u32> {
let margin_ratio = margin_ratio.safe_mul(LIQUIDATION_FEE_TO_MARGIN_PRECISION_RATIO)?;
if oracle_price == 0
|| quote_oracle_price == 0
|| margin_ratio <= liquidator_fee
|| user_base_asset_amount == 0
{
return Ok(0);
}
let price = oracle_price
.cast::<u128>()?
.safe_mul(quote_oracle_price.cast()?)?
.safe_div(PRICE_PRECISION)?;
// margin ratio - liquidator fee - (margin shortage / (user base asset amount * price))
let implied_if_fee = margin_ratio
.saturating_sub(liquidator_fee)
.saturating_sub(
margin_shortage
.safe_mul(BASE_PRECISION)?
.safe_div(user_base_asset_amount.cast()?)?
.safe_mul(PRICE_PRECISION)?
.safe_div(price)?
.cast::<u32>()
.unwrap_or(u32::MAX),
)
// multiply by 95% to avoid situation where fee leads to deposits == negative pnl
// leading to bankruptcy
.safe_mul(19)?
.safe_div(20)?;
Ok(max_if_liquidation_fee.min(implied_if_fee))
}
pub fn calculate_spot_if_fee(
margin_shortage: u128,
token_amount: u128,
asset_weight: u32,
asset_liquidation_multiplier: u32,
liability_weight: u32,
liability_liquidation_multiplier: u32,
liability_decimals: u32,
liability_price: i64,
max_if_fee: u32,
) -> DriftResult<u32> {
if asset_weight >= liability_weight
|| liability_price == 0
|| token_amount == 0
|| liability_liquidation_multiplier == 0
{
return Ok(0);
}
let token_precision = 10_u128.pow(liability_decimals);
let liability_weight = liability_weight
.cast::<u128>()?
.safe_mul(LIQUIDATION_FEE_PRECISION_U128 / SPOT_WEIGHT_PRECISION_U128)?;
let asset_weight = asset_weight
.cast::<u128>()?
.safe_mul(LIQUIDATION_FEE_PRECISION_U128 / SPOT_WEIGHT_PRECISION_U128)?;
let implied_if_fee = liability_weight
.saturating_sub(
asset_weight
.safe_mul(asset_liquidation_multiplier.cast()?)?
.safe_div(liability_liquidation_multiplier.cast()?)?,
)
.saturating_sub(
margin_shortage
.safe_mul(LIQUIDATION_FEE_PRECISION_U128)?
.safe_mul(token_precision)?
.safe_div(token_amount)?
.safe_div(liability_price.cast()?)?, // price and quote precision the same
)
.safe_mul(LIQUIDATION_FEE_PRECISION_U128)?
.safe_div(liability_weight)?
.cast::<u32>()
.unwrap_or(u32::MAX);
Ok(max_if_fee.min(implied_if_fee))
}
pub fn get_liquidation_order_params(
market_index: u16,
existing_direction: PositionDirection,
base_asset_amount: u64,
oracle_price: i64,
liquidation_fee: u32,
) -> DriftResult<OrderParams> {
let direction = existing_direction.opposite();
let oracle_price_u128 = oracle_price.abs().cast::<u128>()?;
let limit_price = match direction {
PositionDirection::Long => oracle_price_u128
.safe_add(
oracle_price_u128
.safe_mul(liquidation_fee.cast()?)?
.safe_div(LIQUIDATION_FEE_PRECISION_U128)?,
)?
.cast::<u64>()?,
PositionDirection::Short => oracle_price_u128
.safe_sub(
oracle_price_u128
.safe_mul(liquidation_fee.cast()?)?
.safe_div(LIQUIDATION_FEE_PRECISION_U128)?,
)?
.cast::<u64>()?,
};
let order_params = OrderParams {
market_index,
direction,
price: limit_price,
order_type: OrderType::Limit,
market_type: MarketType::Perp,
base_asset_amount,
reduce_only: true,
..OrderParams::default()
};
Ok(order_params)
}
pub fn get_liquidation_fee(
base_liquidation_fee: u32,
max_liquidation_fee: u32,
last_active_user_slot: u64,
current_slot: u64,
) -> DriftResult<u32> {
let slots_elapsed = current_slot.safe_sub(last_active_user_slot)?;
if slots_elapsed < LIQUIDATION_FEE_ADJUST_GRACE_PERIOD_SLOTS {
return Ok(base_liquidation_fee);
}
let liquidation_fee = base_liquidation_fee.saturating_add(
slots_elapsed
.safe_mul(LIQUIDATION_FEE_INCREASE_PER_SLOT.cast::<u64>()?)?
.cast::<u32>()
.unwrap_or(u32::MAX),
);
Ok(liquidation_fee.min(max_liquidation_fee))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/repeg.rs
|
use std::cmp::{max, min};
use anchor_lang::prelude::AccountInfo;
use solana_program::msg;
use crate::error::*;
use crate::math::amm;
use crate::math::bn;
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_RESERVE_PRECISION_I128, BID_ASK_SPREAD_PRECISION_U128, PEG_PRECISION_I128,
PRICE_TO_PEG_PRECISION_RATIO, SHARE_OF_FEES_ALLOCATED_TO_DRIFT_DENOMINATOR,
SHARE_OF_FEES_ALLOCATED_TO_DRIFT_NUMERATOR,
};
use crate::math::cp_curve;
use crate::math::oracle;
use crate::math::oracle::OracleValidity;
use crate::math::position::calculate_base_asset_value_and_pnl;
use crate::math::safe_math::SafeMath;
use crate::state::oracle::get_oracle_price;
use crate::state::oracle::OraclePriceData;
use crate::state::perp_market::{PerpMarket, AMM};
use crate::state::state::OracleGuardRails;
use crate::state::user::MarketType;
#[cfg(test)]
mod tests;
pub fn calculate_repeg_validity_from_oracle_account(
market: &PerpMarket,
oracle_account_info: &AccountInfo,
terminal_price_before: u64,
clock_slot: u64,
oracle_guard_rails: &OracleGuardRails,
) -> DriftResult<(bool, bool, bool, bool)> {
let oracle_price_data =
get_oracle_price(&market.amm.oracle_source, oracle_account_info, clock_slot)?;
let oracle_is_valid = oracle::oracle_validity(
MarketType::Perp,
market.market_index,
market.amm.historical_oracle_data.last_oracle_price_twap,
&oracle_price_data,
&oracle_guard_rails.validity,
market.get_max_confidence_interval_multiplier()?,
&market.amm.oracle_source,
true,
)? == OracleValidity::Valid;
let (oracle_is_valid, direction_valid, profitability_valid, price_impact_valid) =
calculate_repeg_validity(
market,
&oracle_price_data,
oracle_is_valid,
terminal_price_before,
)?;
Ok((
oracle_is_valid,
direction_valid,
profitability_valid,
price_impact_valid,
))
}
pub fn calculate_repeg_validity(
market: &PerpMarket,
oracle_price_data: &OraclePriceData,
oracle_is_valid: bool,
terminal_price_before: u64,
) -> DriftResult<(bool, bool, bool, bool)> {
let OraclePriceData {
price: oracle_price,
confidence: oracle_conf,
delay: _,
has_sufficient_number_of_data_points: _,
} = *oracle_price_data;
let oracle_price_u128 = oracle_price.cast::<u64>()?;
let (terminal_price_after, _terminal_quote_reserves, _terminal_base_reserves) =
amm::calculate_terminal_price_and_reserves(&market.amm)?;
let mut direction_valid = true;
let mut price_impact_valid = true;
let mut profitability_valid = true;
// if oracle is valid: check on size/direction of repeg
if oracle_is_valid {
let reserve_price_after = amm::calculate_price(
market.amm.quote_asset_reserve,
market.amm.base_asset_reserve,
market.amm.peg_multiplier,
)?;
let oracle_conf_band_top = oracle_price_u128.safe_add(oracle_conf)?;
let oracle_conf_band_bottom = oracle_price_u128.safe_sub(oracle_conf)?;
#[allow(clippy::comparison_chain)]
if oracle_price_u128 > terminal_price_after {
// only allow terminal up when oracle is higher
if terminal_price_after < terminal_price_before {
msg!(
"oracle: {:?}, termb: {:?}, terma: {:?},",
oracle_price_u128,
terminal_price_before,
terminal_price_after
);
direction_valid = false;
}
// only push terminal up to bottom of oracle confidence band
if oracle_conf_band_bottom < terminal_price_after {
profitability_valid = false;
}
// only push mark up to top of oracle confidence band
if reserve_price_after > oracle_conf_band_top {
price_impact_valid = false;
}
} else if oracle_price_u128 < terminal_price_after {
// only allow terminal down when oracle is lower
if terminal_price_after > terminal_price_before {
msg!(
"oracle: {:?}, termb: {:?}, terma: {:?},",
oracle_price_u128,
terminal_price_before,
terminal_price_after
);
direction_valid = false;
}
// only push terminal down to top of oracle confidence band
if oracle_conf_band_top > terminal_price_after {
profitability_valid = false;
}
// only push mark down to bottom of oracle confidence band
if reserve_price_after < oracle_conf_band_bottom {
price_impact_valid = false;
}
}
} else {
direction_valid = false;
price_impact_valid = false;
profitability_valid = false;
}
Ok((
oracle_is_valid,
direction_valid,
profitability_valid,
price_impact_valid,
))
}
pub fn calculate_peg_from_target_price(
quote_asset_reserve: u128,
base_asset_reserve: u128,
target_price: u64,
) -> DriftResult<u128> {
let new_peg = bn::U192::from(target_price)
.safe_mul(bn::U192::from(base_asset_reserve))?
.safe_div(bn::U192::from(quote_asset_reserve))?
.safe_add(bn::U192::from(PRICE_TO_PEG_PRECISION_RATIO / 2))?
.safe_div(bn::U192::from(PRICE_TO_PEG_PRECISION_RATIO))?
.try_to_u128()?;
Ok(new_peg.max(1))
}
pub fn adjust_peg_cost(
market: &PerpMarket,
new_peg_candidate: u128,
) -> DriftResult<(PerpMarket, i128)> {
let mut market_clone = *market;
let cost = if new_peg_candidate != market_clone.amm.peg_multiplier {
// Find the net market value before adjusting peg
let (current_net_market_value, _) = calculate_base_asset_value_and_pnl(
market_clone.amm.base_asset_amount_with_amm,
0,
&market_clone.amm,
)?;
market_clone.amm.peg_multiplier = new_peg_candidate;
let (_new_net_market_value, cost) = calculate_base_asset_value_and_pnl(
market_clone.amm.base_asset_amount_with_amm,
current_net_market_value,
&market_clone.amm,
)?;
cost
} else {
0_i128
};
Ok((market_clone, cost))
}
pub fn calculate_repeg_cost(amm: &AMM, new_peg: u128) -> DriftResult<i128> {
amm.quote_asset_reserve
.cast::<i128>()?
.safe_sub(amm.terminal_quote_asset_reserve.cast()?)?
.safe_mul(
new_peg
.cast::<i128>()?
.safe_sub(amm.peg_multiplier.cast()?)?,
)?
.safe_div(AMM_RESERVE_PRECISION_I128)
}
pub fn calculate_per_peg_cost(
quote_asset_reserve: u128,
terminal_quote_asset_reserve: u128,
) -> DriftResult<i128> {
// returns a signed per_peg_cost relative to delta peg
// signed means that "cost" to amm is influenced whether delta_peg is the same sign
let per_peg_cost = if quote_asset_reserve != terminal_quote_asset_reserve {
quote_asset_reserve
.cast::<i128>()?
.safe_sub(terminal_quote_asset_reserve.cast::<i128>()?)?
.safe_div_ceil(AMM_RESERVE_PRECISION_I128 / PEG_PRECISION_I128)?
} else {
0
};
// round to make magnitude higher
Ok(if per_peg_cost > 0 {
per_peg_cost.safe_add(1)?
} else if per_peg_cost < 0 {
per_peg_cost.safe_sub(1)?
} else {
per_peg_cost
})
}
pub fn adjust_amm(
market: &PerpMarket,
optimal_peg: u128,
budget: u128,
adjust_k: bool,
) -> DriftResult<(Box<PerpMarket>, i128)> {
let curve_update_intensity = min(market.amm.curve_update_intensity, 100_u8).cast::<i128>()?;
// return early
if optimal_peg == market.amm.peg_multiplier || curve_update_intensity == 0 {
return Ok((Box::new(*market), 0));
}
let delta_peg = optimal_peg
.cast::<i128>()?
.safe_sub(market.amm.peg_multiplier.cast()?)?; // PEG_PRECISION
let mut per_peg_cost = calculate_per_peg_cost(
market.amm.quote_asset_reserve,
market.amm.terminal_quote_asset_reserve,
)?; // PEG_PRECISION
let budget_i128 = budget.cast::<i128>()?;
let mut market_clone = Box::new(*market);
let mut budget_delta_peg: i128;
let mut budget_delta_peg_magnitude: u128 = 0;
let cost: i128;
let new_peg: u128;
if per_peg_cost != 0 {
budget_delta_peg = budget_i128
.safe_mul(PEG_PRECISION_I128)?
.safe_div(per_peg_cost)?; // PEG_PRECISION
budget_delta_peg_magnitude = budget_delta_peg.unsigned_abs();
}
let use_optimal_peg = (per_peg_cost == 0 // if per peg cost is 0 => free
|| per_peg_cost > 0 && delta_peg < 0 // or if per peg positive and the direction is down => revenue
|| per_peg_cost < 0 && delta_peg > 0) // or if per peg negative and the direction is up => revenue
|| (budget_delta_peg_magnitude > delta_peg.unsigned_abs()); // the peg movement from full budget usage exceeds delta to optimal
if use_optimal_peg {
// use optimal peg
new_peg = optimal_peg;
cost = calculate_repeg_cost(&market_clone.amm, new_peg)?;
} else {
// use full budget peg
let can_lower_k = market.amm.can_lower_k()?;
// equivalent to (but cheaper than) scaling down by .1%
let adjustment_cost: i128 = if adjust_k && can_lower_k {
// TODO can be off by 1?
// always let protocol-owned sqrt_k be either least .1% of lps or the base amount / min order
let new_sqrt_k_lower_bound = market.amm.get_lower_bound_sqrt_k()?;
let new_sqrt_k = market
.amm
.sqrt_k
.safe_sub(market.amm.sqrt_k.safe_div(1000)?)?
.max(new_sqrt_k_lower_bound);
let update_k_result =
cp_curve::get_update_k_result(market, bn::U192::from(new_sqrt_k), true)?;
let adjustment_cost =
cp_curve::adjust_k_cost_and_update(&mut market_clone, &update_k_result)?;
per_peg_cost = calculate_per_peg_cost(
market_clone.amm.quote_asset_reserve,
market_clone.amm.terminal_quote_asset_reserve,
)?;
adjustment_cost
} else {
0
};
budget_delta_peg = budget_i128
.safe_add(adjustment_cost.abs())?
.safe_mul(PEG_PRECISION_I128)?
.safe_div(per_peg_cost)?;
budget_delta_peg_magnitude = budget_delta_peg.unsigned_abs();
new_peg = if budget_delta_peg > 0 {
market
.amm
.peg_multiplier
.safe_add(budget_delta_peg_magnitude)
.unwrap_or(u128::MAX)
} else if market.amm.peg_multiplier > budget_delta_peg_magnitude {
market
.amm
.peg_multiplier
.safe_sub(budget_delta_peg_magnitude)?
} else {
1
};
cost = calculate_repeg_cost(&market_clone.amm, new_peg)?;
}
market_clone.amm.peg_multiplier = new_peg;
Ok((market_clone, cost))
}
pub fn calculate_optimal_peg_and_budget(
market: &PerpMarket,
oracle_price_data: &OraclePriceData,
) -> DriftResult<(u128, u128, bool)> {
let reserve_price_before = market.amm.reserve_price()?;
let mut fee_budget = calculate_fee_pool(market)?;
let target_price_i64 = oracle_price_data.price;
let target_price = target_price_i64.cast()?;
let mut optimal_peg = calculate_peg_from_target_price(
market.amm.quote_asset_reserve,
market.amm.base_asset_reserve,
target_price,
)?;
let optimal_peg_cost = calculate_repeg_cost(&market.amm, optimal_peg)?;
let mut check_lower_bound = true;
if fee_budget < max(0, optimal_peg_cost).cast()? {
let half_max_price_spread = target_price
.cast::<u128>()?
.safe_mul(market.amm.max_spread.safe_div(2)?.cast()?)?
.safe_div(BID_ASK_SPREAD_PRECISION_U128)?
.cast::<i64>()?;
let target_price_gap = reserve_price_before
.cast::<i64>()?
.safe_sub(target_price_i64)?;
if target_price_gap.abs() > half_max_price_spread {
let mark_adj = target_price_gap
.abs()
.safe_sub(half_max_price_spread)?
.cast()?;
let target_price = if target_price_gap < 0 {
reserve_price_before.safe_add(mark_adj)?
} else {
reserve_price_before.safe_sub(mark_adj)?
};
optimal_peg = calculate_peg_from_target_price(
market.amm.quote_asset_reserve,
market.amm.base_asset_reserve,
target_price.cast()?,
)?;
fee_budget = calculate_repeg_cost(&market.amm, optimal_peg)?.cast::<u128>()?;
check_lower_bound = false;
} else if fee_budget == 0 {
check_lower_bound = false;
}
}
Ok((optimal_peg, fee_budget, check_lower_bound))
}
pub fn calculate_fee_pool(market: &PerpMarket) -> DriftResult<u128> {
let total_fee_minus_distributions_lower_bound = get_total_fee_lower_bound(market)?
.safe_add(market.amm.total_liquidation_fee)?
.safe_sub(market.amm.total_fee_withdrawn)?
.cast::<i128>()
.unwrap_or(0);
let fee_pool =
if market.amm.total_fee_minus_distributions > total_fee_minus_distributions_lower_bound {
market
.amm
.total_fee_minus_distributions
.safe_sub(total_fee_minus_distributions_lower_bound)?
.cast()?
} else {
0
};
Ok(fee_pool)
}
pub fn get_total_fee_lower_bound(market: &PerpMarket) -> DriftResult<u128> {
// market to retain half of exchange fees
let total_fee_lower_bound = market
.amm
.total_exchange_fee
.safe_mul(SHARE_OF_FEES_ALLOCATED_TO_DRIFT_NUMERATOR)?
.safe_div(SHARE_OF_FEES_ALLOCATED_TO_DRIFT_DENOMINATOR)?;
Ok(total_fee_lower_bound)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/stats.rs
|
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
use std::cmp::max;
pub fn calculate_rolling_sum(
data1: u64,
data2: u64,
weight1_numer: i64,
weight1_denom: i64,
) -> DriftResult<u64> {
// assumes that missing times are zeros (e.g. handle NaN as 0)
let prev_twap_99 = data1
.cast::<u128>()?
.safe_mul(max(0, weight1_denom.safe_sub(weight1_numer)?).cast::<u128>()?)?
.safe_div(weight1_denom.cast::<u128>()?)?;
prev_twap_99.cast::<u64>()?.safe_add(data2)
}
pub fn calculate_weighted_average(
data1: i64,
data2: i64,
weight1: i64,
weight2: i64,
) -> DriftResult<i64> {
let denominator = weight1.safe_add(weight2)?.cast::<i128>()?;
let prev_twap_99 = data1.cast::<i128>()?.safe_mul(weight1.cast()?)?;
let latest_price_01 = data2.cast::<i128>()?.safe_mul(weight2.cast()?)?;
if weight1 == 0 {
return Ok(data2);
}
if weight2 == 0 {
return Ok(data1);
}
let bias: i64 = if weight2 > 1 {
if latest_price_01 < prev_twap_99 {
-1
} else if latest_price_01 > prev_twap_99 {
1
} else {
0
}
} else {
0
};
let twap = prev_twap_99
.safe_add(latest_price_01)?
.safe_div(denominator)?
.cast::<i64>()?;
if twap == 0 && bias < 0 {
return Ok(twap);
}
twap.safe_add(bias)
}
pub fn calculate_new_twap(
current_price: i64,
current_ts: i64,
last_twap: i64,
last_ts: i64,
period: i64,
) -> DriftResult<i64> {
let since_last = max(0_i64, current_ts.safe_sub(last_ts)?);
let from_start = max(1_i64, period.safe_sub(since_last)?);
calculate_weighted_average(current_price, last_twap, since_last, from_start)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/position.rs
|
use solana_program::msg;
use crate::controller::amm::SwapDirection;
use crate::controller::position::PositionDelta;
use crate::error::{DriftResult, ErrorCode};
use crate::math::amm;
use crate::math::amm::calculate_quote_asset_amount_swapped;
use crate::math::casting::Cast;
use crate::math::constants::{
AMM_RESERVE_PRECISION_I128, PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO,
PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO_I128,
};
use crate::math::helpers::get_proportion_u128;
use crate::math::pnl::calculate_pnl;
use crate::math::safe_math::SafeMath;
use crate::state::perp_market::{ContractType, PerpMarket, AMM};
use crate::state::user::PerpPosition;
use crate::{validate, BASE_PRECISION, MAX_PREDICTION_MARKET_PRICE_U128};
pub fn calculate_base_asset_value_and_pnl(
base_asset_amount: i128,
quote_asset_amount: u128,
amm: &AMM,
) -> DriftResult<(u128, i128)> {
if base_asset_amount == 0 {
return Ok((0, 0));
}
let swap_direction = swap_direction_to_close_position(base_asset_amount);
let base_asset_value = calculate_base_asset_value(base_asset_amount, amm)?;
let pnl = calculate_pnl(base_asset_value, quote_asset_amount, swap_direction)?;
Ok((base_asset_value, pnl))
}
pub fn calculate_base_asset_value(base_asset_amount: i128, amm: &AMM) -> DriftResult<u128> {
if base_asset_amount == 0 {
return Ok(0);
}
let swap_direction = swap_direction_to_close_position(base_asset_amount);
let (base_asset_reserve, quote_asset_reserve) =
(amm.base_asset_reserve, amm.quote_asset_reserve);
let amm_lp_shares = amm.sqrt_k.safe_sub(amm.user_lp_shares)?;
let base_asset_reserve_proportion =
get_proportion_u128(base_asset_reserve, amm_lp_shares, amm.sqrt_k)?;
let quote_asset_reserve_proportion =
get_proportion_u128(quote_asset_reserve, amm_lp_shares, amm.sqrt_k)?;
let (new_quote_asset_reserve, _new_base_asset_reserve) = amm::calculate_swap_output(
base_asset_amount.unsigned_abs(),
base_asset_reserve_proportion,
swap_direction,
amm_lp_shares,
)?;
let base_asset_value = calculate_quote_asset_amount_swapped(
quote_asset_reserve_proportion,
new_quote_asset_reserve,
swap_direction,
amm.peg_multiplier,
)?;
Ok(base_asset_value)
}
pub fn calculate_base_asset_value_with_oracle_price(
base_asset_amount: i128,
oracle_price: i64,
) -> DriftResult<u128> {
if base_asset_amount == 0 {
return Ok(0);
}
let oracle_price = if oracle_price > 0 {
oracle_price.unsigned_abs()
} else {
0
};
base_asset_amount
.unsigned_abs()
.safe_mul(oracle_price.cast()?)?
.safe_div(PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO)
}
pub fn calculate_perp_liability_value(
base_asset_amount: i128,
oracle_price: i64,
contract_type: ContractType,
) -> DriftResult<u128> {
if contract_type != ContractType::Prediction {
return calculate_base_asset_value_with_oracle_price(base_asset_amount, oracle_price);
}
let price_u128 = oracle_price.abs().cast::<u128>()?;
let liability_value = if base_asset_amount < 0 {
base_asset_amount
.unsigned_abs()
.safe_mul(MAX_PREDICTION_MARKET_PRICE_U128.saturating_sub(price_u128))?
.safe_div(BASE_PRECISION)? // price precision same as quote precision, save extra mul/div
} else {
base_asset_amount
.unsigned_abs()
.safe_mul(price_u128)?
.safe_div(BASE_PRECISION)? // price precision same as quote precision, save extra mul/div
};
Ok(liability_value)
}
pub fn calculate_base_asset_value_and_pnl_with_oracle_price(
market_position: &PerpPosition,
oracle_price: i64,
) -> DriftResult<(u128, i128)> {
if market_position.base_asset_amount == 0 {
return Ok((0, market_position.quote_asset_amount.cast()?));
}
let oracle_price = if oracle_price > 0 {
oracle_price.abs()
} else {
0
};
let base_asset_value = market_position
.base_asset_amount
.cast::<i128>()?
.safe_mul(oracle_price.cast()?)?
.safe_div(AMM_RESERVE_PRECISION_I128)?;
let pnl = base_asset_value.safe_add(market_position.quote_asset_amount.cast()?)?;
Ok((base_asset_value.unsigned_abs(), pnl))
}
pub fn calculate_base_asset_value_with_expiry_price(
market_position: &PerpPosition,
expiry_price: i64,
) -> DriftResult<i64> {
if market_position.base_asset_amount == 0 {
return Ok(0);
}
market_position
.base_asset_amount
.cast::<i128>()?
.safe_mul(expiry_price.cast()?)?
.safe_div(PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO_I128)?
.cast::<i64>()
}
pub fn swap_direction_to_close_position(base_asset_amount: i128) -> SwapDirection {
if base_asset_amount >= 0 {
SwapDirection::Add
} else {
SwapDirection::Remove
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PositionUpdateType {
Open,
Increase,
Reduce,
Close,
Flip,
}
pub fn get_position_update_type(
position: &PerpPosition,
delta: &PositionDelta,
) -> DriftResult<PositionUpdateType> {
if position.base_asset_amount == 0 && position.remainder_base_asset_amount == 0 {
return Ok(PositionUpdateType::Open);
}
let position_base_with_remainder = if position.remainder_base_asset_amount != 0 {
position
.base_asset_amount
.safe_add(position.remainder_base_asset_amount.cast::<i64>()?)?
} else {
position.base_asset_amount
};
let delta_base_with_remainder =
if let Some(remainder_base_asset_amount) = delta.remainder_base_asset_amount {
delta
.base_asset_amount
.safe_add(remainder_base_asset_amount.cast()?)?
} else {
delta.base_asset_amount
};
if position_base_with_remainder.signum() == delta_base_with_remainder.signum() {
Ok(PositionUpdateType::Increase)
} else if position_base_with_remainder.abs() > delta_base_with_remainder.abs() {
Ok(PositionUpdateType::Reduce)
} else if position_base_with_remainder.abs() == delta_base_with_remainder.abs() {
Ok(PositionUpdateType::Close)
} else {
Ok(PositionUpdateType::Flip)
}
}
pub fn get_new_position_amounts(
position: &PerpPosition,
delta: &PositionDelta,
market: &PerpMarket,
) -> DriftResult<(i64, i64, i64, i64)> {
let new_quote_asset_amount = position
.quote_asset_amount
.safe_add(delta.quote_asset_amount)?;
let mut new_base_asset_amount = position
.base_asset_amount
.safe_add(delta.base_asset_amount)?;
let mut new_remainder_base_asset_amount = position
.remainder_base_asset_amount
.cast::<i64>()?
.safe_add(
delta
.remainder_base_asset_amount
.unwrap_or(0)
.cast::<i64>()?,
)?;
let mut new_settled_base_asset_amount = delta.base_asset_amount;
if delta.remainder_base_asset_amount.is_some() {
if new_remainder_base_asset_amount.unsigned_abs() >= market.amm.order_step_size {
let (standardized_remainder_base_asset_amount, remainder_base_asset_amount) =
crate::math::orders::standardize_base_asset_amount_with_remainder_i128(
new_remainder_base_asset_amount.cast()?,
market.amm.order_step_size.cast()?,
)?;
new_base_asset_amount =
new_base_asset_amount.safe_add(standardized_remainder_base_asset_amount.cast()?)?;
new_settled_base_asset_amount = new_settled_base_asset_amount
.safe_add(standardized_remainder_base_asset_amount.cast()?)?;
new_remainder_base_asset_amount = remainder_base_asset_amount.cast()?;
} else {
new_remainder_base_asset_amount = new_remainder_base_asset_amount.cast()?;
}
validate!(
new_remainder_base_asset_amount.abs() <= i32::MAX as i64,
ErrorCode::InvalidPositionDelta,
"new_remainder_base_asset_amount={} > i32 max",
new_remainder_base_asset_amount
)?;
}
Ok((
new_base_asset_amount,
new_settled_base_asset_amount,
new_quote_asset_amount,
new_remainder_base_asset_amount,
))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/spot_withdraw.rs
|
use solana_program::msg;
use crate::error::{DriftResult, ErrorCode};
use crate::math::casting::Cast;
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::get_token_amount;
use crate::state::spot_market::{SpotBalance, SpotBalanceType, SpotMarket};
use crate::state::user::User;
use crate::validate;
use super::constants::SPOT_UTILIZATION_PRECISION;
pub fn calculate_min_deposit_token_amount(
deposit_token_twap: u128,
withdraw_guard_threshold: u128,
) -> DriftResult<u128> {
// minimum required deposit amount after withdrawal
// minimum deposit amount lower of 75% of TWAP or withdrawal guard threshold below TWAP
// for high withdrawal guard threshold, minimum deposit amount is 0
let min_deposit_token = deposit_token_twap
.safe_sub((deposit_token_twap / 4).max(withdraw_guard_threshold.min(deposit_token_twap)))?;
Ok(min_deposit_token)
}
pub fn calculate_max_borrow_token_amount(
deposit_token_amount: u128,
deposit_token_twap: u128,
borrow_token_twap: u128,
withdraw_guard_threshold: u128,
max_token_borrows: u128,
) -> DriftResult<u128> {
// maximum permitted borrows after withdrawal
// allows at least up to the withdraw_guard_threshold
// and between ~15-80% utilization with friction on twap in 10% increments
let lesser_deposit_amount = deposit_token_amount.min(deposit_token_twap);
let max_borrow_token = withdraw_guard_threshold
.max(
(lesser_deposit_amount / 6)
.max(borrow_token_twap.safe_add(lesser_deposit_amount / 10)?)
.min(lesser_deposit_amount.safe_sub(lesser_deposit_amount / 5)?),
)
.min(max_token_borrows);
Ok(max_borrow_token)
}
pub fn check_user_exception_to_withdraw_limits(
spot_market: &SpotMarket,
user: Option<&User>,
token_amount_withdrawn: Option<u128>,
) -> DriftResult<bool> {
// allow a smaller user in a market to bypass and withdraw their principal
let mut valid_user_withdraw = false;
if let Some(user) = user {
let spot_position = user.get_spot_position(spot_market.market_index)?;
let net_deposits = user
.total_deposits
.cast::<i128>()?
.safe_sub(user.total_withdraws.cast::<i128>()?)?;
msg!(
"net_deposits={}({}-{})",
net_deposits,
user.total_deposits,
user.total_withdraws
);
if net_deposits >= 0
&& spot_position.cumulative_deposits >= 0
&& spot_position.balance_type == SpotBalanceType::Deposit
{
if let Some(token_amount_withdrawn) = token_amount_withdrawn {
let user_deposit_token_amount = get_token_amount(
spot_position.scaled_balance.cast::<u128>()?,
spot_market,
&spot_position.balance_type,
)?;
if user_deposit_token_amount.safe_add(token_amount_withdrawn)?
< spot_market
.withdraw_guard_threshold
.cast::<u128>()?
.safe_div(10)?
{
valid_user_withdraw = true;
}
}
}
}
Ok(valid_user_withdraw)
}
pub fn calculate_token_utilization_limits(
deposit_token_amount: u128,
borrow_token_amount: u128,
spot_market: &SpotMarket,
) -> DriftResult<(u128, u128)> {
// Calculates the allowable minimum deposit and maximum borrow amounts after withdrawal based on market utilization.
// First, it determines a maximum withdrawal utilization from the market's target and historic utilization.
// Then, it deduces corresponding deposit/borrow amounts.
// Note: For deposit sizes below the guard threshold, withdrawals aren't blocked.
let max_withdraw_utilization: u128 = spot_market.optimal_utilization.cast::<u128>()?.max(
spot_market.utilization_twap.cast::<u128>()?.safe_add(
SPOT_UTILIZATION_PRECISION.saturating_sub(spot_market.utilization_twap.cast()?) / 2,
)?,
);
let mut min_deposit_tokens_for_utilization = borrow_token_amount
.safe_mul(SPOT_UTILIZATION_PRECISION)?
.safe_div(max_withdraw_utilization)?;
// dont block withdraws for deposit sizes below guard threshold
min_deposit_tokens_for_utilization = min_deposit_tokens_for_utilization
.min(deposit_token_amount.saturating_sub(spot_market.withdraw_guard_threshold.cast()?));
let mut max_borrow_tokens_for_utilization = max_withdraw_utilization
.safe_mul(deposit_token_amount)?
.safe_div(SPOT_UTILIZATION_PRECISION)?;
// dont block borrows for sizes below guard threshold
max_borrow_tokens_for_utilization =
max_borrow_tokens_for_utilization.max(spot_market.withdraw_guard_threshold.cast()?);
Ok((
min_deposit_tokens_for_utilization,
max_borrow_tokens_for_utilization,
))
}
pub fn check_withdraw_limits(
spot_market: &SpotMarket,
user: Option<&User>,
token_amount_withdrawn: Option<u128>,
) -> DriftResult<bool> {
// calculates min/max deposit/borrow amounts permitted for immediate withdraw
// takes the stricter of absolute caps on level changes and utilization changes vs 24hr moving averrages
let deposit_token_amount = get_token_amount(
spot_market.deposit_balance,
spot_market,
&SpotBalanceType::Deposit,
)?;
let borrow_token_amount = get_token_amount(
spot_market.borrow_balance,
spot_market,
&SpotBalanceType::Borrow,
)?;
let max_token_borrows: u128 = if spot_market.max_token_borrows_fraction > 0 {
spot_market
.max_token_deposits
.safe_mul(spot_market.max_token_borrows_fraction.cast()?)?
.safe_div(10000)?
.cast()?
} else {
u128::MAX
};
let max_borrow_token_for_twap = calculate_max_borrow_token_amount(
deposit_token_amount,
spot_market.deposit_token_twap.cast()?,
spot_market.borrow_token_twap.cast()?,
spot_market.withdraw_guard_threshold.cast()?,
max_token_borrows,
)?;
let (min_deposit_token_for_utilization, max_borrow_token_for_utilization) =
calculate_token_utilization_limits(deposit_token_amount, borrow_token_amount, spot_market)?;
let max_borrow_token = max_borrow_token_for_twap.min(max_borrow_token_for_utilization);
let min_deposit_token_for_twap = calculate_min_deposit_token_amount(
spot_market.deposit_token_twap.cast()?,
spot_market.withdraw_guard_threshold.cast()?,
)?;
let min_deposit_token = min_deposit_token_for_twap.max(min_deposit_token_for_utilization);
// for resulting deposit or ZERO, check if deposits above minimum
// for resulting borrow, check both deposit and borrow constraints
let valid_global_withdrawal = if let Some(user) = user {
let spot_position_index = user.get_spot_position_index(spot_market.market_index)?;
if user.spot_positions[spot_position_index].balance_type() == &SpotBalanceType::Borrow {
borrow_token_amount <= max_borrow_token && deposit_token_amount >= min_deposit_token
} else {
deposit_token_amount >= min_deposit_token
}
} else {
deposit_token_amount >= min_deposit_token && borrow_token_amount <= max_borrow_token
};
let valid_withdrawal = if !valid_global_withdrawal {
msg!(
"withdraw_guard_threshold={:?}",
spot_market.withdraw_guard_threshold
);
msg!("min_deposit_token={:?}", min_deposit_token);
msg!("deposit_token_amount={:?}", deposit_token_amount);
msg!("max_borrow_token={:?}", max_borrow_token);
msg!("borrow_token_amount={:?}", borrow_token_amount);
check_user_exception_to_withdraw_limits(spot_market, user, token_amount_withdrawn)?
} else {
true
};
Ok(valid_withdrawal)
}
pub fn get_max_withdraw_for_market_with_token_amount(
spot_market: &SpotMarket,
token_amount: i128,
is_leaving_drift: bool,
) -> DriftResult<u128> {
let deposit_token_amount = get_token_amount(
spot_market.deposit_balance,
spot_market,
&SpotBalanceType::Deposit,
)?;
let borrow_token_amount = get_token_amount(
spot_market.borrow_balance,
spot_market,
&SpotBalanceType::Borrow,
)?;
// if leaving drift, need to consider utilization limits
let (min_deposit_token_for_utilization, max_borrow_token_for_utilization) = if is_leaving_drift
{
calculate_token_utilization_limits(deposit_token_amount, borrow_token_amount, spot_market)?
} else {
(0, u128::MAX)
};
let mut max_withdraw_amount = 0_u128;
if token_amount > 0 {
let min_deposit_token_for_twap = calculate_min_deposit_token_amount(
spot_market.deposit_token_twap.cast()?,
spot_market.withdraw_guard_threshold.cast()?,
)?;
let min_deposit_token = min_deposit_token_for_twap.max(min_deposit_token_for_utilization);
let withdraw_limit = deposit_token_amount.saturating_sub(min_deposit_token);
let token_amount = token_amount.unsigned_abs();
if withdraw_limit <= token_amount && is_leaving_drift {
return Ok(withdraw_limit);
}
max_withdraw_amount = token_amount;
}
let max_token_borrows: u128 = if spot_market.max_token_borrows_fraction > 0 {
spot_market
.max_token_deposits
.safe_mul(spot_market.max_token_borrows_fraction.cast()?)?
.safe_div(10000)?
.cast()?
} else {
u128::MAX
};
let max_borrow_token_for_twap = calculate_max_borrow_token_amount(
deposit_token_amount,
spot_market.deposit_token_twap.cast()?,
spot_market.borrow_token_twap.cast()?,
spot_market.withdraw_guard_threshold.cast()?,
max_token_borrows,
)?;
let max_borrow_token = max_borrow_token_for_twap.min(max_borrow_token_for_utilization);
let mut borrow_limit = max_borrow_token
.saturating_sub(borrow_token_amount)
.min(deposit_token_amount.saturating_sub(borrow_token_amount));
if spot_market.max_token_borrows_fraction > 0 {
// min with max allowed borrows
let borrows = spot_market.get_borrows()?;
let max_token_borrows = spot_market
.max_token_deposits
.safe_mul(spot_market.max_token_borrows_fraction.cast()?)?
.safe_div(10000)?
.cast::<u128>()?;
borrow_limit = borrow_limit.min(max_token_borrows.saturating_sub(borrows));
}
max_withdraw_amount.safe_add(borrow_limit)
}
pub fn validate_spot_balances(spot_market: &SpotMarket) -> DriftResult<i64> {
let depositors_amount: u64 = get_token_amount(
spot_market.deposit_balance,
spot_market,
&SpotBalanceType::Deposit,
)?
.cast()?;
let borrowers_amount: u64 = get_token_amount(
spot_market.borrow_balance,
spot_market,
&SpotBalanceType::Borrow,
)?
.cast()?;
let revenue_amount: u64 = get_token_amount(
spot_market.revenue_pool.scaled_balance,
spot_market,
&SpotBalanceType::Deposit,
)?
.cast()?;
let depositors_claim = depositors_amount
.cast::<i64>()?
.safe_sub(borrowers_amount.cast()?)?;
validate!(
revenue_amount <= depositors_amount,
ErrorCode::SpotMarketVaultInvariantViolated,
"revenue_amount={} greater or equal to the depositors_amount={} (depositors_claim={}, spot_market.deposit_balance={})",
revenue_amount,
depositors_amount,
depositors_claim,
spot_market.deposit_balance
)?;
Ok(depositors_claim)
}
pub fn validate_spot_market_vault_amount(
spot_market: &SpotMarket,
vault_amount: u64,
) -> DriftResult<i64> {
let depositors_claim = validate_spot_balances(spot_market)?;
validate!(
vault_amount.cast::<i64>()? >= depositors_claim,
ErrorCode::SpotMarketVaultInvariantViolated,
"spot market vault ={} holds less than remaining depositor claims = {}",
vault_amount,
depositors_claim
)?;
Ok(depositors_claim)
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/bn.rs
|
//! Big number types
#![allow(clippy::assign_op_pattern)]
#![allow(clippy::ptr_offset_with_cast)]
#![allow(clippy::manual_range_contains)]
use crate::error::ErrorCode::BnConversionError;
use std::borrow::BorrowMut;
use std::convert::TryInto;
use std::mem::size_of;
use uint::construct_uint;
use crate::error::DriftResult;
construct_uint! {
/// 256-bit unsigned integer.
pub struct U256(4);
}
impl U256 {
/// Convert u256 to u64
pub fn to_u64(self) -> Option<u64> {
self.try_to_u64().map_or_else(|_| None, Some)
}
/// Convert u256 to u64
pub fn try_to_u64(self) -> DriftResult<u64> {
self.try_into().map_err(|_| BnConversionError)
}
/// Convert u256 to u128
pub fn to_u128(self) -> Option<u128> {
self.try_to_u128().map_or_else(|_| None, Some)
}
/// Convert u256 to u128
pub fn try_to_u128(self) -> DriftResult<u128> {
self.try_into().map_err(|_| BnConversionError)
}
/// Convert from little endian bytes
pub fn from_le_bytes(bytes: [u8; 32]) -> Self {
U256::from_little_endian(&bytes)
}
/// Convert to little endian bytes
pub fn to_le_bytes(self) -> [u8; 32] {
let mut buf: Vec<u8> = Vec::with_capacity(size_of::<Self>());
self.to_little_endian(buf.borrow_mut());
let mut bytes: [u8; 32] = [0u8; 32];
bytes.copy_from_slice(buf.as_slice());
bytes
}
}
construct_uint! {
/// 192-bit unsigned integer.
pub struct U192(3);
}
impl U192 {
/// Convert u192 to u64
pub fn to_u64(self) -> Option<u64> {
self.try_to_u64().map_or_else(|_| None, Some)
}
/// Convert u192 to u64
pub fn try_to_u64(self) -> DriftResult<u64> {
self.try_into().map_err(|_| BnConversionError)
}
/// Convert u192 to u128
pub fn to_u128(self) -> Option<u128> {
self.try_to_u128().map_or_else(|_| None, Some)
}
/// Convert u192 to u128
pub fn try_to_u128(self) -> DriftResult<u128> {
self.try_into().map_err(|_| BnConversionError)
}
/// Convert from little endian bytes
pub fn from_le_bytes(bytes: [u8; 24]) -> Self {
U192::from_little_endian(&bytes)
}
/// Convert to little endian bytes
pub fn to_le_bytes(self) -> [u8; 24] {
let mut buf: Vec<u8> = Vec::with_capacity(size_of::<Self>());
self.to_little_endian(buf.borrow_mut());
let mut bytes: [u8; 24] = [0u8; 24];
bytes.copy_from_slice(buf.as_slice());
bytes
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/amm_jit.rs
|
use crate::controller::position::PositionDirection;
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::constants::{AMM_RESERVE_PRECISION, PERCENTAGE_PRECISION_U64};
use crate::math::orders::standardize_base_asset_amount;
use crate::math::safe_math::SafeMath;
use crate::state::perp_market::{AMMLiquiditySplit, PerpMarket};
#[cfg(test)]
mod tests;
// assumption: market.amm.amm_jit_is_active() == true
// assumption: taker_baa will improve market balance (see orders.rs & amm_wants_to_jit_make)
pub fn calculate_jit_base_asset_amount(
market: &PerpMarket,
maker_base_asset_amount: u64,
auction_price: u64,
valid_oracle_price: Option<i64>,
taker_direction: PositionDirection,
liquidity_split: AMMLiquiditySplit,
) -> DriftResult<u64> {
// AMM can only take up to 50% of size the maker is offering
let mut max_jit_amount = maker_base_asset_amount.safe_div(2)?;
// check for wash trade
if let Some(oracle_price) = valid_oracle_price {
let baseline_price = oracle_price;
let baseline_price_u64 = oracle_price.cast::<u64>()?;
let five_bps_of_baseline = baseline_price_u64 / 2000;
// maker taking a short below oracle = likely to be a wash
// so we want to take under 50% of typical
if taker_direction == PositionDirection::Long
&& auction_price < baseline_price_u64.safe_sub(five_bps_of_baseline)?
|| taker_direction == PositionDirection::Short
&& auction_price > baseline_price_u64.saturating_add(five_bps_of_baseline)
{
// shrink by at least 50% based on distance from oracle
let opposite_spread_price = if taker_direction == PositionDirection::Long {
market
.amm
.short_spread
.cast::<u64>()?
.safe_mul(baseline_price_u64)?
.safe_div(PERCENTAGE_PRECISION_U64)?
} else {
market
.amm
.long_spread
.cast::<u64>()?
.safe_mul(baseline_price_u64)?
.safe_div(PERCENTAGE_PRECISION_U64)?
};
let price_difference_from_baseline = auction_price
.cast::<i64>()?
.safe_sub(baseline_price)?
.unsigned_abs();
let max_jit_amount_scale_numerator =
opposite_spread_price.saturating_sub(price_difference_from_baseline);
max_jit_amount = max_jit_amount
.safe_mul(max_jit_amount_scale_numerator)?
.safe_div(opposite_spread_price.max(1))?;
}
} else {
max_jit_amount = 0;
};
if max_jit_amount == 0 {
return Ok(0);
}
// check for market imbalance
// e.g,
// 0 2.5 5 7.5 10
// min | -- | -- mid -- |-- | max
// mim mam
// base @ mid = ratio = 1
// base @ mim = ratio = 2.5 / 7.5 = 3 == imbalanced
// ratio >= 3 == imbalanced
let (max_bids, max_asks) = crate::math::amm::calculate_market_open_bids_asks(&market.amm)?;
let (max_bids, max_asks) = (max_bids.unsigned_abs(), max_asks.unsigned_abs());
let numerator = max_bids.max(max_asks);
let denominator = max_bids.min(max_asks);
let ratio = numerator
.safe_mul(AMM_RESERVE_PRECISION)?
.safe_div(denominator)
.unwrap_or(u128::MAX);
let imbalanced_bound = 15_u128.safe_mul(AMM_RESERVE_PRECISION.safe_div(10)?)?;
let amm_is_imbalanced = ratio >= imbalanced_bound;
// take more when amm is imbalanced
let mut jit_base_asset_amount = if amm_is_imbalanced {
maker_base_asset_amount
} else {
maker_base_asset_amount.safe_div(4)?
};
if jit_base_asset_amount == 0 {
return Ok(0);
}
jit_base_asset_amount =
calculate_clamped_jit_base_asset_amount(market, liquidity_split, jit_base_asset_amount)?;
jit_base_asset_amount = jit_base_asset_amount.min(max_jit_amount);
// last step we always standardize
jit_base_asset_amount =
standardize_base_asset_amount(jit_base_asset_amount, market.amm.order_step_size)?;
Ok(jit_base_asset_amount)
}
// assumption: taker_baa will improve market balance (see orders.rs & amm_wants_to_jit_make)
// note: we split it into two (calc and clamp) bc its easier to maintain tests
pub fn calculate_clamped_jit_base_asset_amount(
market: &PerpMarket,
liquidity_split: AMMLiquiditySplit,
jit_base_asset_amount: u64,
) -> DriftResult<u64> {
// apply intensity
// todo more efficient method do here
let jit_base_asset_amount: u64 = jit_base_asset_amount
.cast::<u128>()?
.safe_mul(market.amm.amm_jit_intensity.min(100).cast::<u128>()?)?
.safe_div(100_u128)?
.cast::<u64>()?;
// bound it; dont flip the net_baa
let max_amm_base_asset_amount = if liquidity_split != AMMLiquiditySplit::LPOwned {
market
.amm
.base_asset_amount_with_amm
.unsigned_abs()
.cast::<u64>()?
} else {
market
.amm
.imbalanced_base_asset_amount_with_lp()?
.unsigned_abs()
.cast::<u64>()?
};
let jit_base_asset_amount = jit_base_asset_amount.min(max_amm_base_asset_amount);
Ok(jit_base_asset_amount)
}
pub fn calculate_amm_jit_liquidity(
market: &mut PerpMarket,
taker_direction: PositionDirection,
maker_price: u64,
valid_oracle_price: Option<i64>,
base_asset_amount: u64,
taker_base_asset_amount: u64,
maker_base_asset_amount: u64,
taker_has_limit_price: bool,
amm_lp_allowed_to_jit_make: Option<bool>,
) -> DriftResult<(u64, AMMLiquiditySplit)> {
let mut jit_base_asset_amount: u64 = 0;
let mut liquidity_split: AMMLiquiditySplit = AMMLiquiditySplit::ProtocolOwned;
// taker has_limit_price = false means (limit price = 0 AND auction is complete) so
// market order will always land and fill on amm next round
let amm_will_fill_next_round: bool =
!taker_has_limit_price && maker_base_asset_amount < taker_base_asset_amount;
// return early
if amm_will_fill_next_round {
return Ok((jit_base_asset_amount, liquidity_split));
}
let amm_wants_to_jit_make = market.amm.amm_wants_to_jit_make(taker_direction)?;
let amm_lp_wants_to_jit_make = market.amm.amm_lp_wants_to_jit_make(taker_direction)?;
let amm_lp_allowed_to_jit_make = match amm_lp_allowed_to_jit_make {
Some(allowed) => allowed,
None => market
.amm
.amm_lp_allowed_to_jit_make(amm_wants_to_jit_make)?,
};
let split_with_lps = amm_lp_allowed_to_jit_make && amm_lp_wants_to_jit_make;
if amm_wants_to_jit_make {
liquidity_split = if split_with_lps {
AMMLiquiditySplit::Shared
} else {
AMMLiquiditySplit::ProtocolOwned
};
jit_base_asset_amount = calculate_jit_base_asset_amount(
market,
base_asset_amount,
maker_price,
valid_oracle_price,
taker_direction,
liquidity_split,
)?;
} else if split_with_lps {
liquidity_split = AMMLiquiditySplit::LPOwned;
jit_base_asset_amount = calculate_jit_base_asset_amount(
market,
base_asset_amount,
maker_price,
valid_oracle_price,
taker_direction,
liquidity_split,
)?;
}
Ok((jit_base_asset_amount, liquidity_split))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/spot_swap.rs
|
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::margin::MarginRequirementType;
use crate::math::orders::{calculate_fill_price, validate_fill_price_within_price_bands};
use crate::math::safe_math::SafeMath;
use crate::math::spot_balance::{get_strict_token_value, get_token_value};
use crate::state::oracle::StrictOraclePrice;
use crate::state::spot_market::SpotMarket;
use crate::{PositionDirection, PRICE_PRECISION, SPOT_WEIGHT_PRECISION_U128};
#[cfg(test)]
mod tests;
pub fn calculate_swap_price(
asset_amount: u128,
liability_amount: u128,
asset_decimals: u32,
liability_decimals: u32,
) -> DriftResult<u128> {
asset_amount
.safe_mul(PRICE_PRECISION)?
.safe_div(10_u128.pow(asset_decimals))?
.safe_mul(10_u128.pow(liability_decimals))?
.safe_div(liability_amount)
}
pub fn select_margin_type_for_swap(
in_market: &SpotMarket,
out_market: &SpotMarket,
in_strict_price: &StrictOraclePrice,
out_strict_price: &StrictOraclePrice,
in_token_amount_before: i128,
out_token_amount_before: i128,
in_token_amount_after: i128,
out_token_amount_after: i128,
strict_margin_type: MarginRequirementType,
) -> DriftResult<MarginRequirementType> {
let calculate_free_collateral_contribution =
|market: &SpotMarket, strict_oracle_price: &StrictOraclePrice, token_amount: i128| {
let token_value =
get_strict_token_value(token_amount, market.decimals, strict_oracle_price)?;
let weight = if token_amount >= 0 {
market.get_asset_weight(
token_amount.unsigned_abs(),
strict_oracle_price.current,
&MarginRequirementType::Initial,
)?
} else {
market.get_liability_weight(
token_amount.unsigned_abs(),
&MarginRequirementType::Initial,
)?
};
token_value
.safe_mul(weight.cast::<i128>()?)?
.safe_div(SPOT_WEIGHT_PRECISION_U128.cast()?)
};
let in_free_collateral_contribution_before =
calculate_free_collateral_contribution(in_market, in_strict_price, in_token_amount_before)?;
let out_free_collateral_contribution_before = calculate_free_collateral_contribution(
out_market,
out_strict_price,
out_token_amount_before,
)?;
let free_collateral_contribution_before =
in_free_collateral_contribution_before.safe_add(out_free_collateral_contribution_before)?;
let in_free_collateral_contribution_after =
calculate_free_collateral_contribution(in_market, in_strict_price, in_token_amount_after)?;
let out_free_collateral_contribution_after = calculate_free_collateral_contribution(
out_market,
out_strict_price,
out_token_amount_after,
)?;
let free_collateral_contribution_after =
in_free_collateral_contribution_after.safe_add(out_free_collateral_contribution_after)?;
let margin_type = if free_collateral_contribution_after > free_collateral_contribution_before {
MarginRequirementType::Maintenance
} else {
strict_margin_type
};
Ok(margin_type)
}
pub fn validate_price_bands_for_swap(
in_market: &SpotMarket,
out_market: &SpotMarket,
amount_in: u64,
amount_out: u64,
in_price: i64,
out_price: i64,
oracle_twap_5min_percent_divergence: u64,
) -> DriftResult {
let (fill_price, direction, oracle_price, oracle_twap_5min, margin_ratio) = {
let in_market_margin_ratio = in_market.get_margin_ratio(&MarginRequirementType::Initial)?;
if in_market_margin_ratio != 0 {
// quote value for out amount
let out_value = get_token_value(amount_out.cast()?, out_market.decimals, out_price)?
.cast::<u64>()?;
// calculate fill price in quote
let fill_price = calculate_fill_price(out_value, amount_in, in_market.get_precision())?;
(
fill_price,
PositionDirection::Short,
in_price,
in_market.historical_oracle_data.last_oracle_price_twap_5min,
in_market_margin_ratio,
)
} else {
let fill_price =
calculate_fill_price(amount_in, amount_out, out_market.get_precision())?;
(
fill_price,
PositionDirection::Long,
out_price,
out_market
.historical_oracle_data
.last_oracle_price_twap_5min,
out_market.get_margin_ratio(&MarginRequirementType::Initial)?,
)
}
};
validate_fill_price_within_price_bands(
fill_price,
direction,
oracle_price,
oracle_twap_5min,
margin_ratio,
oracle_twap_5min_percent_divergence,
false,
)?;
Ok(())
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/casting.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::math::bn::U192;
use solana_program::msg;
use std::convert::TryInto;
use std::panic::Location;
pub trait Cast: Sized {
#[track_caller]
#[inline(always)]
fn cast<T: std::convert::TryFrom<Self>>(self) -> DriftResult<T> {
match self.try_into() {
Ok(result) => Ok(result),
Err(_) => {
let caller = Location::caller();
msg!(
"Casting error thrown at {}:{}",
caller.file(),
caller.line()
);
Err(ErrorCode::CastingFailure)
}
}
}
}
impl Cast for U192 {}
impl Cast for u128 {}
impl Cast for u64 {}
impl Cast for u32 {}
impl Cast for u16 {}
impl Cast for u8 {}
impl Cast for usize {}
impl Cast for i128 {}
impl Cast for i64 {}
impl Cast for i32 {}
impl Cast for i16 {}
impl Cast for i8 {}
impl Cast for bool {}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/quote_asset.rs
|
use crate::error::DriftResult;
use crate::math::constants::AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO;
use crate::math::safe_math::SafeMath;
use std::ops::Div;
pub fn reserve_to_asset_amount(
quote_asset_reserve: u128,
peg_multiplier: u128,
) -> DriftResult<u128> {
Ok(quote_asset_reserve
.safe_mul(peg_multiplier)?
.div(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO))
}
pub fn asset_to_reserve_amount(
quote_asset_amount: u128,
peg_multiplier: u128,
) -> DriftResult<u128> {
Ok(quote_asset_amount
.safe_mul(AMM_TIMES_PEG_TO_QUOTE_PRECISION_RATIO)?
.div(peg_multiplier))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/matching.rs
|
use std::cmp::min;
use crate::controller::position::PositionDirection;
use crate::error::DriftResult;
use crate::math::casting::Cast;
use crate::math::constants::{BID_ASK_SPREAD_PRECISION_I128, TEN_BPS_I64};
use crate::math::orders::calculate_quote_asset_amount_for_maker_order;
use crate::math::safe_math::SafeMath;
use crate::state::fill_mode::FillMode;
use crate::state::user::Order;
#[cfg(test)]
mod tests;
pub fn is_maker_for_taker(
maker_order: &Order,
taker_order: &Order,
slot: u64,
fill_mode: FillMode,
) -> DriftResult<bool> {
// Maker and taker order not allowed to match if both were placed in the current slot
if slot == maker_order.slot
&& slot == taker_order.slot
&& !(maker_order.is_jit_maker() || fill_mode.is_rfq())
{
return Ok(false);
};
// taker cant be post only and maker must be resting limit order
if taker_order.post_only || !maker_order.is_resting_limit_order(slot)? {
Ok(false)
// can make if taker order isn't resting (market order or limit going through auction)
} else if !taker_order.is_resting_limit_order(slot)? || maker_order.post_only {
Ok(true)
// otherwise the maker must be older than the taker order
} else {
Ok(maker_order
.slot
.safe_add(maker_order.auction_duration.cast()?)?
<= taker_order
.slot
.safe_add(taker_order.auction_duration.cast()?)?)
}
}
pub fn are_orders_same_market_but_different_sides(
maker_order: &Order,
taker_order: &Order,
) -> bool {
maker_order.market_index == taker_order.market_index
&& maker_order.market_type == taker_order.market_type
&& maker_order.direction != taker_order.direction
}
pub fn do_orders_cross(
maker_direction: PositionDirection,
maker_price: u64,
taker_price: u64,
) -> bool {
match maker_direction {
PositionDirection::Long => taker_price <= maker_price,
PositionDirection::Short => taker_price >= maker_price,
}
}
pub fn calculate_fill_for_matched_orders(
maker_base_asset_amount: u64,
maker_price: u64,
taker_base_asset_amount: u64,
base_decimals: u32,
maker_direction: PositionDirection,
) -> DriftResult<(u64, u64)> {
let base_asset_amount = min(maker_base_asset_amount, taker_base_asset_amount);
let quote_asset_amount = calculate_quote_asset_amount_for_maker_order(
base_asset_amount,
maker_price,
base_decimals,
maker_direction,
)?;
Ok((base_asset_amount, quote_asset_amount))
}
pub fn calculate_filler_multiplier_for_matched_orders(
maker_price: u64,
maker_direction: PositionDirection,
oracle_price: i64,
) -> DriftResult<u64> {
// percentage oracle_price is above maker_price
let price_pct_diff = oracle_price
.safe_sub(maker_price.cast::<i64>()?)?
.cast::<i128>()?
.safe_mul(BID_ASK_SPREAD_PRECISION_I128)?
.safe_div(oracle_price.cast()?)?
.cast::<i64>()?;
// offer filler multiplier based on price improvement from reasonable baseline
// multiplier between 1x and 100x
let multiplier = match maker_direction {
PositionDirection::Long => (-price_pct_diff).safe_add(TEN_BPS_I64 * 2)?,
PositionDirection::Short => price_pct_diff.safe_add(TEN_BPS_I64 * 2)?,
}
.max(TEN_BPS_I64)
.min(TEN_BPS_I64 * 100);
multiplier.cast()
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/lp.rs
|
use crate::error::{DriftResult, ErrorCode};
use crate::{
validate, MARGIN_PRECISION_U128, PRICE_PRECISION, PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO,
};
use solana_program::msg;
use std::u64;
use crate::math::amm::calculate_market_open_bids_asks;
use crate::math::casting::Cast;
use crate::math::helpers;
use crate::math::margin::MarginRequirementType;
use crate::math::orders::{
standardize_base_asset_amount, standardize_base_asset_amount_ceil,
standardize_base_asset_amount_with_remainder_i128,
};
use crate::math::safe_math::SafeMath;
use crate::state::perp_market::PerpMarket;
use crate::state::perp_market::AMM;
use crate::state::user::PerpPosition;
#[cfg(test)]
mod tests;
#[derive(Debug)]
pub struct LPMetrics {
pub base_asset_amount: i128,
pub quote_asset_amount: i128,
pub remainder_base_asset_amount: i128,
}
pub fn calculate_settle_lp_metrics(amm: &AMM, position: &PerpPosition) -> DriftResult<LPMetrics> {
let (base_asset_amount, quote_asset_amount) = calculate_settled_lp_base_quote(amm, position)?;
// stepsize it
let (standardized_base_asset_amount, remainder_base_asset_amount) =
standardize_base_asset_amount_with_remainder_i128(
base_asset_amount,
amm.order_step_size.cast()?,
)?;
let lp_metrics = LPMetrics {
base_asset_amount: standardized_base_asset_amount,
quote_asset_amount,
remainder_base_asset_amount: remainder_base_asset_amount.cast()?,
};
Ok(lp_metrics)
}
pub fn calculate_settled_lp_base_quote(
amm: &AMM,
position: &PerpPosition,
) -> DriftResult<(i128, i128)> {
let n_shares = position.lp_shares;
let base_unit: i128 = amm.get_per_lp_base_unit()?;
validate!(
amm.per_lp_base == position.per_lp_base,
ErrorCode::InvalidPerpPositionDetected,
"calculate_settled_lp_base_quote :: position/market per_lp_base unequal {} != {}",
position.per_lp_base,
amm.per_lp_base
)?;
let n_shares_i128 = n_shares.cast::<i128>()?;
// give them slice of the damm market position
let amm_net_base_asset_amount_per_lp = amm
.base_asset_amount_per_lp
.safe_sub(position.last_base_asset_amount_per_lp.cast()?)?;
let base_asset_amount = amm_net_base_asset_amount_per_lp
.cast::<i128>()?
.safe_mul(n_shares_i128)?
.safe_div(base_unit)?;
let amm_net_quote_asset_amount_per_lp = amm
.quote_asset_amount_per_lp
.safe_sub(position.last_quote_asset_amount_per_lp.cast()?)?;
let quote_asset_amount = amm_net_quote_asset_amount_per_lp
.cast::<i128>()?
.safe_mul(n_shares_i128)?
.safe_div(base_unit)?;
Ok((base_asset_amount, quote_asset_amount))
}
pub fn calculate_lp_open_bids_asks(
market_position: &PerpPosition,
market: &PerpMarket,
) -> DriftResult<(i64, i64)> {
let total_lp_shares = market.amm.sqrt_k;
let lp_shares = market_position.lp_shares;
let (max_bids, max_asks) = calculate_market_open_bids_asks(&market.amm)?;
let open_asks = helpers::get_proportion_i128(max_asks, lp_shares.cast()?, total_lp_shares)?;
let open_bids = helpers::get_proportion_i128(max_bids, lp_shares.cast()?, total_lp_shares)?;
Ok((open_bids.cast()?, open_asks.cast()?))
}
pub fn calculate_lp_shares_to_burn_for_risk_reduction(
perp_position: &PerpPosition,
market: &PerpMarket,
oracle_price: i64,
quote_oracle_price: i64,
margin_shortage: u128,
user_custom_margin_ratio: u32,
user_high_leverage_mode: bool,
) -> DriftResult<(u64, u64)> {
let settled_lp_position = perp_position.simulate_settled_lp_position(market, oracle_price)?;
let worse_case_base_asset_amount =
settled_lp_position.worst_case_base_asset_amount(oracle_price, market.contract_type)?;
let open_orders_from_lp_shares = if worse_case_base_asset_amount >= 0 {
worse_case_base_asset_amount.safe_sub(
settled_lp_position
.base_asset_amount
.safe_add(perp_position.open_bids)?
.cast()?,
)?
} else {
worse_case_base_asset_amount.safe_sub(
settled_lp_position
.base_asset_amount
.safe_add(perp_position.open_asks)?
.cast()?,
)?
};
let margin_ratio = market
.get_margin_ratio(
worse_case_base_asset_amount.unsigned_abs(),
MarginRequirementType::Initial,
user_high_leverage_mode,
)?
.max(user_custom_margin_ratio);
let base_asset_amount_to_cover = margin_shortage
.safe_mul(PRICE_TIMES_AMM_TO_QUOTE_PRECISION_RATIO)?
.safe_div(
oracle_price
.cast::<u128>()?
.safe_mul(quote_oracle_price.cast()?)?
.safe_div(PRICE_PRECISION)?
.safe_mul(margin_ratio.cast()?)?
.safe_div(MARGIN_PRECISION_U128)?,
)?
.cast::<u64>()?;
let current_base_asset_amount = settled_lp_position.base_asset_amount.unsigned_abs();
// if closing position is enough to cover margin shortage, then only a small % of lp shares need to be burned
if base_asset_amount_to_cover < current_base_asset_amount {
let base_asset_amount_to_close = standardize_base_asset_amount_ceil(
base_asset_amount_to_cover,
market.amm.order_step_size,
)?
.min(current_base_asset_amount);
let lp_shares_to_burn = standardize_base_asset_amount(
settled_lp_position.lp_shares / 10,
market.amm.order_step_size,
)?
.max(market.amm.order_step_size);
return Ok((lp_shares_to_burn, base_asset_amount_to_close));
}
let base_asset_amount_to_cover =
base_asset_amount_to_cover.safe_sub(current_base_asset_amount)?;
let percent_to_burn = base_asset_amount_to_cover
.cast::<u128>()?
.safe_mul(100)?
.safe_div_ceil(open_orders_from_lp_shares.unsigned_abs())?;
let lp_shares_to_burn = settled_lp_position
.lp_shares
.cast::<u128>()?
.safe_mul(percent_to_burn.cast()?)?
.safe_div_ceil(100)?
.cast::<u64>()?;
let standardized_lp_shares_to_burn =
standardize_base_asset_amount_ceil(lp_shares_to_burn, market.amm.order_step_size)?
.clamp(market.amm.order_step_size, settled_lp_position.lp_shares);
Ok((standardized_lp_shares_to_burn, current_base_asset_amount))
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/matching/tests.rs
|
use crate::controller::position::PositionDirection;
use crate::math::constants::{PRICE_PRECISION_I64, PRICE_PRECISION_U64};
use crate::math::matching::*;
mod is_maker_for_taker {
use crate::math::matching::is_maker_for_taker;
use crate::state::fill_mode::FillMode;
use crate::state::user::{Order, OrderType};
#[test]
fn taker_is_post_only() {
let taker = Order {
post_only: true,
..Default::default()
};
let maker = Order {
post_only: false,
..Default::default()
};
assert_eq!(
is_maker_for_taker(&maker, &taker, 0, FillMode::Fill).unwrap(),
false
);
}
#[test]
fn maker_is_market_order() {
let taker = Order {
post_only: false,
order_type: OrderType::Market,
..Default::default()
};
let maker = Order {
post_only: false,
order_type: OrderType::Market,
..Default::default()
};
assert_eq!(
is_maker_for_taker(&maker, &taker, 0, FillMode::Fill).unwrap(),
false
);
}
#[test]
fn maker_is_limit_order_in_auction() {
// market order
let taker = Order {
post_only: false,
order_type: OrderType::Market,
..Default::default()
};
let maker = Order {
post_only: false,
order_type: OrderType::Limit,
auction_duration: 10,
slot: 0,
..Default::default()
};
assert_eq!(
is_maker_for_taker(&maker, &taker, 0, FillMode::Fill).unwrap(),
false
);
// limit order in auction
let taker = Order {
post_only: false,
order_type: OrderType::Limit,
auction_duration: 10,
..Default::default()
};
assert_eq!(
is_maker_for_taker(&maker, &taker, 0, FillMode::Fill).unwrap(),
false
);
}
#[test]
fn maker_is_post_only() {
let slot = 1;
// market order
let taker = Order {
post_only: false,
order_type: OrderType::Market,
slot: slot - 1,
..Default::default()
};
let maker = Order {
post_only: true,
order_type: OrderType::Limit,
slot: slot - 1,
..Default::default()
};
assert_eq!(
is_maker_for_taker(&maker, &taker, slot, FillMode::Fill).unwrap(),
true
);
// limit order in auction
let taker = Order {
post_only: false,
order_type: OrderType::Limit,
auction_duration: 10,
slot: slot - 1,
..Default::default()
};
assert_eq!(
is_maker_for_taker(&maker, &taker, slot, FillMode::Fill).unwrap(),
true
);
}
#[test]
fn maker_is_resting_limit_order_after_auction() {
// market order
let taker = Order {
post_only: false,
order_type: OrderType::Market,
..Default::default()
};
let maker = Order {
post_only: false,
order_type: OrderType::Limit,
auction_duration: 10,
..Default::default()
};
let slot = 11;
assert_eq!(maker.is_resting_limit_order(slot).unwrap(), true);
assert_eq!(
is_maker_for_taker(&maker, &taker, slot, FillMode::Fill).unwrap(),
true
);
// limit order in auction
let taker = Order {
post_only: false,
order_type: OrderType::Limit,
slot,
auction_duration: 10,
..Default::default()
};
assert_eq!(taker.is_resting_limit_order(slot).unwrap(), false);
assert_eq!(
is_maker_for_taker(&maker, &taker, slot, FillMode::Fill).unwrap(),
true
);
}
#[test]
fn maker_is_post_only_for_resting_taker_limit() {
let slot = 11;
let taker = Order {
post_only: false,
order_type: OrderType::Limit,
slot: 0,
auction_duration: 10,
..Default::default()
};
assert_eq!(taker.is_resting_limit_order(slot).unwrap(), true);
let maker = Order {
slot: 1,
post_only: true,
order_type: OrderType::Limit,
..Default::default()
};
assert_eq!(
is_maker_for_taker(&maker, &taker, slot, FillMode::Fill).unwrap(),
true
);
}
#[test]
fn maker_and_taker_resting_limit_orders() {
let slot = 15;
let taker = Order {
post_only: false,
order_type: OrderType::Limit,
slot: 0,
auction_duration: 10,
..Default::default()
};
assert_eq!(taker.is_resting_limit_order(slot).unwrap(), true);
let maker = Order {
post_only: false,
order_type: OrderType::Limit,
slot: 1,
auction_duration: 10,
..Default::default()
};
assert_eq!(taker.is_resting_limit_order(slot).unwrap(), true);
assert_eq!(
is_maker_for_taker(&maker, &taker, slot, FillMode::Fill).unwrap(),
false
);
let taker = Order {
post_only: false,
order_type: OrderType::Limit,
slot: 2,
auction_duration: 10,
..Default::default()
};
assert_eq!(taker.is_resting_limit_order(slot).unwrap(), true);
assert_eq!(
is_maker_for_taker(&maker, &taker, slot, FillMode::Fill).unwrap(),
true
);
}
}
#[test]
fn filler_multiplier_maker_long() {
let direction = PositionDirection::Long;
let oracle_price = 34 * PRICE_PRECISION_I64;
let mult = calculate_filler_multiplier_for_matched_orders(
oracle_price as u64,
direction,
oracle_price,
)
.unwrap();
assert_eq!(mult, 2000); // 2x
let mult = calculate_filler_multiplier_for_matched_orders(
(oracle_price - oracle_price / 10000) as u64, // barely bad 1 bp
direction,
oracle_price,
)
.unwrap();
assert_eq!(mult, 1900); // 1.9x
let maker_price_bad = 30 * PRICE_PRECISION_U64;
let maker_price_good = 40 * PRICE_PRECISION_U64;
let mult =
calculate_filler_multiplier_for_matched_orders(maker_price_good, direction, oracle_price)
.unwrap();
assert_eq!(mult, 100000); // 100x
let mult =
calculate_filler_multiplier_for_matched_orders(maker_price_bad, direction, oracle_price)
.unwrap();
assert_eq!(mult, 1000); // 1x
}
#[test]
fn filler_multiplier_maker_short() {
let direction = PositionDirection::Short;
let oracle_price = 34 * PRICE_PRECISION_I64;
let maker_price_good = 30 * PRICE_PRECISION_U64;
let maker_price_bad = 40 * PRICE_PRECISION_U64;
let mult =
calculate_filler_multiplier_for_matched_orders(maker_price_good, direction, oracle_price)
.unwrap();
assert_eq!(mult, 100000);
let mult =
calculate_filler_multiplier_for_matched_orders(maker_price_bad, direction, oracle_price)
.unwrap();
assert_eq!(mult, 1000);
let mult = calculate_filler_multiplier_for_matched_orders(
(oracle_price + oracle_price / 10000) as u64, // barely bad 1 bp
direction,
oracle_price,
)
.unwrap();
assert_eq!(mult, 1900); // 1.9x
let mult = calculate_filler_multiplier_for_matched_orders(
(oracle_price - oracle_price / 10000) as u64, // barely good 1 bp
direction,
oracle_price,
)
.unwrap();
assert_eq!(mult, 2100); // 2.1x
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/repeg/tests.rs
|
use crate::controller::amm::SwapDirection;
use crate::math::constants::{
AMM_RESERVE_PRECISION, MAX_CONCENTRATION_COEFFICIENT, PRICE_PRECISION, PRICE_PRECISION_U64,
QUOTE_PRECISION,
};
use crate::math::repeg::*;
use crate::state::oracle::HistoricalOracleData;
use crate::state::state::{PriceDivergenceGuardRails, State, ValidityGuardRails};
#[test]
fn calc_peg_tests() {
let qar = AMM_RESERVE_PRECISION;
let bar = AMM_RESERVE_PRECISION;
let px = 19401125456; // 19401.125
let mut new_peg = calculate_peg_from_target_price(qar, bar, px).unwrap();
assert_eq!(new_peg, 19401125456);
new_peg = calculate_peg_from_target_price(qar - 10000, bar + 10000, px).unwrap();
assert_eq!(new_peg, 19401513482);
new_peg = calculate_peg_from_target_price(qar + 10000, bar - 10000, px).unwrap();
assert_eq!(new_peg, 19400737437);
new_peg = calculate_peg_from_target_price(qar / 2, bar * 2, px).unwrap();
assert_eq!(new_peg, 77604501824);
let px2 = PRICE_PRECISION_U64 + (PRICE_PRECISION_U64 / 10000) * 5;
new_peg = calculate_peg_from_target_price(qar, bar, px2).unwrap();
assert_eq!(new_peg, 1000500);
new_peg = calculate_peg_from_target_price(qar, bar, px2 - 1).unwrap();
assert_eq!(new_peg, 1000499);
}
#[test]
fn calculate_optimal_peg_and_budget_test() {
let mut market = PerpMarket {
amm: AMM {
base_asset_reserve: 65 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 63015384615,
terminal_quote_asset_reserve: 64 * AMM_RESERVE_PRECISION,
sqrt_k: 64 * AMM_RESERVE_PRECISION,
peg_multiplier: 19_400_000_000,
base_asset_amount_with_amm: -(AMM_RESERVE_PRECISION as i128),
mark_std: PRICE_PRECISION as u64,
last_mark_price_twap_ts: 0,
base_spread: 250,
curve_update_intensity: 100,
max_spread: 500 * 100,
total_exchange_fee: QUOTE_PRECISION,
total_fee_minus_distributions: (40 * QUOTE_PRECISION) as i128,
..AMM::default()
},
margin_ratio_initial: 500,
..PerpMarket::default()
};
let reserve_price = market.amm.reserve_price().unwrap();
assert_eq!(reserve_price, 18807668638); //$ 18,807.6686390578
// positive target_price_gap exceeding max_spread
let oracle_price_data = OraclePriceData {
price: (12_400 * PRICE_PRECISION) as i64,
confidence: 0,
delay: 2,
has_sufficient_number_of_data_points: true,
};
let (optimal_peg, budget, check_lb) =
calculate_optimal_peg_and_budget(&market, &oracle_price_data).unwrap();
assert_eq!(optimal_peg, 13110290527);
assert_eq!(optimal_peg > oracle_price_data.price as u128, true);
assert_eq!(budget, 6192944714);
assert!(!check_lb);
// positive target_price_gap within max_spread
let oracle_price_data = OraclePriceData {
price: (18_901 * PRICE_PRECISION) as i64,
confidence: 167,
delay: 21,
has_sufficient_number_of_data_points: true,
};
let (optimal_peg, budget, check_lb) =
calculate_optimal_peg_and_budget(&market, &oracle_price_data).unwrap();
assert_eq!(optimal_peg, 19496270752);
assert_eq!(budget, 39500000);
assert!(check_lb);
// positive target_price_gap 2 within max_spread?
let oracle_price_data = OraclePriceData {
price: (18_601 * PRICE_PRECISION) as i64,
confidence: 167,
delay: 21,
has_sufficient_number_of_data_points: true,
};
let (optimal_peg, budget, check_lb) =
calculate_optimal_peg_and_budget(&market, &oracle_price_data).unwrap();
assert_eq!(optimal_peg, 19186822509);
assert_eq!(budget, 39500000);
assert!(check_lb);
// negative target_price_gap within max_spread
let oracle_price_data = OraclePriceData {
price: (20_400 * PRICE_PRECISION) as i64,
confidence: 1234567,
delay: 21,
has_sufficient_number_of_data_points: true,
};
let (optimal_peg, budget, check_lb) =
calculate_optimal_peg_and_budget(&market, &oracle_price_data).unwrap();
assert_eq!(optimal_peg, 21042480468);
assert_eq!(budget, 39500000);
assert!(check_lb);
// negative target_price_gap exceeding max_spread (in favor of vAMM)
let oracle_price_data = OraclePriceData {
price: (42_400 * PRICE_PRECISION) as i64,
confidence: 0,
delay: 2,
has_sufficient_number_of_data_points: true,
};
let (optimal_peg, budget, check_lb) =
calculate_optimal_peg_and_budget(&market, &oracle_price_data).unwrap();
assert_eq!(optimal_peg, 43735351562);
assert_eq!(budget, 39500000);
assert!(check_lb);
market.amm.base_asset_amount_with_amm = AMM_RESERVE_PRECISION as i128;
let swap_direction = if market.amm.base_asset_amount_with_amm > 0 {
SwapDirection::Add
} else {
SwapDirection::Remove
};
let (new_terminal_quote_reserve, _new_terminal_base_reserve) = amm::calculate_swap_output(
market.amm.base_asset_amount_with_amm.unsigned_abs(),
market.amm.base_asset_reserve,
swap_direction,
market.amm.sqrt_k,
)
.unwrap();
market.amm.terminal_quote_asset_reserve = new_terminal_quote_reserve;
// negative target_price_gap exceeding max_spread (not in favor of vAMM)
let oracle_price_data = OraclePriceData {
price: (42_400 * PRICE_PRECISION) as i64,
confidence: 0,
delay: 2,
has_sufficient_number_of_data_points: true,
};
let (optimal_peg, budget, check_lb) =
calculate_optimal_peg_and_budget(&market, &oracle_price_data).unwrap();
assert_eq!(optimal_peg, 42641967773);
assert_eq!(budget, 22190932405); // $2219.032405
assert!(!check_lb);
}
#[test]
fn calculate_optimal_peg_and_budget_2_test() {
let mut market = PerpMarket {
amm: AMM {
base_asset_reserve: 2270516211133,
quote_asset_reserve: 2270925669621,
terminal_quote_asset_reserve: 2270688451627,
sqrt_k: 2270720931148,
peg_multiplier: 17723081263,
base_asset_amount_with_amm: 237200000,
mark_std: 43112524,
last_mark_price_twap_ts: 0,
base_spread: 250,
curve_update_intensity: 100,
max_spread: 500 * 100,
total_exchange_fee: 298628987,
total_fee_minus_distributions: -242668966,
total_fee_withdrawn: 124247717,
concentration_coef: 1020710,
historical_oracle_data: HistoricalOracleData {
last_oracle_price_twap: 17765940050,
last_oracle_price_twap_5min: 17763317077,
..HistoricalOracleData::default()
},
..AMM::default()
},
margin_ratio_initial: 500,
..PerpMarket::default()
};
let (new_terminal_quote_reserve, new_terminal_base_reserve) =
amm::calculate_terminal_reserves(&market.amm).unwrap();
market.amm.terminal_quote_asset_reserve = new_terminal_quote_reserve;
let (min_base_asset_reserve, max_base_asset_reserve) =
amm::calculate_bid_ask_bounds(market.amm.concentration_coef, new_terminal_base_reserve)
.unwrap();
market.amm.min_base_asset_reserve = min_base_asset_reserve;
market.amm.max_base_asset_reserve = max_base_asset_reserve;
let oracle_price_data = OraclePriceData {
price: (17_800 * PRICE_PRECISION) as i64,
confidence: 10233,
delay: 2,
has_sufficient_number_of_data_points: true,
};
let (optimal_peg, budget, check_lb) =
calculate_optimal_peg_and_budget(&market, &oracle_price_data).unwrap();
assert_eq!(optimal_peg, 17796790576);
assert_eq!(optimal_peg > oracle_price_data.price as u128, false);
assert_eq!(budget, 0);
assert_eq!(check_lb, false); // because market.amm.total_fee_minus_distributions < get_total_fee_lower_bound(market)?.cast()
use crate::controller::repeg::*;
let state = State {
oracle_guard_rails: OracleGuardRails {
price_divergence: PriceDivergenceGuardRails {
mark_oracle_percent_divergence: 1,
oracle_twap_5min_percent_divergence: 10,
},
validity: ValidityGuardRails {
slots_before_stale_for_amm: 10, // 5s
slots_before_stale_for_margin: 120, // 60s
confidence_interval_max_size: 1000,
too_volatile_ratio: 5,
},
},
..State::default()
};
// test amm update
assert_eq!(market.amm.last_update_slot, 0);
let c = _update_amm(&mut market, &oracle_price_data, &state, 1, 1337).unwrap();
assert!(market.amm.is_recent_oracle_valid(1337).unwrap());
assert!(!market.amm.is_recent_oracle_valid(1338).unwrap());
assert!(!market.amm.is_recent_oracle_valid(1336).unwrap());
assert_eq!(c, 442);
assert_eq!(market.amm.last_update_slot, 1337);
}
#[test]
fn calc_adjust_amm_tests_repeg_in_favour() {
// btc-esque market
let market = PerpMarket {
amm: AMM {
base_asset_reserve: 65 * AMM_RESERVE_PRECISION,
quote_asset_reserve: 63015384615,
terminal_quote_asset_reserve: 64 * AMM_RESERVE_PRECISION,
sqrt_k: 64 * AMM_RESERVE_PRECISION,
peg_multiplier: 19_400_000_000,
base_asset_amount_with_amm: AMM_RESERVE_PRECISION as i128,
mark_std: PRICE_PRECISION as u64,
last_mark_price_twap_ts: 0,
curve_update_intensity: 100,
..AMM::default()
},
..PerpMarket::default()
};
let prev_price = market.amm.reserve_price().unwrap();
let px = 20_401_125_456;
let optimal_peg = calculate_peg_from_target_price(
market.amm.quote_asset_reserve,
market.amm.base_asset_reserve,
px,
)
.unwrap();
assert!(optimal_peg > market.amm.peg_multiplier);
let (repegged_market, _amm_update_cost) = adjust_amm(&market, optimal_peg, 0, true).unwrap();
assert_eq!(_amm_update_cost, -1618354580);
assert_eq!(repegged_market.amm.peg_multiplier, optimal_peg);
let post_price = repegged_market.amm.reserve_price().unwrap();
assert_eq!(post_price - prev_price, 1593456817); // todo: (15934564582252/1e4 - 1615699103 is the slippage cost?)
}
#[test]
fn calc_adjust_amm_tests_sufficent_fee_for_repeg() {
// btc-esque market
let mut market = PerpMarket {
amm: AMM {
order_step_size: 1000,
base_asset_reserve: 60437939720095,
quote_asset_reserve: 60440212459368,
terminal_quote_asset_reserve: 60439072663003,
sqrt_k: 60439076079049,
peg_multiplier: 34353000,
base_asset_amount_with_amm: AMM_RESERVE_PRECISION as i128,
last_mark_price_twap: 34128370,
last_mark_price_twap_ts: 165705,
curve_update_intensity: 100,
base_spread: 1000,
total_fee_minus_distributions: 304289,
total_fee: 607476,
total_exchange_fee: 0, // new fee pool lowerbound
funding_period: 3600,
concentration_coef: MAX_CONCENTRATION_COEFFICIENT,
..AMM::default()
},
next_curve_record_id: 1,
next_fill_record_id: 4,
margin_ratio_initial: 1000,
margin_ratio_maintenance: 500,
..PerpMarket::default()
};
let (new_terminal_quote_reserve, new_terminal_base_reserve) =
amm::calculate_terminal_reserves(&market.amm).unwrap();
market.amm.terminal_quote_asset_reserve = new_terminal_quote_reserve;
let (min_base_asset_reserve, max_base_asset_reserve) =
amm::calculate_bid_ask_bounds(market.amm.concentration_coef, new_terminal_base_reserve)
.unwrap();
market.amm.min_base_asset_reserve = min_base_asset_reserve;
market.amm.max_base_asset_reserve = max_base_asset_reserve;
let px = 35768 * PRICE_PRECISION_U64 / 1000;
let optimal_peg = calculate_peg_from_target_price(
market.amm.quote_asset_reserve,
market.amm.base_asset_reserve,
px,
)
.unwrap();
assert!(optimal_peg > market.amm.peg_multiplier);
let fee_budget = calculate_fee_pool(&market).unwrap();
assert!(fee_budget > 0);
let (repegged_market, _amm_update_cost) =
adjust_amm(&market, optimal_peg, fee_budget, true).unwrap();
// insufficient fee to repeg
let new_peg = repegged_market.amm.peg_multiplier;
let old_peg = market.amm.peg_multiplier;
assert!(new_peg > old_peg);
assert_eq!(new_peg, 34657283);
assert_eq!(_amm_update_cost, 304289);
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/fuel/tests.rs
|
mod calculate_perp_fuel_bonus {
use crate::math::fuel::calculate_perp_fuel_bonus;
use crate::state::perp_market::PerpMarket;
use crate::{FUEL_WINDOW_U128, QUOTE_PRECISION_I128};
#[test]
fn test() {
let perp_market = PerpMarket {
fuel_boost_position: 1,
..PerpMarket::default()
};
let bonus =
calculate_perp_fuel_bonus(&perp_market, QUOTE_PRECISION_I128, FUEL_WINDOW_U128 as i64)
.unwrap();
assert_eq!(bonus, 10);
}
}
mod calculate_spot_fuel_bonus {
use crate::math::fuel::calculate_spot_fuel_bonus;
use crate::state::spot_market::SpotMarket;
use crate::{FUEL_WINDOW_U128, QUOTE_PRECISION_I128};
#[test]
fn test() {
let mut spot_market = SpotMarket {
fuel_boost_deposits: 1,
..SpotMarket::default()
};
let bonus =
calculate_spot_fuel_bonus(&spot_market, QUOTE_PRECISION_I128, FUEL_WINDOW_U128 as i64)
.unwrap();
assert_eq!(bonus, 10);
spot_market.fuel_boost_borrows = 1;
let bonus =
calculate_spot_fuel_bonus(&spot_market, -QUOTE_PRECISION_I128, FUEL_WINDOW_U128 as i64)
.unwrap();
assert_eq!(bonus, 10);
}
}
mod calculate_insurance_fuel_bonus {
use crate::math::fuel::calculate_insurance_fuel_bonus;
use crate::state::spot_market::SpotMarket;
use crate::{FUEL_WINDOW_U128, QUOTE_PRECISION_U64};
#[test]
fn test() {
let spot_market = SpotMarket {
fuel_boost_insurance: 1,
..SpotMarket::default()
};
let bonus = calculate_insurance_fuel_bonus(
&spot_market,
QUOTE_PRECISION_U64,
0,
FUEL_WINDOW_U128 as u32,
)
.unwrap();
assert_eq!(bonus, 10);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/auction/tests.rs
|
mod calculate_auction_prices {
use crate::controller::position::PositionDirection;
use crate::math::auction::calculate_auction_prices;
use crate::math::constants::PRICE_PRECISION_I64;
use crate::state::oracle::OraclePriceData;
#[test]
fn no_limit_price_long() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Long;
let limit_price = 0;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 100500000);
}
#[test]
fn no_limit_price_short() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Short;
let limit_price = 0;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 99500000);
}
#[test]
fn limit_price_much_better_than_oracle_long() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Long;
let limit_price = 90000000;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 89550000);
assert_eq!(auction_end_price, 90000000);
}
#[test]
fn limit_price_slightly_better_than_oracle_long() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Long;
let limit_price = 99999999;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 99500000);
assert_eq!(auction_end_price, 99999999);
}
#[test]
fn limit_price_much_worse_than_oracle_long() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Long;
let limit_price = 110000000;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 100500000);
}
#[test]
fn limit_price_slightly_worse_than_oracle_long() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Long;
let limit_price = 100400000;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 100400000);
}
#[test]
fn limit_price_much_better_than_oracle_short() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Short;
let limit_price = 110000000;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 110550000);
assert_eq!(auction_end_price, 110000000);
}
#[test]
fn limit_price_slightly_better_than_oracle_short() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Short;
let limit_price = 100000001;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 100500001);
assert_eq!(auction_end_price, 100000001);
}
#[test]
fn limit_price_much_worse_than_oracle_short() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Short;
let limit_price = 90000000;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 99500000);
}
#[test]
fn limit_price_slightly_worse_than_oracle_short() {
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let position_direction = PositionDirection::Short;
let limit_price = 99999999;
let (auction_start_price, auction_end_price) =
calculate_auction_prices(&oracle_price_data, position_direction, limit_price).unwrap();
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 99999999);
}
}
mod calculate_auction_price {
use crate::math::auction::calculate_auction_price;
use crate::math::constants::{PRICE_PRECISION_I64, PRICE_PRECISION_U64};
use crate::state::user::{Order, OrderType};
use crate::PositionDirection;
#[test]
fn long_oracle_order() {
let tick_size = 1;
// auction starts $.10 below oracle and ends $.1 above oracle
let order = Order {
order_type: OrderType::Oracle,
auction_duration: 10,
slot: 0,
auction_start_price: -PRICE_PRECISION_I64 / 10,
auction_end_price: PRICE_PRECISION_I64 / 10,
..Order::default()
};
let oracle_price = Some(PRICE_PRECISION_I64);
let slot = 0;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 9 * PRICE_PRECISION_U64 / 10);
let slot = 5;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, PRICE_PRECISION_U64);
let slot = 10;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 11 * PRICE_PRECISION_U64 / 10);
// auction starts $.20 below oracle and ends $.1 below oracle
let order = Order {
order_type: OrderType::Oracle,
auction_duration: 10,
slot: 0,
auction_start_price: -PRICE_PRECISION_I64 / 5,
auction_end_price: -PRICE_PRECISION_I64 / 10,
..Order::default()
};
let slot = 0;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 8 * PRICE_PRECISION_U64 / 10);
let slot = 5;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 85 * PRICE_PRECISION_U64 / 100);
let slot = 10;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 9 * PRICE_PRECISION_U64 / 10);
// auction starts $.10 above oracle and ends $.2 above oracle
let order = Order {
order_type: OrderType::Oracle,
auction_duration: 10,
slot: 0,
auction_start_price: PRICE_PRECISION_I64 / 10,
auction_end_price: PRICE_PRECISION_I64 / 5,
..Order::default()
};
let slot = 0;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 11 * PRICE_PRECISION_U64 / 10);
let slot = 5;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 115 * PRICE_PRECISION_U64 / 100);
let slot = 10;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 12 * PRICE_PRECISION_U64 / 10);
}
#[test]
fn short_oracle_order() {
let tick_size = 1;
// auction starts $.10 above oracle and ends $.1 below oracle
let order = Order {
order_type: OrderType::Oracle,
auction_duration: 10,
slot: 0,
auction_start_price: PRICE_PRECISION_I64 / 10,
auction_end_price: -PRICE_PRECISION_I64 / 10,
..Order::default()
};
let oracle_price = Some(PRICE_PRECISION_I64);
let slot = 0;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 11 * PRICE_PRECISION_U64 / 10);
let slot = 5;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, PRICE_PRECISION_U64);
let slot = 10;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 9 * PRICE_PRECISION_U64 / 10);
// auction starts $.20 above oracle and ends $.1 above oracle
let order = Order {
order_type: OrderType::Oracle,
auction_duration: 10,
slot: 0,
auction_start_price: PRICE_PRECISION_I64 / 5,
auction_end_price: PRICE_PRECISION_I64 / 10,
..Order::default()
};
let slot = 0;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 12 * PRICE_PRECISION_U64 / 10);
let slot = 5;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 115 * PRICE_PRECISION_U64 / 100);
let slot = 10;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 11 * PRICE_PRECISION_U64 / 10);
// auction starts $.10 below oracle and ends $.2 below oracle
let order = Order {
order_type: OrderType::Oracle,
auction_duration: 10,
slot: 0,
auction_start_price: -PRICE_PRECISION_I64 / 10,
auction_end_price: -PRICE_PRECISION_I64 / 5,
..Order::default()
};
let slot = 0;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 9 * PRICE_PRECISION_U64 / 10);
let slot = 5;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 85 * PRICE_PRECISION_U64 / 100);
let slot = 10;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 8 * PRICE_PRECISION_U64 / 10);
}
#[test]
fn same_auction_start_and_end() {
let tick_size = 1;
let mut order = Order {
order_type: OrderType::Market,
direction: PositionDirection::Long,
auction_duration: 10,
slot: 0,
auction_start_price: PRICE_PRECISION_I64,
auction_end_price: PRICE_PRECISION_I64,
..Order::default()
};
let slot = 5;
let price = calculate_auction_price(&order, slot, tick_size, None, false).unwrap();
assert_eq!(price, PRICE_PRECISION_U64);
order.direction = PositionDirection::Short;
let price = calculate_auction_price(&order, slot, tick_size, None, false).unwrap();
assert_eq!(price, PRICE_PRECISION_U64);
let mut order = Order {
order_type: OrderType::Oracle,
direction: PositionDirection::Long,
auction_duration: 10,
slot: 0,
auction_start_price: PRICE_PRECISION_I64 / 2,
auction_end_price: PRICE_PRECISION_I64 / 2,
..Order::default()
};
let oracle_price = Some(PRICE_PRECISION_I64);
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 3 * PRICE_PRECISION_U64 / 2);
order.direction = PositionDirection::Short;
let price = calculate_auction_price(&order, slot, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 3 * PRICE_PRECISION_U64 / 2);
}
#[test]
fn long_order_with_auction_and_oracle_price_offset() {
let tick_size = 1;
let order = Order {
order_type: OrderType::Limit,
direction: PositionDirection::Long,
auction_duration: 10,
slot: 0,
auction_start_price: 100 * PRICE_PRECISION_I64 / 20, // 5% above oracle
auction_end_price: 100 * PRICE_PRECISION_I64 / 10, // 10% above oracle
oracle_price_offset: (100 * PRICE_PRECISION_I64 / 5) as i32, // 20% above oracle
..Order::default()
};
let oracle_price = Some(100 * PRICE_PRECISION_I64);
// At start of auction
let price = calculate_auction_price(&order, 0, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 105 * PRICE_PRECISION_U64);
// Midway through auction
let price = calculate_auction_price(&order, 5, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 107_5 * PRICE_PRECISION_U64 / 10);
// End of auction
let price = calculate_auction_price(&order, 10, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 110 * PRICE_PRECISION_U64);
}
#[test]
fn short_order_with_auction_and_oracle_price_offset() {
let tick_size = 1;
let order = Order {
order_type: OrderType::Limit,
direction: PositionDirection::Short,
auction_duration: 10,
slot: 0,
auction_start_price: -100 * PRICE_PRECISION_I64 / 20, // 5% below oracle
auction_end_price: -100 * PRICE_PRECISION_I64 / 10, // 10% below oracle
oracle_price_offset: (-100 * PRICE_PRECISION_I64 / 5) as i32, // 20% below oracle
..Order::default()
};
let oracle_price = Some(100 * PRICE_PRECISION_I64);
// At start of auction
let price = calculate_auction_price(&order, 0, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 95 * PRICE_PRECISION_U64);
// Midway through auction
let price = calculate_auction_price(&order, 5, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 92_5 * PRICE_PRECISION_U64 / 10);
// End of auction
let price = calculate_auction_price(&order, 10, tick_size, oracle_price, false).unwrap();
assert_eq!(price, 90 * PRICE_PRECISION_U64);
}
}
mod calculate_auction_params_for_trigger_order {
use crate::math::auction::calculate_auction_params_for_trigger_order;
use crate::state::oracle::OraclePriceData;
use crate::state::user::{Order, OrderType};
use crate::{PositionDirection, PRICE_PRECISION_I64, PRICE_PRECISION_U64};
#[test]
fn trigger_limit() {
let mut order = Order {
order_type: OrderType::TriggerLimit,
direction: PositionDirection::Long,
trigger_price: 100 * PRICE_PRECISION_U64,
price: 90 * PRICE_PRECISION_U64,
..Order::default()
};
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let min_auction_duration = 10;
order.direction = PositionDirection::Long;
order.price = 110 * PRICE_PRECISION_U64;
let (auction_duration, auction_start_price, auction_end_price) =
calculate_auction_params_for_trigger_order(
&order,
&oracle_price_data,
min_auction_duration,
None,
)
.unwrap();
assert_eq!(auction_duration, 10);
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 100500000);
order.direction = PositionDirection::Short;
order.price = 90 * PRICE_PRECISION_U64;
let (auction_duration, auction_start_price, auction_end_price) =
calculate_auction_params_for_trigger_order(
&order,
&oracle_price_data,
min_auction_duration,
None,
)
.unwrap();
assert_eq!(auction_duration, 10);
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 99500000);
}
#[test]
fn trigger_market() {
let mut order = Order {
order_type: OrderType::TriggerMarket,
direction: PositionDirection::Long,
trigger_price: 100 * PRICE_PRECISION_U64,
..Order::default()
};
let oracle_price_data = OraclePriceData {
price: 100 * PRICE_PRECISION_I64,
..OraclePriceData::default()
};
let min_auction_duration = 10;
let (auction_duration, auction_start_price, auction_end_price) =
calculate_auction_params_for_trigger_order(
&order,
&oracle_price_data,
min_auction_duration,
None,
)
.unwrap();
assert_eq!(auction_duration, 10);
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 100500000);
order.direction = PositionDirection::Short;
let (auction_duration, auction_start_price, auction_end_price) =
calculate_auction_params_for_trigger_order(
&order,
&oracle_price_data,
min_auction_duration,
None,
)
.unwrap();
assert_eq!(auction_duration, 10);
assert_eq!(auction_start_price, 100000000);
assert_eq!(auction_end_price, 99500000);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/fees/tests.rs
|
mod calculate_fee_for_taker_and_maker {
use crate::math::constants::QUOTE_PRECISION_U64;
use crate::math::fees::{calculate_fee_for_fulfillment_with_match, FillFees};
use crate::state::state::FeeStructure;
use crate::state::user::{MarketType, UserStats};
#[test]
fn no_filler() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let mut maker_stats = UserStats::default();
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&FeeStructure::test_default(),
0,
0,
0,
false,
&None,
&MarketType::Perp,
0,
false,
)
.unwrap();
assert_eq!(taker_fee, 100000);
assert_eq!(maker_rebate, 60000);
assert_eq!(fee_to_market, 40000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
}
#[test]
fn filler_size_reward() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let mut maker_stats = UserStats::default();
let mut fee_structure = FeeStructure::test_default();
fee_structure
.filler_reward_structure
.time_based_reward_lower_bound = 10000000000000000; // big number
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&fee_structure,
0,
0,
1,
false,
&None,
&MarketType::Perp,
0,
false,
)
.unwrap();
assert_eq!(taker_fee, 100000);
assert_eq!(maker_rebate, 60000);
assert_eq!(fee_to_market, 30000);
assert_eq!(filler_reward, 10000);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
}
#[test]
fn time_reward_no_time_passed() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let mut maker_stats = UserStats::default();
let mut fee_structure = FeeStructure::test_default();
fee_structure.filler_reward_structure.reward_numerator = 1; // will make size reward the whole fee
fee_structure.filler_reward_structure.reward_denominator = 1;
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&fee_structure,
0,
0,
1,
false,
&None,
&MarketType::Perp,
0,
false,
)
.unwrap();
assert_eq!(taker_fee, 100000);
assert_eq!(maker_rebate, 60000);
assert_eq!(fee_to_market, 30000);
assert_eq!(filler_reward, 10000);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
}
#[test]
fn time_reward_time_passed() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let mut maker_stats = UserStats::default();
let mut fee_structure = FeeStructure::test_default();
fee_structure.filler_reward_structure.reward_numerator = 1; // will make size reward the whole fee
fee_structure.filler_reward_structure.reward_denominator = 1;
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&fee_structure,
0,
60,
1,
false,
&None,
&MarketType::Perp,
0,
false,
)
.unwrap();
assert_eq!(taker_fee, 100000);
assert_eq!(maker_rebate, 60000);
assert_eq!(fee_to_market, 12200);
assert_eq!(filler_reward, 27800);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
}
#[test]
fn referrer() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let mut maker_stats = UserStats::default();
let fee_structure = FeeStructure::test_default();
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&fee_structure,
0,
0,
0,
true,
&None,
&MarketType::Perp,
0,
false,
)
.unwrap();
assert_eq!(taker_fee, 90000);
assert_eq!(maker_rebate, 60000);
assert_eq!(fee_to_market, 20000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 10000);
assert_eq!(referee_discount, 10000);
}
#[test]
fn fee_adjustment() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let mut maker_stats = UserStats::default();
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&FeeStructure::test_default(),
0,
0,
0,
false,
&None,
&MarketType::Perp,
-50,
false,
)
.unwrap();
assert_eq!(taker_fee, 50000);
assert_eq!(maker_rebate, 30000);
assert_eq!(fee_to_market, 20000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&FeeStructure::test_default(),
0,
0,
0,
false,
&None,
&MarketType::Perp,
50,
false,
)
.unwrap();
assert_eq!(taker_fee, 150000);
assert_eq!(maker_rebate, 90000);
assert_eq!(fee_to_market, 60000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
// reward referrer
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&FeeStructure::test_default(),
0,
0,
0,
true,
&None,
&MarketType::Perp,
-50,
false,
)
.unwrap();
assert_eq!(taker_fee, 45000);
assert_eq!(maker_rebate, 30000);
assert_eq!(fee_to_market, 10000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 5000);
assert_eq!(referee_discount, 5000);
// reward referrer + filler
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&FeeStructure::test_default(),
0,
0,
1,
true,
&None,
&MarketType::Perp,
-50,
false,
)
.unwrap();
assert_eq!(taker_fee, 45000);
assert_eq!(maker_rebate, 30000);
assert_eq!(fee_to_market, 5500);
assert_eq!(filler_reward, 4500);
assert_eq!(referrer_reward, 5000);
assert_eq!(referee_discount, 5000);
}
#[test]
fn high_leverage_mode() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let mut maker_stats = UserStats::default();
let FillFees {
user_fee: taker_fee,
maker_rebate,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_match(
&taker_stats,
&Some(&mut maker_stats),
quote_asset_amount,
&FeeStructure::test_default(),
0,
0,
1,
false,
&None,
&MarketType::Perp,
-50,
true,
)
.unwrap();
assert_eq!(taker_fee, 100000);
assert_eq!(maker_rebate, 30000);
assert_eq!(fee_to_market, 60000);
assert_eq!(filler_reward, 10000);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
}
}
mod calculate_fee_for_order_fulfill_against_amm {
use crate::math::constants::QUOTE_PRECISION_U64;
use crate::math::fees::{calculate_fee_for_fulfillment_with_amm, FillFees};
use crate::state::state::FeeStructure;
use crate::state::user::UserStats;
#[test]
fn referrer() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let fee_structure = FeeStructure::test_default();
let FillFees {
user_fee,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_amm(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
60,
false,
true,
&None,
0,
false,
0,
false,
)
.unwrap();
assert_eq!(user_fee, 90000);
assert_eq!(fee_to_market, 80000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 10000);
assert_eq!(referee_discount, 10000);
}
#[test]
fn fee_adjustment() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let fee_structure = FeeStructure::test_default();
let FillFees {
user_fee,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_amm(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
60,
false,
false,
&None,
0,
false,
-50,
false,
)
.unwrap();
assert_eq!(user_fee, 50000);
assert_eq!(fee_to_market, 50000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
let FillFees {
user_fee,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_amm(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
60,
false,
false,
&None,
0,
false,
50,
false,
)
.unwrap();
assert_eq!(user_fee, 150000);
assert_eq!(fee_to_market, 150000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
// reward referrer
let FillFees {
user_fee,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_amm(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
60,
false,
true,
&None,
0,
false,
-50,
false,
)
.unwrap();
assert_eq!(user_fee, 45000);
assert_eq!(fee_to_market, 40000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 5000);
assert_eq!(referee_discount, 5000);
// reward referrer + filler
let FillFees {
user_fee,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_amm(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
60,
true,
true,
&None,
0,
false,
-50,
false,
)
.unwrap();
assert_eq!(user_fee, 45000);
assert_eq!(fee_to_market, 35500);
assert_eq!(filler_reward, 4500);
assert_eq!(referrer_reward, 5000);
assert_eq!(referee_discount, 5000);
}
#[test]
fn high_leverage_mode() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let taker_stats = UserStats::default();
let fee_structure = FeeStructure::test_default();
let FillFees {
user_fee,
fee_to_market,
filler_reward,
referee_discount,
referrer_reward,
..
} = calculate_fee_for_fulfillment_with_amm(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
60,
false,
false,
&None,
0,
false,
-50,
true,
)
.unwrap();
assert_eq!(user_fee, 100000);
assert_eq!(fee_to_market, 100000);
assert_eq!(filler_reward, 0);
assert_eq!(referrer_reward, 0);
assert_eq!(referee_discount, 0);
}
}
mod calculate_fee_for_fulfillment_with_serum {
use crate::math::constants::QUOTE_PRECISION_U64;
use crate::math::fees::{calculate_fee_for_fulfillment_with_external_market, ExternalFillFees};
use crate::state::state::FeeStructure;
use crate::state::user::UserStats;
#[test]
fn no_filler() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let serum_fee = 32000_u64; // 3.2 bps
let serum_referrer_rebate = 8000_u64; // .8 bps
let fee_pool_token_amount = 0_u64;
let taker_stats = UserStats::default();
let fee_structure = FeeStructure::test_default();
let ExternalFillFees {
user_fee,
fee_to_market,
fee_pool_delta,
filler_reward,
} = calculate_fee_for_fulfillment_with_external_market(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
0,
false,
serum_fee,
serum_referrer_rebate,
fee_pool_token_amount,
0,
)
.unwrap();
assert_eq!(user_fee, 100000);
assert_eq!(fee_to_market, 68000);
assert_eq!(fee_pool_delta, 60000);
assert_eq!(filler_reward, 0);
}
#[test]
fn filler_reward_from_excess_user_fee() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let serum_fee = 32000_u64; // 3.2 bps
let serum_referrer_rebate = 8000_u64; // .8 bps
let fee_pool_token_amount = 0_u64;
let taker_stats = UserStats::default();
let fee_structure = FeeStructure::test_default();
let ExternalFillFees {
user_fee,
fee_to_market,
fee_pool_delta,
filler_reward,
} = calculate_fee_for_fulfillment_with_external_market(
&taker_stats,
quote_asset_amount,
&fee_structure,
0,
0,
true,
serum_fee,
serum_referrer_rebate,
fee_pool_token_amount,
0,
)
.unwrap();
assert_eq!(user_fee, 100000);
assert_eq!(fee_to_market, 58000);
assert_eq!(fee_pool_delta, 50000);
assert_eq!(filler_reward, 10000);
}
#[test]
fn filler_reward_from_fee_pool() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let serum_fee = 32000_u64; // 3.2 bps
let serum_referrer_rebate = 8000_u64; // .8 bps
let fee_pool_token_amount = 10000_u64;
let user_stats = UserStats::default();
let mut fee_structure = FeeStructure::test_default();
fee_structure.fee_tiers[0].fee_numerator = 4;
let ExternalFillFees {
user_fee,
fee_to_market,
fee_pool_delta,
filler_reward,
} = calculate_fee_for_fulfillment_with_external_market(
&user_stats,
quote_asset_amount,
&fee_structure,
0,
0,
true,
serum_fee,
serum_referrer_rebate,
fee_pool_token_amount,
0,
)
.unwrap();
assert_eq!(user_fee, 40000);
assert_eq!(fee_to_market, 0);
assert_eq!(fee_pool_delta, -8000);
assert_eq!(filler_reward, 8000);
}
#[test]
fn filler_reward_from_smaller_fee_pool() {
let quote_asset_amount = 100 * QUOTE_PRECISION_U64;
let serum_fee = 32000_u64; // 3.2 bps
let serum_referrer_rebate = 8000_u64; // .8 bps
let fee_pool_token_amount = 2000_u64;
let user_stats = UserStats::default();
let mut fee_structure = FeeStructure::test_default();
fee_structure.fee_tiers[0].fee_numerator = 4;
let ExternalFillFees {
user_fee,
fee_to_market,
fee_pool_delta,
filler_reward,
} = calculate_fee_for_fulfillment_with_external_market(
&user_stats,
quote_asset_amount,
&fee_structure,
0,
0,
true,
serum_fee,
serum_referrer_rebate,
fee_pool_token_amount,
0,
)
.unwrap();
assert_eq!(user_fee, 40000);
assert_eq!(fee_to_market, 6000);
assert_eq!(fee_pool_delta, -2000);
assert_eq!(filler_reward, 2000);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/liquidation/tests.rs
|
mod calculate_base_asset_amount_to_cover_margin_shortage {
use crate::math::constants::{
AMM_TO_QUOTE_PRECISION_RATIO, BASE_PRECISION_U64, LIQUIDATION_FEE_PRECISION,
LIQUIDATION_FEE_PRECISION_U128, MARGIN_PRECISION, MARGIN_PRECISION_U128, PRICE_PRECISION,
PRICE_PRECISION_I64, QUOTE_PRECISION,
};
use crate::math::liquidation::calculate_base_asset_amount_to_cover_margin_shortage;
#[test]
pub fn zero_percent_liquidation_fee() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let margin_ratio = MARGIN_PRECISION / 10; // 10x leverage
let liquidation_fee = 0; // 0 percent
let oracle_price = 100 * PRICE_PRECISION_I64; // $100 / base
let base_asset_amount = calculate_base_asset_amount_to_cover_margin_shortage(
margin_shortage,
margin_ratio,
liquidation_fee,
0,
oracle_price,
PRICE_PRECISION_I64,
)
.unwrap();
assert_eq!(base_asset_amount, BASE_PRECISION_U64); // must lose 1 base
}
#[test]
pub fn usdc_not_one() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let margin_ratio = MARGIN_PRECISION / 10; // 10x leverage
let liquidation_fee = 0; // 0 percent
let oracle_price = 100 * PRICE_PRECISION_I64; // $100 / base
let quote_oracle_price = 99 * 10000;
let base_asset_amount = calculate_base_asset_amount_to_cover_margin_shortage(
margin_shortage,
margin_ratio,
liquidation_fee,
0,
oracle_price,
quote_oracle_price,
)
.unwrap();
assert_eq!(base_asset_amount, 1010101010);
let quote_oracle_price = 101 * 10000;
let base_asset_amount = calculate_base_asset_amount_to_cover_margin_shortage(
margin_shortage,
margin_ratio,
liquidation_fee,
0,
oracle_price,
quote_oracle_price,
)
.unwrap();
assert_eq!(base_asset_amount, 990099009);
}
#[test]
pub fn one_percent_liquidation_fee() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let margin_ratio = MARGIN_PRECISION / 10; // 10x leverage
let liquidation_fee = LIQUIDATION_FEE_PRECISION / 100; // 1 percent
let oracle_price = 100 * PRICE_PRECISION_I64; // $100 / base
let base_asset_amount = calculate_base_asset_amount_to_cover_margin_shortage(
margin_shortage,
margin_ratio,
liquidation_fee,
0,
oracle_price,
PRICE_PRECISION_I64,
)
.unwrap();
let freed_collateral = (base_asset_amount as u128) * (oracle_price as u128)
/ PRICE_PRECISION
/ AMM_TO_QUOTE_PRECISION_RATIO
* margin_ratio as u128
/ MARGIN_PRECISION_U128;
let negative_pnl = (base_asset_amount as u128) * (oracle_price as u128)
/ PRICE_PRECISION
/ AMM_TO_QUOTE_PRECISION_RATIO
* liquidation_fee as u128
/ LIQUIDATION_FEE_PRECISION_U128;
assert_eq!(freed_collateral - negative_pnl, 10000000); // ~$10
assert_eq!(base_asset_amount, BASE_PRECISION_U64 * 10 / 9); // must lose 10/9 base
}
#[test]
pub fn one_percent_liquidation_fee_and_one_percent_if_liquidation_fee() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let margin_ratio = MARGIN_PRECISION / 10; // 10x leverage
let liquidation_fee = LIQUIDATION_FEE_PRECISION / 100; // 1 percent
let oracle_price = 100 * PRICE_PRECISION_I64; // $100 / base
let if_liquidation_fee = LIQUIDATION_FEE_PRECISION / 100; // 1 percent
let base_asset_amount = calculate_base_asset_amount_to_cover_margin_shortage(
margin_shortage,
margin_ratio,
liquidation_fee,
if_liquidation_fee,
oracle_price,
PRICE_PRECISION_I64,
)
.unwrap();
let if_fee = (base_asset_amount as u128) * (oracle_price as u128)
/ PRICE_PRECISION
/ AMM_TO_QUOTE_PRECISION_RATIO
* if_liquidation_fee as u128
/ LIQUIDATION_FEE_PRECISION_U128;
let freed_collateral = (base_asset_amount as u128) * (oracle_price as u128)
/ PRICE_PRECISION
/ AMM_TO_QUOTE_PRECISION_RATIO
* margin_ratio as u128
/ MARGIN_PRECISION_U128;
let negative_pnl = (base_asset_amount as u128) * (oracle_price as u128)
/ PRICE_PRECISION
/ AMM_TO_QUOTE_PRECISION_RATIO
* liquidation_fee as u128
/ LIQUIDATION_FEE_PRECISION_U128;
let if_fee_consume_collateral = if_fee;
assert_eq!(
freed_collateral - negative_pnl - if_fee_consume_collateral,
10000000 // ~$10
);
assert_eq!(base_asset_amount, 1250000000); // must lose 10/9 base
}
}
mod calculate_liability_transfer_to_cover_margin_shortage {
use crate::math::constants::{
LIQUIDATION_FEE_PRECISION, LIQUIDATION_FEE_PRECISION_U128, PRICE_PRECISION,
PRICE_PRECISION_I64, QUOTE_PRECISION, SPOT_WEIGHT_PRECISION, SPOT_WEIGHT_PRECISION_U128,
};
use crate::math::liquidation::calculate_liability_transfer_to_cover_margin_shortage;
#[test]
pub fn zero_asset_and_liability_fee() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let asset_weight = 8 * SPOT_WEIGHT_PRECISION / 10; // .8
let asset_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let liability_weight = 12 * SPOT_WEIGHT_PRECISION / 10; // 1.2
let liability_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let liability_transfer = calculate_liability_transfer_to_cover_margin_shortage(
margin_shortage,
asset_weight,
asset_liquidation_multiplier,
liability_weight,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
0,
)
.unwrap();
assert_eq!(liability_transfer, 250000000); // .25 base
}
#[test]
pub fn ten_percent_asset_and_liability_fee() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let asset_weight = 8 * SPOT_WEIGHT_PRECISION / 10; // .8
let asset_liquidation_multiplier = 110 * LIQUIDATION_FEE_PRECISION / 100;
let liability_weight = 12 * SPOT_WEIGHT_PRECISION / 10; // 1.2
let liability_liquidation_multiplier = 90 * LIQUIDATION_FEE_PRECISION / 100;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let liability_transfer = calculate_liability_transfer_to_cover_margin_shortage(
margin_shortage,
asset_weight,
asset_liquidation_multiplier,
liability_weight,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
0,
)
.unwrap();
assert_eq!(liability_transfer, 449984250);
}
#[test]
pub fn zero_asset_and_liability_fee_with_one_percent_if_fee() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let asset_weight = 8 * SPOT_WEIGHT_PRECISION / 10; // .8
let asset_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let liability_weight = 12 * SPOT_WEIGHT_PRECISION / 10; // 1.2
let liability_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let if_liquidation_fee = LIQUIDATION_FEE_PRECISION / 100;
let liability_transfer = calculate_liability_transfer_to_cover_margin_shortage(
margin_shortage,
asset_weight,
asset_liquidation_multiplier,
liability_weight,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
if_liquidation_fee,
)
.unwrap();
let if_fee =
liability_transfer * if_liquidation_fee as u128 / LIQUIDATION_FEE_PRECISION_U128;
let liability_transfer_freed_collateral =
liability_transfer * (liability_price as u128) / PRICE_PRECISION / 1000
* (liability_weight - asset_weight) as u128
/ SPOT_WEIGHT_PRECISION_U128;
let if_fee_consumed_collateral =
if_fee * (liability_price as u128) / PRICE_PRECISION / 1000 * liability_weight as u128
/ SPOT_WEIGHT_PRECISION_U128;
assert_eq!(
liability_transfer_freed_collateral - if_fee_consumed_collateral,
10000001
);
assert_eq!(liability_transfer, 257731958);
}
#[test]
pub fn ten_percent_asset_and_liability_fee_with_one_percent_if_fee() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let asset_weight = 8 * SPOT_WEIGHT_PRECISION / 10; // .8
let asset_liquidation_multiplier = 110 * LIQUIDATION_FEE_PRECISION / 100;
let liability_weight = 12 * SPOT_WEIGHT_PRECISION / 10; // 1.2
let liability_liquidation_multiplier = 90 * LIQUIDATION_FEE_PRECISION / 100;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let if_liquidation_fee = LIQUIDATION_FEE_PRECISION / 100;
let liability_transfer = calculate_liability_transfer_to_cover_margin_shortage(
margin_shortage,
asset_weight,
asset_liquidation_multiplier,
liability_weight,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
if_liquidation_fee,
)
.unwrap();
let if_fee =
liability_transfer * (if_liquidation_fee as u128) / LIQUIDATION_FEE_PRECISION_U128;
let liability_transfer_freed_collateral =
liability_transfer * (liability_price as u128) / PRICE_PRECISION / 1000
* (liability_weight as u128
- asset_weight as u128 * asset_liquidation_multiplier as u128
/ liability_liquidation_multiplier as u128)
/ SPOT_WEIGHT_PRECISION_U128;
let if_fee_consumed_collateral =
if_fee * (liability_price as u128) / PRICE_PRECISION / 1000
* (liability_weight as u128)
/ SPOT_WEIGHT_PRECISION_U128;
assert_eq!(
liability_transfer_freed_collateral - if_fee_consumed_collateral,
10003330 // ~$10
);
assert_eq!(liability_transfer, 475669504);
}
#[test]
pub fn liability_weight_component_less_than_asset_weight_component() {
let margin_shortage = 10 * QUOTE_PRECISION; // $10 shortage
let asset_weight = SPOT_WEIGHT_PRECISION; // .8
let asset_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let liability_weight = SPOT_WEIGHT_PRECISION; // 1
let liability_liquidation_multiplier = 75 * LIQUIDATION_FEE_PRECISION / 100; // .75
let liability_decimals = 6;
let liability_price = 100 * PRICE_PRECISION_I64;
let liability_transfer = calculate_liability_transfer_to_cover_margin_shortage(
margin_shortage,
asset_weight,
asset_liquidation_multiplier,
liability_weight,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
0,
)
.unwrap();
assert_eq!(liability_transfer, u128::MAX);
}
}
mod calculate_liability_transfer_implied_by_asset_amount {
use crate::math::constants::{LIQUIDATION_FEE_PRECISION, PRICE_PRECISION_I64, QUOTE_PRECISION};
use crate::math::liquidation::calculate_liability_transfer_implied_by_asset_amount;
#[test]
pub fn zero_asset_and_liability_fee() {
let asset_transfer = 10 * QUOTE_PRECISION; // $10
let asset_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let asset_price = PRICE_PRECISION_I64;
let liability_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let liability_transfer = calculate_liability_transfer_implied_by_asset_amount(
asset_transfer,
asset_liquidation_multiplier,
6,
asset_price,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
)
.unwrap();
assert_eq!(liability_transfer, 100000000); // .1 base
}
#[test]
pub fn one_percent_asset_and_liability_fee() {
let asset_transfer = 10 * QUOTE_PRECISION; // $10
let asset_liquidation_multiplier = 101 * LIQUIDATION_FEE_PRECISION / 100;
let asset_price = PRICE_PRECISION_I64;
let liability_liquidation_multiplier = 99 * LIQUIDATION_FEE_PRECISION / 100;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let liability_transfer = calculate_liability_transfer_implied_by_asset_amount(
asset_transfer,
asset_liquidation_multiplier,
6,
asset_price,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
)
.unwrap();
assert_eq!(liability_transfer, 98019802); // .1 base
}
}
mod calculate_asset_transfer_for_liability_transfer {
use crate::math::constants::{
BASE_PRECISION, LIQUIDATION_FEE_PRECISION, PRICE_PRECISION_I64, QUOTE_PRECISION,
};
use crate::math::liquidation::calculate_asset_transfer_for_liability_transfer;
#[test]
pub fn zero_asset_and_liability_fee() {
let asset_amount = 100 * QUOTE_PRECISION;
let asset_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let asset_price = PRICE_PRECISION_I64;
let liability_transfer = BASE_PRECISION;
let liability_liquidation_multiplier = LIQUIDATION_FEE_PRECISION;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let asset_transfer = calculate_asset_transfer_for_liability_transfer(
asset_amount,
asset_liquidation_multiplier,
6,
asset_price,
liability_transfer,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
)
.unwrap();
assert_eq!(asset_transfer, 100000000); // 100 quote
}
#[test]
pub fn one_percent_asset_and_liability_fee() {
let asset_amount = 200 * QUOTE_PRECISION;
let asset_liquidation_multiplier = 101 * LIQUIDATION_FEE_PRECISION / 100;
let asset_price = PRICE_PRECISION_I64;
let liability_transfer = BASE_PRECISION;
let liability_liquidation_multiplier = 99 * LIQUIDATION_FEE_PRECISION / 100;
let liability_decimals = 9;
let liability_price = 100 * PRICE_PRECISION_I64;
let asset_transfer = calculate_asset_transfer_for_liability_transfer(
asset_amount,
asset_liquidation_multiplier,
6,
asset_price,
liability_transfer,
liability_liquidation_multiplier,
liability_decimals,
liability_price,
)
.unwrap();
assert_eq!(asset_transfer, 102020202); // 100 quote
}
}
mod calculate_funding_rate_deltas_to_resolve_bankruptcy {
use crate::math::constants::{BASE_PRECISION_I128, QUOTE_PRECISION_I128};
use crate::math::liquidation::calculate_funding_rate_deltas_to_resolve_bankruptcy;
use crate::state::perp_market::{PerpMarket, AMM};
#[test]
fn total_base_asset_amount_is_zero() {
let loss = -QUOTE_PRECISION_I128;
let market = PerpMarket {
amm: AMM {
base_asset_amount_long: 0,
base_asset_amount_short: 0,
..AMM::default()
},
..PerpMarket::default()
};
assert!(calculate_funding_rate_deltas_to_resolve_bankruptcy(loss, &market).is_err());
}
#[test]
fn total_base_asset_amount_not_zero() {
let loss = -100 * QUOTE_PRECISION_I128;
let market = PerpMarket {
amm: AMM {
base_asset_amount_long: 7 * BASE_PRECISION_I128,
base_asset_amount_short: -4 * BASE_PRECISION_I128,
..AMM::default()
},
..PerpMarket::default()
};
let cumulative_funding_rate_delta =
calculate_funding_rate_deltas_to_resolve_bankruptcy(loss, &market).unwrap();
assert_eq!(cumulative_funding_rate_delta, 9090910000);
}
}
mod calculate_cumulative_deposit_interest_delta_to_resolve_bankruptcy {
use crate::math::constants::{
QUOTE_PRECISION, SPOT_BALANCE_PRECISION, SPOT_CUMULATIVE_INTEREST_PRECISION,
};
use crate::math::liquidation::calculate_cumulative_deposit_interest_delta_to_resolve_bankruptcy;
use crate::state::spot_market::SpotMarket;
#[test]
fn zero_total_deposits() {
let loss = 100 * QUOTE_PRECISION;
let spot_market = SpotMarket {
deposit_balance: 0,
cumulative_deposit_interest: 1111 * SPOT_CUMULATIVE_INTEREST_PRECISION / 1000,
..SpotMarket::default()
};
let delta =
calculate_cumulative_deposit_interest_delta_to_resolve_bankruptcy(loss, &spot_market)
.unwrap();
assert_eq!(delta, 0);
}
#[test]
fn non_zero_total_deposits() {
let loss = 11 * QUOTE_PRECISION;
let spot_market = SpotMarket {
deposit_balance: 120 * SPOT_BALANCE_PRECISION,
cumulative_deposit_interest: SPOT_CUMULATIVE_INTEREST_PRECISION,
decimals: 6,
..SpotMarket::default()
};
let delta =
calculate_cumulative_deposit_interest_delta_to_resolve_bankruptcy(loss, &spot_market)
.unwrap();
assert_eq!(delta, 916666667);
}
}
mod validate_transfer_satisfies_limit_price {
use crate::math::constants::{PRICE_PRECISION_U64, QUOTE_PRECISION};
use crate::math::liquidation::validate_transfer_satisfies_limit_price;
use anchor_lang::solana_program::native_token::LAMPORTS_PER_SOL;
#[test]
fn sol_asset_usdc_liability() {
let limit_price = PRICE_PRECISION_U64 / 100; // 1 SOL / $100 USD
let asset = LAMPORTS_PER_SOL as u128;
let asset_decimals = 9_u32;
let liability = 100 * QUOTE_PRECISION;
let liability_decimals = 6_u32;
assert!(validate_transfer_satisfies_limit_price(
asset,
liability,
asset_decimals,
liability_decimals,
Some(limit_price)
)
.is_ok());
let asset = asset / 10;
assert!(validate_transfer_satisfies_limit_price(
asset,
liability,
asset_decimals,
liability_decimals,
Some(limit_price)
)
.is_err());
}
#[test]
fn usdc_asset_sol_liability() {
let limit_price = PRICE_PRECISION_U64 * 100; // $100 / 1 SOL
let asset = 100 * QUOTE_PRECISION;
let asset_decimals = 6_u32;
let liability = LAMPORTS_PER_SOL as u128;
let liability_decimals = 9_u32;
assert!(validate_transfer_satisfies_limit_price(
asset,
liability,
asset_decimals,
liability_decimals,
Some(limit_price)
)
.is_ok());
let asset = asset / 10;
assert!(validate_transfer_satisfies_limit_price(
asset,
liability,
asset_decimals,
liability_decimals,
Some(limit_price)
)
.is_err());
}
}
mod calculate_perp_if_fee {
use crate::math::liquidation::calculate_perp_if_fee;
use crate::{
BASE_PRECISION_U64, LIQUIDATION_FEE_PRECISION, MARGIN_PRECISION, PRICE_PRECISION_I64,
QUOTE_PRECISION,
};
#[test]
fn test() {
let margin_shortage = 20 * QUOTE_PRECISION;
let oracle_price = 100 * PRICE_PRECISION_I64;
let quote_price = PRICE_PRECISION_I64;
let liquidator_fee = LIQUIDATION_FEE_PRECISION / 100; // 1%
let margin_ratio = MARGIN_PRECISION / 20; // 5%
let base_asset_amount = 10 * BASE_PRECISION_U64;
let max_if_fee = LIQUIDATION_FEE_PRECISION / 20; // 5%
let fee = calculate_perp_if_fee(
margin_shortage,
base_asset_amount,
margin_ratio,
liquidator_fee,
oracle_price,
quote_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 19000); // 2% * .95
let tiny_margin_shortage = QUOTE_PRECISION;
let fee = calculate_perp_if_fee(
tiny_margin_shortage,
base_asset_amount,
margin_ratio,
liquidator_fee,
oracle_price,
quote_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 37050); // 3.9% * .95
let huge_margin_shortage = 1000 * QUOTE_PRECISION;
let fee = calculate_perp_if_fee(
huge_margin_shortage,
base_asset_amount,
margin_ratio,
liquidator_fee,
oracle_price,
quote_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let large_liquidator_fee = LIQUIDATION_FEE_PRECISION / 10; // 10%
let fee = calculate_perp_if_fee(
margin_shortage,
base_asset_amount,
margin_ratio,
large_liquidator_fee,
oracle_price,
quote_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let zero_oracle_price = 0;
let fee = calculate_perp_if_fee(
margin_shortage,
base_asset_amount,
margin_ratio,
liquidator_fee,
zero_oracle_price,
quote_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let zero_quote_price = 0;
let fee = calculate_perp_if_fee(
margin_shortage,
base_asset_amount,
margin_ratio,
liquidator_fee,
oracle_price,
zero_quote_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let zero_base_asset_amount = 0;
let fee = calculate_perp_if_fee(
margin_shortage,
zero_base_asset_amount,
margin_ratio,
liquidator_fee,
oracle_price,
quote_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
}
}
mod calculate_spot_if_fee {
use crate::math::liquidation::calculate_spot_if_fee;
use crate::{
LIQUIDATION_FEE_PRECISION, PRICE_PRECISION_I64, QUOTE_PRECISION, SPOT_WEIGHT_PRECISION,
};
#[test]
fn test() {
let margin_shortage = 5 * QUOTE_PRECISION;
let oracle_price = 100 * PRICE_PRECISION_I64;
let asset_weight = SPOT_WEIGHT_PRECISION;
let asset_multiplier = 101 * LIQUIDATION_FEE_PRECISION / 100;
let liability_weight = 11 * SPOT_WEIGHT_PRECISION / 10;
let liability_multiplier = LIQUIDATION_FEE_PRECISION;
let decimals = 9_u32;
let token_amount = 10_u128.pow(decimals);
let max_if_fee = LIQUIDATION_FEE_PRECISION / 20; // 5%
let fee = calculate_spot_if_fee(
margin_shortage,
token_amount,
asset_weight,
asset_multiplier,
liability_weight,
liability_multiplier,
decimals,
oracle_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 36363); // 4% /1.1
let large_margin_shortage = 100 * QUOTE_PRECISION;
let fee = calculate_spot_if_fee(
large_margin_shortage,
token_amount,
asset_weight,
asset_multiplier,
liability_weight,
liability_multiplier,
decimals,
oracle_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let tiny_margin_shortage = QUOTE_PRECISION;
let fee = calculate_spot_if_fee(
tiny_margin_shortage,
token_amount,
asset_weight,
asset_multiplier,
liability_weight,
liability_multiplier,
decimals,
oracle_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, max_if_fee);
let large_asset_weight = SPOT_WEIGHT_PRECISION * 2;
let fee = calculate_spot_if_fee(
tiny_margin_shortage,
token_amount,
large_asset_weight,
asset_multiplier,
liability_weight,
liability_multiplier,
decimals,
oracle_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let zero_liability_weight = 0;
let fee = calculate_spot_if_fee(
margin_shortage,
token_amount,
asset_weight,
asset_multiplier,
zero_liability_weight,
liability_multiplier,
decimals,
oracle_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let zero_token_amount = 0;
let fee = calculate_spot_if_fee(
margin_shortage,
zero_token_amount,
asset_weight,
asset_multiplier,
liability_weight,
liability_multiplier,
decimals,
oracle_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
let zero_liability_multiplier = 0;
let fee = calculate_spot_if_fee(
margin_shortage,
token_amount,
asset_weight,
asset_multiplier,
liability_weight,
zero_liability_multiplier,
decimals,
oracle_price,
max_if_fee,
)
.unwrap();
assert_eq!(fee, 0);
}
}
mod calculate_max_pct_to_liquidate {
use crate::math::liquidation::calculate_max_pct_to_liquidate;
use crate::state::user::User;
use crate::{LIQUIDATION_PCT_PRECISION, QUOTE_PRECISION};
#[test]
fn test() {
let user = User::default();
let margin_shortage = 49 * QUOTE_PRECISION;
let pct = calculate_max_pct_to_liquidate(
&user,
margin_shortage,
1,
LIQUIDATION_PCT_PRECISION / 10,
10,
)
.unwrap();
assert_eq!(pct, LIQUIDATION_PCT_PRECISION);
}
}
mod get_liquidation_fee {
use crate::math::liquidation::get_liquidation_fee;
use crate::LIQUIDATION_FEE_PRECISION;
#[test]
fn test() {
let user_slot: u64 = 0;
let base_liq_fee: u32 = 2 * LIQUIDATION_FEE_PRECISION / 100;
let max_liq_fee: u32 = 5 * LIQUIDATION_FEE_PRECISION / 100;
// Huge slot difference
let curr_slot: u64 = 100000;
let fee = get_liquidation_fee(base_liq_fee, max_liq_fee, user_slot, curr_slot).unwrap();
assert_eq!(fee, max_liq_fee);
// Small slot difference within grace period
let curr_slot: u64 = 10;
let fee = get_liquidation_fee(base_liq_fee, max_liq_fee, user_slot, curr_slot).unwrap();
assert_eq!(fee, base_liq_fee);
// Successful increase
let target_liq_fee: u32 = 3 * LIQUIDATION_FEE_PRECISION / 100;
let curr_slot: u64 = 10000;
let fee = get_liquidation_fee(base_liq_fee, max_liq_fee, user_slot, curr_slot).unwrap();
assert_eq!(fee, target_liq_fee);
}
}
| 0
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math
|
solana_public_repos/drift-labs/protocol-v2/programs/drift/src/math/amm_jit/tests.rs
|
use crate::math::amm_jit::*;
use crate::state::perp_market::AMM;
#[test]
fn balanced_market_zero_jit() {
let market = PerpMarket {
amm: AMM {
base_asset_amount_with_amm: 0,
amm_jit_intensity: 100,
..AMM::default_test()
},
..PerpMarket::default()
};
let jit_base_asset_amount = 100;
let jit_amount = calculate_clamped_jit_base_asset_amount(
&market,
AMMLiquiditySplit::ProtocolOwned,
jit_base_asset_amount,
)
.unwrap();
assert_eq!(jit_amount, 0);
}
#[test]
fn balanced_market_zero_intensity() {
let market = PerpMarket {
amm: AMM {
base_asset_amount_with_amm: 100,
amm_jit_intensity: 0,
..AMM::default_test()
},
..PerpMarket::default()
};
let jit_base_asset_amount = 100;
let jit_amount = calculate_clamped_jit_base_asset_amount(
&market,
AMMLiquiditySplit::ProtocolOwned,
jit_base_asset_amount,
)
.unwrap();
assert_eq!(jit_amount, 0);
}
#[test]
fn balanced_market_full_intensity() {
let market = PerpMarket {
amm: AMM {
base_asset_amount_with_amm: 100,
amm_jit_intensity: 100,
..AMM::default_test()
},
..PerpMarket::default()
};
let jit_base_asset_amount = 100;
let jit_amount = calculate_clamped_jit_base_asset_amount(
&market,
AMMLiquiditySplit::ProtocolOwned,
jit_base_asset_amount,
)
.unwrap();
assert_eq!(jit_amount, 100);
}
#[test]
fn balanced_market_half_intensity() {
let market = PerpMarket {
amm: AMM {
base_asset_amount_with_amm: 100,
amm_jit_intensity: 50,
..AMM::default_test()
},
..PerpMarket::default()
};
let jit_base_asset_amount = 100;
let jit_amount = calculate_clamped_jit_base_asset_amount(
&market,
AMMLiquiditySplit::ProtocolOwned,
jit_base_asset_amount,
)
.unwrap();
assert_eq!(jit_amount, 50);
}
| 0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.