Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

program: add support for switchboard #878

Merged
merged 20 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3,146 changes: 2,931 additions & 215 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions programs/drift/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ phoenix-v1 = { git = "https://github.com/drift-labs/phoenix-v1", rev = "bf6b84",
solana-security-txt = "1.1.0"
static_assertions = "1.1.0"
drift-macros = { git = "https://github.com/drift-labs/drift-macros.git", rev = "c57d87" }
switchboard-solana = "0.27.26"
getrandom = { version = "0.2.2", features = ["custom"] }

[dev-dependencies]
bytes = "1.2.0"
Expand Down
5 changes: 5 additions & 0 deletions programs/drift/src/ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@ pub mod pyth_program {
declare_id!("gSbePebfvPy7tRqimPoVecS2UsBvYv46ynrzWocc92s");
}

pub mod switchboard_program {
use solana_program::declare_id;
declare_id!("SW1TCH7qEPTdLsDHRgPuMQjbQxKdH2aBStViMFnt64f");
}

pub mod bonk_oracle {
use solana_program::declare_id;
#[cfg(feature = "mainnet-beta")]
Expand Down
15 changes: 10 additions & 5 deletions programs/drift/src/instructions/admin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ use crate::state::fulfillment_params::serum::SerumContext;
use crate::state::fulfillment_params::serum::SerumV3FulfillmentConfig;
use crate::state::insurance_fund_stake::ProtocolIfSharesTransferConfig;
use crate::state::oracle::{
get_oracle_price, get_pyth_price, HistoricalIndexData, HistoricalOracleData, OraclePriceData,
OracleSource,
get_oracle_price, get_pyth_price, get_switchboard_price, HistoricalIndexData,
HistoricalOracleData, OraclePriceData, OracleSource,
};
use crate::state::paused_operations::{PerpOperation, SpotOperation};
use crate::state::perp_market::{
Expand Down Expand Up @@ -568,8 +568,13 @@ pub fn handle_initialize_perp_market(
(oracle_price, oracle_delay, QUOTE_PRECISION_I64)
}
OracleSource::Switchboard => {
msg!("Switchboard oracle cant be used for perp market");
return Err(ErrorCode::InvalidOracle.into());
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");
Expand Down Expand Up @@ -1101,7 +1106,7 @@ pub fn handle_update_amm_oracle_twap(ctx: Context<RepegCurve>) -> Result<()> {

let perp_market = &mut load_mut!(ctx.accounts.perp_market)?;
let price_oracle = &ctx.accounts.oracle;
let oracle_twap = perp_market.amm.get_oracle_twap(price_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
Expand Down
103 changes: 59 additions & 44 deletions programs/drift/src/state/oracle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ 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_solana::{AggregatorAccountData, SwitchboardDecimal};

use crate::math::safe_unwrap::SafeUnwrap;
use crate::validate;
Expand Down Expand Up @@ -143,10 +144,7 @@ pub fn get_oracle_price(
OracleSource::Pyth1K => get_pyth_price(price_oracle, clock_slot, 1000),
OracleSource::Pyth1M => get_pyth_price(price_oracle, clock_slot, 1000000),
OracleSource::PythStableCoin => get_pyth_stable_coin_price(price_oracle, clock_slot),
OracleSource::Switchboard => {
msg!("Switchboard oracle not yet supported");
Err(crate::error::ErrorCode::InvalidOracle)
}
OracleSource::Switchboard => get_switchboard_price(price_oracle, clock_slot),
OracleSource::QuoteAsset => Ok(OraclePriceData {
price: PRICE_PRECISION_I64,
confidence: 1,
Expand Down Expand Up @@ -231,46 +229,63 @@ pub fn get_pyth_stable_coin_price(
Ok(oracle_price_data)
}

// pub fn get_switchboard_price(
// _price_oracle: &AccountInfo,
// _clock_slot: u64,
// ) -> DriftResult<OraclePriceData> {
// updating solana/anchor cause this to make compiler complan
// fix when we're using switchboard again
// let aggregator_data = AggregatorAccountData::new(price_oracle)
// .or(Err(crate::error::ErrorCode::UnableToLoadOracle))?;
//
// let price = convert_switchboard_decimal(&aggregator_data.latest_confirmed_round.result)?;
// let confidence =
// convert_switchboard_decimal(&aggregator_data.latest_confirmed_round.std_deviation)?;
//
// // 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 {
// u128::MAX
// } else {
// let price_10bps = price
// .unsigned_abs()
// .safe_div(1000)
// ?;
// max(confidence.unsigned_abs(), price_10bps)
// };
//
// let delay: i64 = cast_to_i64(clock_slot)?
// .safe_sub(cast(
// aggregator_data.latest_confirmed_round.round_open_slot,
// )?)
// ?;
//
// 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_switchboard_price(
price_oracle: &AccountInfo,
clock_slot: u64,
) -> DriftResult<OraclePriceData> {
let aggregator_data_loader: AccountLoader<AggregatorAccountData> =
AccountLoader::try_from(price_oracle).or(Err(ErrorCode::UnableToLoadOracle))?;
let aggregator_data = aggregator_data_loader
.load()
.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)
Copy link
Member

@0xbigz 0xbigz Feb 16, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

doc link
perhaps should look into this instead of std_deviation?

};

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,
})
}

/// 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)
}
}

#[derive(Clone, Copy)]
pub struct StrictOraclePrice {
Expand Down
4 changes: 2 additions & 2 deletions programs/drift/src/state/oracle/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ fn pyth_1k() {
..AMM::default()
};

let twap = amm.get_oracle_twap(&oracle_account_info).unwrap();
let twap = amm.get_oracle_twap(&oracle_account_info, 0).unwrap();
assert_eq!(twap, Some(839));
}

Expand All @@ -55,6 +55,6 @@ fn pyth_1m() {
..AMM::default()
};

let twap = amm.get_oracle_twap(&oracle_account_info).unwrap();
let twap = amm.get_oracle_twap(&oracle_account_info, 0).unwrap();
assert_eq!(twap, Some(839400));
}
27 changes: 26 additions & 1 deletion programs/drift/src/state/oracle_map.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use crate::error::{DriftResult, ErrorCode};
use crate::ids::{bonk_oracle, pepe_oracle, pyth_program, usdc_oracle, usdt_oracle_mainnet};
use crate::ids::{
bonk_oracle, pepe_oracle, pyth_program, switchboard_program, usdc_oracle, usdt_oracle_mainnet,
};
use crate::math::constants::PRICE_PRECISION_I64;
use crate::math::oracle::{oracle_validity, OracleValidity};
use crate::state::oracle::{get_oracle_price, OraclePriceData, OracleSource};
Expand Down Expand Up @@ -183,6 +185,18 @@ impl<'a> OracleMap<'a> {
);

continue;
} else if account_info.owner == &switchboard_program::id() {
let account_info = account_info_iter.next().safe_unwrap()?;
let pubkey = account_info.key();

let oracle_source = OracleSource::Switchboard;
oracles.insert(
pubkey,
AccountInfoAndOracleSource {
account_info: account_info.clone(),
oracle_source,
},
);
}

