Skip to content

Commit

Permalink
Revert "program: add support for switchboard (#878)"
Browse files Browse the repository at this point in the history
This reverts commit 6fd8756.
  • Loading branch information
crispheaney committed Mar 6, 2024
1 parent ebc2d88 commit 8bcefcb
Show file tree
Hide file tree
Showing 12 changed files with 441 additions and 11,599 deletions.
3,437 changes: 382 additions & 3,055 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 0 additions & 2 deletions programs/drift/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ 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: 0 additions & 5 deletions programs/drift/src/ids.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,6 @@ 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: 5 additions & 10 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, get_switchboard_price, HistoricalIndexData,
HistoricalOracleData, OraclePriceData, OracleSource,
get_oracle_price, get_pyth_price, HistoricalIndexData, HistoricalOracleData, OraclePriceData,
OracleSource,
};
use crate::state::paused_operations::{PerpOperation, SpotOperation};
use crate::state::perp_market::{
Expand Down Expand Up @@ -569,13 +569,8 @@ pub fn handle_initialize_perp_market(
(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)
msg!("Switchboard oracle cant be used for perp market");
return Err(ErrorCode::InvalidOracle.into());

Check warning on line 573 in programs/drift/src/instructions/admin.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/instructions/admin.rs#L572-L573

Added lines #L572 - L573 were not covered by tests
}
OracleSource::QuoteAsset => {
msg!("Quote asset oracle cant be used for perp market");
Expand Down Expand Up @@ -1107,7 +1102,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, clock.slot)?;
let oracle_twap = perp_market.amm.get_oracle_twap(price_oracle)?;

Check warning on line 1105 in programs/drift/src/instructions/admin.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/instructions/admin.rs#L1105

Added line #L1105 was not covered by tests

if let Some(oracle_twap) = oracle_twap {
let oracle_mark_gap_before = perp_market
Expand Down
103 changes: 44 additions & 59 deletions programs/drift/src/state/oracle.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ 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 @@ -147,7 +146,10 @@ 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 => get_switchboard_price(price_oracle, clock_slot),
OracleSource::Switchboard => {
msg!("Switchboard oracle not yet supported");
Err(crate::error::ErrorCode::InvalidOracle)

Check warning on line 151 in programs/drift/src/state/oracle.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/state/oracle.rs#L150-L151

Added lines #L150 - L151 were not covered by tests
}
OracleSource::QuoteAsset => Ok(OraclePriceData {
price: PRICE_PRECISION_I64,
confidence: 1,
Expand Down Expand Up @@ -237,63 +239,46 @@ pub fn get_pyth_stable_coin_price(
Ok(oracle_price_data)
}

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

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

#[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, 0).unwrap();
let twap = amm.get_oracle_twap(&oracle_account_info).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, 0).unwrap();
let twap = amm.get_oracle_twap(&oracle_account_info).unwrap();
assert_eq!(twap, Some(839400));
}
27 changes: 1 addition & 26 deletions programs/drift/src/state/oracle_map.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
use crate::error::{DriftResult, ErrorCode};
use crate::ids::{
bonk_oracle, pepe_oracle, pyth_program, switchboard_program, usdc_oracle, usdt_oracle_mainnet,
};
use crate::ids::{bonk_oracle, pepe_oracle, pyth_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 @@ -194,18 +192,6 @@ 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 @@ -254,17 +240,6 @@ 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: 3 additions & 7 deletions programs/drift/src/state/perp_market.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ use crate::math::safe_math::SafeMath;
use crate::math::stats;
use crate::state::events::OrderActionExplanation;

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

pub fn get_oracle_twap(
&self,
price_oracle: &AccountInfo,
slot: u64,
) -> DriftResult<Option<i64>> {
pub fn get_oracle_twap(&self, price_oracle: &AccountInfo) -> 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(Some(get_switchboard_price(price_oracle, slot)?.price)),
OracleSource::Switchboard => Ok(None),

Check warning on line 1210 in programs/drift/src/state/perp_market.rs

View check run for this annotation

Codecov / codecov/patch

programs/drift/src/state/perp_market.rs#L1210

Added line #L1210 was not covered by tests
OracleSource::QuoteAsset => {
msg!("Can't get oracle twap for quote asset");
Err(ErrorCode::DefaultError)
Expand Down
7 changes: 3 additions & 4 deletions sdk/src/factory/oracleClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { PythClient } from '../oracles/pythClient';
// import { SwitchboardClient } from '../oracles/switchboardClient';
import { QuoteAssetOracleClient } from '../oracles/quoteAssetOracleClient';
import { BN } from '@coral-xyz/anchor';
import { SwitchboardClient } from '../oracles/switchboardClient';

export function getOracleClient(
oracleSource: OracleSource,
Expand All @@ -27,9 +26,9 @@ export function getOracleClient(
return new PythClient(connection, undefined, true);
}

if (isVariant(oracleSource, 'switchboard')) {
return new SwitchboardClient(connection);
}
// if (isVariant(oracleSource, 'switchboard')) {
// return new SwitchboardClient(connection);
// }

if (isVariant(oracleSource, 'quoteAsset')) {
return new QuoteAssetOracleClient();
Expand Down
Loading

0 comments on commit 8bcefcb

Please sign in to comment.