diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 466e630e5..d79114f78 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -17,5 +17,5 @@ repos: - id: cargo-clippy name: Cargo clippy language: "rust" - entry : cargo +nightly clippy -- -D warnings + entry : cargo +nightly clippy --tests -- -D warnings pass_filenames : false diff --git a/program/rust/build.rs b/program/rust/build.rs index 42bfff8ec..e1fb226ab 100644 --- a/program/rust/build.rs +++ b/program/rust/build.rs @@ -4,10 +4,10 @@ use bindgen::Builder; fn main() { println!("cargo:rustc-link-search=./program/c/target"); - //make a parser and to it type, traits pairs + // Make a parser and to it type, traits pairs let parser = build_utils::DeriveAdderParserCallback::new(); - //generate and write bindings + // Generate and write bindings let bindings = Builder::default() .clang_arg("-I../../../solana/sdk/bpf/c/inc/") .header("./src/bindings.h") diff --git a/program/rust/build_utils.rs b/program/rust/build_utils.rs index 6767fdd38..53c6f2d86 100644 --- a/program/rust/build_utils.rs +++ b/program/rust/build_utils.rs @@ -1,30 +1,32 @@ -use bindgen::callbacks::ParseCallbacks; -use std::collections::HashMap; -use std::panic::UnwindSafe; +use { + bindgen::callbacks::ParseCallbacks, + std::{ + collections::HashMap, + panic::UnwindSafe, + }, +}; -///This type stores a hashmap from structnames -///to vectors of trait names, and ensures -///that the traits of each struct are added to its -///definition when an instance of this struct -///is provided as a ParseCallback for bindgen +/// This type stores a hashmap from structnames to vectors of trait names, and ensures that the +/// traits of each struct are added to its definition when an instance of this struct is provided +/// as a ParseCallback for bindgen #[derive(Debug, Default)] pub struct DeriveAdderParserCallback<'a> { pub types_to_traits: HashMap<&'a str, Vec>, } impl<'a> DeriveAdderParserCallback<'a> { - ///create a parser that does not add any traits + /// Create a parser that does not add any traits pub fn new() -> Self { Default::default() } - //add pairs of types and their desired traits + /// Add pairs of types and their desired traits #[allow(dead_code)] pub fn register_traits(&mut self, type_name: &'a str, traits: Vec) { self.types_to_traits.insert(type_name, traits); } } -//this is required to implement the callback trait +/// This is required to implement the callback trait. impl UnwindSafe for DeriveAdderParserCallback<'_> { } diff --git a/program/rust/src/c_oracle_header.rs b/program/rust/src/c_oracle_header.rs index e8537b7c5..e45f04a84 100644 --- a/program/rust/src/c_oracle_header.rs +++ b/program/rust/src/c_oracle_header.rs @@ -1,18 +1,19 @@ #![allow(non_camel_case_types)] #![allow(non_snake_case)] -//we do not use all the variables in oracle.h, so this helps with the warnings +// We do not use all the variables in oracle.h, so this helps with the warnings #![allow(dead_code)] -//All the custom trait imports should go here -use bytemuck::{ - Pod, - Zeroable, +// All the custom trait imports should go here +use { + crate::instruction::OracleCommand, + bytemuck::{ + Pod, + Zeroable, + }, + solana_program::pubkey::Pubkey, + std::mem::size_of, }; -use solana_program::pubkey::Pubkey; -use std::mem::size_of; -use crate::instruction::OracleCommand; -//bindings.rs is generated by build.rs to include -//things defined in bindings.h +// Bindings.rs is generated by build.rs to include things defined in bindings.h include!("../bindings.rs"); pub const PERMISSIONS_SEED: &str = "permissions"; @@ -21,6 +22,7 @@ pub const PERMISSIONS_SEED: &str = "permissions"; /// If ci > price / PC_MAX_CI_DIVISOR, set publisher status to unknown. /// (e.g., 20 means ci must be < 5% of price) pub const MAX_CI_DIVISOR: i64 = 20; + /// Bound on the range of the exponent in price accounts. This number is set such that the /// PD-based EMA computation does not lose too much precision. pub const MAX_NUM_DECIMALS: i32 = 8; diff --git a/program/rust/src/deserialize.rs b/program/rust/src/deserialize.rs index e7772168e..1ede25495 100644 --- a/program/rust/src/deserialize.rs +++ b/program/rust/src/deserialize.rs @@ -1,32 +1,38 @@ -use std::mem::size_of; - -use bytemuck::{ - try_from_bytes, - try_from_bytes_mut, - Pod, -}; -use solana_program::pubkey::Pubkey; - -use crate::c_oracle_header::{ - AccountHeader, - PythAccount, - PC_MAGIC, -}; -use crate::error::OracleError; -use crate::utils::{ - allocate_data, - assign_owner, - check_valid_fresh_account, - clear_account, - get_rent, - pyth_assert, - send_lamports, -}; -use solana_program::account_info::AccountInfo; -use solana_program::program_error::ProgramError; -use std::cell::{ - Ref, - RefMut, +use { + crate::{ + c_oracle_header::{ + AccountHeader, + PythAccount, + PC_MAGIC, + }, + error::OracleError, + utils::{ + allocate_data, + assign_owner, + check_valid_fresh_account, + clear_account, + get_rent, + pyth_assert, + send_lamports, + }, + }, + bytemuck::{ + try_from_bytes, + try_from_bytes_mut, + Pod, + }, + solana_program::{ + account_info::AccountInfo, + program_error::ProgramError, + pubkey::Pubkey, + }, + std::{ + cell::{ + Ref, + RefMut, + }, + mem::size_of, + }, }; /// Interpret the bytes in `data` as a value of type `T` diff --git a/program/rust/src/error.rs b/program/rust/src/error.rs index 369a3cb26..8604ba9ff 100644 --- a/program/rust/src/error.rs +++ b/program/rust/src/error.rs @@ -1,6 +1,8 @@ //! Error types -use solana_program::program_error::ProgramError; -use thiserror::Error; +use { + solana_program::program_error::ProgramError, + thiserror::Error, +}; /// Errors that may be returned by the oracle program #[derive(Clone, Debug, Eq, Error, PartialEq)] diff --git a/program/rust/src/instruction.rs b/program/rust/src/instruction.rs index 7853a35d6..d97d7d769 100644 --- a/program/rust/src/instruction.rs +++ b/program/rust/src/instruction.rs @@ -1,16 +1,20 @@ -use crate::c_oracle_header::PC_VERSION; -use crate::deserialize::load; -use crate::error::OracleError; -use bytemuck::{ - Pod, - Zeroable, +use { + crate::{ + c_oracle_header::PC_VERSION, + deserialize::load, + error::OracleError, + }, + bytemuck::{ + Pod, + Zeroable, + }, + num_derive::{ + FromPrimitive, + ToPrimitive, + }, + num_traits::FromPrimitive, + solana_program::pubkey::Pubkey, }; -use num_derive::{ - FromPrimitive, - ToPrimitive, -}; -use num_traits::FromPrimitive; -use solana_program::pubkey::Pubkey; /// WARNING : NEW COMMANDS SHOULD BE ADDED AT THE END OF THE LIST #[repr(i32)] diff --git a/program/rust/src/lib.rs b/program/rust/src/lib.rs index 54190d79d..3ded58934 100644 --- a/program/rust/src/lib.rs +++ b/program/rust/src/lib.rs @@ -17,24 +17,25 @@ mod tests; #[cfg(feature = "debug")] mod log; -use crate::error::OracleError; -use processor::process_instruction; - -use solana_program::entrypoint; - -//Below is a high lever description of the rust/c setup. - -//As we migrate from C to Rust, our Rust code needs to be able to interact with C -//build-bpf.sh is set up to compile the C code into a two archive files -//contained in `./program/c/target/` -// - `libcpyth-bpf.a` contains the bpf version for production code -// - `libcpyth-native.a` contains the systems architecture version for tests - -//We also generate bindings for the types and constants in oracle.h (as well as other things -//included in bindings.h), these bindings can be accessed through c_oracle_header.rs -//Bindings allow us to access type definitions, function definitions and constants. In order to -//add traits to the bindings, we use the parser in build.rs. The traits must be defined/included -//at the the top of c_oracle_headers.rs. One of the most important traits we deal are the Borsh -//serialization traits. +use { + crate::error::OracleError, + processor::process_instruction, + solana_program::entrypoint, +}; + +// Below is a high lever description of the rust/c setup. + +// As we migrate from C to Rust, our Rust code needs to be able to interact with C +// build-bpf.sh is set up to compile the C code into a two archive files +// contained in `./program/c/target/` +// - `libcpyth-bpf.a` contains the bpf version for production code +// - `libcpyth-native.a` contains the systems architecture version for tests + +// We also generate bindings for the types and constants in oracle.h (as well as other things +// included in bindings.h), these bindings can be accessed through c_oracle_header.rs +// Bindings allow us to access type definitions, function definitions and constants. In order to +// add traits to the bindings, we use the parser in build.rs. The traits must be defined/included +// at the the top of c_oracle_headers.rs. One of the most important traits we deal are the Borsh +// serialization traits. entrypoint!(process_instruction); diff --git a/program/rust/src/log.rs b/program/rust/src/log.rs index 7ca8e3fed..af6cfd0da 100644 --- a/program/rust/src/log.rs +++ b/program/rust/src/log.rs @@ -1,15 +1,21 @@ -use crate::c_oracle_header::*; -use crate::deserialize::{ - load, - load_account_as, +use { + crate::{ + c_oracle_header::*, + deserialize::{ + load, + load_account_as, + }, + error::OracleError, + }, + solana_program::{ + account_info::AccountInfo, + clock::Clock, + entrypoint::ProgramResult, + msg, + program_error::ProgramError, + sysvar::Sysvar, + }, }; -use crate::error::OracleError; -use solana_program::account_info::AccountInfo; -use solana_program::clock::Clock; -use solana_program::entrypoint::ProgramResult; -use solana_program::msg; -use solana_program::program_error::ProgramError; -use solana_program::sysvar::Sysvar; pub fn pre_log(accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResult { msg!("Pyth oracle contract"); @@ -87,7 +93,7 @@ pub fn pre_log(accounts: &[AccountInfo], instruction_data: &[u8]) -> ProgramResu } command_t_e_cmd_resize_price_account => { - //accounts[1] is the updated account + // accounts[1] is the updated account msg!("ResizePriceAccount: {}", accounts[1].key); } _ => { diff --git a/program/rust/src/processor.rs b/program/rust/src/processor.rs index e1751caf4..8aefe4623 100644 --- a/program/rust/src/processor.rs +++ b/program/rust/src/processor.rs @@ -1,31 +1,36 @@ -use crate::error::OracleError; -use crate::instruction::{ - load_command_header_checked, - OracleCommand, +use { + crate::{ + error::OracleError, + instruction::{ + load_command_header_checked, + OracleCommand, + }, + rust_oracle::{ + add_mapping, + add_price, + add_product, + add_publisher, + del_price, + del_product, + del_publisher, + init_mapping, + init_price, + resize_price_account, + set_min_pub, + upd_permissions, + upd_price, + upd_price_no_fail_on_error, + upd_product, + }, + }, + solana_program::{ + entrypoint::ProgramResult, + pubkey::Pubkey, + sysvar::slot_history::AccountInfo, + }, }; -use solana_program::entrypoint::ProgramResult; -use solana_program::pubkey::Pubkey; -use solana_program::sysvar::slot_history::AccountInfo; -use crate::rust_oracle::{ - add_mapping, - add_price, - add_product, - add_publisher, - del_price, - del_product, - del_publisher, - init_mapping, - init_price, - resize_price_account, - set_min_pub, - upd_permissions, - upd_price, - upd_price_no_fail_on_error, - upd_product, -}; - -///dispatch to the right instruction in the oracle +/// Dispatch to the right instruction in the oracle. pub fn process_instruction( program_id: &Pubkey, accounts: &[AccountInfo], diff --git a/program/rust/src/rust_oracle.rs b/program/rust/src/rust_oracle.rs index d7f200315..b6e0148f8 100644 --- a/program/rust/src/rust_oracle.rs +++ b/program/rust/src/rust_oracle.rs @@ -1,72 +1,76 @@ -use std::mem::{ - size_of, - size_of_val, +use { + crate::{ + c_oracle_header::{ + MappingAccount, + PermissionAccount, + PriceAccount, + PriceComponent, + PriceEma, + PriceInfo, + ProductAccount, + PythAccount, + MAX_CI_DIVISOR, + PC_COMP_SIZE, + PC_MAP_TABLE_SIZE, + PC_PROD_ACC_SIZE, + PC_PTYPE_UNKNOWN, + PC_STATUS_UNKNOWN, + PC_VERSION, + PERMISSIONS_SEED, + }, + deserialize::{ + create_pda_if_needed, + initialize_pyth_account_checked, + load, + load_checked, + }, + instruction::{ + AddPriceArgs, + AddPublisherArgs, + CommandHeader, + DelPublisherArgs, + InitPriceArgs, + SetMinPubArgs, + UpdPermissionsArgs, + UpdPriceArgs, + }, + time_machine_types::PriceAccountWrapper, + utils::{ + check_exponent_range, + check_is_upgrade_authority_for_program, + check_valid_funding_account, + check_valid_signable_account_or_permissioned_funding_account, + check_valid_writable_account, + get_rent, + is_component_update, + pyth_assert, + read_pc_str_t, + send_lamports, + try_convert, + }, + OracleError, + }, + bytemuck::bytes_of_mut, + solana_program::{ + account_info::AccountInfo, + clock::Clock, + entrypoint::ProgramResult, + program_error::ProgramError, + program_memory::{ + sol_memcpy, + sol_memset, + }, + pubkey::Pubkey, + rent::Rent, + system_program::check_id, + sysvar::Sysvar, + }, + std::mem::{ + size_of, + size_of_val, + }, }; -use crate::c_oracle_header::{ - MappingAccount, - PermissionAccount, - PriceAccount, - PriceComponent, - PriceEma, - PriceInfo, - ProductAccount, - PythAccount, - MAX_CI_DIVISOR, - PC_COMP_SIZE, - PC_MAP_TABLE_SIZE, - PC_PROD_ACC_SIZE, - PC_PTYPE_UNKNOWN, - PC_STATUS_UNKNOWN, - PC_VERSION, - PERMISSIONS_SEED, -}; - -use crate::deserialize::{ - create_pda_if_needed, - initialize_pyth_account_checked, - load, - load_checked, -}; -use crate::instruction::{ - AddPriceArgs, - AddPublisherArgs, - CommandHeader, - DelPublisherArgs, - InitPriceArgs, - SetMinPubArgs, - UpdPermissionsArgs, - UpdPriceArgs, -}; -use crate::time_machine_types::PriceAccountWrapper; -use crate::utils::{ - check_exponent_range, - check_is_upgrade_authority_for_program, - check_valid_funding_account, - check_valid_signable_account_or_permissioned_funding_account, - check_valid_writable_account, - get_rent, - is_component_update, - pyth_assert, - read_pc_str_t, - send_lamports, - try_convert, -}; -use crate::OracleError; -use bytemuck::bytes_of_mut; -use solana_program::account_info::AccountInfo; -use solana_program::clock::Clock; -use solana_program::entrypoint::ProgramResult; -use solana_program::program_error::ProgramError; -use solana_program::program_memory::{ - sol_memcpy, - sol_memset, -}; -use solana_program::pubkey::Pubkey; -use solana_program::rent::Rent; -use solana_program::system_program::check_id; -use solana_program::sysvar::Sysvar; - #[cfg(target_arch = "bpf")] #[link(name = "cpyth-bpf")] diff --git a/program/rust/src/tests/pyth_simulator.rs b/program/rust/src/tests/pyth_simulator.rs index 9448e3e91..b9314ed22 100644 --- a/program/rust/src/tests/pyth_simulator.rs +++ b/program/rust/src/tests/pyth_simulator.rs @@ -1,54 +1,60 @@ -use std::mem::size_of; -use std::path::Path; - -use bytemuck::{ - bytes_of, - Pod, -}; -use solana_program::bpf_loader_upgradeable::{ - self, - UpgradeableLoaderState, -}; -use solana_program::hash::Hash; -use solana_program::instruction::{ - AccountMeta, - Instruction, -}; -use solana_program::native_token::LAMPORTS_PER_SOL; -use solana_program::pubkey::Pubkey; -use solana_program::rent::Rent; -use solana_program::stake_history::Epoch; -use solana_program::{ - system_instruction, - system_program, -}; -use solana_program_test::{ - read_file, - BanksClient, - BanksClientError, - ProgramTest, - ProgramTestBanksClientExt, -}; -use solana_sdk::account::Account; -use solana_sdk::signature::{ - Keypair, - Signer, -}; -use solana_sdk::transaction::Transaction; - -use crate::c_oracle_header::{ - MappingAccount, - PriceAccount, - PC_PROD_ACC_SIZE, - PC_PTYPE_PRICE, - PERMISSIONS_SEED, -}; -use crate::deserialize::load; -use crate::instruction::{ - AddPriceArgs, - CommandHeader, - OracleCommand, - UpdPermissionsArgs, +use { + crate::{ + c_oracle_header::{ + MappingAccount, + PriceAccount, + PC_PROD_ACC_SIZE, + PC_PTYPE_PRICE, + PERMISSIONS_SEED, + }, + deserialize::load, + instruction::{ + AddPriceArgs, + CommandHeader, + OracleCommand, + UpdPermissionsArgs, + }, + }, + bytemuck::{ + bytes_of, + Pod, + }, + solana_program::{ + bpf_loader_upgradeable::{ + self, + UpgradeableLoaderState, + }, + hash::Hash, + instruction::{ + AccountMeta, + Instruction, + }, + native_token::LAMPORTS_PER_SOL, + pubkey::Pubkey, + rent::Rent, + stake_history::Epoch, + system_instruction, + system_program, + }, + solana_program_test::{ + read_file, + BanksClient, + BanksClientError, + ProgramTest, + ProgramTestBanksClientExt, + }, + solana_sdk::{ + account::Account, + signature::{ + Keypair, + Signer, + }, + transaction::Transaction, + }, + std::{ + mem::size_of, + path::Path, + }, }; @@ -134,7 +140,7 @@ impl PythSimulator { .await .unwrap(); - return result; + result } @@ -230,7 +236,7 @@ impl PythSimulator { self.process_ix( instruction, - &vec![&mapping_keypair, &product_keypair], + &vec![mapping_keypair, &product_keypair], ©_keypair(&self.genesis_keypair), ) .await @@ -256,7 +262,7 @@ impl PythSimulator { self.process_ix( instruction, - &vec![&mapping_keypair, &product_keypair], + &vec![mapping_keypair, product_keypair], ©_keypair(&self.genesis_keypair), ) .await @@ -288,7 +294,7 @@ impl PythSimulator { self.process_ix( instruction, - &vec![&product_keypair, &price_keypair], + &vec![product_keypair, &price_keypair], ©_keypair(&self.genesis_keypair), ) .await @@ -314,7 +320,7 @@ impl PythSimulator { self.process_ix( instruction, - &vec![&product_keypair, &price_keypair], + &vec![product_keypair, price_keypair], ©_keypair(&self.genesis_keypair), ) .await @@ -339,7 +345,7 @@ impl PythSimulator { self.process_ix( instruction, - &vec![&price_keypair], + &vec![price_keypair], ©_keypair(&self.genesis_keypair), ) .await @@ -385,7 +391,7 @@ impl PythSimulator { pub async fn get_account_data_as(&mut self, key: Pubkey) -> Option { self.get_account(key) .await - .map(|x| load::(&x.data).unwrap().clone()) + .map(|x| *load::(&x.data).unwrap()) } pub fn is_owned_by_oracle(&self, account: &Account) -> bool { @@ -403,10 +409,10 @@ impl PythSimulator { pub fn get_permissions_pubkey(&self) -> Pubkey { let (permissions_pubkey, __bump) = Pubkey::find_program_address(&[PERMISSIONS_SEED.as_bytes()], &self.program_id); - return permissions_pubkey; + permissions_pubkey } } pub fn copy_keypair(keypair: &Keypair) -> Keypair { - return Keypair::from_bytes(&keypair.to_bytes()).unwrap(); + Keypair::from_bytes(&keypair.to_bytes()).unwrap() } diff --git a/program/rust/src/tests/test_add_mapping.rs b/program/rust/src/tests/test_add_mapping.rs index ddb6f2f47..087ce94a1 100644 --- a/program/rust/src/tests/test_add_mapping.rs +++ b/program/rust/src/tests/test_add_mapping.rs @@ -1,25 +1,31 @@ -use crate::c_oracle_header::{ - MappingAccount, - PC_MAGIC, - PC_MAP_TABLE_SIZE, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + MappingAccount, + PC_MAGIC, + PC_MAP_TABLE_SIZE, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_account_as_mut, + load_checked, + }, + error::OracleError, + instruction::{ + CommandHeader, + OracleCommand, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + utils::clear_account, + }, + bytemuck::bytes_of, + solana_program::{ + program_error::ProgramError, + pubkey::Pubkey, + }, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_account_as_mut, - load_checked, -}; -use crate::error::OracleError; -use crate::instruction::{ - CommandHeader, - OracleCommand, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use crate::utils::clear_account; -use bytemuck::bytes_of; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; #[test] fn test_add_mapping() { @@ -29,14 +35,14 @@ fn test_add_mapping() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut curr_mapping_setup = AccountSetup::new::(&program_id); - let cur_mapping = curr_mapping_setup.to_account_info(); + let cur_mapping = curr_mapping_setup.as_account_info(); initialize_pyth_account_checked::(&cur_mapping, PC_VERSION).unwrap(); let mut next_mapping_setup = AccountSetup::new::(&program_id); - let next_mapping = next_mapping_setup.to_account_info(); + let next_mapping = next_mapping_setup.as_account_info(); { let mut cur_mapping_data = diff --git a/program/rust/src/tests/test_add_price.rs b/program/rust/src/tests/test_add_price.rs index a384221a7..62b617e39 100644 --- a/program/rust/src/tests/test_add_price.rs +++ b/program/rust/src/tests/test_add_price.rs @@ -1,25 +1,31 @@ -use crate::c_oracle_header::{ - MappingAccount, - PriceAccount, - ProductAccount, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + MappingAccount, + PriceAccount, + ProductAccount, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + }, + error::OracleError, + instruction::{ + AddPriceArgs, + CommandHeader, + OracleCommand, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + utils::clear_account, + }, + bytemuck::bytes_of, + solana_program::{ + program_error::ProgramError, + pubkey::Pubkey, + }, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, -}; -use crate::error::OracleError; -use crate::instruction::{ - AddPriceArgs, - CommandHeader, - OracleCommand, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use crate::utils::clear_account; -use bytemuck::bytes_of; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; #[test] fn test_add_price() { @@ -36,20 +42,20 @@ fn test_add_price() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut mapping_setup = AccountSetup::new::(&program_id); - let mapping_account = mapping_setup.to_account_info(); + let mapping_account = mapping_setup.as_account_info(); initialize_pyth_account_checked::(&mapping_account, PC_VERSION).unwrap(); let mut product_setup = AccountSetup::new::(&program_id); - let product_account = product_setup.to_account_info(); + let product_account = product_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); let mut price_setup_2 = AccountSetup::new::(&program_id); - let price_account_2 = price_setup_2.to_account_info(); + let price_account_2 = price_setup_2.as_account_info(); assert!(process_instruction( &program_id, @@ -153,7 +159,7 @@ fn test_add_price() { ); - //Price not signing + // Price not signing hdr_add_price = AddPriceArgs { header: OracleCommand::AddPrice.into(), exponent: 6, diff --git a/program/rust/src/tests/test_add_product.rs b/program/rust/src/tests/test_add_product.rs index 96f0a9a25..4d9ec2316 100644 --- a/program/rust/src/tests/test_add_product.rs +++ b/program/rust/src/tests/test_add_product.rs @@ -1,34 +1,39 @@ -use std::mem::size_of; - -use crate::c_oracle_header::{ - MappingAccount, - ProductAccount, - PythAccount, - PC_ACCTYPE_PRODUCT, - PC_MAGIC, - PC_MAP_TABLE_SIZE, - PC_PROD_ACC_SIZE, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + MappingAccount, + ProductAccount, + PythAccount, + PC_ACCTYPE_PRODUCT, + PC_MAGIC, + PC_MAP_TABLE_SIZE, + PC_PROD_ACC_SIZE, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_account_as, + load_checked, + }, + error::OracleError, + instruction::{ + CommandHeader, + OracleCommand, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + utils::clear_account, + }, + bytemuck::bytes_of, + solana_program::{ + account_info::AccountInfo, + clock::Epoch, + program_error::ProgramError, + pubkey::Pubkey, + rent::Rent, + }, + std::mem::size_of, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_account_as, - load_checked, -}; -use crate::error::OracleError; -use crate::instruction::{ - CommandHeader, - OracleCommand, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use crate::utils::clear_account; -use bytemuck::bytes_of; -use solana_program::account_info::AccountInfo; -use solana_program::clock::Epoch; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; -use solana_program::rent::Rent; #[test] @@ -39,17 +44,17 @@ fn test_add_product() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut mapping_setup = AccountSetup::new::(&program_id); - let mapping_account = mapping_setup.to_account_info(); + let mapping_account = mapping_setup.as_account_info(); initialize_pyth_account_checked::(&mapping_account, PC_VERSION).unwrap(); let mut product_setup = AccountSetup::new::(&program_id); - let product_account = product_setup.to_account_info(); + let product_account = product_setup.as_account_info(); let mut product_setup_2 = AccountSetup::new::(&program_id); - let product_account_2 = product_setup_2.to_account_info(); + let product_account_2 = product_setup_2.as_account_info(); assert!(process_instruction( &program_id, diff --git a/program/rust/src/tests/test_add_publisher.rs b/program/rust/src/tests/test_add_publisher.rs index 8f2c1c103..1a233a1a0 100644 --- a/program/rust/src/tests/test_add_publisher.rs +++ b/program/rust/src/tests/test_add_publisher.rs @@ -1,27 +1,33 @@ -use crate::c_oracle_header::{ - PriceAccount, - PriceComponent, - PythAccount, - PC_COMP_SIZE, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + PriceAccount, + PriceComponent, + PythAccount, + PC_COMP_SIZE, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + }, + instruction::{ + AddPublisherArgs, + OracleCommand, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + utils::clear_account, + OracleError, + }, + bytemuck::bytes_of, + solana_program::{ + program_error::ProgramError, + pubkey::Pubkey, + rent::Rent, + }, + std::mem::size_of, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, -}; -use crate::instruction::{ - AddPublisherArgs, - OracleCommand, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use crate::utils::clear_account; -use crate::OracleError; -use bytemuck::bytes_of; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; -use solana_program::rent::Rent; -use std::mem::size_of; #[test] fn test_add_publisher() { @@ -35,10 +41,10 @@ fn test_add_publisher() { let mut instruction_data = bytes_of::(&cmd); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let price_account = price_setup.to_account_info(); + let price_account = price_setup.as_account_info(); initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); @@ -100,7 +106,7 @@ fn test_add_publisher() { initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); - //Fill up price node + // Fill up price node for i in 0..PC_COMP_SIZE { cmd.publisher = Pubkey::new_unique(); instruction_data = bytes_of::(&cmd); diff --git a/program/rust/src/tests/test_del_price.rs b/program/rust/src/tests/test_del_price.rs index 7fa91887f..cfa0d222b 100644 --- a/program/rust/src/tests/test_del_price.rs +++ b/program/rust/src/tests/test_del_price.rs @@ -1,8 +1,11 @@ -use solana_program::pubkey::Pubkey; -use solana_sdk::signer::Signer; - -use crate::c_oracle_header::ProductAccount; -use crate::tests::pyth_simulator::PythSimulator; +use { + crate::{ + c_oracle_header::ProductAccount, + tests::pyth_simulator::PythSimulator, + }, + solana_program::pubkey::Pubkey, + solana_sdk::signer::Signer, +}; #[tokio::test] async fn test_del_price() { diff --git a/program/rust/src/tests/test_del_product.rs b/program/rust/src/tests/test_del_product.rs index 586cb94f6..b3d9c1500 100644 --- a/program/rust/src/tests/test_del_product.rs +++ b/program/rust/src/tests/test_del_product.rs @@ -1,14 +1,16 @@ -use std::mem::{ - size_of, - size_of_val, +use { + crate::{ + c_oracle_header::MappingAccount, + tests::pyth_simulator::PythSimulator, + }, + solana_program::pubkey::Pubkey, + solana_sdk::signer::Signer, + std::mem::{ + size_of, + size_of_val, + }, }; -use solana_program::pubkey::Pubkey; -use solana_sdk::signer::Signer; - -use crate::c_oracle_header::MappingAccount; -use crate::tests::pyth_simulator::PythSimulator; - #[tokio::test] async fn test_del_product() { @@ -79,12 +81,5 @@ fn mapping_product_list_equals(mapping_data: &MappingAccount, expected: Vec(&program_id); - let price_account = price_setup.to_account_info(); + let price_account = price_setup.as_account_info(); initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); { let mut price_data = load_checked::(&price_account, PC_VERSION).unwrap(); diff --git a/program/rust/src/tests/test_init_mapping.rs b/program/rust/src/tests/test_init_mapping.rs index 1bb9e91ff..4bcc19ee2 100644 --- a/program/rust/src/tests/test_init_mapping.rs +++ b/program/rust/src/tests/test_init_mapping.rs @@ -1,26 +1,32 @@ -use crate::c_oracle_header::{ - MappingAccount, - PermissionAccount, - PC_ACCTYPE_MAPPING, - PC_MAGIC, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + MappingAccount, + PermissionAccount, + PC_ACCTYPE_MAPPING, + PC_MAGIC, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_account_as, + }, + error::OracleError, + instruction::{ + CommandHeader, + OracleCommand, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + utils::clear_account, + }, + bytemuck::bytes_of, + solana_program::pubkey::Pubkey, + std::{ + cell::RefCell, + rc::Rc, + }, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_account_as, -}; -use crate::error::OracleError; -use crate::instruction::{ - CommandHeader, - OracleCommand, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use crate::utils::clear_account; -use bytemuck::bytes_of; -use solana_program::pubkey::Pubkey; -use std::cell::RefCell; -use std::rc::Rc; #[test] fn test_init_mapping() { @@ -31,13 +37,13 @@ fn test_init_mapping() { let program_id_2 = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let mut funding_account = funding_setup.to_account_info(); + let mut funding_account = funding_setup.as_account_info(); let mut attacker_setup = AccountSetup::new_funding(); - let attacker_account = attacker_setup.to_account_info(); + let attacker_account = attacker_setup.as_account_info(); let mut mapping_setup = AccountSetup::new::(&program_id); - let mut mapping_account = mapping_setup.to_account_info(); + let mut mapping_account = mapping_setup.as_account_info(); assert!(process_instruction( &program_id, @@ -156,7 +162,7 @@ fn test_init_mapping() { mapping_account.is_signer = false; let mut permissions_setup = AccountSetup::new_permission(&program_id); - let permissions_account = permissions_setup.to_account_info(); + let permissions_account = permissions_setup.as_account_info(); // Permissions account is unitialized assert_eq!( @@ -195,7 +201,7 @@ fn test_init_mapping() { // Attacker tries to impersonate permissions account let mut impersonating_permission_setup = AccountSetup::new::(&program_id); - let impersonating_permission_account = impersonating_permission_setup.to_account_info(); + let impersonating_permission_account = impersonating_permission_setup.as_account_info(); { let mut impersonating_permission_account_data = diff --git a/program/rust/src/tests/test_init_price.rs b/program/rust/src/tests/test_init_price.rs index 1449b2ea2..5211704b4 100644 --- a/program/rust/src/tests/test_init_price.rs +++ b/program/rust/src/tests/test_init_price.rs @@ -1,23 +1,28 @@ -use bytemuck::bytes_of; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; - -use crate::c_oracle_header::{ - PriceAccount, - MAX_NUM_DECIMALS, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + PriceAccount, + MAX_NUM_DECIMALS, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + }, + instruction::{ + InitPriceArgs, + OracleCommand, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + OracleError, + }, + bytemuck::bytes_of, + solana_program::{ + program_error::ProgramError, + pubkey::Pubkey, + }, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, -}; -use crate::instruction::{ - InitPriceArgs, - OracleCommand, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use crate::OracleError; #[test] fn test_init_price() { @@ -38,10 +43,10 @@ fn test_init_price() { let next_price = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); // Price account must be initialized assert_eq!( diff --git a/program/rust/src/tests/test_permission_migration.rs b/program/rust/src/tests/test_permission_migration.rs index 67c817289..480fcdf32 100644 --- a/program/rust/src/tests/test_permission_migration.rs +++ b/program/rust/src/tests/test_permission_migration.rs @@ -1,63 +1,67 @@ -use crate::c_oracle_header::{ - MappingAccount, - PermissionAccount, - PriceAccount, - ProductAccount, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + MappingAccount, + PermissionAccount, + PriceAccount, + ProductAccount, + PC_VERSION, + }, + deserialize::initialize_pyth_account_checked, + error::OracleError, + instruction::{ + AddPriceArgs, + AddPublisherArgs, + CommandHeader, + DelPublisherArgs, + InitPriceArgs, + OracleCommand::{ + AddMapping, + AddPrice, + AddProduct, + AddPublisher, + DelPrice, + DelProduct, + DelPublisher, + InitMapping, + InitPrice, + ResizePriceAccount, + SetMinPub, + UpdProduct, + }, + SetMinPubArgs, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + }, + bytemuck::bytes_of, + solana_program::pubkey::Pubkey, }; -use crate::deserialize::initialize_pyth_account_checked; -use crate::error::OracleError; -use crate::instruction::OracleCommand::{ - AddMapping, - AddPrice, - AddProduct, - AddPublisher, - DelPrice, - DelProduct, - DelPublisher, - InitMapping, - InitPrice, - ResizePriceAccount, - SetMinPub, - UpdProduct, -}; -use crate::instruction::{ - AddPriceArgs, - AddPublisherArgs, - CommandHeader, - DelPublisherArgs, - InitPriceArgs, - SetMinPubArgs, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use bytemuck::bytes_of; -use solana_program::pubkey::Pubkey; #[test] fn test_permission_migration() { let program_id = Pubkey::new_unique(); let mut permissions_setup = AccountSetup::new_permission(&program_id); - let permissions_account = permissions_setup.to_account_info(); + let permissions_account = permissions_setup.as_account_info(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut attacker_setup = AccountSetup::new_funding(); - let attacker_account = attacker_setup.to_account_info(); + let attacker_account = attacker_setup.as_account_info(); let mut mapping_setup = AccountSetup::new::(&program_id); - let mut mapping_account = mapping_setup.to_account_info(); + let mut mapping_account = mapping_setup.as_account_info(); let mut next_mapping_setup = AccountSetup::new::(&program_id); - let mut next_mapping_account = next_mapping_setup.to_account_info(); + let mut next_mapping_account = next_mapping_setup.as_account_info(); let mut product_setup = AccountSetup::new::(&program_id); - let mut product_account = product_setup.to_account_info(); + let mut product_account = product_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); product_account.is_signer = false; diff --git a/program/rust/src/tests/test_resize_account.rs b/program/rust/src/tests/test_resize_account.rs index 15c598173..6f1b60476 100644 --- a/program/rust/src/tests/test_resize_account.rs +++ b/program/rust/src/tests/test_resize_account.rs @@ -1,9 +1,12 @@ -use solana_sdk::signer::Signer; -use std::mem::size_of; - -use crate::c_oracle_header::pc_price_t; -use crate::tests::pyth_simulator::PythSimulator; -use crate::time_machine_types::PriceAccountWrapper; +use { + crate::{ + c_oracle_header::pc_price_t, + tests::pyth_simulator::PythSimulator, + time_machine_types::PriceAccountWrapper, + }, + solana_sdk::signer::Signer, + std::mem::size_of, +}; /// Warning : This test will fail if you run cargo test instead of cargo test-bpf diff --git a/program/rust/src/tests/test_set_min_pub.rs b/program/rust/src/tests/test_set_min_pub.rs index c22ba8f12..d1a0c6d08 100644 --- a/program/rust/src/tests/test_set_min_pub.rs +++ b/program/rust/src/tests/test_set_min_pub.rs @@ -1,24 +1,28 @@ -use std::mem::size_of; - -use solana_program::account_info::AccountInfo; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; - -use crate::c_oracle_header::{ - PriceAccount, - PC_VERSION, -}; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, - load_mut, -}; -use crate::instruction::{ - OracleCommand, - SetMinPubArgs, +use { + crate::{ + c_oracle_header::{ + PriceAccount, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + load_mut, + }, + instruction::{ + OracleCommand, + SetMinPubArgs, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + }, + solana_program::{ + account_info::AccountInfo, + program_error::ProgramError, + pubkey::Pubkey, + }, + std::mem::size_of, }; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; #[test] fn test_set_min_pub() { @@ -27,10 +31,10 @@ fn test_set_min_pub() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let price_account = price_setup.to_account_info(); + let price_account = price_setup.as_account_info(); initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); assert_eq!(get_min_pub(&price_account), Ok(0)); @@ -55,7 +59,7 @@ fn test_set_min_pub() { } // Create an upd_product instruction that sets the product metadata to strings -fn populate_instruction(instruction_data: &mut [u8], min_pub: u8) -> () { +fn populate_instruction(instruction_data: &mut [u8], min_pub: u8) { let mut hdr = load_mut::(instruction_data).unwrap(); hdr.header = OracleCommand::SetMinPub.into(); hdr.minimum_publishers = min_pub; diff --git a/program/rust/src/tests/test_sizes.rs b/program/rust/src/tests/test_sizes.rs index cdb34ffa4..62c33f6ed 100644 --- a/program/rust/src/tests/test_sizes.rs +++ b/program/rust/src/tests/test_sizes.rs @@ -1,39 +1,43 @@ -use crate::c_oracle_header::{ - AccountHeader, - MappingAccount, - PermissionAccount, - PriceAccount, - PriceComponent, - PriceEma, - PriceInfo, - ProductAccount, - PythAccount, - PC_COMP_SIZE, - PC_MAP_TABLE_SIZE, - PC_VERSION, - PRICE_ACCOUNT_SIZE, -}; -use crate::deserialize::{ - initialize_pyth_account_checked, - load, - load_checked, -}; -use crate::instruction::{ - AddPriceArgs, - AddPublisherArgs, - CommandHeader, - DelPublisherArgs, - InitPriceArgs, - SetMinPubArgs, - UpdPriceArgs, -}; -use crate::tests::test_utils::AccountSetup; -use crate::time_machine_types::PriceAccountWrapper; -use crate::utils::try_convert; -use solana_program::pubkey::Pubkey; -use std::mem::{ - size_of, - size_of_val, +use { + crate::{ + c_oracle_header::{ + AccountHeader, + MappingAccount, + PermissionAccount, + PriceAccount, + PriceComponent, + PriceEma, + PriceInfo, + ProductAccount, + PythAccount, + PC_COMP_SIZE, + PC_MAP_TABLE_SIZE, + PC_VERSION, + PRICE_ACCOUNT_SIZE, + }, + deserialize::{ + initialize_pyth_account_checked, + load, + load_checked, + }, + instruction::{ + AddPriceArgs, + AddPublisherArgs, + CommandHeader, + DelPublisherArgs, + InitPriceArgs, + SetMinPubArgs, + UpdPriceArgs, + }, + tests::test_utils::AccountSetup, + time_machine_types::PriceAccountWrapper, + utils::try_convert, + }, + solana_program::pubkey::Pubkey, + std::mem::{ + size_of, + size_of_val, + }, }; #[test] @@ -50,7 +54,7 @@ fn test_sizes() { ); assert_eq!( size_of::(), - 48 + 8 * size_of::() + 48 + u64::BITS as usize + 3 * size_of::() + size_of::() + (PC_COMP_SIZE as usize) * size_of::() @@ -81,7 +85,7 @@ fn test_offsets() { let program_id = Pubkey::new_unique(); let mut price_setup = AccountSetup::new::(&program_id); - let price_account = price_setup.to_account_info(); + let price_account = price_setup.as_account_info(); initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); let price_data = load_checked::(&price_account, PC_VERSION).unwrap(); @@ -92,7 +96,7 @@ fn test_offsets() { ); let mut mapping_setup = AccountSetup::new::(&program_id); - let mapping_account = mapping_setup.to_account_info(); + let mapping_account = mapping_setup.as_account_info(); initialize_pyth_account_checked::(&mapping_account, PC_VERSION).unwrap(); let mapping_data = load_checked::(&mapping_account, PC_VERSION).unwrap(); diff --git a/program/rust/src/tests/test_sma.rs b/program/rust/src/tests/test_sma.rs index 2019fd441..89e9488e9 100644 --- a/program/rust/src/tests/test_sma.rs +++ b/program/rust/src/tests/test_sma.rs @@ -1,10 +1,11 @@ -use quickcheck::Arbitrary; -use quickcheck_macros::quickcheck; - -use crate::time_machine_types::{ - DataPoint, - SmaTracker, - NUM_BUCKETS_THIRTY_MIN, +use { + crate::time_machine_types::{ + DataPoint, + SmaTracker, + NUM_BUCKETS_THIRTY_MIN, + }, + quickcheck::Arbitrary, + quickcheck_macros::quickcheck, }; #[derive(Clone, Debug, Copy)] @@ -57,7 +58,7 @@ fn test_sma(input: Vec) -> bool { let mut data = Vec::::new(); let mut current_time = 0i64; - for data_event in input.clone() { + for data_event in input { let datapoint = DataPoint { previous_timestamp: current_time, current_timestamp: current_time + data_event.time_gap, @@ -85,13 +86,13 @@ fn test_sma(input: Vec) -> bool { tracker5.check_array_fields(&data, current_time); } - return true; + true } impl SmaTracker { pub fn zero() -> Self { - return SmaTracker:: { + SmaTracker:: { granularity: 0, threshold: 0, current_epoch_denominator: 0, @@ -99,10 +100,10 @@ impl SmaTracker { current_epoch_numerator: 0, running_valid_epoch_counter: [0u64; NUM_ENTRIES], running_sum_of_price_averages: [0i128; NUM_ENTRIES], - }; + } } - pub fn check_current_epoch_fields(&self, data: &Vec, time: i64) { + pub fn check_current_epoch_fields(&self, data: &[DataPoint], time: i64) { let curent_epoch = self.time_to_epoch(time).unwrap(); let result = self.compute_epoch_expected_values(data, curent_epoch); @@ -111,7 +112,7 @@ impl SmaTracker { assert_eq!(self.current_epoch_is_valid, result.2); } - pub fn check_array_fields(&self, data: &Vec, time: i64) { + pub fn check_array_fields(&self, data: &[DataPoint], time: i64) { let current_epoch = self.time_to_epoch(time).unwrap(); let mut values = vec![]; @@ -122,8 +123,8 @@ impl SmaTracker { // Get running sums let running_sum_price_iter = values.iter().scan((0, 0), |res, &y| { - res.0 = res.0 + y.1 / i128::from(y.0); - res.1 = res.1 + u64::from(y.2); + res.0 += y.1 / i128::from(y.0); + res.1 += u64::from(y.2); Some(*res) }); @@ -143,7 +144,7 @@ impl SmaTracker { pub fn compute_epoch_expected_values( &self, - data: &Vec, + data: &[DataPoint], epoch_number: usize, ) -> (u64, i128, bool) { let left_bound = self @@ -158,9 +159,8 @@ impl SmaTracker { let mut result = data.iter().fold((0, 0, true), |x: (u64, i128, bool), y| { - if !((left_bound > y.current_timestamp) || (right_bound <= y.previous_timestamp)) - //Check interval intersection - { + // Check interval intersection + if !((left_bound > y.current_timestamp) || (right_bound <= y.previous_timestamp)) { let is_valid = y.slot_gap <= self.threshold; return ( x.0 + y.slot_gap, @@ -168,12 +168,13 @@ impl SmaTracker { x.2 && is_valid, ); } - return x; + x }); if epoch_number == 0 { result.2 = false; } - return result; + + result } } diff --git a/program/rust/src/tests/test_sma_epoch_transition.rs b/program/rust/src/tests/test_sma_epoch_transition.rs index fc022c61c..111bf7ae8 100644 --- a/program/rust/src/tests/test_sma_epoch_transition.rs +++ b/program/rust/src/tests/test_sma_epoch_transition.rs @@ -1,31 +1,33 @@ -use solana_program::pubkey::Pubkey; -use std::mem::size_of; - -use crate::c_oracle_header::{ - PC_MAX_SEND_LATENCY, - PC_STATUS_TRADING, - PC_VERSION, -}; - -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, - load_mut, -}; -use crate::instruction::{ - OracleCommand, - UpdPriceArgs, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::{ - update_clock_slot, - update_clock_timestamp, - AccountSetup, -}; -use crate::time_machine_types::{ - PriceAccountWrapper, - NUM_BUCKETS_THIRTY_MIN, - THIRTY_MINUTES, +use { + crate::{ + c_oracle_header::{ + PC_MAX_SEND_LATENCY, + PC_STATUS_TRADING, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + load_mut, + }, + instruction::{ + OracleCommand, + UpdPriceArgs, + }, + processor::process_instruction, + tests::test_utils::{ + update_clock_slot, + update_clock_timestamp, + AccountSetup, + }, + time_machine_types::{ + PriceAccountWrapper, + NUM_BUCKETS_THIRTY_MIN, + THIRTY_MINUTES, + }, + }, + solana_program::pubkey::Pubkey, + std::mem::size_of, }; /// Manually test some epoch transitions @@ -36,10 +38,10 @@ fn test_sma_epoch_transition() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); price_account.is_signer = false; initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); @@ -56,7 +58,7 @@ fn test_sma_epoch_transition() { } let mut clock_setup = AccountSetup::new_clock(); - let mut clock_account = clock_setup.to_account_info(); + let mut clock_account = clock_setup.as_account_info(); clock_account.is_signer = false; clock_account.is_writable = false; @@ -85,7 +87,7 @@ fn test_sma_epoch_transition() { ); assert_eq!(price_data.time_machine.granularity, THIRTY_MINUTES); assert_eq!(price_data.time_machine.current_epoch_numerator, 0); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 0); for i in 0..NUM_BUCKETS_THIRTY_MIN { assert_eq!(price_data.time_machine.running_sum_of_price_averages[i], 0); @@ -118,7 +120,7 @@ fn test_sma_epoch_transition() { ); assert_eq!(price_data.time_machine.granularity, THIRTY_MINUTES); assert_eq!(price_data.time_machine.current_epoch_numerator, 42 / 2 * 2); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 2); for i in 0..NUM_BUCKETS_THIRTY_MIN { assert_eq!(price_data.time_machine.running_sum_of_price_averages[i], 0); @@ -155,7 +157,7 @@ fn test_sma_epoch_transition() { price_data.time_machine.current_epoch_numerator, (80 + 42) / 2 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, true); + assert!(price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 1); for i in 1..NUM_BUCKETS_THIRTY_MIN { @@ -199,7 +201,7 @@ fn test_sma_epoch_transition() { price_data.time_machine.current_epoch_numerator, (80 + 42) / 2 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, true); + assert!(price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 1); for i in 1..NUM_BUCKETS_THIRTY_MIN { @@ -244,7 +246,7 @@ fn test_sma_epoch_transition() { price_data.time_machine.current_epoch_numerator, (40 + 80) / 2 * 28 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 28); for i in 2..NUM_BUCKETS_THIRTY_MIN { @@ -294,7 +296,7 @@ fn test_sma_epoch_transition() { price_data.time_machine.current_epoch_numerator, (40 + 41) / 2 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, true); + assert!(price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 1); for i in 5..NUM_BUCKETS_THIRTY_MIN { @@ -316,7 +318,7 @@ fn test_sma_epoch_transition() { assert_eq!( price_data.time_machine.running_sum_of_price_averages[2], - price_data.time_machine.running_sum_of_price_averages[1] + (60 * 28 + 1 * 41) / 29 + price_data.time_machine.running_sum_of_price_averages[1] + (60 * 28 + 41) / 29 ); assert_eq!(price_data.time_machine.running_valid_epoch_counter[2], 0); @@ -363,7 +365,7 @@ fn test_sma_epoch_transition() { price_data.time_machine.current_epoch_numerator, (40 + 41) / 2 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, true); + assert!(price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 1); for i in 5..NUM_BUCKETS_THIRTY_MIN { @@ -385,7 +387,7 @@ fn test_sma_epoch_transition() { assert_eq!( price_data.time_machine.running_sum_of_price_averages[2], - price_data.time_machine.running_sum_of_price_averages[1] + (60 * 28 + 1 * 41) / 29 + price_data.time_machine.running_sum_of_price_averages[1] + (60 * 28 + 41) / 29 ); assert_eq!(price_data.time_machine.running_valid_epoch_counter[2], 0); @@ -430,7 +432,7 @@ fn test_sma_epoch_transition() { price_data.time_machine.current_epoch_numerator, (41 + 100) / 2 * 69 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 69); for i in 0..NUM_BUCKETS_THIRTY_MIN { assert_eq!( @@ -448,7 +450,7 @@ fn test_sma_epoch_transition() { } // Create an upd_price instruction with the provided parameters -fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) -> () { +fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) { let mut cmd = load_mut::(instruction_data).unwrap(); cmd.header = OracleCommand::UpdPrice.into(); cmd.status = PC_STATUS_TRADING; diff --git a/program/rust/src/tests/test_upd_aggregate.rs b/program/rust/src/tests/test_upd_aggregate.rs index b3e17d981..c792ce1a3 100644 --- a/program/rust/src/tests/test_upd_aggregate.rs +++ b/program/rust/src/tests/test_upd_aggregate.rs @@ -1,25 +1,28 @@ -use solana_program::pubkey::Pubkey; -use std::mem::size_of; - -use crate::c_oracle_header::{ - PriceAccount, - PriceInfo, - PC_STATUS_TRADING, - PC_STATUS_UNKNOWN, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + PriceAccount, + PriceInfo, + PC_STATUS_TRADING, + PC_STATUS_UNKNOWN, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + load_mut, + }, + instruction::{ + OracleCommand, + UpdPriceArgs, + }, + rust_oracle::c_upd_aggregate, + tests::test_utils::AccountSetup, + }, + solana_program::pubkey::Pubkey, + std::mem::size_of, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, - load_mut, -}; -use crate::instruction::{ - OracleCommand, - UpdPriceArgs, -}; -use crate::rust_oracle::c_upd_aggregate; -use crate::tests::test_utils::AccountSetup; #[test] fn test_upd_aggregate() { let p1: PriceInfo = PriceInfo { @@ -60,7 +63,7 @@ fn test_upd_aggregate() { let program_id = Pubkey::new_unique(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); price_account.is_signer = false; initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); @@ -267,7 +270,7 @@ fn test_upd_aggregate() { } // Create an upd_price instruction with the provided parameters -fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) -> () { +fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) { let mut cmd = load_mut::(instruction_data).unwrap(); cmd.header = OracleCommand::AggPrice.into(); cmd.status = PC_STATUS_TRADING; diff --git a/program/rust/src/tests/test_upd_permissions.rs b/program/rust/src/tests/test_upd_permissions.rs index c2e216d3d..16e6ae64a 100644 --- a/program/rust/src/tests/test_upd_permissions.rs +++ b/program/rust/src/tests/test_upd_permissions.rs @@ -1,26 +1,32 @@ -use solana_program::pubkey::Pubkey; -use solana_program::rent::Rent; -use solana_sdk::signer::Signer; - -use crate::c_oracle_header::{ - PermissionAccount, - PythAccount, -}; -use crate::deserialize::load; -use crate::error::OracleError; -use crate::instruction::{ - OracleCommand, - UpdPermissionsArgs, -}; -use crate::tests::pyth_simulator::{ - copy_keypair, - PythSimulator, +use { + crate::{ + c_oracle_header::{ + PermissionAccount, + PythAccount, + }, + deserialize::load, + error::OracleError, + instruction::{ + OracleCommand, + UpdPermissionsArgs, + }, + tests::pyth_simulator::{ + copy_keypair, + PythSimulator, + }, + }, + solana_program::{ + pubkey::Pubkey, + rent::Rent, + }, + solana_sdk::signer::Signer, }; + #[tokio::test] async fn test_upd_permissions() { let mut sim = PythSimulator::new().await; - //Check that the program got deployed properly and can be interacted with + // Check that the program got deployed properly and can be interacted with let mapping_keypair = sim.init_mapping().await.unwrap(); let product = sim.add_product(&mapping_keypair).await.unwrap(); let price = sim.add_price(&product, -8).await.unwrap(); @@ -30,7 +36,7 @@ async fn test_upd_permissions() { let mut data_curation_authority = Pubkey::new_unique(); let mut security_authority = Pubkey::new_unique(); - //Airdrop some lamports to check whether someone can DDOS the account + // Airdrop some lamports to check whether someone can DDOS the account let permissions_pubkey = sim.get_permissions_pubkey(); sim.airdrop(&permissions_pubkey, Rent::default().minimum_balance(0)) .await @@ -82,9 +88,8 @@ async fn test_upd_permissions() { ); assert!(sim.is_owned_by_oracle(&permission_account)); - let mut permission_data = load::(permission_account.data.as_slice()) - .unwrap() - .clone(); + let mut permission_data = + *load::(permission_account.data.as_slice()).unwrap(); assert_eq!(master_authority, permission_data.master_authority); assert_eq!( diff --git a/program/rust/src/tests/test_upd_price.rs b/program/rust/src/tests/test_upd_price.rs index e314da14f..59c69a4b5 100644 --- a/program/rust/src/tests/test_upd_price.rs +++ b/program/rust/src/tests/test_upd_price.rs @@ -1,28 +1,33 @@ -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; -use std::mem::size_of; - -use crate::c_oracle_header::{ - PriceAccount, - PC_STATUS_TRADING, - PC_STATUS_UNKNOWN, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + PriceAccount, + PC_STATUS_TRADING, + PC_STATUS_UNKNOWN, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + load_mut, + }, + instruction::{ + OracleCommand, + UpdPriceArgs, + }, + processor::process_instruction, + tests::test_utils::{ + update_clock_slot, + AccountSetup, + }, + }, + solana_program::{ + program_error::ProgramError, + pubkey::Pubkey, + }, + std::mem::size_of, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, - load_mut, -}; -use crate::instruction::{ - OracleCommand, - UpdPriceArgs, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::{ - update_clock_slot, - AccountSetup, -}; #[test] fn test_upd_price() { let mut instruction_data = [0u8; size_of::()]; @@ -31,10 +36,10 @@ fn test_upd_price() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); price_account.is_signer = false; initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); @@ -45,7 +50,7 @@ fn test_upd_price() { } let mut clock_setup = AccountSetup::new_clock(); - let mut clock_account = clock_setup.to_account_info(); + let mut clock_account = clock_setup.as_account_info(); clock_account.is_signer = false; clock_account.is_writable = false; @@ -272,7 +277,7 @@ fn test_upd_price() { } // Create an upd_price instruction with the provided parameters -fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) -> () { +fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) { let mut cmd = load_mut::(instruction_data).unwrap(); cmd.header = OracleCommand::UpdPrice.into(); cmd.status = PC_STATUS_TRADING; diff --git a/program/rust/src/tests/test_upd_price_no_fail_on_error.rs b/program/rust/src/tests/test_upd_price_no_fail_on_error.rs index 533b9d813..27e730e0f 100644 --- a/program/rust/src/tests/test_upd_price_no_fail_on_error.rs +++ b/program/rust/src/tests/test_upd_price_no_fail_on_error.rs @@ -1,28 +1,33 @@ -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; -use std::mem::size_of; - -use crate::c_oracle_header::{ - PriceAccount, - PC_STATUS_TRADING, - PC_STATUS_UNKNOWN, - PC_VERSION, +use { + crate::{ + c_oracle_header::{ + PriceAccount, + PC_STATUS_TRADING, + PC_STATUS_UNKNOWN, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + load_mut, + }, + instruction::{ + OracleCommand, + UpdPriceArgs, + }, + processor::process_instruction, + tests::test_utils::{ + update_clock_slot, + AccountSetup, + }, + }, + solana_program::{ + program_error::ProgramError, + pubkey::Pubkey, + }, + std::mem::size_of, }; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, - load_mut, -}; -use crate::instruction::{ - OracleCommand, - UpdPriceArgs, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::{ - update_clock_slot, - AccountSetup, -}; #[test] fn test_upd_price_no_fail_on_error_no_fail_on_error() { let mut instruction_data = [0u8; size_of::()]; @@ -30,15 +35,15 @@ fn test_upd_price_no_fail_on_error_no_fail_on_error() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); price_account.is_signer = false; initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); let mut clock_setup = AccountSetup::new_clock(); - let mut clock_account = clock_setup.to_account_info(); + let mut clock_account = clock_setup.as_account_info(); clock_account.is_signer = false; clock_account.is_writable = false; @@ -169,7 +174,7 @@ fn populate_instruction( conf: u64, pub_slot: u64, fail_on_error: bool, -) -> () { +) { let mut cmd = load_mut::(instruction_data).unwrap(); cmd.header = if fail_on_error { OracleCommand::UpdPrice.into() diff --git a/program/rust/src/tests/test_upd_product.rs b/program/rust/src/tests/test_upd_product.rs index 419a263d6..595172e79 100644 --- a/program/rust/src/tests/test_upd_product.rs +++ b/program/rust/src/tests/test_upd_product.rs @@ -1,29 +1,33 @@ -use std::mem::size_of; - -use crate::instruction::{ - CommandHeader, - OracleCommand, -}; -use crate::processor::process_instruction; -use crate::tests::test_utils::AccountSetup; -use crate::utils::{ - read_pc_str_t, - try_convert, -}; -use solana_program::account_info::AccountInfo; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; - -use crate::c_oracle_header::{ - ProductAccount, - PythAccount, - PC_PROD_ACC_SIZE, - PC_VERSION, -}; -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, - load_mut, +use { + crate::{ + c_oracle_header::{ + ProductAccount, + PythAccount, + PC_PROD_ACC_SIZE, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + load_mut, + }, + instruction::{ + CommandHeader, + OracleCommand, + }, + processor::process_instruction, + tests::test_utils::AccountSetup, + utils::{ + read_pc_str_t, + try_convert, + }, + }, + solana_program::{ + account_info::AccountInfo, + program_error::ProgramError, + pubkey::Pubkey, + }, + std::mem::size_of, }; #[test] @@ -33,10 +37,10 @@ fn test_upd_product() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut product_setup = AccountSetup::new::(&program_id); - let product_account = product_setup.to_account_info(); + let product_account = product_setup.as_account_info(); initialize_pyth_account_checked::(&product_account, PC_VERSION).unwrap(); diff --git a/program/rust/src/tests/test_upd_sma.rs b/program/rust/src/tests/test_upd_sma.rs index 044d4b62f..1d757d819 100644 --- a/program/rust/src/tests/test_upd_sma.rs +++ b/program/rust/src/tests/test_upd_sma.rs @@ -1,32 +1,36 @@ -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; -use std::mem::size_of; - -use crate::c_oracle_header::{ - PC_MAX_SEND_LATENCY, - PC_STATUS_TRADING, - PC_STATUS_UNKNOWN, - PC_VERSION, -}; - -use crate::deserialize::{ - initialize_pyth_account_checked, - load_checked, - load_mut, -}; -use crate::instruction::{ - OracleCommand, - UpdPriceArgs, -}; -use crate::processor::process_instruction; // use crate::processor::process_instruction; -use crate::tests::test_utils::{ - update_clock_slot, - AccountSetup, -}; -use crate::time_machine_types::{ - PriceAccountWrapper, - THIRTY_MINUTES, +use { + crate::{ + c_oracle_header::{ + PC_MAX_SEND_LATENCY, + PC_STATUS_TRADING, + PC_STATUS_UNKNOWN, + PC_VERSION, + }, + deserialize::{ + initialize_pyth_account_checked, + load_checked, + load_mut, + }, + instruction::{ + OracleCommand, + UpdPriceArgs, + }, + processor::process_instruction, + tests::test_utils::{ + update_clock_slot, + AccountSetup, + }, + time_machine_types::{ + PriceAccountWrapper, + THIRTY_MINUTES, + }, + }, + solana_program::{ + program_error::ProgramError, + pubkey::Pubkey, + }, + std::mem::size_of, }; /// Clone of test_upd_price that also checks sma fields @@ -38,10 +42,10 @@ fn test_upd_sma() { let program_id = Pubkey::new_unique(); let mut funding_setup = AccountSetup::new_funding(); - let funding_account = funding_setup.to_account_info(); + let funding_account = funding_setup.as_account_info(); let mut price_setup = AccountSetup::new::(&program_id); - let mut price_account = price_setup.to_account_info(); + let mut price_account = price_setup.as_account_info(); price_account.is_signer = false; initialize_pyth_account_checked::(&price_account, PC_VERSION).unwrap(); @@ -58,7 +62,7 @@ fn test_upd_sma() { } let mut clock_setup = AccountSetup::new_clock(); - let mut clock_account = clock_setup.to_account_info(); + let mut clock_account = clock_setup.as_account_info(); clock_account.is_signer = false; clock_account.is_writable = false; @@ -90,7 +94,7 @@ fn test_upd_sma() { assert_eq!(price_data.price_data.agg_.status_, PC_STATUS_UNKNOWN); assert_eq!(price_data.time_machine.current_epoch_numerator, 0); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 0); } @@ -125,7 +129,7 @@ fn test_upd_sma() { assert_eq!(price_data.price_data.agg_.status_, PC_STATUS_UNKNOWN); assert_eq!(price_data.time_machine.current_epoch_numerator, 0); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 0); } @@ -159,7 +163,7 @@ fn test_upd_sma() { assert_eq!(price_data.price_data.agg_.status_, PC_STATUS_TRADING); assert_eq!(price_data.time_machine.current_epoch_numerator, 42 / 2 * 3); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 3); } @@ -195,7 +199,7 @@ fn test_upd_sma() { price_data.time_machine.current_epoch_numerator, 42 / 2 * 3 + (81 + 42) / 2 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 3 + 1); } @@ -231,7 +235,7 @@ fn test_upd_sma() { price_data.time_machine.current_epoch_numerator, 42 / 2 * 3 + (81 + 42) / 2 + 81 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 3 + 1 + 1); } @@ -269,7 +273,7 @@ fn test_upd_sma() { price_data.time_machine.current_epoch_numerator, 42 / 2 * 3 + (81 + 42) / 2 + 81 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!(price_data.time_machine.current_epoch_denominator, 3 + 1 + 1); } @@ -316,7 +320,7 @@ fn test_upd_sma() { price_data.time_machine.current_epoch_numerator, 42 / 2 * 3 + (81 + 42) / 2 + 81 + 81 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!( price_data.time_machine.current_epoch_denominator, 3 + 1 + 1 + 1 @@ -356,7 +360,7 @@ fn test_upd_sma() { price_data.time_machine.current_epoch_numerator, 42 / 2 * 3 + (81 + 42) / 2 + 81 + 81 ); - assert_eq!(price_data.time_machine.current_epoch_is_valid, false); + assert!(!price_data.time_machine.current_epoch_is_valid); assert_eq!( price_data.time_machine.current_epoch_denominator, 3 + 1 + 1 + 1 @@ -365,7 +369,7 @@ fn test_upd_sma() { } // Create an upd_price instruction with the provided parameters -fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) -> () { +fn populate_instruction(instruction_data: &mut [u8], price: i64, conf: u64, pub_slot: u64) { let mut cmd = load_mut::(instruction_data).unwrap(); cmd.header = OracleCommand::UpdPrice.into(); cmd.status = PC_STATUS_TRADING; diff --git a/program/rust/src/tests/test_utils.rs b/program/rust/src/tests/test_utils.rs index e145337e4..53a5d4890 100644 --- a/program/rust/src/tests/test_utils.rs +++ b/program/rust/src/tests/test_utils.rs @@ -1,32 +1,39 @@ -use crate::c_oracle_header::{ - PermissionAccount, - PythAccount, - PC_VERSION, - PERMISSIONS_SEED, +use { + crate::{ + c_oracle_header::{ + PermissionAccount, + PythAccount, + PC_VERSION, + PERMISSIONS_SEED, + }, + error::OracleError, + instruction::{ + CommandHeader, + OracleCommand, + }, + }, + num_traits::ToPrimitive, + solana_program::{ + account_info::AccountInfo, + clock::{ + self, + Epoch, + }, + instruction::InstructionError, + native_token::LAMPORTS_PER_SOL, + program_error::ProgramError, + pubkey::Pubkey, + rent::Rent, + system_program, + sysvar::{ + self, + Sysvar, + SysvarId, + }, + }, + solana_sdk::transaction::TransactionError, }; -use crate::error::OracleError; -use crate::instruction::{ - CommandHeader, - OracleCommand, -}; -use num_traits::ToPrimitive; -use solana_program::account_info::AccountInfo; -use solana_program::clock::Epoch; -use solana_program::instruction::InstructionError; -use solana_program::native_token::LAMPORTS_PER_SOL; -use solana_program::program_error::ProgramError; -use solana_program::pubkey::Pubkey; -use solana_program::rent::Rent; -use solana_program::sysvar::{ - Sysvar, - SysvarId, -}; -use solana_program::{ - clock, - system_program, - sysvar, -}; -use solana_sdk::transaction::TransactionError; + const UPPER_BOUND_OF_ALL_ACCOUNT_SIZES: usize = 20536; /// The goal of this struct is to easily instantiate fresh solana accounts @@ -49,17 +56,17 @@ pub struct AccountSetup { impl AccountSetup { pub fn new(owner: &Pubkey) -> Self { let key = Pubkey::new_unique(); - let owner = owner.clone(); + let owner = *owner; let balance = Rent::minimum_balance(&Rent::default(), T::MINIMUM_SIZE); let size = T::MINIMUM_SIZE; let data = [0; UPPER_BOUND_OF_ALL_ACCOUNT_SIZES]; - return AccountSetup { + AccountSetup { key, owner, balance, size, data, - }; + } } pub fn new_funding() -> Self { @@ -68,28 +75,28 @@ impl AccountSetup { let balance = LAMPORTS_PER_SOL; let size = 0; let data = [0; UPPER_BOUND_OF_ALL_ACCOUNT_SIZES]; - return AccountSetup { + AccountSetup { key, owner, balance, size, data, - }; + } } pub fn new_permission(owner: &Pubkey) -> Self { let (key, _bump) = Pubkey::find_program_address(&[PERMISSIONS_SEED.as_bytes()], owner); - let owner = owner.clone(); + let owner = *owner; let balance = Rent::minimum_balance(&Rent::default(), PermissionAccount::MINIMUM_SIZE); let size = PermissionAccount::MINIMUM_SIZE; let data = [0; UPPER_BOUND_OF_ALL_ACCOUNT_SIZES]; - return AccountSetup { + AccountSetup { key, owner, balance, size, data, - }; + } } pub fn new_clock() -> Self { @@ -98,17 +105,17 @@ impl AccountSetup { let balance = Rent::minimum_balance(&Rent::default(), clock::Clock::size_of()); let size = clock::Clock::size_of(); let data = [0u8; UPPER_BOUND_OF_ALL_ACCOUNT_SIZES]; - return AccountSetup { + AccountSetup { key, owner, balance, size, data, - }; + } } - pub fn to_account_info(&mut self) -> AccountInfo { - return AccountInfo::new( + pub fn as_account_info(&mut self) -> AccountInfo { + AccountInfo::new( &self.key, true, true, @@ -117,7 +124,7 @@ impl AccountSetup { &self.owner, false, Epoch::default(), - ); + ) } } @@ -133,17 +140,17 @@ pub fn update_clock_timestamp(clock_account: &mut AccountInfo, timestamp: i64) { clock_data.to_account_info(clock_account); } -impl Into for OracleCommand { - fn into(self) -> CommandHeader { - return CommandHeader { +impl From for CommandHeader { + fn from(val: OracleCommand) -> Self { + CommandHeader { version: PC_VERSION, - command: self.to_i32().unwrap(), // This can never fail and is only used in tests - }; + command: val.to_i32().unwrap(), // This can never fail and is only used in tests + } } } -impl Into for OracleError { - fn into(self) -> TransactionError { +impl From for TransactionError { + fn from(_: OracleError) -> Self { TransactionError::InstructionError( 0, InstructionError::try_from(u64::from(ProgramError::from( diff --git a/program/rust/src/time_machine_types.rs b/program/rust/src/time_machine_types.rs index a186cd1a6..2fbec88c5 100644 --- a/program/rust/src/time_machine_types.rs +++ b/program/rust/src/time_machine_types.rs @@ -1,18 +1,22 @@ #![allow(unused_imports)] #![allow(dead_code)] -use crate::c_oracle_header::{ - PriceAccount, - PythAccount, - EXTRA_PUBLISHER_SPACE, - PC_ACCTYPE_PRICE, - PC_MAX_SEND_LATENCY, - PC_PRICE_T_COMP_OFFSET, -}; -use crate::error::OracleError; -use crate::utils::try_convert; -use bytemuck::{ - Pod, - Zeroable, +use { + crate::{ + c_oracle_header::{ + PriceAccount, + PythAccount, + EXTRA_PUBLISHER_SPACE, + PC_ACCTYPE_PRICE, + PC_MAX_SEND_LATENCY, + PC_PRICE_T_COMP_OFFSET, + }, + error::OracleError, + utils::try_convert, + }, + bytemuck::{ + Pod, + Zeroable, + }, }; pub const THIRTY_MINUTES: i64 = 30 * 60; @@ -49,13 +53,14 @@ impl PriceAccountWrapper { pub fn add_price_to_time_machine(&mut self) -> Result<(), OracleError> { // This is only enabled in tests while in development #[cfg(test)] - self.time_machine.add_datapoint( &DataPoint{ - previous_timestamp : self.price_data.prev_timestamp_, - current_timestamp: self.price_data.timestamp_, - slot_gap : (self.price_data.last_slot_ - self.price_data.prev_slot_), - price: self.price_data.prev_price_ /2 + self.price_data.agg_.price_ / 2 + (self.price_data.prev_price_ % 2) * (self.price_data.agg_.price_ % 2), // Hack to avoid overflow - } - )?; + self.time_machine.add_datapoint(&DataPoint { + previous_timestamp: self.price_data.prev_timestamp_, + current_timestamp: self.price_data.timestamp_, + slot_gap: (self.price_data.last_slot_ - self.price_data.prev_slot_), + price: self.price_data.prev_price_ / 2 + + self.price_data.agg_.price_ / 2 + + (self.price_data.prev_price_ % 2) * (self.price_data.agg_.price_ % 2), // Hack to avoid overflow + })?; Ok(()) } } @@ -211,27 +216,32 @@ impl PythAccount for PriceAccountWrapper { #[cfg(test)] pub mod tests { - use crate::c_oracle_header::{ - PRICE_ACCOUNT_SIZE, - TIME_MACHINE_STRUCT_SIZE, + use { + crate::{ + c_oracle_header::{ + PRICE_ACCOUNT_SIZE, + TIME_MACHINE_STRUCT_SIZE, + }, + time_machine_types::{ + PriceAccountWrapper, + SmaTracker, + NUM_BUCKETS_THIRTY_MIN, + }, + }, + std::mem::size_of, }; - use crate::time_machine_types::{ - PriceAccountWrapper, - SmaTracker, - NUM_BUCKETS_THIRTY_MIN, - }; - use std::mem::size_of; + #[test] - ///test that the size defined in C matches that - ///defined in Rust + /// Test that the size defined in C matches that defined in Rust fn c_time_machine_size_is_correct() { assert_eq!( TIME_MACHINE_STRUCT_SIZE as usize, size_of::>() ); } + #[test] - ///test that priceAccountWrapper has a correct size + /// Test that priceAccountWrapper has a correct size fn c_price_account_size_is_correct() { assert_eq!( size_of::(), diff --git a/program/rust/src/utils.rs b/program/rust/src/utils.rs index 7f714d9a2..e9f066f83 100644 --- a/program/rust/src/utils.rs +++ b/program/rust/src/utils.rs @@ -1,36 +1,42 @@ -use crate::c_oracle_header::{ - AccountHeader, - PermissionAccount, - MAX_NUM_DECIMALS, - PERMISSIONS_SEED, +use { + crate::{ + c_oracle_header::{ + AccountHeader, + PermissionAccount, + MAX_NUM_DECIMALS, + PERMISSIONS_SEED, + }, + deserialize::{ + load_account_as, + load_checked, + }, + instruction::{ + CommandHeader, + OracleCommand, + UpdPriceArgs, + }, + OracleError, + }, + num_traits::FromPrimitive, + solana_program::{ + account_info::AccountInfo, + bpf_loader_upgradeable::UpgradeableLoaderState, + program::{ + invoke, + invoke_signed, + }, + program_error::ProgramError, + program_memory::sol_memset, + pubkey::Pubkey, + system_instruction::{ + allocate, + assign, + transfer, + }, + sysvar::rent::Rent, + }, + std::borrow::BorrowMut, }; -use crate::deserialize::{ - load_account_as, - load_checked, -}; -use crate::instruction::{ - CommandHeader, - OracleCommand, - UpdPriceArgs, -}; -use crate::OracleError; -use num_traits::FromPrimitive; -use solana_program::account_info::AccountInfo; -use solana_program::bpf_loader_upgradeable::UpgradeableLoaderState; -use solana_program::program::{ - invoke, - invoke_signed, -}; -use solana_program::program_error::ProgramError; -use solana_program::program_memory::sol_memset; -use solana_program::pubkey::Pubkey; -use solana_program::system_instruction::{ - allocate, - assign, - transfer, -}; -use solana_program::sysvar::rent::Rent; -use std::borrow::BorrowMut; pub fn pyth_assert(condition: bool, error_code: ProgramError) -> Result<(), ProgramError> { diff --git a/rustfmt.toml b/rustfmt.toml index 89ad8b9a5..23711c847 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,22 +1,17 @@ -# Merge similar crates together to avoid multiple use statements. -imports_granularity = "Module" +# Merge all imports into a clean vertical list of module imports. +imports_granularity = "One" +group_imports = "One" +imports_layout = "Vertical" -# Consistency in formatting makes tool based searching/editing better. -empty_item_single_line = false +# Better grep-ability. +empty_item_single_line = false -# Easier editing when arbitrary mixed use statements do not collapse. -imports_layout = "Vertical" - -# Default rustfmt formatting of match arms with branches is awful. -match_arm_leading_pipes = "Preserve" +# Consistent pipe layout. +match_arm_leading_pipes = "Preserve" # Align Fields enum_discrim_align_threshold = 80 struct_field_align_threshold = 80 -# Allow up to two blank lines for grouping. -blank_lines_upper_bound = 2 - -# Wrap comments -comment_width = 120 -wrap_comments = true \ No newline at end of file +# Allow up to two blank lines for visual grouping. +blank_lines_upper_bound = 2