break;
Expand Down Expand Up @@ -231,6 +245,17 @@ impl<'a> OracleMap<'a> {
oracle_source,
},
);
} else if account_info.owner == &switchboard_program::id() {
let pubkey = account_info.key();

let oracle_source = OracleSource::Switchboard;
oracles.insert(
pubkey,
AccountInfoAndOracleSource {
account_info: account_info.clone(),
oracle_source,
},
);
} else if account_info.key() != Pubkey::default() {
return Err(ErrorCode::InvalidOracle);
}
Expand Down
10 changes: 7 additions & 3 deletions programs/drift/src/state/perp_market.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use crate::math::safe_math::SafeMath;
use crate::math::stats;
use crate::state::events::OrderActionExplanation;

use crate::state::oracle::{HistoricalOracleData, OracleSource};
use crate::state::oracle::{get_switchboard_price, HistoricalOracleData, OracleSource};
use crate::state::spot_market::{AssetTier, SpotBalance, SpotBalanceType};
use crate::state::traits::{MarketIndexOffset, Size};
use crate::{AMM_TO_QUOTE_PRECISION_RATIO, PRICE_PRECISION};
Expand Down Expand Up @@ -1109,14 +1109,18 @@ impl AMM {
Ok(can_lower)
}

pub fn get_oracle_twap(&self, price_oracle: &AccountInfo) -> DriftResult<Option<i64>> {
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, 1)?))
}
OracleSource::Pyth1K => Ok(Some(self.get_pyth_twap(price_oracle, 1000)?)),
OracleSource::Pyth1M => Ok(Some(self.get_pyth_twap(price_oracle, 1000000)?)),
OracleSource::Switchboard => Ok(None),
OracleSource::Switchboard => Ok(Some(get_switchboard_price(price_oracle, slot)?.price)),
OracleSource::QuoteAsset => {
msg!("Can't get oracle twap for quote asset");
Err(ErrorCode::DefaultError)
Expand Down
Loading