text
stringlengths
8
4.13M
use z80::Z80; /* ** ADD A, r|(hl)|$xx ** Condition Bits: R0RR ** Clocks: ** r: 1 ** $xx: 2 ** hl: 2 */ pub fn add_a(z80: &mut Z80, op: u8) { let a = z80.r.a; let val = match op { 0xC6 => { z80.r.pc += 1; z80.mmu.rb(z80.r.pc - 1) }, 0x86 => z80.mmu.rb(z80.r.get_hl()), 0x87 => z80.r.a, 0x80 => z80.r.b, 0x81 => z80.r.c, 0x82 => z80.r.d, 0x83 => z80.r.e, 0x84 => z80.r.h, 0x85 => z80.r.l, _ => 0, }; z80.r.clear_flags(); z80.r.a = a.wrapping_add(val); if z80.r.a == 0 { z80.r.set_zero(true); } else if z80.r.a < a { z80.r.set_carry(true); } if (z80.r.a ^ val ^ a) & 0x10 != 0 { z80.r.set_half_carry(true); } if op == 0x86 || op == 0xC6 { z80.set_register_clock(2); } else { z80.set_register_clock(1); } } /* ** ADD SP, $xx ** Condition Bits: 00RR ** Clocks: 2 */ pub fn add_sp_n(z80: &mut Z80) { let val = z80.mmu.rb(z80.r.pc) as u16; let sp = z80.r.sp; z80.r.pc += 1; z80.r.clear_flags(); if val > 127 { z80.r.sp = z80.r.sp.wrapping_sub(256 - val as u16); } else { z80.r.sp = z80.r.sp.wrapping_add(val as u16); } if z80.r.sp == 0 { z80.r.set_zero(true); } else if z80.r.sp < sp { z80.r.set_carry(true); } if (z80.r.sp ^ val ^ sp) & 0x10 != 0 { z80.r.set_half_carry(true); } z80.set_register_clock(2); } /* ** ADD hl, rr|sp ** Condition Bits: _0RR ** Clocks: ** All: 3 */ pub fn add_hl(z80: &mut Z80, op: u8) { let hl = z80.r.get_hl(); let val = match op { 0x09 => z80.r.get_bc(), 0x19 => z80.r.get_de(), 0x29 => z80.r.get_hl(), 0x39 => z80.r.sp, _ => 0, }; z80.r.set_hl(hl.wrapping_add(val)); z80.r.set_subtract(false); if z80.r.get_hl() < hl { z80.r.set_carry(true); } else { z80.r.set_carry(false); } if (z80.r.get_hl() ^ val ^ hl) & 0x10 != 0 { z80.r.set_half_carry(true); } else { z80.r.set_half_carry(false); } z80.set_register_clock(3); }
use near_sdk::serde_json::json; use near_sdk::AccountId; use near_sdk_sim::transaction::ExecutionStatus; use near_sdk_sim::DEFAULT_GAS; use near_sdk::json_types::{U128, U64}; use crate::utils::init_without_macros as init; // /** // * FluxAggregator tests were ported from this file https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts // */ // /** // * #constructor - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L214 // */ // #[test] // fn constructor_tests() { // let payment_amount: u128 = 3; // let timeout: u64 = 1800; // let decimals: u64 = 24; // let description: String = "LINK/USD".to_string(); // let version: u128 = 3; // let validator: String = "".to_string(); // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let expected_payment_amount: u128 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(payment_amount, expected_payment_amount); // let expected_timeout: u64 = root // .call( // flux_aggregator.account_id(), // "get_timeout", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(timeout, expected_timeout); // let expected_decimals: u64 = root // .call( // flux_aggregator.account_id(), // "get_decimals", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(decimals, expected_decimals); // let expected_description: String = root // .call( // flux_aggregator.account_id(), // "get_description", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(description, expected_description); // let expected_version: u128 = root // .call( // flux_aggregator.account_id(), // "get_version", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(version, expected_version); // let expected_validator: String = root // .call( // flux_aggregator.account_id(), // "get_validator", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(validator, expected_validator); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L249 // * *TODO* Fix parsing of the log // */ // #[test] // fn updates_the_allocated_and_available_funds_counters() { // let payment_amount: u128 = 3; // let deposit: u128 = 100; // let answer: u128 = 100; // let rr_delay: u128 = 0; // let next_round: u128 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let mut allocated_funds: u128 = root // .view( // flux_aggregator.account_id(), // "allocated_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(allocated_funds, 0); // let tx = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let mut receipt = tx.promise_results(); // allocated_funds = root // .view( // flux_aggregator.account_id(), // "allocated_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // let available_funds: u128 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(payment_amount, allocated_funds); // let expected_available: u128 = deposit - payment_amount; // assert_eq!(expected_available, available_funds); // // *TODO* Fix parsing of the log // let logged: u128 = receipt.remove(1).unwrap().outcome().logs[3] // .parse() // .unwrap(); // assert_eq!(expected_available, logged); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L262 // */ // #[test] // fn emits_a_log_event_announcing_submission_details() { // let payment_amount: u128 = 3; // let deposit: u128 = 100; // let answer: u128 = 100; // let rr_delay: u128 = 0; // let next_round: u128 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let mut allocated_funds: u128 = root // .view( // flux_aggregator.account_id(), // "allocated_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(allocated_funds, 0); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // allocated_funds = root // .view( // flux_aggregator.account_id(), // "allocated_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // let available_funds: u128 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(payment_amount, allocated_funds); // let expected_available: u128 = deposit - payment_amount; // assert_eq!(expected_available, available_funds); // let tx = oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!(tx.logs()[0], "100, 1, oracle_three"); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L269 // */ // #[test] // fn when_the_minimum_oracles_have_not_reported_and_pays_the_oracles_that_have_reported() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min_max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let withdrawable_payment: u128 = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_one.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, withdrawable_payment); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let withdrawable_payment_oracle_one: u128 = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_one.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(payment_amount, withdrawable_payment_oracle_one); // let withdrawable_payment_oracle_two: u128 = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_two.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, withdrawable_payment_oracle_two); // let withdrawable_payment_oracle_three: u128 = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_three.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, withdrawable_payment_oracle_three); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L285 // */ // #[test] // fn when_the_minimum_oracles_have_not_reported_and_does_not_update_the_answer() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min_max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let not_updated: u128 = root // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(0, not_updated); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let still_not_updated: u128 = root // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(0, still_not_updated); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L302 // */ // #[test] // fn when_an_oracle_prematurely_bumps_the_round_and_reverts() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_previous_round_not_supersedable = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": (next_round + 1).to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_previous_round_not_supersedable // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("previous round not supersedable")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L310 // */ // #[test] // fn updates_the_answer_with_the_median() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_latest_answer: u128 = test_helper // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(0, expected_latest_answer); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": 99.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_latest_answer_first: u128 = test_helper // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(99, expected_latest_answer_first); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": 101.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_latest_answer_second: u128 = test_helper // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(100, expected_latest_answer_second); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L327 // */ // #[test] // fn updates_the_updated_timestamp() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let original_timestamp: u128 = test_helper // .call( // flux_aggregator.account_id(), // "latest_timestamp", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(original_timestamp > 0, true); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let current_timestamp: u128 = test_helper // .call( // flux_aggregator.account_id(), // "latest_timestamp", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(current_timestamp > original_timestamp, true); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L337 // * *TODO* Look into emitting necessary log // */ // #[test] // fn announces_the_new_answer_with_a_log_event() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let mut receipt = oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let new_answer: u64 = receipt.promise_results().remove(1).unwrap().outcome().logs[0] // .parse() // .unwrap(); // let latest_answer: u64 = test_helper // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(latest_answer, new_answer); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L346 // */ // #[test] // fn does_not_set_the_timedout_flag() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_no_data_present = test_helper.call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": next_round.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("No data present")); // } else { // unreachable!(); // } // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let latest_round_data: (u64, u128, u64, u64, u64) = test_helper // .call( // flux_aggregator.account_id(), // "latest_round_data", // &json!({"_round_id": next_round.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(next_round, latest_round_data.4); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L355 // */ // #[test] // fn submit_and_updates_the_round_details() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_no_data_present = test_helper.call( // flux_aggregator.account_id(), // "latest_round_data", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // println!("{:?}", execution_error.to_string()); // assert!(execution_error.to_string().contains("No data present")); // } else { // unreachable!(); // } // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let round_after: (u64, u128, u64, u64, u64) = test_helper // .call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": next_round.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(next_round, round_after.0); // assert_eq!(answer, round_after.1); // assert_eq!(false, round_after.2 == 0); // let original_timestamp: u128 = test_helper // .call( // flux_aggregator.account_id(), // "latest_timestamp", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(original_timestamp as u64, round_after.3); // assert_eq!(1, round_after.4); // assert_eq!(true, round_after.2 < round_after.3); // let latest_round_data: (u64, u128, u64, u64, u64) = test_helper // .call( // flux_aggregator.account_id(), // "latest_round_data", // &json!({"_round_id": next_round.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(true, round_after.0 == latest_round_data.0); // assert_eq!(true, round_after.1 == latest_round_data.1); // assert_eq!(true, round_after.2 == latest_round_data.2); // assert_eq!(true, round_after.3 == latest_round_data.3); // assert_eq!(true, round_after.4 == latest_round_data.4); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L380 // */ // #[test] // fn when_an_oracle_submits_for_a_round_twice_and_reverts() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min_max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let withdrawable_payment: u128 = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_one.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, withdrawable_payment); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let cannout_report_on_previous_rounds = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &cannout_report_on_previous_rounds // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("cannot report on previous rounds")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L396 // */ // #[test] // fn when_updated_after_the_max_answers_submitted_and_reverts() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L484 sets the min and max submissions back to 1 // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let round_not_accepting_submissions = oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &round_not_accepting_submissions // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error // .to_string() // .contains("round not accepting submissions")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L402 // * **TODO** Look into why oracle_round_state_suggest_round is returning the wrong data. // */ // #[test] // fn when_a_new_highest_round_number_is_passed_in_and_increments_the_answer_round() { // let rr_delay: u64 = 0; // let answer: u64 = 100; // let next_round: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = test_helper // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_one.account_id(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(1, starting_state.1); // // Advance round non-refactored function, https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L498 // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L498 - Look into the oracle_round_state and oracle_round_suggest_state functions to return the correct results for 0 state. // let updated_state = test_helper.call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_one.account_id(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // println!("{:?} SEC", starting_state); // assert_eq!(2, starting_state.1); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L412 // * **TODO** Look into grabbing the block timestamp from tx. // */ // #[test] // fn when_a_new_highest_round_number_is_passed_in_and_sets_the_started_at_time_for_the_reporting_round( // ) { // let rr_delay: u64 = 0; // let answer: u64 = 100; // let next_round: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_no_data_present = root.call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": next_round.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("No data present")); // } else { // unreachable!(); // } // // Advance round non-refactored function, https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L498 // let tx = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let updated_state: (u64, u128, u64, u64, u64) = root // .call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": next_round.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // *TODO* Look into grabbing the block timestamp from tx. // // assert_eq!(2, updated_state.2); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L425 // * // */ // #[test] // fn when_a_new_highest_round_number_is_passed_in_and_announces_a_new_round_by_emitting_a_log() { // let rr_delay: u64 = 0; // let answer: u64 = 100; // let next_round: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_no_data_present = root.call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": next_round.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("No data present")); // } else { // unreachable!(); // } // let tx = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!(tx.logs()[0].contains("1, oracle_one"), true); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L439 // * **TODO** Look into why oracle_round_state_suggest_round is returning the wrong data. // */ // #[test] // fn when_a_round_is_passed_in_higher_than_expected_and_reverts() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let invalid_round_to_report = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": (next_round + 1).to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &invalid_round_to_report // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("invalid round to report")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L445 // * **TODO** Look into why oracle_round_state_suggest_round is returning the wrong data. // */ // #[test] // fn when_called_by_a_non_oracle_and_reverts() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let min: u64 = 2; // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // Carol // let not_enabled_oracle = root.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &not_enabled_oracle // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error.to_string().contains("not enabled oracle")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L450 // * **TODO** Look into subtraction overflow errors // */ // #[test] // fn when_there_are_not_sufficient_available_funds() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let max: u64 = 3; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": max.to_string(), "_max_submissions": max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // Carol // root.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": root.account_id().to_string(), "_amount": 82.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // let subtraction_overflow_math_error = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // println!("{:?}", subtraction_overflow_math_error.promise_results()); // if let ExecutionStatus::Failure(execution_error) = &subtraction_overflow_math_error // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // SafeMath: subtraction overflow // assert!(execution_error // .to_string() // .contains("SafeMath: subtraction overflow")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L479 // * // */ // #[test] // fn when_a_new_round_opens_before_the_previous_rounds_closes_and_still_allows_the_previous_round_to_be_answered( // ) { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id() ], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_four.account_id(), oracle_five.account_id() ], "_min_submissions": 3.to_string(), "_max_submissions": 4.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = 2; // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // still allows the previous round to be answered // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": (next_round - 1).to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L491 // * // */ // #[test] // fn once_the_current_round_is_answered_does_not_allow_reports_for_the_previous_round() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id() ], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_four.account_id(), oracle_five.account_id() ], "_min_submissions": 3.to_string(), "_max_submissions": 4.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = 2; // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // once the current round is answered // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // does not allow reports for the previous round // let invalid_round_to_report = oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": (next_round - 1).to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &invalid_round_to_report // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("invalid round to report")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L501 // * // */ // #[test] // fn when_the_previous_round_has_finished_and_does_not_allow_reports_for_the_previous_round() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id() ], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_four.account_id(), oracle_five.account_id() ], "_min_submissions": 3.to_string(), "_max_submissions": 4.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = 2; // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // when the previous round has finished // oracle_five // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // does not allow reports for the previous round // let round_not_accepting_submissions = oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &round_not_accepting_submissions // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("round not accepting submissions")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L513 // * // */ // #[test] // fn when_price_is_updated_mid_round_and_pays_the_same_amount_to_all_oracles_per_round() { // let new_amount: u128 = 50; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let min_max: u128 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id() ], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // link.account_id(), // "ft_transfer", // &json!({ // "receiver_id": flux_aggregator.account_id().to_string(), "amount": 300.to_string(), "memo": "None" // }) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1 // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "update_available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .assert_success(); // let mut withdrawable_payment_oracle_one: u128 = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_one.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, withdrawable_payment_oracle_one); // let mut withdrawable_payment_oracle_three: u128 = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_three.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, withdrawable_payment_oracle_three); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": new_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // withdrawable_payment_oracle_one = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_one.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(3, withdrawable_payment_oracle_one); // withdrawable_payment_oracle_three = root // .view( // flux_aggregator.account_id(), // "withdrawable_payment", // &json!({ // "_oracle": oracle_three.account_id().to_string() // }) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(3, withdrawable_payment_oracle_three); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L549 // * // */ // #[test] // fn when_delay_is_on_does_not_revert_on_the_oracles_first_round() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 1; // let timeout: u64 = 1800; // let next_round: u128 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id() ], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L557 // * // */ // #[test] // fn when_delay_is_on_and_does_revert_before_the_delay() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 1; // let timeout: u64 = 1800; // let mut next_round: u128 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id() ], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // let expected_previous_round_not_supersedable = oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_previous_round_not_supersedable // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error // .to_string() // .contains("previous round not supersedable")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L590 // * // */ // #[test] // fn when_called_by_an_oracle_who_has_not_answered_recently_and_does_not_revert() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 2.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 3.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // Since Ned and Nelly have answered recently, and we set the delay // // to 2, only Nelly can answer as she is the only oracle that hasn't // // started the last two rounds. // // await updateFutureRounds(aggregator, { // // maxAnswers: oracles.length, // // restartDelay: newDelay, // // }) // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 1.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 2.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // when called by an oracle who has not answered recently // // it does not revert // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 4.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L596 // * // */ // #[test] // fn when_called_by_an_oracle_who_has_answered_recently_and_reverts() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 2.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 3.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // Since Ned and Nelly have answered recently, and we set the delay // // to 2, only Nelly can answer as she is the only oracle that hasn't // // started the last two rounds. // // await updateFutureRounds(aggregator, { // // maxAnswers: oracles.length, // // restartDelay: newDelay, // // }) // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 1.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 2.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // when called by an oracle who has answered recently // // it does not revert // let expected_round_not_accepting_submissions = oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 4.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_round_not_accepting_submissions // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error // .to_string() // .contains("round not accepting submissions")); // } else { // unreachable!(); // } // let expected_round_not_accepting_submissions_two = oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 4.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_round_not_accepting_submissions_two // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error // .to_string() // .contains("round not accepting submissions")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L630 // * *TODO* Look into why the contract panics on oracle_three starting a new round. Error: previous round not supersedable. // */ // #[test] // fn when_the_price_is_not_updated_for_a_round_and_allows_a_new_round_to_be_started() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let min_max: u128 = 3; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // allows a new round to be started // // *TODO* Look into why the contract panics on oracle_three starting a new round. Error: previous round not supersedable. // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L634 // * *TODO* Look into how to acheive this with NEAR's sdk const block = await provider.getBlock(receipt.blockHash ?? '') // */ // #[test] // fn sets_the_info_for_the_previous_round() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let min_max: u128 = 3; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // sets the info for the previous round // let mut expected_updated_timestamp: u128 = root // .view( // flux_aggregator.account_id(), // "get_timestamp", // &json!({"_round_id": (next_round - 1).to_string()}) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, expected_updated_timestamp); // let mut expected_answer: u128 = root // .view( // flux_aggregator.account_id(), // "get_answer", // &json!({"_round_id": (next_round - 1).to_string()}) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(0, expected_answer); // let tx = oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // println!("{:?}", tx); // // *TODO*: Look into this const block = await provider.getBlock(receipt.blockHash ?? '') // // matchers.bigNum(ethers.utils.bigNumberify(block.timestamp), updated) // expected_updated_timestamp = root // .view( // flux_aggregator.account_id(), // "get_timestamp", // &json!({"_round_id": (next_round - 1).to_string()}) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // // assert_eq!(tx.timestamp, expected_updated_timestamp); // expected_answer = root // .view( // flux_aggregator.account_id(), // "get_answer", // &json!({"_round_id": (next_round - 1).to_string()}) // .to_string() // .into_bytes(), // ) // .unwrap_json(); // assert_eq!(answer, expected_answer); // let expected_round: (u64, u128, u64, u64, u64) = root // .call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": (next_round - 1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(2, expected_round.0); // assert_eq!(answer, expected_round.1); // assert_eq!(expected_updated_timestamp as u64, expected_round.3); // assert_eq!(1, expected_round.4); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L658 // */ // #[test] // fn sets_the_previous_round_as_timed_out() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let min_max: u128 = 3; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // sets the previous round as timed out // // *TODO* Look into why the panic error contains previous round not supersedable and not No data present // let expected_no_data_present = root.call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": (next_round - 1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error.to_string().contains("No data present")); // } else { // unreachable!(); // } // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_round: (u64, u128, u64, u64, u64) = root // .call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": 2.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(2, expected_round.0); // assert_eq!(1, expected_round.4); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L669 // */ // #[test] // fn still_respects_the_delay_restriction() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let min_max: u128 = 3; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // println!("{:?}", next_round); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // let expected_revert = oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_revert // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // expected to revert because the sender started the last round // assert!(execution_error // .to_string() // .contains("previous round not supersedable")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L674 // */ // #[test] // fn uses_the_set_timeout_at_the_beginning_of_the_round() { // let payment_amount: u128 = 3; // let answer: u128 = 100; // let rr_delay: u64 = 0; // let timeout: u64 = 1800; // let min_max: u128 = 3; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // println!("{:?}", next_round); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": (timeout+100000).to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L684 // */ // #[test] // fn rejects_values_below_the_submission_value_range() { // let rr_delay: u64 = 0; // let min_submission_value: u64 = 1; // let next_round: u64 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_value_below_min_submission_value = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": (min_submission_value-1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_value_below_min_submission_value // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error // .to_string() // .contains("value below min_submission_value")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L691 // */ // #[test] // fn accepts_submissions_equal_to_the_min_submission_value() { // let rr_delay: u64 = 0; // let min_submission_value: u64 = 1; // let next_round: u64 = 1; // let min_max: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": (min_submission_value).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L695 // */ // #[test] // fn accepts_submissions_equal_to_the_max_submission_value() { // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let min_max: u128 = 3; // let max_submission_value: u128 = 100000000000000000000; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": (max_submission_value).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L699 // */ // #[test] // fn rejects_values_above_the_max_submission_value() { // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let min_max: u128 = 3; // let max_submission_value: u128 = 100000000000000000000; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_value_above_max_submission_value = oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": (max_submission_value + 1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_value_above_max_submission_value // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // // No data present should be error // assert!(execution_error // .to_string() // .contains("value above max_submission_value")); // } else { // unreachable!(); // } // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L716 // */ // #[test] // fn calls_out_to_the_validator() { // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let min_max: u128 = 3; // let payment_amount: u128 = 3; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_max.to_string(), "_max_submissions": min_max.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 1.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // Carol // root.call( // flux_aggregator.account_id(), // "set_validator", // &json!({"_new_validator": aggregator_validator_mock.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let tx = oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!(tx.promise_results().remove(2).unwrap().outcome().logs[0], "0, 0, 1, 100") // } // /** // * #submit - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L240 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L733 // */ // #[test] // fn still_updates() { // } // /** // * #get_answer - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L743 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L754 // */ // #[test] // fn retrieves_the_answer_recorded_for_past_rounds() { // let answers: Vec<u128> = [1, 10, 101, 1010, 10101, 101010, 1010101].to_vec(); // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let mut n = 0; // let mut y = 1; // let mut x = 0; // while n < answers.len() { // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[n].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round += 1; // n += 1; // } // while y < next_round { // let answer: u128 = root // .call( // flux_aggregator.account_id(), // "get_answer", // &json!({"_round_id": y.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_answer: u128 = answers[x] as u128; // x += 1; // y += 1; // assert_eq!(answer, expected_answer); // } // } // /** // * #get_answer - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L743 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L761 // * *TODO* Research overflowedId issue for Rust uint type // */ // #[test] // fn returns_zero_for_answers_greater_than_uint32s_max() { // } // /** // * #get_timestamp - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L768 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L777 // */ // #[test] // fn retrieves_the_timestamp_recorded_for_past_rounds() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let mut i = 0; // let mut z = 1; // let mut latest_timestamp: u128 = 0; // while i < 10 { // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": (i + 1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round += 1; // i += 1; // } // while z < next_round { // let current_timestamp: u128 = root // .call( // flux_aggregator.account_id(), // "get_timestamp", // &json!({"_round_id": z.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // z += 1; // assert_eq!(current_timestamp >= latest_timestamp, true); // latest_timestamp = current_timestamp; // } // } // /** // * #get_timestamp - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L768 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L787 // */ // #[test] // fn returns_zero_for_timestamps_greater_than_uint32s_max() { // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L796 // */ // #[test] // fn increases_the_oracle_count() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let past_count: u128 = root // .view( // flux_aggregator.account_id(), // "oracle_count", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let current_count: u128 = root // .view( // flux_aggregator.account_id(), // "oracle_count", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(past_count + 1, current_count); // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L804 // */ // #[test] // fn adds_the_address_in_get_oracles() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracle_one.account_id().to_string(), oracles[0]); // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L809 // */ // #[test] // fn change_oracles_and_updates_the_round_details() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": 2.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let min_submission_count: u64 = root // .view( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // let max_submission_count: u64 = root // .view( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // let restart_delay: u64 = root // .view( // flux_aggregator.account_id(), // "restart_delay", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(min_submission_count, 1); // assert_eq!(max_submission_count, 3); // assert_eq!(restart_delay, 2); // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L816 // */ // #[test] // fn emits_a_log() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let oracle_added_event = root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_two.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).promise_results(); // let oracle_added_event_oracle: String = oracle_added_event.clone().remove(1).unwrap().outcome().logs[0] // .parse() // .unwrap(); // let result = [oracle_two.account_id(), ", true".to_string()].join(""); // assert_eq!(result, oracle_added_event_oracle); // let oracle_admin_updated_event_oracle: String = oracle_added_event.clone().remove(1).unwrap().outcome().logs[1] // .parse() // .unwrap(); // let result_two = [oracle_one.account_id(), ", true".to_string()].join(""); // assert_eq!(result_two, oracle_admin_updated_event_oracle); // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L834 // */ // #[test] // fn when_the_oracle_has_already_been_added_and_reverts() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_oracle_already_enabled = root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_oracle_already_enabled // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("oracle already enabled")); // } else { // unreachable!(); // } // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L840 // */ // #[test] // fn change_oracles_and_when_called_by_anyone_but_the_owner_and_reverts() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let ( // _root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let expected_only_callable_by_owner = oracle_one.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_owner // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("Only callable by owner")); // } else { // unreachable!(); // } // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L867 // */ // #[test] // fn does_not_allow_the_oracle_to_update_the_round() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_not_yet_enabled_oracle = oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_not_yet_enabled_oracle // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("not yet enabled oracle")); // } else { // unreachable!(); // } // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L871 // */ // #[test] // fn does_allow_the_oracle_to_update_future_rounds() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // next_round = next_round + 1; // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L881 // */ // #[test] // fn when_an_oracle_is_added_after_removed_for_a_round_and_allows_the_oracle_to_update() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L903 // */ // #[test] // fn when_an_oracle_is_added_and_immediately_removed_mid_round_allows_the_oracle_to_update() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let mut next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L924 // * **TODO** Research why the contract is not panicking with owner cannot overwrite admin, reckoning that the issue is in remove_oracle // */ // #[test] // fn when_an_oracle_is_re_added_after_with_a_different_admin_address_and_reverts() { // let answer: u128 = 100; // let rr_delay: u64 = 0; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 3.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_owner_cannot_override_admin = root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [root.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // // *TODO* Research why the contract is not panicking with owner cannot overwrite admin // if let ExecutionStatus::Failure(execution_error) = &expected_owner_cannot_override_admin // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // println!("{:?}", execution_error // .to_string()); // assert!(execution_error // .to_string() // .contains("owner cannot overwrite admin")); // } else { // unreachable!(); // } // } // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L975 // * **TODO** Look into a simple way to implement this function // */ // #[test] // fn not_use_too_much_gas() {} // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1011 // * **TODO** Look into a simple way to implement this function // */ // #[test] // fn reverts_when_another_oracle_is_added() {} // /** // * #change_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L794 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1028 // * **TODO** Look into a simple way to implement this function // */ // #[test] // fn reverts_when_min_submissions_is_set_to_0() {} // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1039 // */ // #[test] // fn decreases_the_oracle_count() { // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let past_count: u128 = root.view( // flux_aggregator.account_id(), // "oracle_count", // &json!({}).to_string().into_bytes() // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let current_count: u128 = root.view( // flux_aggregator.account_id(), // "oracle_count", // &json!({}).to_string().into_bytes() // ) // .unwrap_json(); // assert_eq!(past_count - 1, current_count); // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1049 // */ // #[test] // fn removing_oracles_and_updates_the_round_details() { // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let restart_delay: u64 = root // .call( // flux_aggregator.account_id(), // "restart_delay", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(min_submission_count, 1); // assert_eq!(max_submission_count, 1); // assert_eq!(restart_delay, 0); // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1057 // */ // #[test] // fn removing_oracles_and_emits_a_log() { // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let oracle_removed_event = root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).promise_results(); // let oracle_removed_event_log: String = oracle_removed_event // .clone() // .remove(1) // .unwrap() // .outcome() // .logs[0] // .parse() // .unwrap(); // let result = [oracle_one.account_id(), ", false".to_string()].join(""); // assert_eq!(result, oracle_removed_event_log); // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1067 // */ // #[test] // fn removing_oracles_and_removes_the_address_in_get_oracles() { // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // let mut n = 0; // while n < oracles.len() { // assert_ne!(oracles[n], oracle_one.account_id()); // n += 1; // } // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1081 // */ // #[test] // fn when_the_oracle_is_not_currently_added_and_reverts() { // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_oracle_not_enabled = root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_oracle_not_enabled // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("oracle not enabled")); // } else { // unreachable!(); // } // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1092 // */ // #[test] // fn when_removing_the_last_oracle_and_does_not_revert() { // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 0.to_string(), "_max_submissions": 0.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1101 // */ // #[test] // fn removing_oracles_and_when_called_by_anyone_but_the_owner_and_reverts() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_only_callable_by_owner = oracle_two.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_owner // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("Only callable by owner")); // } else { // unreachable!(); // } // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1101 // * **TODO** Look into why the contract is failing with round not accepting submissions and not no longer allowed oracle // */ // #[test] // fn it_is_allowed_to_report_on_one_more_round() { // let mut next_round: u128 = 1; // let answer: u128 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_no_longer_allowed_oracle = oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // // *TODO* Look into why the contract is failing with round not accepting submissions and not no longer allowed oracle // if let ExecutionStatus::Failure(execution_error) = &expected_no_longer_allowed_oracle // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("no longer allowed oracle")); // } else { // unreachable!(); // } // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1137 // */ // #[test] // fn it_is_allowed_to_finish_that_round_and_one_more_round() { // let mut next_round: u128 = 1; // let answer: u128 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // let expected_no_longer_allowed_oracle = oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // // *TODO* Look into why the contract is allowing oracle_three to future in participate in future rounds // // cannot participate in future rounds // if let ExecutionStatus::Failure(execution_error) = &expected_no_longer_allowed_oracle // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("no longer allowed oracle")); // } else { // unreachable!(); // } // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1147 // */ // #[test] // fn it_reverts_when_min_submissions_is_set_to_0() { // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_min_must_be_greater_than_0 = root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 0.to_string(), "_max_submissions": 0.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_min_must_be_greater_than_0 // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("min must be greater than 0")); // } else { // unreachable!(); // } // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1161 // */ // #[test] // fn can_swap_out_oracles() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // let mut n = 0; // while n < oracles.len() { // assert_ne!(oracles[n], oracle_three.account_id()); // if oracles[n] == oracle_two.account_id() { // assert_eq!(oracles[n] == oracle_two.account_id(), true); // } // n += 1; // } // n = 0; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_two.account_id()], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles_second: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // while n < oracles_second.len() { // assert_ne!(oracles_second[n], oracle_two.account_id()); // if oracles_second[n] == oracle_three.account_id() { // assert_eq!(oracles_second[n] == oracle_three.account_id(), true); // } // n += 1; // } // } // /** // * #removing_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1033 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1180 // * *TODO* Look into why the contract is panicking when removing and adding an oracle at the same time, not intended functionality. (oracle already enabled) // */ // #[test] // fn it_is_possible_to_remove_and_add_the_same_address() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // let mut n = 0; // while n < oracles.len() { // if oracles[n] == oracle_two.account_id() { // assert_eq!(oracles[n] == oracle_two.account_id(), true); // } // n += 1; // } // n = 0; // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_two.account_id()], "_added": [oracle_two.account_id()], "_added_admins": [oracle_two.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles_second: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // // *TODO* Look into why the contract is panicking when removing and adding an oracle at the same time, not intended functionality. (oracle already enabled) // while n < oracles_second.len() { // if oracles_second[n] == oracle_two.account_id() { // assert_eq!(oracles_second[n] == oracle_two.account_id(), true); // } // n += 1; // } // } // /** // * #get_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1199 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1207 // */ // #[test] // fn returns_the_addresses_of_addded_oracles() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracles[0], oracle_one.account_id()); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_two.account_id()], "_added_admins": [oracle_two.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let mut n = 0; // let oracles_second: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // while n < oracles_second.len() { // if oracles_second[n] == oracle_two.account_id() { // assert_eq!(oracles_second[n] == oracle_two.account_id(), true); // } // if oracles_second[n] == oracle_one.account_id() { // assert_eq!(oracles_second[n] == oracle_one.account_id(), true); // } // n += 1; // } // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let mut n = 0; // let oracles_third: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // while n < oracles_third.len() { // if oracles_third[n] == oracle_two.account_id() { // assert_eq!(oracles_third[n] == oracle_two.account_id(), true); // } // if oracles_third[n] == oracle_one.account_id() { // assert_eq!(oracles_third[n] == oracle_one.account_id(), true); // } // if oracles_third[n] == oracle_three.account_id() { // assert_eq!(oracles_third[n] == oracle_three.account_id(), true); // } // n += 1; // } // } // /** // * #get_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1199 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1233 // */ // #[test] // fn reorders_when_removing_from_the_beginning() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracles[0], oracle_one.account_id()); // assert_eq!(oracles[1], oracle_two.account_id()); // assert_eq!(oracles[2], oracle_three.account_id()); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles_second: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracles_second[0], oracle_three.account_id()); // assert_eq!(oracles_second[1], oracle_two.account_id()); // } // /** // * #get_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1199 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1243 // */ // #[test] // fn reorders_when_removing_from_the_middle() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracles[0], oracle_one.account_id()); // assert_eq!(oracles[1], oracle_two.account_id()); // assert_eq!(oracles[2], oracle_three.account_id()); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_two.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles_second: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracles_second[0], oracle_one.account_id()); // assert_eq!(oracles_second[1], oracle_three.account_id()); // } // /** // * #get_oracles - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1199 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1253 // */ // #[test] // fn pops_the_last_node_off_at_the_end() { // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracles[0], oracle_one.account_id()); // assert_eq!(oracles[1], oracle_two.account_id()); // assert_eq!(oracles[2], oracle_three.account_id()); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_three.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let oracles_second: Vec<String> = root // .view( // flux_aggregator.account_id(), // "get_oracles", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(oracles_second[0], oracle_one.account_id()); // assert_eq!(oracles_second[1], oracle_two.account_id()); // } // /** // * #withdraw_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1265 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1266 // */ // #[test] // fn withdraw_funds_and_succeeds() { // let deposit: u64 = 100; // let ( // root, // _aca, // link, // _oracle_one, // _oracle_two, // _oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // // Carol // root.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": test_helper.account_id().to_string(), "_amount": deposit.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // ).assert_success(); // let available_funds: u128 = root // .call( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .unwrap_json(); // assert_eq!(0, available_funds); // let balance: U128 = root // .call( // link.account_id(), // "ft_balance_of", // &json!({"account_id": test_helper.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(u128::from(balance), 100); // } // /** // * #withdraw_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1265 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1273 // */ // #[test] // fn does_not_let_withdrawls_happen_multiple_times() { // let deposit: u64 = 100; // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // _oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": test_helper.account_id().to_string(), "_amount": deposit.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_insufficient_reserve_funds = root.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": test_helper.account_id().to_string(), "_amount": deposit.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_insufficient_reserve_funds // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("insufficient reserve funds")); // } else { // unreachable!(); // } // } // /** // * #withdraw_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1265 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1289 // */ // #[test] // fn with_a_number_higher_than_the_available_link_balance_and_fails() { // let deposit: u64 = 100; // let answer: u128 = 100; // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let next_round: u128 = 1; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_insufficient_reserve_funds = root.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": test_helper.account_id().to_string(), "_amount": deposit.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_insufficient_reserve_funds // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("insufficient reserve funds")); // } else { // unreachable!(); // } // let available_funds: u128 = root // .call( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(97, available_funds); // } // /** // * #withdraw_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1265 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1307 // */ // #[test] // fn does_not_allow_withdrawal_with_less_than_2x_rounds_of_payments() { // let allowed: u128 = 82; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let available_funds: u128 = root // .call( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(100, available_funds); // let expected_insufficient_reserve_funds = root.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": test_helper.account_id().to_string(), "_amount": (allowed + 1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_insufficient_reserve_funds // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("insufficient reserve funds")); // } else { // unreachable!(); // } // root.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": test_helper.account_id().to_string(), "_amount": allowed.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // } // /** // * #withdraw_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1265 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1323 // */ // #[test] // fn when_called_by_a_non_owner_and_fails() { // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // _oracle_three, // test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let expected_only_callable_by_owner = eddy.call( // flux_aggregator.account_id(), // "withdraw_funds", // &json!({"_recipient": test_helper.account_id().to_string(), "_amount": 100.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_owner // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("Only callable by owner")); // } else { // unreachable!(); // } // let available_funds: u128 = root // .call( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(100, available_funds); // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1352 // */ // #[test] // fn updates_the_min_and_max_answer_counts() { // let rr_delay: u64 = 0; // let new_delay: u64 = 2; // let new_min: u64 = 1; // let new_max: u64 = 3; // let new_payment_amount: u64 = 2; // let mut min_submission_count: u64 = 3; // let mut max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let mut expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let mut expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let mut expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": new_payment_amount.to_string(), "_min_submissions": new_min.to_string(), "_max_submissions": new_max.to_string(), "_restart_delay": new_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_restart_delay: u64 = root // .call( // flux_aggregator.account_id(), // "restart_delay", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // expected_payment_amount = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // expected_min_submission_count = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // expected_max_submission_count = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, new_payment_amount); // assert_eq!(expected_min_submission_count, new_min); // assert_eq!(expected_max_submission_count, new_max); // assert_eq!(expected_restart_delay, new_delay); // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1352 // * *TODO* Try to implement a more type heavy assertion from the log instead of comparing strings // */ // #[test] // fn emits_a_log_announcing_the_new_round_details() { // let rr_delay: u64 = 0; // let new_delay: u64 = 2; // let new_min: u64 = 1; // let new_max: u64 = 3; // let new_payment_amount: u64 = 2; // let min_submission_count: u64 = 3; // let max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // let receipt = root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": new_payment_amount.to_string(), "_min_submissions": new_min.to_string(), "_max_submissions": new_max.to_string(), "_restart_delay": new_delay.to_string(), "_timeout": (timeout + 1).to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // // let expected_min_submission_count_log: u64 = // // receipt.promise_results().remove(1).unwrap().outcome().logs[1] // // .parse() // // .unwrap(); // // let expected_max_submission_count_log: u64 = // // receipt.promise_results().remove(1).unwrap().outcome().logs[2] // // .parse() // // .unwrap(); // // let expected_restart_delay_log: u64 = // // receipt.promise_results().remove(1).unwrap().outcome().logs[3] // // .parse() // // .unwrap(); // // let expected_timeout_log: u64 = receipt.promise_results().remove(1).unwrap().outcome().logs[4] // // .parse() // // .unwrap(); // assert_eq!(receipt.promise_results().remove(1).unwrap().outcome().logs[0], "2, 1, 3, 2, 1801"); // // assert_eq!(expected_min_submission_count_log, new_min); // // assert_eq!(expected_max_submission_count_log, new_max); // // assert_eq!(expected_restart_delay_log, new_min); // // assert_eq!(expected_timeout_log, (timeout + 1)); // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1381 // */ // #[test] // fn when_it_is_set_to_higher_than_the_number_or_oracles_and_reverts() { // let rr_delay: u64 = 0; // let min_submission_count: u64 = 3; // let max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // let expected_max_cannot_exceed_total = root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": min_submission_count.to_string(), "_max_submissions": 4.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_max_cannot_exceed_total // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("max cannot exceed total")); // } else { // unreachable!(); // } // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1392 // */ // #[test] // fn when_it_is_sets_the_min_higher_than_the_max_and_reverts() { // let rr_delay: u64 = 0; // let min_submission_count: u64 = 3; // let max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // let expected_max_must_equal_exceed_min = root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 3.to_string(), "_max_submissions": 2.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_max_must_equal_exceed_min // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("max must equal/exceed min")); // } else { // unreachable!(); // } // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1404 // */ // #[test] // fn when_delay_equal_or_greater_the_oracle_count_and_reverts() { // let rr_delay: u64 = 0; // let min_submission_count: u64 = 3; // let max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // let expected_revert_delay_cannot_exceed_total = root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": 3.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_revert_delay_cannot_exceed_total // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("revert delay cannot exceed total")); // } else { // unreachable!(); // } // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1417 // * *TODO* Look into why you cannot pass a decimal number into the update_future_rounds payment_amount // */ // #[test] // fn when_the_payment_amount_does_not_cover_reserve_rounds_and_reverts() { // let rr_delay: u64 = 0; // let min_submission_count: u64 = 3; // let max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // // *TODO* Look into why you cannot pass a decimal number into the update_future_rounds payment_amount (17.67) // let expected_insufficient_funds_for_payment = root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": "18", "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_insufficient_funds_for_payment // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("insufficient funds for payment")); // } else { // unreachable!(); // } // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1434 // */ // #[test] // fn min_oracles_is_set_to_0_and_reverts() { // let rr_delay: u64 = 0; // let min_submission_count: u64 = 3; // let max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // let expected_min_must_be_greater_than_0 = root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": 0.to_string(), "_max_submissions": 0.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_min_must_be_greater_than_0 // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("min must be greater than 0")); // } else { // unreachable!(); // } // } // /** // * #update_future_rounds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1334 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1434 // * *TODO* Look into why the self.only_owner() function breaks the contract in update_future_rounds // */ // #[test] // fn update_future_rounds_and_when_called_by_anyone_but_the_owner_and_reverts() { // let rr_delay: u64 = 0; // let min_submission_count: u64 = 3; // let max_submission_count: u64 = 3; // let payment_amount: u64 = 3; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected_payment_amount: u64 = root // .call( // flux_aggregator.account_id(), // "get_payment_amount", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_min_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "min_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_max_submission_count: u64 = root // .call( // flux_aggregator.account_id(), // "max_submission_count", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(expected_payment_amount, payment_amount); // assert_eq!(expected_min_submission_count, min_submission_count); // assert_eq!(expected_max_submission_count, max_submission_count); // let expected_only_callable_by_owner = oracle_two.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": payment_amount.to_string(), "_min_submissions": min_submission_count.to_string(), "_max_submissions": max_submission_count.to_string(), "_restart_delay": rr_delay.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_owner // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("Only callable by owner")); // } else { // unreachable!(); // } // } // /** // * #update_available_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1449 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1450 // */ // #[test] // fn checks_the_link_token_to_see_if_any_additional_funds_are_available() { // let deposit: u64 = 100; // let ( // root, // _aca, // link, // _oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let original_balance: u64 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_available_funds", // &json!({}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let original_balance_updated: u64 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(original_balance, original_balance_updated); // root.call( // link.account_id(), // "ft_transfer", // &json!({ // "receiver_id": flux_aggregator.account_id(), "amount": deposit.to_string(), "memo": "None" // }) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "update_available_funds", // &json!({}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let new_balance: u64 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!((original_balance + deposit), new_balance); // } // /** // * #update_available_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1449 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1464 // */ // #[test] // fn removes_allocated_funds_from_the_available_balance() { // let deposit: u64 = 100; // let ( // root, // _aca, // link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let original_balance: u64 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": 100.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // link.account_id(), // "ft_transfer", // &json!({ // "receiver_id": flux_aggregator.account_id(), "amount": deposit.to_string(), "memo": "None" // }) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "update_available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected: u64 = (original_balance + deposit) - 3; // let new_balance: u64 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(expected, new_balance); // } // /** // * #update_available_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1449 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1464 // * **TODO** Figure out how to assert a failure here // */ // #[test] // fn update_available_funds_and_emits_a_log() { // let deposit: u64 = 100; // let ( // root, // _aca, // link, // _oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // link.account_id(), // "ft_transfer", // &json!({ // "receiver_id": flux_aggregator.account_id(), "amount": deposit.to_string(), "memo": "None" // }) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1, // deposit // ) // .assert_success(); // let receipt = root.call( // flux_aggregator.account_id(), // "update_available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // let expected: u64 = receipt.promise_results().remove(5).unwrap().outcome().logs[0] // .parse::<u64>() // .unwrap(); // let new_balance: u64 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(new_balance, expected); // } // /** // * #update_available_funds - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1449 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1464 // */ // #[test] // fn when_the_available_funds_have_not_changed_does_not_emit_a_log() { // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let receipt = root.call( // flux_aggregator.account_id(), // "update_available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // // *TODO* Figure out how to assert a failure here. // assert_eq!(receipt.logs().len(), 0); // } // /** // * #withdraw_payment - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1497 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1503 // */ // #[test] // fn transfers_link_to_the_recipient() { // let payment_amount: u64 = 3; // let ( // root, // _aca, // link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": 100.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let original_balance: U128 = root // .call( // link.account_id(), // "ft_balance_of", // &json!({"account_id": flux_aggregator.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let original_oracle_one_balance: U128 = root // .call( // link.account_id(), // "ft_balance_of", // &json!({"account_id": oracle_one.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(0, u128::from(original_oracle_one_balance)); // oracle_one // .call( // flux_aggregator.account_id(), // "withdraw_payment", // &json!({"_oracle": oracle_one.account_id().to_string(), "_recipient": oracle_one.account_id().to_string(), "_amount": payment_amount.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1, // deposit // ) // .assert_success(); // let updated_balance: U128 = root // .call( // link.account_id(), // "ft_balance_of", // &json!({"account_id": flux_aggregator.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(97, u128::from(updated_balance)); // let updated_oracle_one_balance: U128 = root // .call( // link.account_id(), // "ft_balance_of", // &json!({"account_id": oracle_one.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(3, u128::from(updated_oracle_one_balance)); // } // /** // * #withdraw_payment - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1497 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1515 // */ // #[test] // fn decrements_the_allocated_funds_counter() { // let payment_amount: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": 100.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let original_allocation: u128 = root // .call( // flux_aggregator.account_id(), // "allocated_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // oracle_one // .call( // flux_aggregator.account_id(), // "withdraw_payment", // &json!({"_oracle": oracle_one.account_id().to_string(), "_recipient": oracle_one.account_id().to_string(), "_amount": payment_amount.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let updated_allocation: u128 = root // .call( // flux_aggregator.account_id(), // "allocated_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!((original_allocation - payment_amount), updated_allocation); // } // /** // * #withdraw_payment - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1497 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1526 // */ // #[test] // fn when_the_caller_withdraws_more_than_they_have_and_reverts() { // let payment_amount: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": 100.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_revert_insufficient_withdrawable_funds = oracle_one // .call( // flux_aggregator.account_id(), // "withdraw_payment", // &json!({"_oracle": oracle_one.account_id().to_string(), "_recipient": oracle_one.account_id().to_string(), "_amount": (payment_amount + 1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = // &expected_revert_insufficient_withdrawable_funds // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("revert insufficient withdrawable funds")); // } else { // unreachable!(); // } // } // /** // * #withdraw_payment - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1497 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1540 // */ // #[test] // fn when_the_caller_is_not_the_admin_and_reverts() { // let payment_amount: u128 = 3; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": 1.to_string(), "_submission": 100.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_only_callable_by_admin = oracle_three // .call( // flux_aggregator.account_id(), // "withdraw_payment", // &json!({"_oracle": oracle_one.account_id().to_string(), "_recipient": oracle_three.account_id().to_string(), "_amount": 1.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_admin // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("only callable by admin")); // } else { // unreachable!(); // } // } // /** // * #transfer_admin - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1552 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1567 // */ // #[test] // fn when_the_admin_tries_to_transfer_the_admin_and_works() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_two.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let receipt = oracle_one // .call( // flux_aggregator.account_id(), // "transfer_admin", // &json!({"_oracle": oracle_two.account_id().to_string(), "_new_admin": oracle_three.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!( // "oracle_two, oracle_one, oracle_three", // receipt.promise_results().remove(1).unwrap().outcome().logs[0] // ); // let get_admin: String = oracle_one // .call( // flux_aggregator.account_id(), // "get_admin", // &json!({"_oracle": oracle_two.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(oracle_one.account_id(), get_admin); // } // /** // * #transfer_admin - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1552 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1584 // */ // #[test] // fn when_the_non_admin_owner_tries_to_update_the_admin_and_reverts() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_two.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_only_callable_by_admin = root.call( // flux_aggregator.account_id(), // "transfer_admin", // &json!({"_oracle": oracle_two.account_id().to_string(), "_new_admin": oracle_three.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_admin // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("revert only callable by admin")); // } else { // unreachable!(); // } // } // /** // * #transfer_admin - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1552 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1595 // */ // #[test] // fn when_the_non_admin_oracle_tries_to_update_the_admin_and_reverts() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_two.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_only_callable_by_admin = oracle_two.call( // flux_aggregator.account_id(), // "transfer_admin", // &json!({"_oracle": oracle_two.account_id().to_string(), "_new_admin": oracle_three.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_admin // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("revert only callable by admin")); // } else { // unreachable!(); // } // } // /** // * #accept_admin - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1606 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1624 // */ // #[test] // fn when_the_new_admin_tries_to_accept_and_works() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_two.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "transfer_admin", // &json!({"_oracle": oracle_two.account_id().to_string(), "_new_admin": oracle_three.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let receipt = oracle_three.call( // flux_aggregator.account_id(), // "accept_admin", // &json!({"_oracle": oracle_two.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!( // "oracle_two, oracle_three", // receipt.promise_results().remove(1).unwrap().outcome().logs[0] // ); // let get_admin: String = oracle_one // .call( // flux_aggregator.account_id(), // "get_admin", // &json!({"_oracle": oracle_two.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(oracle_three.account_id(), get_admin); // } // /** // * #accept_admin - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1606 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1634 // */ // #[test] // fn when_someone_other_than_the_admin_tries_to_accept_and_reverts() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_two.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "transfer_admin", // &json!({"_oracle": oracle_two.account_id().to_string(), "_new_admin": oracle_three.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_only_callable_by_pending_admin = oracle_two.call( // flux_aggregator.account_id(), // "accept_admin", // &json!({"_oracle": oracle_two.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_pending_admin // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("only callable by pending admin")); // } else { // unreachable!(); // } // let expected_only_callable_by_pending_admin_second = oracle_one.call( // flux_aggregator.account_id(), // "accept_admin", // &json!({"_oracle": oracle_two.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = // &expected_only_callable_by_pending_admin_second // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("only callable by pending admin")); // } else { // unreachable!(); // } // } // /** // * #on_token_transfer (ft_on_transfer) - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1647 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1648 // */ // #[test] // fn updates_the_available_balance() { // let ( // root, // _aca, // link, // _oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let original_balance: u128 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_available_funds", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // ) // .assert_success(); // let updated_balance: u128 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(original_balance, updated_balance); // let prom = root.call( // link.account_id(), // "ft_transfer_call", // &json!({ // "receiver_id": flux_aggregator.account_id(), "amount": 100.to_string(), "memo": "None", "msg": "".to_string() // }) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1 // ); // println!("{:?}", prom.promise_results()); // let new_balance: u128 = root // .view( // flux_aggregator.account_id(), // "available_funds", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(200, new_balance); // } // /** // * #on_token_transfer (ft_on_transfer) - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1647 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1661 // */ // #[test] // fn reverts_given_calldata() { // let ( // root, // _aca, // link, // _oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let prom = root.call( // link.account_id(), // "ft_transfer_call", // &json!({ // "receiver_id": flux_aggregator.account_id(), "amount": 100.to_string(), "memo": "None", "msg": "12345678".to_string() // }) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 1 // ); // println!("{:?}", prom.promise_results()); // } // /** // * #request_new_round - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1669 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1679 // */ // #[test] // fn announces_a_new_round_via_log_event() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": root.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let receipt = root.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!( // "2, root, 161000000000", // receipt.promise_results().remove(1).unwrap().outcome().logs[0] // ); // } // /** // * #request_new_round - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1669 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1683 // */ // #[test] // fn returns_the_new_round_id() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": root.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": flux_aggregator_test_helper_contract.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let mut round_id: u64 = root // .view( // flux_aggregator_test_helper_contract.account_id(), // "requested_round_id", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(round_id, 0); // root.call( // flux_aggregator_test_helper_contract.account_id(), // "request_new_round", // &json!({"_aggregator": flux_aggregator.account_id()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // round_id = root // .view( // flux_aggregator_test_helper_contract.account_id(), // "requested_round_id", // &json!({}).to_string().into_bytes(), // ) // .unwrap_json(); // assert_eq!(round_id > 0, true); // } // /** // * #request_new_round - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1669 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1701 // */ // #[test] // fn when_there_is_a_new_round_in_progress_and_reverts() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": root.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_previous_round_must_be_supersedable = root.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_previous_round_must_be_supersedable // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("prev round must be supersedable")); // } else { // unreachable!(); // } // } // /** // * #request_new_round - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1669 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1701 // * *TODO* Look into increaseTimeBy and mineBlock implementation // */ // #[test] // fn when_that_round_has_timed_out_and_starts_a_new_round() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": root.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // *TODO* Look into increaseTimeBy and mineBlock implementation // let receipt = root.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // } // /** // * #request_new_round - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1669 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1722 // */ // #[test] // fn when_there_is_a_restart_delay_set_and_reverts_if_a_round_is_started_before_the_delay() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": root.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": eddy.account_id().to_string(), "_authorized": true, "_delay": 1.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // eddy.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // next_round = next_round + 1; // // Eddy can't start because of the delay // let expected_must_delay_requests = eddy.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_must_delay_requests // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("must delay requests")); // } else { // unreachable!(); // } // // Carol starts a new round instead // root.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // // round completes // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // next_round = next_round + 1; // eddy.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #request_new_round - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1669 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1722 // * *TODO* Look into increaseTimeBy and mineBlock implementation // */ // #[test] // fn when_all_oracles_have_been_removed_and_then_re_added_and_does_not_get_stuck() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": root.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [oracle_one.account_id()], "_added": [], "_added_admins": [], "_min_submissions": 0.to_string(), "_max_submissions": 0.to_string(), "_restart_delay": 0.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // *TODO* Look into increaseTimeBy and mineBlock functions // // advance a few rounds // // for (let i = 0; i < 7; i++) { // // await aggregator.requestNewRound(); // // nextRound = nextRound + 1; // // await increaseTimeBy(timeout + 1, ethers.provider); // // await mineBlock(ethers.provider); // // } // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // round completes // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // } // /** // * #set_requester_permissions - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1760 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1769 // */ // #[test] // fn when_called_by_the_owner_and_allows_the_specified_address_to_start_new_rounds() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // } // /** // * #set_requester_permissions - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1760 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1775 // */ // #[test] // fn emits_a_log_announcing_the_update() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // let receipt = root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!( // "oracle_one, true, 0", // receipt.promise_results().remove(1).unwrap().outcome().logs[0] // ); // } // /** // * #set_requester_permissions - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1760 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1786 // */ // #[test] // fn when_the_address_is_already_authorized_and_does_not_emit_a_log_for_already_authorized_accounts() // { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let receipt = root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!(0, receipt.logs().len()); // } // /** // * #set_requester_permissions - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1760 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1798 // */ // #[test] // fn when_permission_is_removed_by_the_owner_and_does_not_allow_the_specified_address_to_start_new_rounds( // ) { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": false, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_not_authorized_requester = oracle_one.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_not_authorized_requester // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("not authorized requester")); // } else { // unreachable!(); // } // } // /** // * #set_requester_permissions - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1760 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1804 // */ // #[test] // fn when_permission_is_removed_by_the_owner_and_emits_a_log_announcing_the_update() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let receipt = root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": false, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!( // "oracle_one, false, 0", // receipt.promise_results().remove(1).unwrap().outcome().logs[0] // ); // } // /** // * #set_requester_permissions - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1760 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1810 // * *TODO* Look into why a log is still being emitted, looks as though it's still emitting in the Solidity code as well // */ // #[test] // fn does_not_emit_a_log_for_accounts_without_authorization() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let receipt = root.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_two.account_id().to_string(), "_authorized": false, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // // *TODO* Look into why a log is still being emitted, looks as though it's still emitting in the Solidity code as well // // println!("{:?}", receipt.logs()); // assert_eq!(0, receipt.logs().len()); // } // /** // * #set_requester_permissions - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1760 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1819 // */ // #[test] // fn when_called_by_a_stranger_and_reverts() { // let min_ans: u64 = 1; // let max_ans: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u64 = 100; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id()], "_added_admins": [oracle_one.account_id()], "_min_submissions": min_ans.to_string(), "_max_submissions": max_ans.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let expected_only_callable_by_owner = oracle_one.call( // flux_aggregator.account_id(), // "set_requester_permissions", // &json!({"_requester": oracle_one.account_id().to_string(), "_authorized": true, "_delay": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_owner // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("Only callable by owner")); // } else { // unreachable!(); // } // let expected_not_authorized_requester = oracle_one.call( // flux_aggregator.account_id(), // "request_new_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_not_authorized_requester // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("not authorized requester")); // } else { // unreachable!(); // } // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1850 // * *TODO* Look into why the started_at is being set, it should not be set // */ // #[test] // fn when_round_id_0_is_passed_in_and_returns_all_of_the_important_round_information() { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let base_funds: u128 = 88; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 2); // assert_eq!(state.2, previous_submission); // // *TODO* Look into why the started_at is being set, it should not be set // // assert_eq!(state.3, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, base_funds); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1865 // */ // #[test] // fn when_round_id_0_is_passed_in_reverts_if_called_by_a_contract() { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_off_chain_reading_only = root.call( // flux_aggregator_test_helper_contract.account_id(), // "read_oracle_round_state", // &json!({"_aggregator": flux_aggregator.account_id(), "_oracle": oracle_one.account_id()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_off_chain_reading_only // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("off-chain reading only")); // } else { // unreachable!(); // } // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1887 // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_less_than_min_submissions_and_oracle_not_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": 0.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 2); // assert_eq!(state.2, previous_submission); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 85); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1908 // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_less_than_min_submissions_and_oracle_included_and_is_not_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": 0.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 2); // assert_eq!(state.2, answer); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 85); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1908 // * *TODO* Look into increaseTimeBy and mineBlock implementation // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_less_than_min_submissions_and_oracle_included_and_is_eligible_to_submit_and_timed_out_is_eligible_to_submit( // ) { // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1951 // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_greater_than_or_equal_to_min_submissions_and_oracle_not_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": 0.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 2); // assert_eq!(state.2, previous_submission); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 79); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1972 // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_greater_than_or_equal_to_min_submissions_and_oracle_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": 0.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 3); // assert_eq!(state.2, answer); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 79); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1993 // * *TODO* Look into increaseTimeBy and mineBlock implementation // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_greater_than_or_equal_to_min_submissions_and_oracle_included_and_timed_out_is_eligible_to_submit( // ) { // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2017 // * *TODO* Look into increaseTimeBy and mineBlock implementation // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_max_submissions_and_oracle_not_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": 0.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_five // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 3); // assert_eq!(state.2, previous_submission); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, 76); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2040 // */ // #[test] // fn when_the_restart_delay_is_not_enforced_and_max_submissions_and_oracle_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": 0.to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 3); // assert_eq!(state.2, answer); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, 76); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2071 // */ // #[test] // fn when_the_restart_delay_is_enforced_and_less_than_min_submissions_and_oracle_not_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": (max_answers - 1).to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 2); // assert_eq!(state.2, previous_submission); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 82); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2092 // */ // #[test] // fn when_the_restart_delay_is_enforced_and_less_than_min_submissions_and_oracle_included_and_is_not_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": (max_answers - 1).to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 2); // assert_eq!(state.2, answer); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 82); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2092 // * *TODO* Look into increaseTimeBy and mineBlock implementation // */ // #[test] // fn when_the_restart_delay_is_enforced_and_less_than_min_submissions_and_oracle_included_and_is_eligible_to_submit_and_timed_out_is_eligible_to_submit( // ) { // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2135 // */ // #[test] // fn when_the_restart_delay_is_enforced_and_greater_than_or_equal_to_min_submissions_and_oracle_not_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": (max_answers - 1).to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 2); // assert_eq!(state.2, previous_submission); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 79); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2156 // * *TODO* Look into why timeout is not 0. // */ // #[test] // fn when_the_restart_delay_is_enforced_and_greater_than_or_equal_to_min_submissions_and_oracle_included_and_is_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": (max_answers - 1).to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 3); // assert_eq!(state.2, answer); // assert_eq!(state.3 > 0, true); // // *TODO* Look into why timeout is not 0. // assert_eq!(state.4, timeout); // assert_eq!(state.5, 79); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2177 // * *TODO* Look into increaseTimeBy and mineBlock implementation // */ // #[test] // fn when_the_restart_delay_is_enforced_and_greater_than_or_equal_to_min_submissions_and_oracle_included_and_timed_out_is_eligible_to_submit( // ) { // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2201 // */ // #[test] // fn when_the_restart_delay_is_enforced_and_max_submissions_and_oracle_not_included_and_is_not_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": (max_answers - 1).to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_five // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 3); // assert_eq!(state.2, previous_submission); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, 76); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2224 // */ // #[test] // fn when_the_restart_delay_is_enforced_and_max_submissions_and_oracle_included_and_is_not_eligible_to_submit( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // oracle_four, // oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id(), oracle_four.account_id(), oracle_five.account_id()], "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // // advanceRound // oracle_three.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_two.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_four.call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": previous_submission.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // next_round = next_round + 1; // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // root.call( // flux_aggregator.account_id(), // "update_future_rounds", // &json!({"_payment_amount": 3.to_string(), "_min_submissions": min_answers.to_string(), "_max_submissions": max_answers.to_string(), "_restart_delay": (max_answers - 1).to_string(), "_timeout": timeout.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_four // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 3); // assert_eq!(state.2, answer); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, 76); // assert_eq!(state.6, 5); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2259 // */ // #[test] // fn when_non_zero_round_id_0_is_passed_in_and_returns_info_about_previous_rounds() { // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answers: Vec<u128> = [0, 42, 47, 52, 57].to_vec(); // let current_funds: u128 = 73; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // advanceRound * 4 (1) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (2) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (3) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (4) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 1.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 1); // assert_eq!(state.2, answers[3]); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, current_funds); // assert_eq!(state.6, 3); // assert_eq!(state.7, 0); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2274 // */ // #[test] // fn when_non_zero_round_id_0_is_passed_in_and_returns_info_about_previous_rounds_that_were_not_submitted_to( // ) { // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answers: Vec<u128> = [0, 42, 47, 52, 57].to_vec(); // let current_funds: u128 = 73; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // advanceRound * 4 (1) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (2) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (3) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (4) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 2.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 2); // assert_eq!(state.2, answers[3]); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, current_funds); // assert_eq!(state.6, 3); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2291 // */ // #[test] // fn when_non_zero_round_id_0_is_passed_in_and_for_the_current_round_which_has_not_been_submitted_to_and_returns_info_about_the_current_round_that_hasnt_been_submitted_to( // ) { // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answers: Vec<u128> = [0, 42, 47, 52, 57].to_vec(); // let current_funds: u128 = 73; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // advanceRound * 4 (1) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (2) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (3) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (4) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 4.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 4); // assert_eq!(state.2, answers[3]); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, current_funds); // assert_eq!(state.6, 3); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2306 // */ // #[test] // fn when_non_zero_round_id_0_is_passed_in_and_for_the_current_round_which_has_not_been_submitted_to_and_returns_info_about_the_subsequent_round( // ) { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answers: Vec<u128> = [0, 42, 47, 52, 57].to_vec(); // let current_funds: u128 = 73; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // advanceRound * 4 (1) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (2) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (3) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (4) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 5.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 5); // assert_eq!(state.2, answers[3]); // assert_eq!(state.3 <= 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, current_funds); // assert_eq!(state.6, 3); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2327 // */ // #[test] // fn when_non_zero_round_id_0_is_passed_in_and_for_the_current_round_which_has_been_submitted_to_and_returns_info_about_the_current_round_that_hasnt_been_submitted_to( // ) { // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answers: Vec<u128> = [0, 42, 47, 52, 57].to_vec(); // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // advanceRound * 4 (1) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (2) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (3) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (4) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 4.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 4); // assert_eq!(state.2, answers[4]); // assert_eq!(state.3 > 0, true); // assert_eq!(state.4, timeout); // assert_eq!(state.5, 70); // assert_eq!(state.6, 3); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2342 // */ // #[test] // fn when_non_zero_round_id_0_is_passed_in_and_for_the_current_round_which_has_been_submitted_to_and_returns_info_about_the_subsequent_round( // ) { // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answers: Vec<u128> = [0, 42, 47, 52, 57].to_vec(); // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // advanceRound * 4 (1) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (2) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (3) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (4) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 5.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, true); // assert_eq!(state.1, 5); // assert_eq!(state.2, answers[4]); // assert_eq!(state.3 <= 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, 70); // assert_eq!(state.6, 3); // assert_eq!(state.7, 3); // } // /** // * #oracle_round_state - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L1830 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2359 // */ // #[test] // fn when_non_zero_round_id_0_is_passed_in_and_returns_speculative_info_about_future_rounds() { // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answers: Vec<u128> = [0, 42, 47, 52, 57].to_vec(); // let current_funds: u128 = 73; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_added_admins": [oracle_one.account_id(), oracle_two.account_id(), oracle_three.account_id()], "_min_submissions": 2.to_string(), "_max_submissions": 3.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let starting_state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 0.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // advanceRound * 4 (1) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[1].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (2) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[2].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (3) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_two // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[3].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // next_round = next_round + 1; // // advanceRound * 4 (4) // oracle_one // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answers[4].to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let state: (bool, u64, u128, u64, u64, u128, u64, u128) = root // .call( // flux_aggregator.account_id(), // "oracle_round_state", // &json!({"_oracle": oracle_three.account_id().to_string(), "_queried_round_id": 6.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // println!( // "{:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}", // state.0, state.1, state.2, state.3, state.4, state.5, state.6, state.7 // ); // assert_eq!(state.0, false); // assert_eq!(state.1, 6); // assert_eq!(state.2, answers[3]); // assert_eq!(state.3 <= 0, true); // assert_eq!(state.4, 0); // assert_eq!(state.5, current_funds); // assert_eq!(state.6, 3); // assert_eq!(state.7, 3); // } // /** // * #get_round_data - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2376 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2386 // * *TODO* Find current time and make sure its above upatedAt // */ // #[test] // fn get_round_data_and_returns_relevant_information() { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let latest_round_id: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let current_funds: u128 = 73; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let latest_round_id: u64 = root // .call( // flux_aggregator.account_id(), // "latest_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let round: (u64, u128, u64, u64, u64) = root // .call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": latest_round_id.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(latest_round_id, round.0); // assert_eq!(answer, round.1); // // const nowSeconds = new Date().valueOf() / 1000; // // assert.isAbove(round.updatedAt.toNumber(), nowSeconds - 120); // // *TODO* Find current time and make sure its above upatedAt // assert_eq!(round.2, round.3); // assert_eq!(latest_round_id, round.4); // } // /** // * #get_round_data - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2376 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2396 // */ // #[test] // fn get_round_data_and_reverts_if_a_round_is_not_present() { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let latest_round_id: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let current_funds: u128 = 73; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let latest_round_id: u64 = root // .call( // flux_aggregator.account_id(), // "latest_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let expected_no_data_present = root.call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": (latest_round_id + 1).to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("No data present")); // } else { // unreachable!(); // } // } // /** // * #get_round_data - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2376 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2396 // * *TODO* Calculate math for overflowed u64 integer // */ // #[test] // fn get_round_data_and_reverts_if_a_round_ID_is_too_big() { // let previous_submission: u128 = 42; // let min_answers: u64 = 3; // let max_answers: u64 = 4; // let latest_round_id: u64 = 1; // let rr_delay: u64 = 0; // let mut next_round: u64 = 1; // let answer: u128 = 100; // let current_funds: u128 = 73; // let timeout: u64 = 1800; // let ( // root, // _aca, // _link, // oracle_one, // oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let latest_round_id: u64 = root // .call( // flux_aggregator.account_id(), // "latest_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // // // *TODO* Calculate math for overflowed u64 integer // let expected_no_data_present = root.call( // flux_aggregator.account_id(), // "get_round_data", // &json!({"_round_id": 100.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("No data present")); // } else { // unreachable!(); // } // } // /** // * #latest_round_data - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2407 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2419 // * *TODO* Find current time and make sure its above upatedAt // */ // #[test] // fn latest_round_data_when_an_answer_has_been_received_and_returns_the_relevant_round_info_without_reverting( // ) { // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let answer: u128 = 100; // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let round: (u64, u128, u64, u64, u64) = root // .call( // flux_aggregator.account_id(), // "latest_round_data", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // let latest_round_id: u64 = root // .call( // flux_aggregator.account_id(), // "latest_round", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(latest_round_id, round.0); // assert_eq!(answer, round.1); // // const nowSeconds = new Date().valueOf() / 1000; // // assert.isAbove(round.updatedAt.toNumber(), nowSeconds - 120); // // *TODO* Find current time and make sure its above upatedAt // assert_eq!(round.2, round.3); // assert_eq!(latest_round_id, round.4); // } // /** // * #latest_round_data - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2407 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2432 // */ // #[test] // fn latest_round_data_when_an_answer_has_been_received_and_reverts_if_a_round_is_not_present() { // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let expected_no_data_present = root.call( // flux_aggregator.account_id(), // "latest_round_data", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_no_data_present // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error.to_string().contains("No data present")); // } else { // unreachable!(); // } // } // /** // * #latest_answer - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2437 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2449 // */ // #[test] // fn latest_answer_when_an_answer_has_already_been_received_and_returns_the_latest_answer_without_reverting( // ) { // let rr_delay: u64 = 0; // let next_round: u64 = 1; // let answer: u128 = 100; // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // oracle_three // .call( // flux_aggregator.account_id(), // "submit", // &json!({"_round_id": next_round.to_string(), "_submission": answer.to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .assert_success(); // let latest_answer: u128 = root // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(answer, latest_answer); // } // /** // * #latest_answer - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2437 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2454 // */ // #[test] // fn latest_answer_and_returns_zero() { // let rr_delay: u64 = 0; // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // _aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // root.call( // flux_aggregator.account_id(), // "change_oracles", // &json!({"_removed": [], "_added": [oracle_three.account_id()], "_added_admins": [oracle_three.account_id()], "_min_submissions": 1.to_string(), "_max_submissions": 1.to_string(), "_restart_delay": rr_delay.to_string()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ).assert_success(); // let latest_answer: u128 = root // .call( // flux_aggregator.account_id(), // "latest_answer", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!(0, latest_answer); // } // /** // * #set_validator - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2459 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2465 // */ // #[test] // fn set_validator_and_emits_a_log_event_showing_the_validator_was_changed() { // let ( // root, // _aca, // _link, // _oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let empty_address: String = root // .call( // flux_aggregator.account_id(), // "get_validator", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!("", empty_address); // let receipt = root.call( // flux_aggregator.account_id(), // "set_validator", // &json!({"_new_validator": aggregator_validator_mock.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!( // receipt.promise_results().remove(1).unwrap().outcome().logs[0], // ", aggregator_validator_mock" // ); // let receipt_two = root.call( // flux_aggregator.account_id(), // "set_validator", // &json!({"_new_validator": aggregator_validator_mock.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // assert_eq!(receipt_two.logs().len(), 0); // } // /** // * #set_validator - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2459 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2479 // */ // #[test] // fn set_validator_and_when_called_by_a_non_owner_and_reverts() { // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // _controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let empty_address: String = root // .call( // flux_aggregator.account_id(), // "get_validator", // &json!({}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!("", empty_address); // let expected_only_callable_by_owner = oracle_one.call( // flux_aggregator.account_id(), // "set_validator", // &json!({"_new_validator": aggregator_validator_mock.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_owner // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("Only callable by owner")); // } else { // unreachable!(); // } // } // /** // * integrating with historic deviation checker - https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2485 // * https://github.com/smartcontractkit/chainlink-brownie-contracts/blob/8071761a5b0e5444fc0de1751b7b398caf69ced4/contracts/test/v0.6/FluxAggregator.test.ts#L2504 // */ // #[test] // fn raises_a_flag_on_with_high_enough_deviation() { // let flagging_threshold: u128 = 1000; // let ( // root, // _aca, // _link, // oracle_one, // _oracle_two, // _oracle_three, // _test_helper, // _eac, // _eac_without_access_controller, // _oracle_four, // _oracle_five, // aggregator_validator_mock, // _flags, // _consumer, // _flags_consumer, // controller, // _controller_2, // _flux_aggregator_test_helper_contract, // _eddy, // _mock_v3_aggregator, // _mock_v3_aggregator_second, // _read_controller, // flux_aggregator, // ) = init(); // let empty_address: String = root // .call( // controller.account_id(), // "add_access", // &json!({"_user": aggregator_validator_mock.account_id()}).to_string().into_bytes(), // DEFAULT_GAS, // 0, // deposit // ) // .unwrap_json(); // assert_eq!("", empty_address); // let expected_only_callable_by_owner = oracle_one.call( // flux_aggregator.account_id(), // "set_validator", // &json!({"_new_validator": aggregator_validator_mock.account_id().to_string()}) // .to_string() // .into_bytes(), // DEFAULT_GAS, // 0, // deposit // ); // if let ExecutionStatus::Failure(execution_error) = &expected_only_callable_by_owner // .promise_errors() // .remove(0) // .unwrap() // .outcome() // .status // { // assert!(execution_error // .to_string() // .contains("Only callable by owner")); // } else { // unreachable!(); // } // }
use crate::ErasureCoding; use blst_rust::types::g1::FsG1; use kzg::G1; use std::iter; use std::num::NonZeroUsize; use subspace_core_primitives::crypto::kzg::Commitment; use subspace_core_primitives::crypto::Scalar; // TODO: This could have been done in-place, once implemented can be exposed as a utility fn concatenated_to_interleaved<T>(input: Vec<T>) -> Vec<T> where T: Clone, { if input.len() <= 1 { return input; } let (first_half, second_half) = input.split_at(input.len() / 2); first_half .iter() .zip(second_half) .flat_map(|(a, b)| [a, b]) .cloned() .collect() } // TODO: This could have been done in-place, once implemented can be exposed as a utility fn interleaved_to_concatenated<T>(input: Vec<T>) -> Vec<T> where T: Clone, { let first_half = input.iter().step_by(2); let second_half = input.iter().skip(1).step_by(2); first_half.chain(second_half).cloned().collect() } #[test] fn basic_data() { let scale = NonZeroUsize::new(8).unwrap(); let num_shards = 2usize.pow(scale.get() as u32); let ec = ErasureCoding::new(scale).unwrap(); let source_shards = (0..num_shards / 2) .map(|_| rand::random::<[u8; Scalar::SAFE_BYTES]>()) .map(Scalar::from) .collect::<Vec<_>>(); let parity_shards = ec.extend(&source_shards).unwrap(); assert_ne!(source_shards, parity_shards); let partial_shards = concatenated_to_interleaved( iter::repeat(None) .take(num_shards / 4) .chain(source_shards.iter().skip(num_shards / 4).copied().map(Some)) .chain(parity_shards.iter().take(num_shards / 4).copied().map(Some)) .chain(iter::repeat(None).take(num_shards / 4)) .collect::<Vec<_>>(), ); let recovered = interleaved_to_concatenated(ec.recover(&partial_shards).unwrap()); assert_eq!( recovered, source_shards .iter() .chain(&parity_shards) .copied() .collect::<Vec<_>>() ); } #[test] fn basic_commitments() { let scale = NonZeroUsize::new(7).unwrap(); let num_shards = 2usize.pow(scale.get() as u32); let ec = ErasureCoding::new(scale).unwrap(); let source_commitments = (0..num_shards / 2) .map(|_| Commitment::from(FsG1::rand())) .collect::<Vec<_>>(); let parity_commitments = ec.extend_commitments(&source_commitments).unwrap(); assert_eq!(source_commitments.len() * 2, parity_commitments.len()); // Even indices must be source assert_eq!( source_commitments, parity_commitments .iter() .step_by(2) .copied() .collect::<Vec<_>>() ); } #[test] fn bad_shards_number() { let scale = NonZeroUsize::new(8).unwrap(); let num_shards = 2usize.pow(scale.get() as u32); let ec = ErasureCoding::new(scale).unwrap(); let source_shards = vec![Default::default(); num_shards - 1]; assert!(ec.extend(&source_shards).is_err()); let partial_shards = vec![Default::default(); num_shards - 1]; assert!(ec.recover(&partial_shards).is_err()); } #[test] fn not_enough_partial() { let scale = NonZeroUsize::new(8).unwrap(); let num_shards = 2usize.pow(scale.get() as u32); let ec = ErasureCoding::new(scale).unwrap(); let mut partial_shards = vec![None; num_shards]; // Less than half is not sufficient partial_shards .iter_mut() .take(num_shards / 2 - 1) .for_each(|maybe_scalar| { maybe_scalar.replace(Scalar::default()); }); assert!(ec.recover(&partial_shards).is_err()); // Any half is sufficient partial_shards .last_mut() .unwrap() .replace(Scalar::default()); assert!(ec.recover(&partial_shards).is_ok()); }
use oxygengine::user_interface::raui::core::prelude::*; use serde::{Deserialize, Serialize}; #[derive(PropsData, Debug, Clone, Serialize, Deserialize)] pub struct MenuState { pub opened: bool, } impl Default for MenuState { fn default() -> Self { Self { opened: false } } }
#[doc( brief = "Communication between tasks", desc = " Communication between tasks is facilitated by ports (in the receiving task), and channels (in the sending task). Any number of channels may feed into a single port. Ports and channels may only transmit values of unique types; that is, values that are statically guaranteed to be accessed by a single 'owner' at a time. Unique types include scalars, vectors, strings, and records, tags, tuples and unique boxes (`~T`) thereof. Most notably, shared boxes (`@T`) may not be transmitted across channels. Example: let p = comm::port(); task::spawn(comm::chan(p), fn (c: chan<str>) { comm::send(c, \"Hello, World\"); }); io::println(comm::recv(p)); ")]; import sys; import task; export send; export recv; export chan::{}; export port::{}; #[abi = "cdecl"] native mod rustrt { type rust_port; fn chan_id_send<T: send>(t: *sys::type_desc, target_task: task::task, target_port: port_id, data: T) -> ctypes::uintptr_t; fn new_port(unit_sz: ctypes::size_t) -> *rust_port; fn del_port(po: *rust_port); fn rust_port_detach(po: *rust_port); fn get_port_id(po: *rust_port) -> port_id; fn rust_port_size(po: *rust_port) -> ctypes::size_t; fn port_recv(dptr: *uint, po: *rust_port, yield: *ctypes::uintptr_t, killed: *ctypes::uintptr_t); } #[abi = "rust-intrinsic"] native mod rusti { fn call_with_retptr<T: send>(&&f: fn@(*uint)) -> T; } type port_id = int; // It's critical that this only have one variant, so it has a record // layout, and will work in the rust_task structure in task.rs. #[doc( brief = "A communication endpoint that can send messages. \ Channels send messages to ports.", desc = "Each channel is bound to a port when the channel is \ constructed, so the destination port for a channel \ must exist before the channel itself. \ Channels are weak: a channel does not keep the port it \ is bound to alive. If a channel attempts to send data \ to a dead port that data will be silently dropped. \ Channels may be duplicated and themselves transmitted \ over other channels." )] enum chan<T: send> { chan_t(task::task, port_id) } resource port_ptr<T: send>(po: *rustrt::rust_port) { // Once the port is detached it's guaranteed not to receive further // messages rustrt::rust_port_detach(po); // Drain the port so that all the still-enqueued items get dropped while rustrt::rust_port_size(po) > 0u { // FIXME: For some reason if we don't assign to something here // we end up with invalid reads in the drop glue. let _t = recv_::<T>(po); } rustrt::del_port(po); } #[doc( brief = "A communication endpoint that can receive messages. \ Ports receive messages from channels.", desc = "Each port has a unique per-task identity and may not \ be replicated or transmitted. If a port value is \ copied, both copies refer to the same port. \ Ports may be associated with multiple <chan>s." )] enum port<T: send> { port_t(@port_ptr<T>) } #[doc( brief = "Sends data over a channel. The sent data is moved \ into the channel, whereupon the caller loses \ access to it." )] fn send<T: send>(ch: chan<T>, -data: T) { let chan_t(t, p) = ch; let res = rustrt::chan_id_send(sys::get_type_desc::<T>(), t, p, data); if res != 0u unsafe { // Data sent successfully unsafe::leak(data); } task::yield(); } #[doc( brief = "Constructs a port." )] fn port<T: send>() -> port<T> { port_t(@port_ptr(rustrt::new_port(sys::size_of::<T>()))) } #[doc( brief = "Receive from a port. \ If no data is available on the port then the task will \ block until data becomes available." )] fn recv<T: send>(p: port<T>) -> T { recv_(***p) } #[doc( brief = "Receive on a raw port pointer" )] fn recv_<T: send>(p: *rustrt::rust_port) -> T { // FIXME: Due to issue 1185 we can't use a return pointer when // calling C code, and since we can't create our own return // pointer on the stack, we're going to call a little intrinsic // that will grab the value of the return pointer, then call this // function, which we will then use to call the runtime. fn recv(dptr: *uint, port: *rustrt::rust_port, yield: *ctypes::uintptr_t, killed: *ctypes::uintptr_t) unsafe { rustrt::port_recv(dptr, port, yield, killed); } let yield = 0u; let yieldp = ptr::addr_of(yield); let killed = 0u; let killedp = ptr::addr_of(killed); let res = rusti::call_with_retptr(bind recv(_, p, yieldp, killedp)); if killed != 0u { fail "killed"; } if yield != 0u { // Data isn't available yet, so res has not been initialized. task::yield(); } ret res; } #[doc( brief = "Constructs a channel. The channel is bound to the \ port used to construct it." )] fn chan<T: send>(p: port<T>) -> chan<T> { chan_t(task::get_task(), rustrt::get_port_id(***p)) } #[test] fn create_port_and_chan() { let p = port::<int>(); chan(p); } #[test] fn send_int() { let p = port::<int>(); let c = chan(p); send(c, 22); } #[test] fn send_recv_fn() { let p = port::<int>(); let c = chan::<int>(p); send(c, 42); assert (recv(p) == 42); } #[test] fn send_recv_fn_infer() { let p = port(); let c = chan(p); send(c, 42); assert (recv(p) == 42); } #[test] fn chan_chan_infer() { let p = port(), p2 = port::<int>(); let c = chan(p); send(c, chan(p2)); recv(p); } #[test] fn chan_chan() { let p = port::<chan<int>>(), p2 = port::<int>(); let c = chan(p); send(c, chan(p2)); recv(p); }
pub mod fetch; pub(crate) mod routing;
//! This crate only exists to work around Cargo bug [#5015]. //! //! [#5015]: https://github.com/rust-lang/cargo/issues/5015
#[doc = "Register `DCKCFGR` reader"] pub type R = crate::R<DCKCFGR_SPEC>; #[doc = "Register `DCKCFGR` writer"] pub type W = crate::W<DCKCFGR_SPEC>; #[doc = "Field `TIMPRE` reader - TIMPRE"] pub type TIMPRE_R = crate::BitReader<TIMPRE_A>; #[doc = "TIMPRE\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TIMPRE_A { #[doc = "0: If the APB prescaler is configured 1, TIMxCLK = PCLKx. Otherwise, TIMxCLK = 2xPCLKx"] Mul1or2 = 0, #[doc = "1: If the APB prescaler is configured 1, 2 or 4, TIMxCLK = HCLK. Otherwise, TIMxCLK = 4xPCLKx"] Mul1or4 = 1, } impl From<TIMPRE_A> for bool { #[inline(always)] fn from(variant: TIMPRE_A) -> Self { variant as u8 != 0 } } impl TIMPRE_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TIMPRE_A { match self.bits { false => TIMPRE_A::Mul1or2, true => TIMPRE_A::Mul1or4, } } #[doc = "If the APB prescaler is configured 1, TIMxCLK = PCLKx. Otherwise, TIMxCLK = 2xPCLKx"] #[inline(always)] pub fn is_mul1or2(&self) -> bool { *self == TIMPRE_A::Mul1or2 } #[doc = "If the APB prescaler is configured 1, 2 or 4, TIMxCLK = HCLK. Otherwise, TIMxCLK = 4xPCLKx"] #[inline(always)] pub fn is_mul1or4(&self) -> bool { *self == TIMPRE_A::Mul1or4 } } #[doc = "Field `TIMPRE` writer - TIMPRE"] pub type TIMPRE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, TIMPRE_A>; impl<'a, REG, const O: u8> TIMPRE_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "If the APB prescaler is configured 1, TIMxCLK = PCLKx. Otherwise, TIMxCLK = 2xPCLKx"] #[inline(always)] pub fn mul1or2(self) -> &'a mut crate::W<REG> { self.variant(TIMPRE_A::Mul1or2) } #[doc = "If the APB prescaler is configured 1, 2 or 4, TIMxCLK = HCLK. Otherwise, TIMxCLK = 4xPCLKx"] #[inline(always)] pub fn mul1or4(self) -> &'a mut crate::W<REG> { self.variant(TIMPRE_A::Mul1or4) } } #[doc = "Field `I2SSRC` reader - I2SSRC"] pub type I2SSRC_R = crate::FieldReader<I2SSRC_A>; #[doc = "I2SSRC\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[repr(u8)] pub enum I2SSRC_A { #[doc = "0: I2Sx clock frequency = f(PLLCLK_R)"] Pllclkr = 0, #[doc = "1: I2Sx clock frequency = I2S_CKIN Alternate function input frequency"] I2sCkin = 1, #[doc = "3: I2Sx clock frequency = HSI/HSE depends on PLLSRC bit (PLLCFGR\\[22\\])"] HsiHse = 3, } impl From<I2SSRC_A> for u8 { #[inline(always)] fn from(variant: I2SSRC_A) -> Self { variant as _ } } impl crate::FieldSpec for I2SSRC_A { type Ux = u8; } impl I2SSRC_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> Option<I2SSRC_A> { match self.bits { 0 => Some(I2SSRC_A::Pllclkr), 1 => Some(I2SSRC_A::I2sCkin), 3 => Some(I2SSRC_A::HsiHse), _ => None, } } #[doc = "I2Sx clock frequency = f(PLLCLK_R)"] #[inline(always)] pub fn is_pllclkr(&self) -> bool { *self == I2SSRC_A::Pllclkr } #[doc = "I2Sx clock frequency = I2S_CKIN Alternate function input frequency"] #[inline(always)] pub fn is_i2s_ckin(&self) -> bool { *self == I2SSRC_A::I2sCkin } #[doc = "I2Sx clock frequency = HSI/HSE depends on PLLSRC bit (PLLCFGR\\[22\\])"] #[inline(always)] pub fn is_hsi_hse(&self) -> bool { *self == I2SSRC_A::HsiHse } } #[doc = "Field `I2SSRC` writer - I2SSRC"] pub type I2SSRC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O, I2SSRC_A>; impl<'a, REG, const O: u8> I2SSRC_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, REG::Ux: From<u8>, { #[doc = "I2Sx clock frequency = f(PLLCLK_R)"] #[inline(always)] pub fn pllclkr(self) -> &'a mut crate::W<REG> { self.variant(I2SSRC_A::Pllclkr) } #[doc = "I2Sx clock frequency = I2S_CKIN Alternate function input frequency"] #[inline(always)] pub fn i2s_ckin(self) -> &'a mut crate::W<REG> { self.variant(I2SSRC_A::I2sCkin) } #[doc = "I2Sx clock frequency = HSI/HSE depends on PLLSRC bit (PLLCFGR\\[22\\])"] #[inline(always)] pub fn hsi_hse(self) -> &'a mut crate::W<REG> { self.variant(I2SSRC_A::HsiHse) } } impl R { #[doc = "Bit 24 - TIMPRE"] #[inline(always)] pub fn timpre(&self) -> TIMPRE_R { TIMPRE_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bits 25:26 - I2SSRC"] #[inline(always)] pub fn i2ssrc(&self) -> I2SSRC_R { I2SSRC_R::new(((self.bits >> 25) & 3) as u8) } } impl W { #[doc = "Bit 24 - TIMPRE"] #[inline(always)] #[must_use] pub fn timpre(&mut self) -> TIMPRE_W<DCKCFGR_SPEC, 24> { TIMPRE_W::new(self) } #[doc = "Bits 25:26 - I2SSRC"] #[inline(always)] #[must_use] pub fn i2ssrc(&mut self) -> I2SSRC_W<DCKCFGR_SPEC, 25> { I2SSRC_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "DCKCFGR register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dckcfgr::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dckcfgr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct DCKCFGR_SPEC; impl crate::RegisterSpec for DCKCFGR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`dckcfgr::R`](R) reader structure"] impl crate::Readable for DCKCFGR_SPEC {} #[doc = "`write(|w| ..)` method takes [`dckcfgr::W`](W) writer structure"] impl crate::Writable for DCKCFGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets DCKCFGR to value 0"] impl crate::Resettable for DCKCFGR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::item::*; use crate::rect::*; use crate::vec2::*; use modelone::object::ApplyContext; use modelone::change_value::ValueChange; /// Describes the relationship of one item to another. pub enum AnchorRelation { Parent, Sibling, } /// These are choices of combinations to anchor to. pub enum AnchorFrom { None, Start(f64), End(f64), StartEnd(f64, f64), Middle(f64), } // Each item is either None or Some((item, anchor position, margin)). pub struct Anchors { horizontal: AnchorFrom, vertical: AnchorFrom, } impl Anchors { /// Create a new anchors instance that does nothing. pub fn new() -> Anchors { Anchors { horizontal: AnchorFrom::None, vertical: AnchorFrom::None, } } fn item_rect(relation: AnchorRelation, item: &Item) -> Rectf { match relation { AnchorRelation::Parent => Rect::new(Vec2::new(0., 0.), item.get_item().size), AnchorRelation::Sibling => Rect::new(item.get_item().pos, item.get_item().size), } } /// Create a new anchors instance that can be used to make another item fill /// the given item, with the given margin. pub fn new_fill_margin(relation: AnchorRelation, item: &Item, margin: f64) -> Anchors { let item_rect = Anchors::item_rect(relation, item); Anchors { horizontal: AnchorFrom::StartEnd(item_rect.left() + margin, item_rect.right() - margin), vertical: AnchorFrom::StartEnd(item_rect.top() + margin, item_rect.bottom() - margin), } } /// Create a new anchors instance that can be used to make another item fill /// the given item. pub fn new_fill(relation: AnchorRelation, item: &Item) -> Anchors { Anchors::new_fill_margin(relation, item, 0.) } /// Offset the left border by the given amount. pub fn move_left_border(&mut self, by: f64) -> &mut Self { match self.horizontal { AnchorFrom::Start(ref mut x) => *x += by, AnchorFrom::StartEnd(ref mut x, _) => *x += by, _ => {} } self } /// Offset the right border by the given amount. pub fn move_right_border(&mut self, by: f64) -> &mut Self { match self.horizontal { AnchorFrom::End(ref mut x) => *x -= by, AnchorFrom::StartEnd(_, ref mut x) => *x -= by, _ => {} } self } /// Offset the top border by the given amount. pub fn move_top_border(&mut self, by: f64) -> &mut Self { match self.vertical { AnchorFrom::Start(ref mut y) => *y += by, AnchorFrom::StartEnd(ref mut y, _) => *y += by, _ => {} } self } /// Offset the bottom border by the given amount. pub fn move_bottom_border(&mut self, by: f64) -> &mut Self { match self.vertical { AnchorFrom::End(ref mut y) => *y -= by, AnchorFrom::StartEnd(_, ref mut y) => *y -= by, _ => {} } self } /*pub fn left_margin(self, left_margin: f64) -> Anchors { match self.horizontal { Start(mut ref anchor_to) => { anchor_to.start_margin(left_margin); }, StartEnd(mut ref anchor_to, _) => { anchor_to.start_margin(left_margin); }, } self }*/ /// Apply the anchor configuration to the given ItemData ApplyContext. pub fn apply(&self, item_data: &ItemData, cxt: &mut ApplyContext<ItemDataChange>) -> &Self { let mut rect = Rect::new(item_data.pos, item_data.size); match self.horizontal { AnchorFrom::None => {}, AnchorFrom::Start(left) => { rect.set_left(left); }, AnchorFrom::End(right) => { rect.set_right(right); }, AnchorFrom::StartEnd(left, right) => { rect.set_left(left); rect.set_right(right); }, AnchorFrom::Middle(middle) => { let half_width = rect.size.x / 2.; rect.pos.x = middle - half_width; }, } match self.vertical { AnchorFrom::None => {}, AnchorFrom::Start(top) => { rect.set_top(top); }, AnchorFrom::End(bottom) => { rect.set_bottom(bottom); }, AnchorFrom::StartEnd(top, bottom) => { rect.set_top(top); rect.set_bottom(bottom); }, AnchorFrom::Middle(middle) => { let half_height = rect.size.y / 2.; rect.pos.y = middle - half_height; }, } if item_data.pos != rect.pos { cxt.apply(ItemDataChange::pos(ValueChange(rect.pos))); } if item_data.size != rect.size { cxt.apply(ItemDataChange::size(ValueChange(rect.size))); //let ah = cxt.apply_handle(); //ah.invoke(ItemDataChange::size(ValueChange(rect.size))); } self } }
extern crate rand; extern crate image; pub mod field; #[test] fn it_works() { }
use std::fmt::Display; use crate::{ scanner::{Token, TokenKind}, value::Value, }; #[derive(thiserror::Error, Debug)] pub enum InterpretError { #[error(transparent)] Compile(#[from] CompileError), #[error(transparent)] Runtime(#[from] RuntimeError), } #[derive(thiserror::Error, Debug)] pub enum CompileError { #[error("{0}")] ScanError(ErrorInfo), #[error("{0}")] ParseError(ErrorInfo), } #[derive(thiserror::Error, Debug)] pub enum RuntimeError { #[error("Byte '{0}' does not map to any op code.")] InvalidOpcode(u8), #[error("Operand for {0} must be number, but was {1}.")] OperandMustBeNumber(String, Value), } #[derive(Debug)] pub struct ErrorInfo { line: usize, location: String, message: String, } impl Display for ErrorInfo { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "[line {}] {}", self.line, self.message) } } impl ErrorInfo { pub fn error<'any>(token: &Token<'any>, message: &str) -> Self { let (location, message) = if token.kind == TokenKind::Eof { (" at end".to_string(), message.to_string()) } else if token.kind == TokenKind::Error { ("".to_string(), token.lexeme.to_string()) } else { ( format!(" at '{}'", token.lexeme.to_string()), message.to_string(), ) }; Self { line: token.line, location, message, } } }
#[no_mangle] pub extern fn fibonacci_recursive(n: u32) -> u64 { match n { 0 => 0, 1 => 1, _ => fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2), } } #[no_mangle] pub extern fn fibonacci_non_recursive(n: u32) -> u64 { match n { 0 => return 0, 1 => return 1, _ => { // start by i = 2 let mut f_i_2 = 0; // f(i-2) = f(0) = 0 let mut f_i_1 = 1; // f(i-1) = f(1) = 1 // loop starting from 2 and to n inclusive for _i in 2..=n { let sum = f_i_2 + f_i_1; f_i_2 = f_i_1; f_i_1 = sum; } return f_i_1; } } }
// Copyright 2014-2018 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. #![warn(clippy::items_after_statements)] fn ok() { fn foo() { println!("foo"); } foo(); } fn last() { foo(); fn foo() { println!("foo"); } } fn main() { foo(); fn foo() { println!("foo"); } foo(); } fn mac() { let mut a = 5; println!("{}", a); // do not lint this, because it needs to be after `a` macro_rules! b { () => {{ a = 6 }}; } b!(); println!("{}", a); }
#[allow(dead_code, unused_attributes, bad_style)] mod ffmpeg_ffi; #[macro_use] mod macroses; mod codec; pub mod error; mod ffmpeg_const; mod format; mod resample; #[link(name = "avutil")] #[link(name = "avcodec")] #[link(name = "avformat")] #[link(name = "swresample")] extern "C" {} pub use codec::{Codec, Decoder, Encoder, Params as CodecParams}; pub use error::{Error, ErrorRepr, InternalError}; pub use resample::Resampler; #[derive(Clone, Copy, Debug, PartialEq)] pub struct AudioParams { pub rate: i32, pub format: AudioSampleFormat, } #[derive(Clone, Copy, Debug, PartialEq)] pub enum AudioSampleFormat { U8, S16Le, FloatLe, U8P, S16LeP, FloatLeP, } impl AudioSampleFormat { fn from_raw(raw: ffmpeg_ffi::AVSampleFormat) -> Option<Self> { match raw { ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_U8 => Some(AudioSampleFormat::U8), ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_S16 => Some(AudioSampleFormat::S16Le), ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_FLT => Some(AudioSampleFormat::FloatLe), ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_U8P => Some(AudioSampleFormat::U8P), ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_S16P => Some(AudioSampleFormat::S16LeP), ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_FLTP => Some(AudioSampleFormat::FloatLeP), _ => None, } } fn to_raw(self) -> ffmpeg_ffi::AVSampleFormat { match self { AudioSampleFormat::U8 => ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_U8, AudioSampleFormat::S16Le => ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_S16, AudioSampleFormat::FloatLe => ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_FLT, AudioSampleFormat::U8P => ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_U8P, AudioSampleFormat::S16LeP => ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_S16P, AudioSampleFormat::FloatLeP => ffmpeg_ffi::AVSampleFormat_AV_SAMPLE_FMT_FLTP, } } fn get_sample_size(self) -> usize { match self { AudioSampleFormat::U8 | AudioSampleFormat::U8P => 1, AudioSampleFormat::S16Le | AudioSampleFormat::S16LeP => 2, AudioSampleFormat::FloatLe | AudioSampleFormat::FloatLeP => 4, } } fn is_planar(self) -> bool { match self { AudioSampleFormat::U8 | AudioSampleFormat::S16Le | AudioSampleFormat::FloatLe => false, AudioSampleFormat::U8P | AudioSampleFormat::S16LeP | AudioSampleFormat::FloatLeP => { true } } } fn to_planar(self) -> Self { match self { AudioSampleFormat::U8 | AudioSampleFormat::U8P => AudioSampleFormat::U8P, AudioSampleFormat::S16Le | AudioSampleFormat::S16LeP => AudioSampleFormat::S16LeP, AudioSampleFormat::FloatLe | AudioSampleFormat::FloatLeP => AudioSampleFormat::FloatLeP, } } fn to_interleaved(self) -> Self { match self { AudioSampleFormat::U8 | AudioSampleFormat::U8P => AudioSampleFormat::U8, AudioSampleFormat::S16Le | AudioSampleFormat::S16LeP => AudioSampleFormat::S16Le, AudioSampleFormat::FloatLe | AudioSampleFormat::FloatLeP => AudioSampleFormat::FloatLe, } } } impl AudioParams { fn get_channels_qty(&self) -> i32 { unsafe { ffmpeg_ffi::av_get_channel_layout_nb_channels(resample::LAYOUT as _) as _ } } fn get_samples_qty_in_buffer(&self, len: usize) -> usize { len / self.get_channels_qty() as usize / self.format.get_sample_size() } } // Errors:
use crate::{content, message::*, saved, subscribe_irc, util, view}; use anyhow::Result; use iced::{button, pane_grid, text_input, Application, Command, Element, Subscription}; use std::{collections::HashMap, sync::Arc}; // Do not use sync::Mutex to avoid dead lock use futures::lock::Mutex; // アプリケーションが保持する全ての情報 #[derive(Debug, Clone)] pub struct State { pub irc_config: irc::client::prelude::Config, pub setting: SettingState, pub main: MainContents, pub pane: PaneState, sender: Option<Arc<Mutex<irc::client::Sender>>>, client_stream: Option<Arc<Mutex<irc::client::ClientStream>>>, pub error: Option<String>, } impl Default for State { fn default() -> Self { Self { irc_config: irc::client::prelude::Config::default(), setting: SettingState::default(), main: MainContents::default(), pane: PaneState::default(), sender: None, client_stream: None, error: None, } } } // 設定画面でのボタンやテキストインプットの状態を保持する構造体 #[derive(Debug, Clone, Default)] pub struct SettingState { saving: bool, dirty: bool, pub save_button: button::State, input_username: text_input::State, input_server: text_input::State, input_port: text_input::State, } // IRC接続するメイン画面で必要な情報 #[derive(Debug, Clone)] pub struct MainContents { pub input_value: String, pub connecting_flag: bool, pub display_value: String, pub channel_texts: HashMap<String, String>, pub current_channel: String, pub show_channels: Vec<String>, pub form: MainFormState, } impl Default for MainContents { fn default() -> Self { let show_channels = vec!["Setting".to_string()]; Self { input_value: String::from(""), connecting_flag: false, display_value: String::from(""), channel_texts: HashMap::new(), current_channel: String::from("Setting"), show_channels: show_channels, form: MainFormState::default(), } } } // IRC接続するメイン画面でのボタンやテキストインプットの状態を保持する情報 #[derive(Debug, Clone, Default)] pub struct MainFormState { pub input: text_input::State, pub irc_button: button::State, pub post_button: button::State, } // icedのpane_grid周りの状態管理 #[derive(Debug, Clone)] pub struct PaneState { pub state: pane_grid::State<content::Content>, pub size: usize, pub focus: Option<pane_grid::Pane>, } impl Default for PaneState { fn default() -> Self { let show_channels = vec!["Setting".to_string()]; let (state, _) = pane_grid::State::new(content::Content::new(0, &show_channels)); Self { state: state, size: 1, focus: None, } } } // 試験的実装。IrcClientを取りまとめるstructを作ってみた。 pub struct IrcClient { client_stream: irc::client::ClientStream, sender: irc::client::Sender, } impl IrcClient { async fn get_client(state: &mut State) -> Result<IrcClient> { let mut client = irc::client::prelude::Client::from_config(state.irc_config.clone()).await?; client.identify()?; Ok(IrcClient { client_stream: client.stream()?, sender: client.sender(), }) } } // 設定ファイル保存時のエラー状態名 #[derive(Debug, Clone)] pub enum SaveError { DirectoryError, FileError, WriteError, FormatError, } // IRC接続エラー状態名 #[derive(Debug, Clone)] pub enum IrcError { IrcError, } // アプリケーションの状態。これが大元。ライブラリからも要求される。Stateを内包する設計になっている。 // このenumの分け方とStateの分け方の設計が良いかどうかは若干考えた方がいい。色々と不便の原因にはなっている。 pub enum App { Loading, Loaded(State), IrcConnecting(State), IrcFinished(State), } // Iced Applicationライブラリが要求する実装 impl Application for App { type Executor = iced::executor::Default; type Message = Message; type Flags = (); // アプリケーションの初期化 App::Loading -> (futureでSaveState::loadが完了したらMessageLoadedが発行される) -> App::Loaded fn new(_flags: ()) -> (App, Command<Message>) { ( App::Loading, Command::perform(saved::SavedConfig::load(), Message::Loaded), ) } // アプリケーションのタイトル fn title(&self) -> String { String::from("Gelato") } // アプリケーションの更新 fn update( &mut self, message: Self::Message, ) -> Command<Self::Message> { // アプリケーションの種類状態でのマッチ match self { // アプリケーション初期化中 App::Loading => { match message { Message::Loaded(Ok(_saved_state)) => { let irc_config = irc::client::prelude::Config { nickname: _saved_state.nickname, username: _saved_state.username, realname: _saved_state.realname, server: _saved_state.server, port: _saved_state.port, use_tls: _saved_state.use_tls, encoding: _saved_state.encoding, channels: _saved_state.channels, ..Default::default() }; let main = MainContents { current_channel: _saved_state.current_channel, ..Default::default() }; let state = State { irc_config: irc_config, main: main, ..Default::default() }; *self = App::Loaded(state); } Message::Loaded(Err(_)) => { let state = State { error: Some("Error happens while loading setting.json, please check setting.json".to_string()), ..Default::default() }; *self = App::Loaded(state); } _ => {} } Command::none() } // アプリケーション初期化完了時 App::Loaded(state) => { let mut start_irc = false; match message { Message::Saved(_) => { state.setting.saving = false; } Message::IrcStart => { start_irc = true; } Message::Save => { state.setting.dirty = true; } _ => {} } if state.setting.dirty && !state.setting.saving { state.setting.dirty = false; state.setting.saving = true; Command::perform( saved::SavedConfig { nickname: state.irc_config.nickname.clone(), username: state.irc_config.username.clone(), realname: state.irc_config.realname.clone(), server: state.irc_config.server.clone(), port: state.irc_config.port.clone(), use_tls: state.irc_config.use_tls.clone(), encoding: state.irc_config.encoding.clone(), channels: state.irc_config.channels.clone(), current_channel: state.main.current_channel.clone(), } .save(), Message::Saved, ) } else if start_irc { // IRCが開始されたら、selfをIRCConnectingに強制上書きする。 let mut current_state = state.clone(); futures::executor::block_on(async { let client = IrcClient::get_client(&mut current_state).await; match client { Ok(c) => { current_state.client_stream = Some(Arc::new(Mutex::new(c.client_stream))); current_state.sender = Some(Arc::new(Mutex::new(c.sender))); } Err(_) => { current_state.error = Some("IRC Connecting Error".to_string()); state.error = Some("IRC Connecting Error".to_string()); println!("client connction error"); } } }); if current_state.error.is_none() { *self = App::IrcConnecting(current_state); } Command::none() } else { Command::none() } } // IRC接続状態の時 App::IrcConnecting(state) => { state.main.connecting_flag = true; // TODO : 本当はここは1:1ではないよね state .main .show_channels .append(&mut state.irc_config.channels); let mut irc_finished = false; let mut posted = false; let mut input_word = String::from(""); match message { // Message::IrcProgressedは、subscription関数のmapで渡されている関数 Message::IrcProgressed(progress_state) => match progress_state { // model/subscribe_irc.rsで実装されているProgressから結果のmessage_textが返却される。 subscribe_irc::Progress::Advanced(message_text) => { // メッセージのフィルタリング util::filter(&message_text, &mut state.main.channel_texts); //state.display_value.push_str(filtered_text); } subscribe_irc::Progress::Finished => { irc_finished = true; } subscribe_irc::Progress::Errored => { irc_finished = true; } _ => {} }, Message::IrcFinished(_) => { irc_finished = true; state.main.connecting_flag = false; } Message::InputChanged(value) => { state.main.input_value = value; } Message::PostMessage => { posted = true; input_word.push_str(&state.main.input_value.clone()); state.main.input_value = String::from(""); } Message::Split(axis, pane) => { let result = state.pane.state.split( axis, &pane, content::Content::new(state.pane.size, &state.main.show_channels), ); if let Some((pane, _)) = result { state.pane.focus = Some(pane); if let Some(pstate) = state.pane.state.get(&pane) { state.main.current_channel = pstate.channel_name.clone(); } } state.pane.size += 1; } Message::SplitFocused(axis) => { if let Some(pane) = state.pane.focus { let result = state.pane.state.split( axis, &pane, content::Content::new(state.pane.size, &state.main.show_channels), ); if let Some((pane, _)) = result { state.pane.focus = Some(pane); if let Some(pstate) = state.pane.state.get(&pane) { state.main.current_channel = pstate.channel_name.clone(); } } state.pane.size += 1; } } Message::FocusAdjacent(direction) => { if let Some(pane) = state.pane.focus { if let Some(adjacent) = state.pane.state.adjacent(&pane, direction) { state.pane.focus = Some(adjacent); if let Some(pstate) = state.pane.state.get(&pane) { state.main.current_channel = pstate.channel_name.clone(); } } } } Message::Clicked(pane) => { state.pane.focus = Some(pane); if let Some(pstate) = state.pane.state.get(&pane) { state.main.current_channel = pstate.channel_name.clone(); } } Message::Resized(pane_grid::ResizeEvent { split, ratio }) => { state.pane.state.resize(&split, ratio); } Message::Dragged(pane_grid::DragEvent::Dropped { pane, target }) => { state.pane.state.swap(&pane, &target); } Message::Dragged(_) => {} Message::Close(pane) => { if let Some((_, sibling)) = state.pane.state.close(&pane) { state.pane.focus = Some(sibling); if let Some(pstate) = state.pane.state.get(&sibling) { state.main.current_channel = pstate.channel_name.clone(); } } } Message::CloseFocused => { if let Some(pane) = state.pane.focus { if let Some((_, sibling)) = state.pane.state.close(&pane) { state.pane.focus = Some(sibling); if let Some(pstate) = state.pane.state.get(&sibling) { state.main.current_channel = pstate.channel_name.clone(); } } } } _ => {} } if posted && !input_word.is_empty() { let sender_original = Arc::clone(&state.sender.as_ref().expect("sender_original error")); let channel = state.main.current_channel.clone(); let dummy = String::new(); let channel_texts = state.main.channel_texts.clone(); let input_text = channel_texts.get(&channel).unwrap_or(&dummy); let nickname = state.irc_config.username(); &state.main.channel_texts.insert( channel.clone(), input_text.clone() + nickname + " " + &input_word + "\n", ); let call = async move { let sender = sender_original.lock().await; (*sender) .send_privmsg(channel, input_word) .expect("call async move send_privmsg"); }; Command::perform(call, Message::None) } else if irc_finished { *self = App::IrcFinished(state.clone()); Command::perform(Message::change(), Message::IrcFinished) } else { Command::none() } } App::IrcFinished(state) => { *self = App::Loaded(state.clone()); Command::none() } } } // サブスクリプションの登録。 // selfはアプリケーションのenumのため、必要に応じてStateの中身を取り出す。 fn subscription(&self) -> Subscription<Message> { match self { App::IrcConnecting(State { client_stream, .. }) => { subscribe_irc::input(client_stream.as_ref(), "").map(Message::IrcProgressed) } // input関数への受け渡しは適当にいろいろ試しているため、何も考えていない。 // IRCと接続時以外は特に何もしない。 _ => Subscription::none(), } } // 更新された時に呼び出される描画関数 fn view(&mut self) -> Element<Message> { match self { App::Loading => view::loading(), App::Loaded(state) => view::loaded(state), App::IrcConnecting(state) | App::IrcFinished(state) => view::main(state), } } }
extern crate ocl; use ocl::Buffer; use ocl::ProQue; use crate::scene_objects::scene_object::SceneObject; use ocl::prm::{Uchar8, Float16}; use ocl::flags::MemFlags; pub struct Scene { scene_objects: Vec<Box<dyn SceneObject>> } impl Scene { pub fn new() -> Self { Scene {scene_objects: Vec::new()} } pub fn push(&mut self, obj: Box<dyn SceneObject>) { self.scene_objects.push(obj); } fn to_ocl_format(&self) -> (Vec<Uchar8>, Vec<Float16>) { let mut objects_integer_data = Vec::<Uchar8>::with_capacity(self.scene_objects.len()); let mut objects_float_data = Vec::<Float16>::with_capacity(self.scene_objects.len()); for object in &self.scene_objects { objects_integer_data.push(object.get_integer_data()); objects_float_data.push(object.get_float_data()); } (objects_integer_data, objects_float_data) } pub fn to_ocl_buffer(&self, pro_que: &ProQue) -> Result<(u32, Buffer<Uchar8>, Buffer<Float16>), ocl::Error>{ let (objects_integer_data, objects_float_data) = self.to_ocl_format(); let scene_object_integer_buffer = pro_que.buffer_builder::<Uchar8>() .len(self.scene_objects.len()) .flags(MemFlags::READ_ONLY) .build()?; let scene_object_float_buffer = pro_que.buffer_builder::<Float16>() .len(self.scene_objects.len()) .flags(MemFlags::READ_ONLY) .build()?; scene_object_integer_buffer.write(objects_integer_data.as_slice()).enq()?; scene_object_float_buffer.write(objects_float_data.as_slice()).enq()?; Ok((self.scene_objects.len() as u32, scene_object_integer_buffer, scene_object_float_buffer)) } }
pub mod branch; pub mod cast; pub mod core; pub mod op; pub mod ty; pub mod value;
use std::io::prelude::*; use mio::*; use mio::tcp::*; use std::collections::HashMap; use event_loop::*; pub trait App : Send + 'static { fn handle(&mut self, stream: &mut TcpStream); fn duplicate(&self) -> Box<App>; } struct AppWithStream { app: Box<App>, stream: TcpStream, } impl AppWithStream { fn new(app: Box<App>, stream: TcpStream) -> AppWithStream { AppWithStream { app: app, stream: stream, } } fn handle(&mut self) { self.app.handle(&mut self.stream); } fn shutdown(&self) { let _ = self.stream.shutdown(Shutdown::Both); } fn flush(&mut self) { let mut buf = Vec::new(); let _ = self.stream.read_to_end(&mut buf); } } struct AppEventHandler { app: Box<App>, conns: HashMap<usize, AppWithStream>, } impl AppEventHandler { fn new(app: Box<App>) -> AppEventHandler { return AppEventHandler { app: app, conns: HashMap::new(), }; } } impl EventHandler for AppEventHandler { fn new_conn(&mut self, id: usize, stream: TcpStream) { println!("Got new connection {}", id); self.conns.insert(id, AppWithStream::new(self.app.duplicate(), stream)); } fn conn_event(&mut self, id: usize, event: Ready) { println!("Handling event!"); if event.is_error() || event.is_hup() { if event.is_error() { println!("Error event on conn {}", id); } else { println!("Hangup event on conn {}", id) } match self.conns.remove(&id) { None => { println!("WARNING: conn no {} can't be found in conns map for shutdown event!", id) } Some(mut conn) => { if event.is_readable() { conn.flush(); } conn.shutdown(); self.conns.remove(&id); return; } } } if event.is_readable() { match self.conns.get_mut(&id) { None => { println!("WARNING: conn no {} can't be found in conns map for read event!", id) } Some(ref mut conn) => { println!("Handling connection {}", id); conn.handle(); } } } } fn duplicate(&self) -> Box<EventHandler> { return Box::new(AppEventHandler::new(self.app.duplicate())); } } pub struct AppServer { host: String, num_workers: usize, app: Box<App>, } impl AppServer { pub fn new(host: &str, num_workers: usize, app: Box<App>) -> AppServer { return AppServer { host: host.to_string(), num_workers: num_workers, app: app, }; } pub fn run(self) { let l = EventLoop::new(&self.host, self.num_workers, Box::new(AppEventHandler::new(self.app))); l.run(); } }
pub mod publishing;
use crate::container::responses::AcquireLeaseResponse; pub type RenewLeaseResponse = AcquireLeaseResponse;
extern crate rabbit; use std::borrow::Cow; const KEYLEN: usize = 16; const PADSTR: &'static str = "Thisismypadding!"; pub fn init(key: &str) -> rabbit::Rabbit { let cipher: rabbit::Key = pad_key(key).as_bytes().into(); return rabbit::Rabbit::new(&cipher); } pub fn encrypt<'a>(rabbit: &mut rabbit::Rabbit, data: &'a [u8]) -> Cow<'a, [u8]> { let mut buf = vec![0u8;data.len()]; rabbit.encrypt(data, &mut buf[..]); buf.into() } pub fn decrypt<'a>(rabbit: &mut rabbit::Rabbit, data: &'a [u8]) -> Cow<'a, [u8]> { let mut buf = vec![0u8;data.len()]; rabbit.decrypt(data, &mut buf[..]); buf.into() } pub fn encrypt_iv<'a>(key: &str, data: &'a [u8]) -> Result<Cow<'a, Vec<u8>>, &'static str> { Err("not yet") } pub fn decrypt_iv<'a>(key: &str, data: &'a [u8]) -> Result<Cow<'a, Vec<u8>>, &'static str> { Err("not yet") } // pad or truncate key according KEYLEN fn pad_key<'a>(key: &'a str) -> Cow<'a, str> { let key_len = key.len(); let mut temp_string = String::with_capacity(KEYLEN); if key_len == 0 { panic!("key must be set!"); } if key_len >= KEYLEN { return key.into(); } else { temp_string.push_str(key); temp_string.push_str(&PADSTR[0..KEYLEN - key_len]); return temp_string.into(); }; } extern crate rand; use librabbit::rand::{Rng, OsRng}; pub fn randombytes<'a>(len: usize) -> Cow<'a, [u8]> { let mut osrng: OsRng = OsRng::new().expect("OsRng create error"); let mut buf: Vec<u8> = vec![0u8;len]; osrng.fill_bytes(&mut buf[..]); buf.into() }
struct ChristmasDay { day: String, gift: String, } fn main() { let christmas_days: [ChristmasDay; 12] = [ ChristmasDay { day: "first".to_string(), gift: "a Partridge in a Pear Tree".to_string(), }, ChristmasDay { day: "second".to_string(), gift: "Two Turtle Doves".to_string(), }, ChristmasDay { day: "third".to_string(), gift: "Three French Hens".to_string(), }, ChristmasDay { day: "fourth".to_string(), gift: "Four Calling Birds".to_string(), }, ChristmasDay { day: "fifth".to_string(), gift: "Five Goldon Rings".to_string(), }, ChristmasDay { day: "sixth".to_string(), gift: "Six Geese a Laying".to_string(), }, ChristmasDay { day: "seventh".to_string(), gift: "Sevens Swans a Swimming".to_string(), }, ChristmasDay { day: "eigth".to_string(), gift: "Eight Maids a Milking".to_string(), }, ChristmasDay { day: "ninth".to_string(), gift: "Nine Ladies Dancing".to_string(), }, ChristmasDay { day: "tenth".to_string(), gift: "Ten Lords a Leaping".to_string(), }, ChristmasDay { day: "eleventh".to_string(), gift: "Eleven Pipers Piping".to_string(), }, ChristmasDay { day: "twelfth".to_string(), gift: "12 Drummers Drumming".to_string(), }, ]; for (i, elem) in christmas_days.iter().enumerate() { println!(); println!( "On the {} day of Christmas, my true love sent to me:", elem.day ); for j in (0..i + 1).rev() { if j == 0 && i > 0 { print!("And "); } println!("{}", christmas_days[j].gift); } } }
extern crate config as rsconfig; use std::collections::HashMap; use std::env; use std::path::PathBuf; use color::Color; #[derive(Deserialize)] pub struct Config { pub dpi: f64, pub colors: HashMap<String, Color>, pub mpd: MpdConfig, } #[derive(Deserialize)] pub struct MpdConfig { pub host: String, pub port: u16, } impl Config { pub fn default() -> Config { let mut config_path = PathBuf::from(env::var("HOME").unwrap_or(".".to_string())); config_path.push(".config/obsidian/config.toml"); let mut config = rsconfig::Config::default(); config .merge(rsconfig::File::from_str(include_str!("default_config.toml"), rsconfig::FileFormat::Toml)).unwrap() .merge(rsconfig::File::new(config_path.to_str().unwrap(), rsconfig::FileFormat::Toml)).unwrap() .merge(rsconfig::Environment::with_prefix("OBSIDIAN")).unwrap(); config.try_into().unwrap() } pub fn get_color(&self, name: &str) -> Color { self.colors.get(name).expect(&format!("missing color: {}", name)).clone() } pub fn dpi_scale<In>(&self, i: In) -> i32 where In: Into<f64>, { (i.into() * self.dpi) as i32 } }
extern crate cc; extern crate bindgen; use std::process::Command; use std::path; fn main() { let out_dir = std::env::var_os("OUT_DIR").map(|s| path::PathBuf::from(s).join("x264-build")).unwrap(); //let out_dir = std::env::current_dir().unwrap(); let install_dir = out_dir.join("x264-build"); let inner_dir = path::PathBuf::from("x264"); if !Command::new("sh") .arg("configure") .arg(format!("--prefix={}", install_dir.display())) .arg("--enable-static") .current_dir(&inner_dir) .status().unwrap().success() { panic!("configure failed"); } if !Command::new("make") .current_dir(&inner_dir) .status().unwrap().success() { panic!("make failed"); } if !Command::new("make") .arg("install") .current_dir(&inner_dir) .status().unwrap().success() { panic!("make install failed"); } let include_dir = install_dir.join("include"); let lib_dir = install_dir.join("lib"); println!("cargo:rustc-link-search=native={}", lib_dir.display()); println!("cargo:rustc-link-lib=static=x264"); println!("cargo:include={}", include_dir.display()); println!("cargo:lib={}", lib_dir.display()); //println!("cargo:rustc-link-lib=static=stdc++"); /* // bindgen let buildver = "161"; bindgen::Builder::default() .header_contents("prefix.h", "#ifndef __PREFIX_H__ #define __PREFIX_H__ # include <stdint.h> #endif") .raw_line(format!( "pub unsafe fn x264_encoder_open(params: *mut x264_param_t) -> *mut x264_t {{ x264_encoder_open_{}(params) }}", buildver )) .header("x264-build/include/x264.h") .parse_callbacks(Box::new(bindgen::CargoCallbacks)) .generate() .expect("failed to generate bindings") .write_to_file("src/x264_bindings.rs") .expect("failed to write bindings"); */ }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ //! A cheap version of [`Clone`](Clone). pub use gazebo_derive::{Dupe, Dupe_}; use std::{cell::Cell, num::*, rc::Rc, sync::Arc}; /// Like [`Clone`](Clone), but should only be available if [`Clone`](Clone) is /// constant time and zero allocation (e.g. a few [`Arc`](Arc) bumps). /// The implementation of `dupe` should _always_ call `clone`. pub trait Dupe: Clone { fn dupe(&self) -> Self { self.clone() } } // Smart pointer/wrapper types impl<A: ?Sized> Dupe for &A {} impl<A: ?Sized> Dupe for *const A {} impl<A: ?Sized> Dupe for *mut A {} impl<A: ?Sized> Dupe for Arc<A> {} impl<A: ?Sized> Dupe for Rc<A> {} impl<A: Copy> Dupe for Cell<A> {} // Small containers impl<A: Dupe> Dupe for Option<A> {} impl<T: Dupe, E: Dupe> Dupe for Result<T, E> {} impl<A: Dupe> Dupe for std::ops::Bound<A> {} impl<A: Dupe> Dupe for std::pin::Pin<A> {} impl<A: Dupe> Dupe for std::ptr::NonNull<A> {} impl<A: Dupe> Dupe for std::task::Poll<A> {} impl<A: Dupe> Dupe for (A,) {} // Not clear if Dupe should be implemented for pairs or not. // Concern is deeply nested pairs could be exponentially more expensive than their inner dupes. // Atomic types impl Dupe for () {} impl Dupe for bool {} impl Dupe for char {} impl Dupe for u8 {} impl Dupe for u16 {} impl Dupe for u32 {} impl Dupe for u64 {} impl Dupe for u128 {} impl Dupe for usize {} impl Dupe for i8 {} impl Dupe for i16 {} impl Dupe for i32 {} impl Dupe for i64 {} impl Dupe for i128 {} impl Dupe for isize {} impl Dupe for f32 {} impl Dupe for f64 {} impl Dupe for NonZeroU8 {} impl Dupe for NonZeroU16 {} impl Dupe for NonZeroU32 {} impl Dupe for NonZeroU64 {} impl Dupe for NonZeroU128 {} impl Dupe for NonZeroUsize {} impl Dupe for NonZeroI8 {} impl Dupe for NonZeroI16 {} impl Dupe for NonZeroI32 {} impl Dupe for NonZeroI64 {} impl Dupe for NonZeroI128 {} impl Dupe for NonZeroIsize {} // Other std types that are Copyable impl Dupe for std::any::TypeId {} impl Dupe for std::marker::PhantomPinned {} impl Dupe for std::net::Ipv4Addr {} impl Dupe for std::net::Ipv6Addr {} impl Dupe for std::net::SocketAddrV4 {} impl Dupe for std::net::SocketAddrV6 {} impl Dupe for std::thread::ThreadId {} impl Dupe for std::time::Instant {} impl Dupe for std::time::SystemTime {} impl<T: ?Sized> Dupe for std::marker::PhantomData<T> {} impl<R> Dupe for fn() -> R {} impl<A1, R> Dupe for fn(A1) -> R {} impl<A1, A2, R> Dupe for fn(A1, A2) -> R {} impl<A1, A2, A3, R> Dupe for fn(A1, A2, A3) -> R {} impl<A1, A2, A3, A4, R> Dupe for fn(A1, A2, A3, A4) -> R {} impl<A1, A2, A3, A4, A5, R> Dupe for fn(A1, A2, A3, A4, A5) -> R {} impl<A1, A2, A3, A4, A5, A6, R> Dupe for fn(A1, A2, A3, A4, A5, A6) -> R {} impl<A1, A2, A3, A4, A5, A6, A7, R> Dupe for fn(A1, A2, A3, A4, A5, A6, A7) -> R {} impl<A1, A2, A3, A4, A5, A6, A7, A8, R> Dupe for fn(A1, A2, A3, A4, A5, A6, A7, A8) -> R {} impl<A1, A2, A3, A4, A5, A6, A7, A8, A9, R> Dupe for fn(A1, A2, A3, A4, A5, A6, A7, A8, A9) -> R {} impl<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, R> Dupe for fn(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10) -> R { } impl<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, R> Dupe for fn(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11) -> R { } impl<A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12, R> Dupe for fn(A1, A2, A3, A4, A5, A6, A7, A8, A9, A10, A11, A12) -> R { } // Rust goes up to 12 arguments for traits, so we follow #[cfg(test)] mod tests { use super::*; #[allow(unused_imports)] // Not actually unused, this makes testing the derive macro work use crate as gazebo; use gazebo_derive::Clone_; #[test] fn test_dupe_generic() { #[derive(Clone, Dupe, Debug, PartialEq, Eq)] struct Foo {} #[derive(Clone, Dupe, Debug, PartialEq, Eq)] struct FooT<T> { foo: T, } #[derive(Clone, Dupe, Debug, PartialEq, Eq)] struct Faz; let x = Foo {}; assert_eq!(x, x.dupe()); let x = FooT { foo: 1 }; assert_eq!(x, x.dupe()); let x = Faz; assert_eq!(x, x.dupe()); } #[test] fn test_dupe_() { #[derive(Debug, PartialEq, Eq)] struct NoClone(); #[derive(Clone_, Dupe_, Debug, PartialEq, Eq)] struct FooT<T> { foo: Arc<T>, } let x = FooT { foo: Arc::new(NoClone()), }; assert_eq!(x, x.dupe()); } #[test] fn test_dupe_enum() { #[derive(Clone, Dupe, Debug, PartialEq, Eq)] struct Foo(); #[derive(Clone, Dupe, Debug, PartialEq, Eq)] struct Foo2; #[derive(Clone, Dupe, Debug, PartialEq, Eq)] struct Bar(i64, bool, Foo2); #[derive(Clone, Dupe, Debug, PartialEq, Eq)] struct Baz { foo: usize, } #[derive(Clone, Dupe, Debug, PartialEq, Eq)] enum Qux { Foo(), Foo2, Bar(Foo, Bar), Baz { foo: Foo, bar: Bar, baz: Baz }, } let x = Qux::Bar(Foo(), Bar(8, true, Foo2)); assert_eq!(x, x.dupe()); let x = Qux::Baz { foo: Foo(), bar: Bar(7, false, Foo2), baz: Baz { foo: 9 }, }; assert_eq!(x, x.dupe()); } #[test] fn test_dupe_fn() where fn(usize): Dupe, fn(String, Vec<usize>) -> bool: Dupe, { // Tests are in the where } }
use std::sync::Once; use std::sync::ONCE_INIT; use std::cell::RefCell; use std::sync::Arc; use std::sync::Mutex; use std::sync::atomic::AtomicBool; use std::sync::atomic::Ordering; use std::collections::LinkedList; use util::AtomicOption; use util::ArcCell; use std::marker::PhantomData; static mut EMPTY_SUB_REF: Option<UnsubRef> = None; static EMPTY_SUB_REF_INIT: Once = ONCE_INIT; #[derive(Clone)] pub struct UnsubRef<'a> { state: Arc<State<'a>>, _unsub_on_drop: bool, } impl<'a> Drop for UnsubRef<'a> { fn drop(&mut self) { if self._unsub_on_drop { self.unsub(); } } } struct State<'a> { disposed: AtomicBool, cb: Option<Box<Fn()+'a+Send+Sync>>, extra: AtomicOption<LinkedList<UnsubRef<'a>>>, } impl<'a> UnsubRef<'a> { pub fn fromFn<F: Fn()+'a+Send+Sync>(unsub: F) -> UnsubRef<'a> { UnsubRef { state: Arc::new( State{ disposed: AtomicBool::new(false), cb: Some(box unsub), extra: AtomicOption::with(LinkedList::new()) }), _unsub_on_drop: false, } } pub fn signal() -> UnsubRef<'static> { UnsubRef { state: Arc::new( State{ disposed: AtomicBool::new(false), cb: None, extra: AtomicOption::with(LinkedList::new()) }), _unsub_on_drop: false, } } pub fn scoped<'s>() -> UnsubRef<'s> { UnsubRef { state: Arc::new( State{ disposed: AtomicBool::new(false), cb: None, extra: AtomicOption::with(LinkedList::new()) }), _unsub_on_drop: true, } } pub fn empty() -> UnsubRef<'a> { unsafe { EMPTY_SUB_REF_INIT.call_once(|| { //todo EMPTY_SUB_REF = Some( UnsubRef { state: Arc::new( State{cb: None, extra: AtomicOption::new(), disposed: AtomicBool::new(true) }, ), _unsub_on_drop: false, } ); }); ::std::mem::transmute(EMPTY_SUB_REF.as_ref().unwrap().clone()) } } pub fn unsub(&self) { if self.state.disposed.compare_and_swap(false, true, Ordering::SeqCst){ return; } if let Some(ref cb) = self.state.cb { cb(); } loop{ if let Some(lst) = self.state.extra.take(Ordering::SeqCst){ lst.iter().for_each(|f| f.unsub()); break; } } } pub fn add<U>(&self, unsub: U) -> &Self where U:IntoUnsubRef<'a> { let un = unsub.into(); if Arc::ptr_eq(&un.state, &self.state) {return self;} loop { if un.disposed() { break; }else if self.state.disposed.load(Ordering::SeqCst) { un.unsub(); break; }else if let Some(mut lst) = self.state.extra.take(Ordering::SeqCst) { lst.push_back(un); self.state.extra.swap(lst, Ordering::SeqCst); break; } } return self; } pub fn combine<U>(self, other: U) -> Self where U : IntoUnsubRef<'a> { self.add(other.into()); self } #[inline] pub fn disposed(&self) -> bool { self.state.disposed.load(Ordering::SeqCst)} } pub trait IntoUnsubRef<'a> { fn into(self) -> UnsubRef<'a>; } impl<'a, F:Fn()+'static+Send+Sync> IntoUnsubRef<'a> for F { fn into(self) -> UnsubRef<'a> { UnsubRef::fromFn(self) } } impl<'a> IntoUnsubRef<'a> for UnsubRef<'a> { fn into(self) -> UnsubRef<'a>{ self } } #[cfg(test)] mod tests { use super::*; use std::thread; use subject::*; use observable::*; #[test] fn disposed() { let u = UnsubRef::fromFn(||{}); u.unsub(); assert!(u.disposed()); } #[test] fn add_after_unsub() { let u = UnsubRef::fromFn(||{}); u.unsub(); let v = Arc::new(AtomicBool::new(false)); let v2 = v.clone(); u.add(move || v2.store(true, Ordering::SeqCst)); assert!(v.load(Ordering::SeqCst)); } #[test] fn threads() { let out = Arc::new(Mutex::new("".to_owned())); let (out2,out3) = (out.clone(), out.clone()); let u = UnsubRef::fromFn(||{}); let (u2,u3) = (u.clone(), u.clone()); let j = thread::spawn(move || { u2.add(move || { out.lock().unwrap().push_str("A"); }); }); u3.add(move || { out2.lock().unwrap().push_str("A"); }); let j2 = thread::spawn(move || { u.unsub(); }); j.join(); j2.join(); assert_eq!(*out3.lock().unwrap(), "AA"); } #[test] fn scoped() { let subj = Subject::new(); let mut result = 0; { let scope = subj.rx().sub_scoped(|v|{ result += v; }); scope.add(|| println!("Where?")); println!("hello"); subj.next(1); } subj.next(2); assert_eq!(result, 1); } #[test] fn scoped2() { use fac::rxfac; use op::*; let mut result = 0; rxfac::range(0..100).take(10).sub_scoped(|v| result += v ); assert_eq!(result, (0..100).take(10).sum()); } }
pub use core::prelude::v1::*; pub use alloc::prelude::v1::*; pub use alloc::{format, vec}; pub use core::mem::size_of; pub use core::marker::PhantomData; pub use core::ptr::{self, null, null_mut}; pub use core::cell::RefCell; pub use sys_consts::SysErr; pub use lazy_static::lazy_static; pub use x86_64::{PhysAddr, VirtAddr}; pub use modular_bitfield::prelude::*; pub use crate::util::misc::*; pub use crate::util::{Err, Error}; pub use crate::arch::x64::bochs_break; pub use crate::{eprint, eprintln, init_array, print, println, rprint, rprintln}; pub use crate::kdata::{cpud, try_cpud, force_cpud, prid}; pub fn d() { crate::arch::x64::bochs_break(); }
pub mod instructions; pub mod frame; use super::objects::{ObjectRef, ObjectContent, Object}; use super::varstack::VarStack; use self::instructions::{CmpOperator, Instruction}; use self::frame::{Block, Frame}; use std::fmt; use std::collections::HashMap; use std::io::Read; use std::cell::RefCell; use std::rc::Rc; use super::marshal; use super::state::{State, PyResult, unwind, raise, return_value}; use super::sandbox::EnvProxy; use super::primitives; #[derive(Debug)] pub enum ProcessorError { CircularReference, InvalidReference, NotACodeObject(String), NotAFunctionObject(String), CodeObjectIsNotBytes, InvalidProgramCounter, StackTooSmall, InvalidConstIndex, InvalidName(String), InvalidNameIndex, InvalidVarnameIndex, UnknownPrimitive(String), UnmarshalError(marshal::decode::UnmarshalError), InvalidModuleName(String), } impl fmt::Display for ProcessorError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Debug::fmt(self, f) } } /// Like try!, but for PyResult instead of Result macro_rules! py_try { ( $py_res: expr ) => { match $py_res { PyResult::Return(res) => res, py_res => return py_res } }; } /// Like Option::unwrap, but raises an exception instead of panic. macro_rules! py_unwrap { ( $state: expr, $rust_res: expr, $err: expr ) => { match $rust_res { Some(res) => res, None => return $state.raise_processor_error($err), } } } macro_rules! pop_stack { ( $state: expr, $stack_name: expr) => { py_unwrap!($state, $stack_name.pop(), ProcessorError::StackTooSmall) } } macro_rules! top_stack { ( $state: expr, $stack_name: expr) => { py_unwrap!($state, $stack_name.top(), ProcessorError::StackTooSmall) } } // Load a name from the namespace fn load_name<EP: EnvProxy>(state: &mut State<EP>, frame: &Frame, name: &String) -> Option<ObjectRef> { if *name == "__primitives__" { return Some(state.store.allocate(Object::new_instance(Some("__primitives__".to_string()), state.primitive_objects.object.clone(), ObjectContent::PrimitiveNamespace))) } if *name == "__name__" { return Some(state.store.allocate(state.primitive_objects.new_string("<module>".to_string()))) } if let Some(obj_ref) = frame.locals.borrow().get(name) { return Some(obj_ref.clone()) } if let Some(m) = state.modules.get("builtins") { if let Some(obj_ref) = m.borrow().get(name) { return Some(obj_ref.clone()) } } if let Some(m) = state.modules.get(&frame.object.module(&state.store)) { if let Some(obj_ref) = m.borrow().get(name) { return Some(obj_ref.clone()) } } None } fn load_attr<EP: EnvProxy>(state: &mut State<EP>, obj: &Object, name: &String) -> Option<ObjectRef> { match name.as_ref() { "__bases__" => { match obj.bases { Some(ref v) => Some(state.store.allocate(state.primitive_objects.new_tuple(v.clone()))), None => Some(state.primitive_objects.none.clone()), } }, "__name__" => { match obj.name { Some(ref s) => Some(state.store.allocate(state.primitive_objects.new_string(s.clone()))), None => None, } }, _ => { if let ObjectContent::PrimitiveNamespace = obj.content { match state.primitive_objects.names_map.get(name) { Some(obj_ref) => Some(obj_ref.clone()), None => Some(state.store.allocate(Object::new_instance(Some(name.clone()), state.primitive_objects.function_type.clone(), ObjectContent::PrimitiveFunction(name.clone())))), } } else { // TODO: special names match obj.attributes { Some(ref attributes) => attributes.borrow().get(name).map(|r| r.clone()), None => None, } } } } } // Call a primitive / function / code object, with arguments. fn call_function<EP: EnvProxy>(state: &mut State<EP>, call_stack: &mut Vec<Frame>, func_ref: &ObjectRef, mut args: Vec<ObjectRef>, kwargs: Vec<(ObjectRef, ObjectRef)>) { // TODO: clone only if necessary match state.store.deref(func_ref).content.clone() { ObjectContent::Class => { let frame = call_stack.last_mut().unwrap(); frame.var_stack.push(func_ref.new_instance(&mut state.store, args, kwargs)) }, ObjectContent::Function(ref _func_module, ref code_ref, ref defaults) => { let code = state.store.deref(code_ref).content.clone(); if let ObjectContent::Code(code) = code { let mut locals = defaults.clone(); if let Some(starargs_name) = code.get_varargs_name() { // If it has a *args argument if code.argcount > args.len() { panic!(format!("{}() takes at least {} arguments, but {} was/were given.", code.name, code.argcount, args.len())) }; let to_vararg = args.drain(code.argcount..).collect(); let obj_ref = state.store.allocate(state.primitive_objects.new_tuple(to_vararg)); // Bind *args assert_eq!(None, locals.insert(starargs_name.clone(), obj_ref)); } else if code.argcount != args.len() { // If it has no *args argument panic!(format!("{}() takes {} arguments, but {} was/were given.", code.name, code.argcount, args.len())) }; // Handle keyword arguments let mut remaining_kwargs = vec![]; // arguments that will go to **kwargs { let explicit_keywords = code.keywords(); for (key, value) in kwargs.into_iter() { let key_str = match state.store.deref(&key).content { ObjectContent::String(ref s) => s, _ => panic!("Keyword names should be strings."), }; if explicit_keywords.contains(key_str) { locals.insert(key_str.clone(), value); } else { remaining_kwargs.push((key, value)) } } } if let Some(starkwargs_name) = code.get_varkwargs_name() { // If it has a **kwargs argument let obj_ref = state.store.allocate(state.primitive_objects.new_dict(remaining_kwargs)); locals.insert(starkwargs_name.clone(), obj_ref); } else { // If it has no **kwargs argument if remaining_kwargs.len() != 0 { panic!(format!("Unknown keyword argument to function {} with no **kwargs", code.name)) } } // Bind positional arguments { for (argname, argvalue) in code.varnames.iter().zip(args) { locals.insert(argname.clone(), argvalue); }; } let new_frame = Frame::new(func_ref.clone(), *code, Rc::new(RefCell::new(locals))); call_stack.push(new_frame); } else { let exc = state.primitive_objects.processorerror.clone(); let repr = code_ref.repr(&state.store); raise(state, call_stack, exc, format!("Not a code object {}", repr)); } }, ObjectContent::PrimitiveFunction(ref name) => { let function_opt = state.primitive_functions.get(name).map(|o| *o); match function_opt { None => { let exc = state.primitive_objects.baseexception.clone(); raise(state, call_stack, exc, format!("Unknown primitive {}", name)); // Should have errored before }, Some(function) => { function(state, call_stack, args); // Call the primitive } } }, _ => { let exc = state.primitive_objects.typeerror.clone(); let repr = func_ref.repr(&state.store); raise(state, call_stack, exc, format!("Not a function object {:?}", repr)); } } } // Main interpreter loop // See https://docs.python.org/3/library/dis.html for a description of instructions fn run_code<EP: EnvProxy>(state: &mut State<EP>, call_stack: &mut Vec<Frame>) -> PyResult { loop { let instruction = { let frame = call_stack.last_mut().unwrap(); let instruction = py_unwrap!(state, frame.instructions.get(frame.program_counter), ProcessorError::InvalidProgramCounter); // Useful for debugging: /* println!(""); for r in frame.var_stack.iter() { println!("{}", r.repr(&state.store)); } println!("{} {:?}", frame.program_counter, instruction); */ frame.program_counter += 1; instruction.clone() }; match instruction { Instruction::PushImmediate(r) => { let frame = call_stack.last_mut().unwrap(); frame.var_stack.push(r); }, Instruction::PopTop => { let frame = call_stack.last_mut().unwrap(); pop_stack!(state, frame.var_stack); () }, Instruction::DupTop => { let frame = call_stack.last_mut().unwrap(); let val = pop_stack!(state, frame.var_stack); frame.var_stack.push(val.clone()); frame.var_stack.push(val); } Instruction::Nop => (), Instruction::BinarySubscr => { let (container, index) = { let frame = call_stack.last_mut().unwrap(); let index_ref = pop_stack!(state, frame.var_stack); let index = state.store.deref(&index_ref).content.clone(); let container_ref = pop_stack!(state, frame.var_stack); let container = state.store.deref(&container_ref).content.clone(); (container, index) }; let typeerror = state.primitive_objects.typeerror.clone(); match (container, index) { (ObjectContent::Tuple(v), ObjectContent::Int(i)) | (ObjectContent::List(v), ObjectContent::Int(i)) => { match v.get(i as usize) { // TODO: overflow check None => { let exc = state.primitive_objects.nameerror.clone(); raise(state, call_stack, exc, format!("Index out of range")) }, Some(obj_ref) => { let frame = call_stack.last_mut().unwrap(); frame.var_stack.push(obj_ref.clone()) }, } }, (ObjectContent::Tuple(_), index) => raise(state, call_stack, typeerror, format!("tuple indices must be int, not {:?}", index)), (ObjectContent::List(_), index) => raise(state, call_stack, typeerror, format!("list indices must be int, not {:?}", index)), (container, _index) => raise(state, call_stack, typeerror, format!("{:?} object is not subscriptable", container)), } } Instruction::GetIter => { let frame = call_stack.last_mut().unwrap(); let obj_ref = pop_stack!(state, frame.var_stack); frame.var_stack.push(obj_ref.iter(state)); } Instruction::LoadBuildClass => { let frame = call_stack.last_mut().unwrap(); let obj = Object::new_instance(Some("__build_class__".to_string()), state.primitive_objects.function_type.clone(), ObjectContent::PrimitiveFunction("build_class".to_string())); frame.var_stack.push(state.store.allocate(obj)); } Instruction::ReturnValue => { if call_stack.len() == 1 { let mut frame = call_stack.pop().unwrap(); let result = pop_stack!(state, frame.var_stack); return PyResult::Return(result); } else { let mut frame = call_stack.pop().unwrap(); let result = pop_stack!(state, frame.var_stack); return_value(call_stack, result) } } Instruction::PopBlock => { let frame = call_stack.last_mut().unwrap(); pop_stack!(state, frame.block_stack); } Instruction::EndFinally => { let status_ref = { let frame = call_stack.last_mut().unwrap(); pop_stack!(state, frame.var_stack) }; let status_content = { let status = state.store.deref(&status_ref); let content = status.content.clone(); // TODO: copy only if needed content }; match status_content { ObjectContent::Int(i) => panic!("TODO: finally int status"), // TODO ObjectContent::OtherObject => { let (val, traceback) = { let frame = call_stack.last_mut().unwrap(); let val = pop_stack!(state, frame.var_stack); // Note: CPython calls this variable “exc” let traceback = pop_stack!(state, frame.var_stack); (val, traceback) }; let exc = status_ref; call_stack.last_mut().unwrap().block_stack.pop().unwrap(); // Remove this try…except block unwind(state, call_stack, traceback, exc, val); } ObjectContent::None => { } _ => panic!(format!("Invalid finally status: {:?}", state.store.deref(&status_ref))) } } Instruction::PopExcept => { let frame = call_stack.last_mut().unwrap(); let mut three_last = frame.var_stack.pop_all_and_get_n_last(3).unwrap(); // TODO: check let _exc_type = three_last.pop(); let _exc_value = three_last.pop(); let _exc_traceback = three_last.pop(); // TODO: do something with exc_* pop_stack!(state, frame.block_stack); }, Instruction::StoreName(i) => { let frame = call_stack.last_mut().unwrap(); let name = py_unwrap!(state, frame.code.names.get(i), ProcessorError::InvalidNameIndex).clone(); let obj_ref = pop_stack!(state, frame.var_stack); frame.locals.borrow_mut().insert(name, obj_ref); } Instruction::ForIter(i) => { let iterator = { let frame = call_stack.last_mut().unwrap(); frame.block_stack.push(Block::ExceptPopGoto(state.primitive_objects.stopiteration.clone(), 1, frame.program_counter+i)); let iterator = top_stack!(state, frame.var_stack); iterator.clone() }; let iter_func = state.store.allocate(Object::new_instance(None, state.primitive_objects.function_type.clone(), ObjectContent::PrimitiveFunction("iter".to_string()))); call_function(state, call_stack, &iter_func, vec![iterator], vec![]); } Instruction::StoreAttr(i) => { let frame = call_stack.last_mut().unwrap(); let name = py_unwrap!(state, frame.code.names.get(i), ProcessorError::InvalidNameIndex).clone(); let owner = pop_stack!(state, frame.var_stack); let value = pop_stack!(state, frame.var_stack); owner.setattr(&mut state.store, name, value); } Instruction::StoreGlobal(i) => { let frame = call_stack.last_mut().unwrap(); let name = py_unwrap!(state, frame.code.varnames.get(i), ProcessorError::InvalidVarnameIndex).clone(); let mut globals = state.modules.get(&frame.object.module(&state.store)).unwrap().borrow_mut(); globals.insert(name, pop_stack!(state, frame.var_stack)); } Instruction::LoadConst(i) => { let frame = call_stack.last_mut().unwrap(); frame.var_stack.push(py_unwrap!(state, frame.code.consts.get(i), ProcessorError::InvalidConstIndex).clone()) } Instruction::LoadName(i) | Instruction::LoadGlobal(i) => { // TODO: LoadGlobal should look only in globals let (name, res) = { let frame = call_stack.last_mut().unwrap(); let name = py_unwrap!(state, frame.code.names.get(i), ProcessorError::InvalidNameIndex); let res = load_name(state, &frame, name); (name.clone(), res) }; match res { None => { let exc = state.primitive_objects.nameerror.clone(); raise(state, call_stack, exc, format!("Unknown variable {}", name)) }, Some(obj_ref) => { let frame = call_stack.last_mut().unwrap(); frame.var_stack.push(obj_ref) } } } Instruction::BuildTuple(size) => { let frame = call_stack.last_mut().unwrap(); let content = py_unwrap!(state, frame.var_stack.pop_many(size), ProcessorError::StackTooSmall); let tuple = state.primitive_objects.new_tuple(content); frame.var_stack.push(state.store.allocate(tuple)); } Instruction::LoadAttr(i) => { let (name, obj) = { let frame = call_stack.last_mut().unwrap(); let name = py_unwrap!(state, frame.code.names.get(i), ProcessorError::InvalidNameIndex).clone(); let obj_ref = py_unwrap!(state, frame.var_stack.pop(), ProcessorError::StackTooSmall); let obj = state.store.deref(&obj_ref).clone(); (name, obj) }; let res = load_attr(state, &obj, &name); match res { None => { let exc = state.primitive_objects.nameerror.clone(); raise(state, call_stack, exc, format!("Unknown attribute {}", name)) }, Some(obj_ref) => { let frame = call_stack.last_mut().unwrap(); frame.var_stack.push(obj_ref) } } }, Instruction::SetupLoop(i) => { let frame = call_stack.last_mut().unwrap(); frame.block_stack.push(Block::Loop(frame.program_counter, frame.program_counter+i)) } Instruction::SetupExcept(i) => { let frame = call_stack.last_mut().unwrap(); frame.block_stack.push(Block::TryExcept(frame.program_counter, frame.program_counter+i)) } Instruction::CompareOp(CmpOperator::Eq) => { let frame = call_stack.last_mut().unwrap(); // TODO: enrich this (support __eq__) let obj1 = state.store.deref(&pop_stack!(state, frame.var_stack)); let obj2 = state.store.deref(&pop_stack!(state, frame.var_stack)); if obj1.name == obj2.name && obj1.content == obj2.content { frame.var_stack.push(state.primitive_objects.true_obj.clone()) } else { frame.var_stack.push(state.primitive_objects.false_obj.clone()) }; } Instruction::CompareOp(CmpOperator::ExceptionMatch) => { let frame = call_stack.last_mut().unwrap(); // TODO: add support for tuples let pattern_ref = pop_stack!(state, frame.var_stack); let exc_ref = pop_stack!(state, frame.var_stack); let val = if primitives::native_isinstance(&state.store, &exc_ref, &pattern_ref) { state.primitive_objects.true_obj.clone() } else { state.primitive_objects.false_obj.clone() }; frame.var_stack.push(val) } Instruction::JumpAbsolute(target) => { let frame = call_stack.last_mut().unwrap(); frame.program_counter = target } Instruction::JumpForward(delta) => { let frame = call_stack.last_mut().unwrap(); frame.program_counter += delta } Instruction::LoadFast(i) => { let frame = call_stack.last_mut().unwrap(); let name = py_unwrap!(state, frame.code.varnames.get(i), ProcessorError::InvalidVarnameIndex).clone(); let obj_ref = py_unwrap!(state, frame.locals.borrow().get(&name), ProcessorError::InvalidName(name)).clone(); frame.var_stack.push(obj_ref) } Instruction::StoreFast(i) => { let frame = call_stack.last_mut().unwrap(); let name = py_unwrap!(state, frame.code.varnames.get(i), ProcessorError::InvalidVarnameIndex).clone(); frame.locals.borrow_mut().insert(name, pop_stack!(state, frame.var_stack)); } Instruction::PopJumpIfFalse(target) => { let frame = call_stack.last_mut().unwrap(); let obj = state.store.deref(&pop_stack!(state, frame.var_stack)); match obj.content { ObjectContent::True => (), ObjectContent::False => frame.program_counter = target, _ => unimplemented!(), } } Instruction::RaiseVarargs(0) => { panic!("RaiseVarargs(0) not implemented.") } Instruction::RaiseVarargs(1) => { let exception = pop_stack!(state, call_stack.last_mut().unwrap().var_stack); let traceback = state.primitive_objects.none.clone(); let value = state.primitive_objects.none.clone(); unwind(state, call_stack, traceback, exception, value); } Instruction::RaiseVarargs(2) => { panic!("RaiseVarargs(2) not implemented.") } Instruction::RaiseVarargs(_) => { // Note: the doc lies, the argument can only be ≤ 2 panic!("Bad RaiseVarargs argument") // TODO: Raise an exception instead } Instruction::CallFunction(nb_args, nb_kwargs) => { // See “Call constructs” at: // http://security.coverity.com/blog/2014/Nov/understanding-python-bytecode.html let kwargs; let args; let func; { let frame = call_stack.last_mut().unwrap(); kwargs = py_unwrap!(state, frame.var_stack.pop_n_pairs(nb_kwargs), ProcessorError::StackTooSmall); args = py_unwrap!(state, frame.var_stack.pop_many(nb_args), ProcessorError::StackTooSmall); func = pop_stack!(state, frame.var_stack); } call_function(state, call_stack, &func, args, kwargs) }, Instruction::MakeFunction(0, nb_default_kwargs, 0) => { // TODO: consume default arguments and annotations let obj = { let frame = call_stack.last_mut().unwrap(); let obj = state.store.deref(&pop_stack!(state, frame.var_stack)).content.clone(); // TODO: clone only if necessary obj }; let func_name = match obj { ObjectContent::String(ref s) => s.clone(), name => { let exc = state.primitive_objects.typeerror.clone(); raise(state, call_stack, exc, format!("function names must be strings, not {:?}", name)); continue } }; let frame = call_stack.last_mut().unwrap(); let code = pop_stack!(state, frame.var_stack); let raw_kwdefaults = py_unwrap!(state, frame.var_stack.pop_n_pairs(nb_default_kwargs), ProcessorError::StackTooSmall); let mut kwdefaults: HashMap<String, ObjectRef> = HashMap::new(); kwdefaults.reserve(nb_default_kwargs); for (key, value) in raw_kwdefaults { match state.store.deref(&key).content { ObjectContent::String(ref s) => { kwdefaults.insert(s.clone(), value); }, _ => panic!("Defaults' keys must be strings."), } } let func = state.primitive_objects.new_function(func_name, frame.object.module(&state.store), code, kwdefaults); frame.var_stack.push(state.store.allocate(func)) }, _ => panic!(format!("todo: instruction {:?}", instruction)), } }; } fn call_module_code<EP: EnvProxy>(state: &mut State<EP>, call_stack: &mut Vec<Frame>, module_name: String, module_ref: ObjectRef) -> PyResult { let code_ref = match state.store.deref(&module_ref).content { ObjectContent::Module(ref code_ref) => code_ref.clone(), ref o => panic!("Not a module: {:?}", o), }; let code = match state.store.deref(&code_ref).content { ObjectContent::Code(ref code) => code.clone(), ref o => return state.raise_processor_error(ProcessorError::NotACodeObject(format!("file code {:?}", o))), }; let module_obj = state.store.allocate(state.primitive_objects.new_module(module_name.clone(), code_ref)); state.modules.insert(module_name.clone(), Rc::new(RefCell::new(HashMap::new()))); call_stack.push(Frame::new(module_obj, *code, state.modules.get(&module_name).unwrap().clone())); let res = run_code(state, call_stack); res // Do not raise exceptions before the pop() } /// Get the code of a module from its name pub fn get_module_code<EP: EnvProxy>(state: &mut State<EP>, module_name: String) -> PyResult { // Load the code let mut module_bytecode = state.envproxy.open_module(module_name.clone()); let mut buf = [0; 12]; module_bytecode.read_exact(&mut buf).unwrap(); if !marshal::check_magic(&buf[0..4]) { panic!(format!("Bad magic number for module {}.", module_name)) } match marshal::read_object(&mut module_bytecode, &mut state.store, &state.primitive_objects) { Err(e) => state.raise_processor_error(ProcessorError::UnmarshalError(e)), Ok(module_code_ref) => PyResult::Return(state.store.allocate(state.primitive_objects.new_module(module_name.clone(), module_code_ref))), } } /// Entry point to run code. Loads builtins in the code's namespace and then run it. pub fn call_main_code<EP: EnvProxy>(state: &mut State<EP>, code_ref: ObjectRef) -> PyResult { let mut call_stack = Vec::new(); let builtins_code_ref = py_try!(get_module_code(state, "builtins".to_string())); py_try!(call_module_code(state, &mut call_stack, "builtins".to_string(), builtins_code_ref)); let mut call_stack = Vec::new(); let module_ref = state.store.allocate(state.primitive_objects.new_module("__main__".to_string(), code_ref)); call_module_code(state, &mut call_stack, "__main__".to_string(), module_ref) }
// 16.22 Langton's Ant // The grid will be represented by a map of coordinates. #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] struct V2 { x: i32, y: i32, } use std::{collections::HashMap, fmt}; impl std::ops::Add for V2 { type Output = Self; fn add(self, rhs: Self) -> Self { V2 { x: self.x + rhs.x, y: self.y + rhs.y, } } } impl V2 { pub fn rotate_cw(self) -> Self { V2 { x: self.y, y: -self.x, } } pub fn rotate_ccw(self) -> Self { V2 { x: -self.y, y: self.x, } } } const ZERO: V2 = V2 { x: 0, y: 0 }; const UP: V2 = V2 { x: 0, y: 1 }; const DOWN: V2 = V2 { x: 0, y: -1 }; const LEFT: V2 = V2 { x: -1, y: 0 }; const RIGHT: V2 = V2 { x: 1, y: 0 }; struct State { board: HashMap<V2, bool>, current_position: V2, current_direction: V2, // normalized V2 in a cardinal direction min_pos: V2, max_pos: V2, } impl State { pub fn new() -> Self { let board = [(ZERO, false)] .iter() .cloned() .collect::<HashMap<V2, bool>>(); State { board, current_position: ZERO, current_direction: RIGHT, max_pos: ZERO, min_pos: ZERO, } } pub fn iterate(&mut self) { let cell = self.board.entry(self.current_position).or_insert(false); if !(*cell) { //white *cell = !*cell; self.current_direction = self.current_direction.rotate_cw(); } else { // black *cell = !*cell; self.current_direction = self.current_direction.rotate_ccw(); } self.current_position = self.current_position + self.current_direction; use std::cmp::{max, min}; self.max_pos.x = max(self.max_pos.x, self.current_position.x); self.max_pos.y = max(self.max_pos.y, self.current_position.y); self.min_pos.x = min(self.min_pos.x, self.current_position.x); self.min_pos.y = min(self.min_pos.y, self.current_position.y); } } impl fmt::Display for State { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str( { let mut rv = String::new(); // Print from top to bottom for y in (self.min_pos.y..=self.max_pos.y).rev() { for x in self.min_pos.x..=self.max_pos.x { let pos = V2 { x, y }; rv += if pos == self.current_position { match self.current_direction { UP => "^", DOWN => "v", LEFT => "<", RIGHT => ">", _ => panic!("Invalid direction!"), } } else { match self.board.get(&pos) { Some(true) => "#", _ => " ", } } } rv += "\n"; } rv } .as_str(), ) } } fn print_k_moves(k: u32) -> String { let mut state = State::new(); for _ in 0..k { state.iterate() } state.to_string() } #[test] fn test() { assert!( print_k_moves(8) == " ## #<# ## "[1..] ); println!("Ex 16.22 ok!"); }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #![deny(warnings)] #[macro_use] extern crate clap; #[macro_use] extern crate failure; extern crate fidl; extern crate fidl_fuchsia_wlan_device as wlan; extern crate fidl_fuchsia_wlan_device_service as wlan_service; extern crate fidl_fuchsia_wlan_sme as fidl_sme; extern crate fuchsia_app as component; #[macro_use] extern crate fuchsia_async as async; extern crate fuchsia_zircon as zx; extern crate futures; #[macro_use] extern crate structopt; use component::client::connect_to_service; use failure::{Error, Fail, ResultExt}; use fidl::endpoints2; use fidl_sme::{ConnectResultCode, ConnectTransactionEvent, ScanTransactionEvent}; use futures::prelude::*; use std::fmt; use structopt::StructOpt; use wlan_service::{DeviceServiceMarker, DeviceServiceProxy}; mod opts; use opts::*; type WlanSvc = DeviceServiceProxy; fn main() -> Result<(), Error> { let opt = Opt::from_args(); println!("{:?}", opt); let mut exec = async::Executor::new().context("error creating event loop")?; let wlan_svc = connect_to_service::<DeviceServiceMarker>().context("failed to connect to device service")?; match opt { Opt::Phy(cmd) => exec.run_singlethreaded(do_phy(cmd, wlan_svc)), Opt::Iface(cmd) => exec.run_singlethreaded(do_iface(cmd, wlan_svc)), Opt::Client(cmd) => exec.run_singlethreaded(do_client(cmd, wlan_svc)), } } fn do_phy(cmd: opts::PhyCmd, wlan_svc: WlanSvc) -> impl Future<Item = (), Error = Error> { match cmd { opts::PhyCmd::List => { // TODO(tkilbourn): add timeouts to prevent hanging commands wlan_svc .list_phys() .map_err(|e| e.context("error getting response").into()) .and_then(|response| { println!("response: {:?}", response); Ok(()) }).left_future() }, opts::PhyCmd::Query { phy_id } => { let mut req = wlan_service::QueryPhyRequest { phy_id }; wlan_svc .query_phy(&mut req) .map_err(|e| e.context("error querying phy").into()) .and_then(|response| { println!("response: {:?}", response); Ok(()) }).right_future() } } } fn do_iface(cmd: opts::IfaceCmd, wlan_svc: WlanSvc) -> impl Future<Item = (), Error = Error> { many_futures!(IfaceFut, [ New, Delete, List ]); match cmd { opts::IfaceCmd::New { phy_id, role } => IfaceFut::New({ let mut req = wlan_service::CreateIfaceRequest { phy_id: phy_id, role: role.into(), }; wlan_svc .create_iface(&mut req) .map_err(|e| e.context("error getting response").into()) .and_then(|response| { println!("response: {:?}", response); Ok(()) }) }), opts::IfaceCmd::Delete { phy_id, iface_id } => IfaceFut::Delete({ let mut req = wlan_service::DestroyIfaceRequest { phy_id: phy_id, iface_id: iface_id, }; wlan_svc .destroy_iface(&mut req) .map(move |status| match zx::Status::ok(status) { Ok(()) => println!("destroyed iface {:?}", iface_id), Err(s) => println!("error destroying iface: {:?}", s), }) .map_err(|e| e.context("error destroying iface").into()) .into_future() }), opts::IfaceCmd::List => IfaceFut::List({ wlan_svc.list_ifaces() .map_err(|e| e.context("error getting response").into()) .and_then(|response| { println!("response: {:?}", response); Ok(()) }) }), } } fn do_client(cmd: opts::ClientCmd, wlan_svc: WlanSvc) -> impl Future<Item = (), Error = Error> { many_futures!(ClientFut, [ Scan, Connect, Status ]); match cmd { opts::ClientCmd::Scan { iface_id } => ClientFut::Scan(get_client_sme(wlan_svc, iface_id) .and_then(|sme| { let (local, remote) = endpoints2::create_endpoints()?; let mut req = fidl_sme::ScanRequest { timeout: 10 }; sme.scan(&mut req, remote) .map_err(|e| e.context("error sending scan request"))?; Ok(local) }) .and_then(handle_scan_transaction) .err_into()), opts::ClientCmd::Connect { iface_id, ssid } => ClientFut::Connect(get_client_sme(wlan_svc, iface_id) .and_then(move |sme| { let (local, remote) = endpoints2::create_endpoints()?; let mut req = fidl_sme::ConnectRequest { ssid: ssid.as_bytes().to_vec(), // TODO(gbonik): take password as an optional argument password: Vec::new(), }; sme.connect(&mut req, Some(remote)) .map_err(|e| e.context("error sending connect request"))?; Ok(local) }) .and_then(handle_connect_transaction) .err_into()), opts::ClientCmd::Status { iface_id } => ClientFut::Status(get_client_sme(wlan_svc, iface_id) .and_then(|sme| sme.status().err_into()) .and_then(|st| { match st.connected_to { Some(bss) => { println!("Connected to '{}' (bssid {})", String::from_utf8_lossy(&bss.ssid), Bssid(bss.bssid)); }, None => println!("Not connected to a network"), } if !st.connecting_to_ssid.is_empty() { println!("Connecting to '{}'", String::from_utf8_lossy(&st.connecting_to_ssid)); } Ok(()) })) } } struct Bssid([u8; 6]); impl fmt::Display for Bssid { fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> { write!(f, "{:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}", self.0[0], self.0[1], self.0[2], self.0[3], self.0[4], self.0[5]) } } fn handle_scan_transaction(scan_txn: fidl_sme::ScanTransactionProxy) -> impl Future<Item = (), Error = Error> { let mut printed_header = false; scan_txn.take_event_stream() .map(move |e| { match e { ScanTransactionEvent::OnResult { aps } => { if !printed_header { print_scan_header(); printed_header = true; } for ap in aps { print_scan_result(ap); } false }, ScanTransactionEvent::OnFinished { } => true, ScanTransactionEvent::OnError { error } => { eprintln!("Error: {}", error.message); true }, } }) .fold(false, |_prev, done| Ok(done)) .err_into::<Error>() .and_then(|done| { if !done { bail!("Failed to fetch all results before the channel was closed"); } Ok(()) }) } fn print_scan_header() { println!("BSSID dBm Channel Protected SSID"); } fn print_scan_result(ess: fidl_sme::EssInfo) { println!("{} {:4} {:7} {:9} {}", Bssid(ess.best_bss.bssid), ess.best_bss.rx_dbm, ess.best_bss.channel, if ess.best_bss.protected { "Y" } else { "N" }, String::from_utf8_lossy(&ess.best_bss.ssid)); } fn handle_connect_transaction(connect_txn: fidl_sme::ConnectTransactionProxy) -> impl Future<Item = (), Error = Error> { connect_txn.take_event_stream() .map(|e| { match e { ConnectTransactionEvent::OnFinished { code } => { match code { ConnectResultCode::Success => println!("Connected successfully"), ConnectResultCode::Canceled => eprintln!("Connecting was canceled or superseded by another command"), ConnectResultCode::Failed => eprintln!("Failed to connect to network"), } true }, } }) .fold(false, |_prev, done| Ok(done)) .err_into::<Error>() .and_then(|done| { if !done { bail!("Failed to receiver a connect result before the channel was closed"); } Ok(()) }) } fn get_client_sme(wlan_svc: WlanSvc, iface_id: u16) -> impl Future<Item = fidl_sme::ClientSmeProxy, Error = Error> { endpoints2::create_endpoints() .into_future() .map_err(|e| e.into()) .and_then(move |(proxy, remote)| { wlan_svc.get_client_sme(iface_id, remote) .map_err(|e| e.context("error sending GetClientSme request").into()) .and_then(move |status| { if status == zx::sys::ZX_OK { Ok(proxy) } else { Err(format_err!("Invalid interface id {}", iface_id)) } }) }) } #[cfg(test)] mod tests { use super::*; #[test] fn format_bssid() { assert_eq!("01:02:03:ab:cd:ef", format!("{}", Bssid([ 0x01, 0x02, 0x03, 0xab, 0xcd, 0xef]))); } }
#![feature(globs)] #![crate_type = "bin"] #![feature(slicing_syntax)] extern crate bmp; use std::cmp::min; use std::io; use std::io::BufferedReader; use std::os; fn main() { let args = os::args(); let orig_file_path = args[1].as_slice(); let b_img = bmp::BMPimage::open(orig_file_path); let width = b_img.width as uint; let height = b_img.height as uint; let mut n_img = bmp::BMPimage::new(b_img.width, b_img.height); let mut z = 2u; let mut sz = 0u64; let mut buffer = [0u8, ..3]; let mut reader = BufferedReader::new(io::stdin()); loop { let _ = match reader.read_exact(3) { Ok(res) => { assert!(res.len() == 3); for i in range(0,3) { buffer[i] = res[i]; } sz += 3; }, Err(_) => { let _ = match reader.read_to_end() { Ok(res) => { assert!(res.len() < 3); if res.len() == 0 { break } for i in range(0, min(res.len(), 3)) { buffer[i] = res[i]; } sz += res.len() as u64; }, Err(_) => break }; } }; if z*4 + 3 > width*height { fail!("Too much data.") } for i in range(0, 4) { let pos = z*4 + i; let p = b_img.get_pixel(pos%width, pos/width); n_img.set_pixel(pos%width, pos/width, bmp::BMPpixel{ r: (p.r & 0xfc) | ((buffer[0] >> (2*i)) & 0x03), g: (p.g & 0xfc) | ((buffer[1] >> (2*i)) & 0x03), b: (p.b & 0xfc) | ((buffer[2] >> (2*i)) & 0x03) }); } z += 1; } let szs = vec![0u8,1,2,3,4,5].map_in_place(|i| ((sz >> (i as uint *8)) & 0xff) as u8 ); for j in range(0, 2) { for i in range(0, 4) { let pos = i+(j*4); let p = b_img.get_pixel(pos%width, pos/width); n_img.set_pixel(pos%width, pos/width, bmp::BMPpixel{ r: (p.r & 0xfc) | ((szs[j*3 ] >> (2*i)) & 0x03), g: (p.g & 0xfc) | ((szs[j*3+1] >> (2*i)) & 0x03), b: (p.b & 0xfc) | ((szs[j*3+2] >> (2*i)) & 0x03) }); } } for pos in range(z*4, width*height) { n_img.set_pixel(pos%width, pos/width, *b_img.get_pixel(pos%width, pos/width)); } let result_file_path = args[2].as_slice(); n_img.save(result_file_path); }
use super::*; use util::Error; #[test] fn test_tcp_type() -> Result<(), Error> { //assert_eq!(TCPType::Unspecified, tcpType) assert_eq!(TcpType::Active, TcpType::from("active")); assert_eq!(TcpType::Passive, TcpType::from("passive")); assert_eq!(TcpType::SimultaneousOpen, TcpType::from("so")); assert_eq!(TcpType::Unspecified, TcpType::from("something else")); assert_eq!("unspecified", TcpType::Unspecified.to_string()); assert_eq!("active", TcpType::Active.to_string()); assert_eq!("passive", TcpType::Passive.to_string()); assert_eq!("so", TcpType::SimultaneousOpen.to_string()); Ok(()) }
use url::Url; use regex::Regex; pub struct LinkParser { base_url: Url, } impl LinkParser { pub fn new(url: Url) -> LinkParser { LinkParser { base_url: url } } pub fn parse(self, data: &str) -> Vec<Url> { lazy_static! { static ref PATTERNS : String = vec![ r#"href="([^"]+)""#, r#"src="([^"]+)""# ].join("|"); static ref RE : Regex = Regex::new( &format!(r#"(?:{})"#, &PATTERNS[..]) ).unwrap(); } let mut output = Vec::new(); for link in RE.captures_iter(data) { // Skip the whole match, keep valid entries and unwrap option for parsed_link in link.iter().skip(1).filter(|l| !l.is_none()).map(Option::unwrap) { let parsed_link = parsed_link.as_str(); if let Ok(url) = Url::parse(parsed_link) { output.push(url); } else if let Ok(url) = self.base_url.join(parsed_link) { output.push(url); } } } output } } #[cfg(test)] mod tests { use super::LinkParser; use url::Url; #[test] fn parse_urls() { let absolute_url = Url::parse("http://www.example.com/foo.html").unwrap(); let image_url = Url::parse("http://www.images.com/image.jpg").unwrap(); let base_url = Url::parse("http://something.com/test").unwrap(); let relative_url = "../bar.html"; let text = format!( r#" <a href="{}">foo</a> <a href="{}">bar</a> <a href="">zar</a> <img src="{}" /> "#, absolute_url, relative_url, image_url ); let parser = LinkParser::new(base_url); let urls = vec![ absolute_url, Url::parse("http://something.com/bar.html").unwrap(), image_url ]; assert_eq!(urls, parser.parse(&text)); } #[test] fn invalid_data() { let base_url = Url::parse("http://www.example.com").unwrap(); let text = "asd"; let parser = LinkParser::new(base_url); assert_eq!(0, parser.parse(&text).len()); } }
#![no_std] #![no_main] program!(0xFFFFFFFE, "GPL"); use redbpf_probes::{bindings::udphdr, net::Transport, xdp::prelude::*}; #[xdp("redirect")] pub fn redirect(ctx: XdpContext) -> XdpResult { if let Ok(Transport::UDP(udp)) = ctx.transport() { unsafe { if u16::from_be((*udp).dest) == 7999 { (*(udp as *mut udphdr)).dest = u16::to_be(7998); } } } Ok(XdpAction::Pass) }
// #![feature(duration_as_u128)] use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, SystemTime}; use std::sync::mpsc; // use std::thread::JoinHandle; fn main() { let (tx, rx) = mpsc::channel(); let now = SystemTime::now(); let handle = thread::spawn(move || { { // 定时器 let tx = tx.clone(); thread::spawn(move || {// do something thread::sleep(Duration::from_millis(500)); tx.send(Err(())).unwrap(); }); } // 干一些不为人知的事情 thread::sleep(Duration::from_millis(300)); tx.send(Ok("result")).unwrap(); }); match rx.recv().unwrap() { // 计时器 Ok(data) => println!("{:?}, {}", data, now.elapsed().unwrap().as_millis()), Err(err) => { handle.join(); } } }
use super::*; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "line")] pub struct Line { pub x1: isize, pub y1: isize, pub x2: isize, pub y2: isize, } impl Line { pub fn new(x1: isize, y1: isize, x2: isize, y2: isize) -> Self { Self { x1, y1, x2, y2 } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "line")] pub struct PolyLine { #[serde(default)] points: String } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "rect")] pub struct Rect { pub x: Option<isize>, pub y: Option<isize>, pub rx: Option<isize>, pub ry: Option<isize>, pub width: usize, pub height: usize } impl Rect { pub fn new(x: Option<isize>, y: Option<isize>, rx: Option<isize>, ry: Option<isize>, width: usize, height: usize) -> Self { Self { x, y, rx, ry, width, height } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename = "text")] pub struct Text { #[serde(default)] pub x: isize, #[serde(default)] pub y: isize, #[serde(rename = "$value", default)] pub text: String } impl Text { pub fn new<S>(x: isize, y: isize, s: S) -> Self where S: Into<String> { Self { x, y, text: s.into() } } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum Shape { #[serde(rename = "line")] Line(Line), #[serde(rename = "rect")] Rect(Rect), #[serde(rename = "text")] Text(Text) } #[cfg(test)] mod tests { use super::*; #[test] fn line() { let svg = r#" <line x1="0" y1="0" x2="3" y2="3" /> "#; let l: Line = from_str(&svg).unwrap(); assert_eq!(l, Line::new(0, 0, 3, 3)); } #[test] fn point() { let svg = r#" <polyline points="20,20 40,25 60,40 80,120 120,140 200,180" /> "#; let p: PolyLine = from_str(&svg).unwrap(); println!("{:?}", p); } #[test] fn rect() { let svg = r#" <rect width="100" height="100" /> "#; let r: Rect = from_str(&svg).unwrap(); assert_eq!(r, Rect::new(None, None, None, None, 100, 100)); } #[test] fn shape() { let svg = r#" <line x1="5" y1="2" x2="12" y2="20" /> <rect width="300" height="200" /> "#; let s: Shape = from_str(&svg).unwrap(); assert_eq!(s, Shape::Line(Line::new(5, 2, 12, 20))); } #[test] fn text() { let svg = r#" <text x="10" y="5">hello world</text> "#; let t: Text = from_str(&svg).unwrap(); assert_eq!(t, Text::new(10, 5, "hello world")); } }
#![allow(unknown_lints, needless_borrow)] use quote; use syn; use syn::MetaItem::*; use syn::Lit::*; #[derive(Default, PartialEq, Debug)] struct GlobalAttrData { default_prefix: Option<String>, } fn get_smelter_attributes(attrs: &[syn::Attribute]) -> Vec<syn::MetaItem> { let smelter_ident = syn::Ident::new("smelter".to_string()); attrs.into_iter().filter(|attr| { if let List(ref ident, _) = attr.value { return ident == &smelter_ident } false }) .flat_map(|attr| { match attr.value { List(_, ref items) => items.clone(), _ => panic!("Attempted to extract item from non-list"), } }) .collect() } impl GlobalAttrData { fn from_attributes(attrs: &[syn::Attribute]) -> GlobalAttrData { let prefix_ident = syn::Ident::new("prefix".to_string()); let mut data = GlobalAttrData { default_prefix: None, }; let smelter_attrs = get_smelter_attributes(attrs); for item in smelter_attrs { if let NameValue(ref key, Str(ref prefix, _)) = item { if *key == prefix_ident { data.default_prefix = Some(prefix.clone()); } } } data } } #[derive(Debug, PartialEq, Default)] struct FieldAttrData { field_name: Option<String>, create_field: bool, force_public: bool, } impl FieldAttrData { fn from_attributes(attrs: &[syn::Attribute]) -> FieldAttrData { use syn::MetaItem::*; use syn::Lit::*; let mut data: FieldAttrData = FieldAttrData { create_field: true, .. Default::default() }; let field_name_ident = syn::Ident::new("field_name".to_string()); let create_field_ident = syn::Ident::new("should_create".to_string()); let force_public_ident = syn::Ident::new("force_public".to_string()); let smelter_attrs = get_smelter_attributes(attrs); for item in smelter_attrs { match item { NameValue(ref key, Str(ref value, _)) => { if field_name_ident == key { if &"".to_string() == value { panic!("Error: empty `field_name` has been specified as a smelter attribute") } data.field_name = Some(value.clone()); } }, NameValue(ref key, Bool(ref value)) => { if create_field_ident == key { data.create_field = *value; } }, Word(ref ident) => { if force_public_ident == ident { data.force_public = true; } } _ => () } } data } } #[derive(PartialEq, Debug)] struct CodeGenData<'a> { attr_data: &'a GlobalAttrData, fields: &'a Vec<syn::Field>, struct_name: &'a syn::Ident, ty_generics: &'a syn::Generics, } fn expand_fields<F>(fields: &[syn::Field], f: F) -> quote::Tokens where F: Fn(&syn::Field) -> quote::Tokens { let mut tokens = quote::Tokens::new(); tokens.append_all(fields.iter().map(f)); tokens } fn get_method_name(field_attrs: &FieldAttrData, field: &syn::Field, mutable: bool, prefix: &Option<String>) -> syn::Ident { let _prefix = match *prefix { Some(ref string) => string.clone(), None => "".to_string(), }; let base_name = match field_attrs.field_name { Some(ref field_name) => { format!("{}{}", _prefix, field_name) }, None => { format!("{}{}", _prefix, &field.ident.as_ref().unwrap()) } }; if mutable { syn::Ident::new(format!("{}_mut", base_name)) } else { syn::Ident::new(base_name) } } fn get_visibility(field_attrs: &FieldAttrData, field: &syn::Field) -> syn::Ident { let is_public = field_attrs.force_public || match field.vis { syn::Visibility::Public => true, _ => false, }; if is_public { syn::Ident::new("pub") } else { syn::Ident::new("") } } fn expand_mutable(data: &CodeGenData, fields: &[syn::Field]) -> quote::Tokens { let prefix = &data.attr_data.default_prefix; expand_fields(fields, |field| { let field_attrs = FieldAttrData::from_attributes(&field.attrs); let ident = field.ident.as_ref().unwrap(); if field_attrs.create_field { let method_name = get_method_name(&field_attrs, field, true, prefix); let pub_ident = get_visibility(&field_attrs, &field); let ty = &field.ty; let struct_name = data.struct_name; let ty_generics = data.ty_generics; quote! { #pub_ident fn #method_name(&mut self, __value: #ty) -> &mut #struct_name #ty_generics { self. #ident = __value; self } } } else { quote! { // Omitted #ident } } }) } fn expand_immutable(data: &CodeGenData, fields: &[syn::Field]) -> quote::Tokens { let prefix = &data.attr_data.default_prefix; expand_fields(fields, move |field| { let attr_data = FieldAttrData::from_attributes(&field.attrs); let ident = field.ident.as_ref().unwrap(); if attr_data.create_field { let method_name = get_method_name(&attr_data, &field, false, prefix); let pub_ident = get_visibility(&attr_data, &field); let ty = &field.ty; let struct_name = data.struct_name; let ty_generics = data.ty_generics; quote! { #pub_ident fn #method_name(self, __value: #ty) -> #struct_name #ty_generics { #struct_name { #ident : __value, .. self } } } } else { quote! { // something is silly here } } }) } fn expand_methods(ast: &syn::MacroInput) -> quote::Tokens { let body = &ast.body; match *body { syn::Body::Struct(ref variant) => { match *variant { syn::VariantData::Struct(ref fields) => { let struct_name = &ast.ident; let (_, ty_generics, _) = ast.generics.split_for_impl(); let attr_data = GlobalAttrData::from_attributes(&ast.attrs); let gen_data = CodeGenData { ty_generics: &ty_generics, struct_name: &struct_name, attr_data: &attr_data, fields: fields, }; let immutable_build_methods = expand_immutable(&gen_data, fields); let mutable_build_methods = expand_mutable(&gen_data, fields); quote! { #immutable_build_methods #mutable_build_methods } }, _ => panic!("Derive builder is not supported for tuple structs and the unit struct") } }, syn::Body::Enum(_) => panic!("Enums are not supported"), } } pub fn expand_builder(ast: syn::MacroInput) -> quote::Tokens { let methods = expand_methods(&ast); let struct_name = &ast.ident; let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl(); quote! { #[allow(unused_attributes)] #[allow(dead_code)] impl #impl_generics #struct_name #ty_generics #where_clause { #methods } } }
#[cfg(test)] mod bencho { use for_each_element; use serde_json; use serde_json::{Deserializer, Value}; use IDHolder; use test::Bencher; #[bench] fn name(b: &mut Bencher) { let data: Vec<serde_json::Value> = (0..20000) .map(|_| { json!({ "a": 1, "commonness": 35, "ent_seq": "1259290", "romaji": "Miru", "text": "みる", "more": ["ok", "nice"], "objects": [{ "stuff": "yii" },{ "stuff": "yaa" }] }) }) .collect(); let mut id_holder = IDHolder::new(); // let data = json!(long_string); // let data_str = serde_json::to_string(&data).unwrap(); // let data = json!(long_string); let mut json_string_line_seperatred = String::new(); for val in data { json_string_line_seperatred.push_str(&serde_json::to_string(&val).unwrap()); json_string_line_seperatred.push_str("\n"); } b.iter(|| { // let texts = vec![]; // texts.reserve(5000); let mut cb_text = |_anchor_id: u32, _value: &str, _path: &str, _parent_val_id: u32| -> Result<(), ()>{ // println!("TEXT: path {} value {} parent_val_id {}",path, value, parent_val_id); Ok(()) }; let mut callback_ids = |_anchor_id: u32, _path: &str, _val_id: u32, _parent_val_id: u32| -> Result<(), ()>{ // println!("IDS: path {} val_id {} parent_val_id {}",path, val_id, parent_val_id); Ok(()) }; // let stream = Deserializer::from_str(&json_string_line_seperatred).into_iter::<Value>(); let stream = json_string_line_seperatred.lines().map(|line| serde_json::from_str(&line)); for_each_element(stream, &mut id_holder, &mut cb_text, &mut callback_ids).unwrap(); }) } }
// Copyright 2015-2016 Joe Neeman. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use error::Error; use nfa::{Nfa, NoLooks}; use runner::anchored::AnchoredEngine; use runner::forward_backward::{ForwardBackwardEngine, Prefix}; use runner::Engine; use std; use std::fmt::Debug; #[derive(Debug)] pub struct Regex { engine: Box<Engine<u8>>, } // An engine that doesn't match anything. #[derive(Clone, Debug)] struct EmptyEngine; impl<Ret: Debug> Engine<Ret> for EmptyEngine { fn find(&self, _: &str) -> Option<(usize, usize, Ret)> { None } fn clone_box(&self) -> Box<Engine<Ret>> { Box::new(EmptyEngine) } } impl Clone for Regex { fn clone(&self) -> Regex { Regex { engine: self.engine.clone_box(), } } } impl Regex { /// Creates a new `Regex` from a regular expression string. pub fn new(re: &str) -> ::Result<Regex> { Regex::new_bounded(re, std::usize::MAX) } /// Creates a new `Regex` from a regular expression string, but only if it doesn't require too /// many states. pub fn new_bounded(re: &str, max_states: usize) -> ::Result<Regex> { let nfa = try!(Nfa::from_regex(re)); let nfa = nfa.remove_looks(); let eng = if nfa.is_empty() { Box::new(EmptyEngine) as Box<Engine<u8>> } else if nfa.is_anchored() { Box::new(try!(Regex::make_anchored(nfa, max_states))) as Box<Engine<u8>> } else { Box::new(try!(Regex::make_forward_backward(nfa, max_states))) as Box<Engine<u8>> }; Ok(Regex { engine: eng }) } fn make_anchored(nfa: Nfa<u32, NoLooks>, max_states: usize) -> ::Result<AnchoredEngine<u8>> { let nfa = try!(nfa.byte_me(max_states)); let dfa = try!(nfa.determinize(max_states)) .optimize() .map_ret(|(_, bytes)| bytes); let prog = dfa.compile(); Ok(AnchoredEngine::new(prog)) } fn make_forward_backward(nfa: Nfa<u32, NoLooks>, max_states: usize) -> ::Result<ForwardBackwardEngine<u8>> { if nfa.is_anchored() { return Err(Error::InvalidEngine("anchors rule out the forward-backward engine")); } let f_nfa = try!(try!(nfa.clone().byte_me(max_states)).anchor(max_states)); let b_nfa = try!(try!(nfa.byte_me(max_states)).reverse(max_states)); let f_dfa = try!(f_nfa.determinize(max_states)).optimize(); let b_dfa = try!(b_nfa.determinize_longest(max_states)).optimize(); let b_dfa = b_dfa.map_ret(|(_, bytes)| bytes); let b_prog = b_dfa.compile(); let f_dfa = f_dfa.map_ret(|(look, bytes)| { let b_dfa_state = b_dfa.init[look.as_usize()].expect("BUG: back dfa must have this init"); (b_dfa_state, bytes) }); let mut f_prog = f_dfa.compile(); let prefix = Prefix::from_parts(f_dfa.prefix_strings()); match prefix { Prefix::Empty => {}, _ => { // If there is a non-trivial prefix, we can usually speed up matching by deleting // transitions that return to the start state. That way, instead of returning to // the start state, we will just fail to match. Then we get to search for the // prefix before trying to match again. let f_dfa = f_dfa.cut_loop_to_init().optimize(); f_prog = f_dfa.compile(); }, } Ok(ForwardBackwardEngine::new(f_prog, prefix, b_prog)) } /// Returns the index range of the first match, if there is a match. The indices returned are /// byte indices of the string. The first index is inclusive; the second is exclusive. pub fn find(&self, s: &str) -> Option<(usize, usize)> { if let Some((start, end, look_behind)) = self.engine.find(s) { Some((start + look_behind as usize, end)) } else { None } } pub fn is_match(&self, s: &str) -> bool { // TODO: for the forward-backward engine, this could be faster because we don't need // to run backward. self.find(s).is_some() } }
use interpreter::Interpreter; use parser::Parser; use resolver::Resolver; use scanner::Scanner; mod ast; mod environment; mod interpreter; mod parser; mod resolver; mod scanner; mod token; mod value; struct Lox {} impl Lox { pub fn new() -> Self { Self {} } pub fn run(&mut self, source: String) -> anyhow::Result<()> { let tokens = Scanner::new(source).scan_tokens()?; let statements = Parser::new(tokens).parse()?; let mut interpreter = Interpreter::new(); let mut resolver = Resolver::new(&mut interpreter); resolver.resolve(&statements); interpreter.interpret(&statements); Ok(()) } pub fn run_file(&mut self, path: &str) -> anyhow::Result<()> { let bytes = std::fs::read(path)?; self.run(std::str::from_utf8(&bytes)?.into()) } pub fn run_prompt(&mut self) -> anyhow::Result<()> { let stdin = std::io::stdin(); let mut stdout = std::io::stdout(); use std::io::{BufRead, Write}; loop { print!("> "); stdout.flush()?; let mut line = String::new(); let mut reader = stdin.lock(); if reader.read_line(&mut line)? == 0 { break; } if let Err(error) = self.run(line) { println!("{}", error); } } Ok(()) } } fn main() -> anyhow::Result<()> { let args = std::env::args().collect::<Vec<_>>(); if args.len() > 2 { println!("Usage: lox [script]"); std::process::exit(64); } else if args.len() == 2 { let mut lox = Lox::new(); lox.run_file(&args[1])?; } else { let mut lox = Lox::new(); lox.run_prompt()?; } Ok(()) }
fn main() { proconio::input! { N: usize, C: [[i32; N]; N] } let mut cmin = std::i32::MAX; let mut ci: usize = 0; let mut cj: usize = 0; for i in 0..N { for j in 0..N { if C[i][j] < cmin{ cmin = C[i][j]; ci = i; cj = j; } } } // println!("{}, {}, {}", cmin, ci, cj); let mut A: Vec<i32> = vec![0; N]; let mut B: Vec<i32> = vec![0; N]; A[ci] = 0; B[cj] = cmin; for i in 0..N { A[i] = C[i][cj] - cmin; // println!("{}, {}, {}", A[i], i, cj); if A[i] < 0 { println!("No"); return; } } // println!("{:?}", A); let mut pre_b: Vec<i32> = vec![0; N]; for i in 0..N { if i != 0 { pre_b = B.clone(); } for j in 0..N { B[j] = C[i][j] - A[i]; if B[j] < 0 { println!("No"); return; } } if i != 0 { for j in 0..N { if B[j] != pre_b[j] { println!("No"); return; } } } } println!("Yes"); let pa: Vec<String> = A.iter().map(|x| x.to_string()).collect(); println!("{}", pa.join(" ")); let pb: Vec<String> = B.iter().map(|x| x.to_string()).collect(); println!("{}", pb.join(" ")); // for i in 0..N { // print!("{} ", A[i]); // } // println!(""); // for j in 0..N { // print!("{} ", B[j]); // } // println!(""); }
pub enum DeviceEvent { KeyPress, KeyRelease, ButtonPress, ButtonRelease, PointerMotion, Button1Motion, Button2Motion, Button3Motion, Button4Motion, Button5Motion, ButtonMotion, }
#[doc = "Reader of register FM_HV_DATA[%s]"] pub type R = crate::R<u32, super::FM_HV_DATA>; #[doc = "Writer for register FM_HV_DATA[%s]"] pub type W = crate::W<u32, super::FM_HV_DATA>; #[doc = "Register FM_HV_DATA[%s] `reset()`'s with value 0"] impl crate::ResetValue for super::FM_HV_DATA { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `DATA32`"] pub type DATA32_R = crate::R<u32, u32>; #[doc = "Write proxy for field `DATA32`"] pub struct DATA32_W<'a> { w: &'a mut W, } impl<'a> DATA32_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff); self.w } } impl R { #[doc = "Bits 0:31 - Four page latch Bytes (when writing to the page latches, it also requires FM_CTL.IF_SEL to be '1'). Note: the high Voltage page latches are readable for test mode functionality."] #[inline(always)] pub fn data32(&self) -> DATA32_R { DATA32_R::new((self.bits & 0xffff_ffff) as u32) } } impl W { #[doc = "Bits 0:31 - Four page latch Bytes (when writing to the page latches, it also requires FM_CTL.IF_SEL to be '1'). Note: the high Voltage page latches are readable for test mode functionality."] #[inline(always)] pub fn data32(&mut self) -> DATA32_W { DATA32_W { w: self } } }
use amethyst::{ core::{ transform::Transform, //SystemDesc, }, derive::SystemDesc, ecs::{ Join, ReadExpect, System, Entity, SystemData, //World, Write, WriteStorage }, ui::UiText }; use crate::game::*; #[derive(SystemDesc)] pub struct WinningSystem; impl<'s> System<'s> for WinningSystem { type SystemData = ( WriteStorage< 's, Ball >, WriteStorage< 's, Transform >, WriteStorage< 's, UiText >, Write< 's, ScoreBoard >, ReadExpect< 's, ScoreText >, ); fn run( &mut self, ( mut balls, mut locals, mut ui_texts, mut scores, score_texts ): Self::SystemData ) { for ( ball, transform ) in ( &mut balls, &mut locals ).join() { let ball_x = transform.translation().x; let mut update_text = | board: &mut i32, entity: Entity | { *board = ( *board + 1 ).min( 999 ); if let Some( text ) = ui_texts.get_mut( entity ) { text.text = board.to_string(); } }; if if ball_x <= ball.radius { update_text( &mut scores.score_right, score_texts.right_score ); true } else if ball_x >= ARENA_WIDTH - ball.radius { update_text( &mut scores.score_left, score_texts.left_score ); true } else { false } { ball.velocity[0] = -ball.velocity[0]; transform.set_translation_x( ARENA_WIDTH / 2.0 ); transform.set_translation_y( ARENA_HEIGHT / 2.0 ); } } } }
use std::cell::RefCell; use std::collections::HashSet; use std::rc::Rc; use std::sync::Arc; use std::{cmp, fmt, mem}; use {Node, Value}; #[derive(Clone)] enum Type { Unit, Sum(RcVar, RcVar), Product(RcVar, RcVar), } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] pub enum FinalTypeInner { Unit, Sum(Arc<FinalType>, Arc<FinalType>), Product(Arc<FinalType>, Arc<FinalType>), } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct FinalType { pub ty: FinalTypeInner, pub bit_width: usize, } impl fmt::Display for FinalType { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.ty { FinalTypeInner::Unit => f.write_str("ε"), FinalTypeInner::Sum(ref a, ref b) => write!(f, "({} + {})", a, b), FinalTypeInner::Product(ref a, ref b) => write!(f, "({} × {})", a, b), } } } impl FinalType { pub fn bit_width(&self) -> usize { self.bit_width } fn from_var(var: RcVar) -> Arc<FinalType> { let var = find_root(var); let mut var_borr = var.borrow_mut(); let existing_type = match var_borr.var { Variable::Free => Type::Unit, Variable::Bound(ref ty, ref mut occurs_check) => { assert!(!*occurs_check); // TODO set an error here *occurs_check = true; ty.clone() } Variable::EqualTo(..) => unreachable!(), Variable::Finalized(ref done) => return done.clone(), }; let (sub1, sub2) = match existing_type { Type::Unit => { let ret = Arc::new(FinalType { ty: FinalTypeInner::Unit, bit_width: 0, }); var_borr.var = Variable::Finalized(ret.clone()); return ret; } Type::Sum(ref sub1, ref sub2) => (sub1.clone(), sub2.clone()), Type::Product(ref sub1, ref sub2) => (sub1.clone(), sub2.clone()), }; let sub1 = find_root(sub1.clone()); let sub2 = find_root(sub2.clone()); let sub1_borr = sub1.borrow_mut(); let final1 = match sub1_borr.var { Variable::Free => Arc::new(FinalType { ty: FinalTypeInner::Unit, bit_width: 0, }), Variable::Bound(..) => { drop(sub1_borr); FinalType::from_var(sub1.clone()) } Variable::EqualTo(..) => unreachable!(), Variable::Finalized(ref f1) => { let ret = f1.clone(); drop(sub1_borr); ret } }; let sub2_borr = sub2.borrow_mut(); let final2 = match sub2_borr.var { Variable::Free => Arc::new(FinalType { ty: FinalTypeInner::Unit, bit_width: 0, }), Variable::Bound(..) => { drop(sub2_borr); FinalType::from_var(sub2) } Variable::EqualTo(..) => unreachable!(), Variable::Finalized(ref f2) => { let ret = f2.clone(); drop(sub2_borr); ret } }; let ret = match existing_type { Type::Unit => unreachable!(), Type::Sum(..) => Arc::new(FinalType { bit_width: 1 + cmp::max(final1.bit_width, final2.bit_width), ty: FinalTypeInner::Sum(final1, final2), }), Type::Product(..) => Arc::new(FinalType { bit_width: final1.bit_width + final2.bit_width, ty: FinalTypeInner::Product(final1, final2), }), }; var_borr.var = Variable::Finalized(ret.clone()); ret } } #[derive(Clone)] enum Variable { /// Free variable Free, /// Bound to some type (which may itself contain other free variables, /// or not). Contains a boolean which is only used by the finalization /// function, for the occurs-check Bound(Type, bool), /// Equal to another variable (the included `RcVar` is the "parent" /// pointer in union-find terms) EqualTo(RcVar), /// Complete type has been set in place Finalized(Arc<FinalType>), } struct UnificationVar { var: Variable, rank: usize, } type RcVar = Rc<RefCell<UnificationVar>>; impl UnificationVar { fn free() -> UnificationVar { UnificationVar { var: Variable::Free, rank: 0, } } fn bind(&mut self, ty: Type) { // Cloning a `Variable` is cheap, as the nontrivial variants merely // hold `Rc`s let self_var = self.var.clone(); match self_var { Variable::Free => self.var = Variable::Bound(ty, false), Variable::EqualTo(..) => unreachable!( "Tried to bind unification variable which was not \ the representative of its equivalence class" ), Variable::Finalized(..) => unreachable!(), Variable::Bound(self_ty, _) => match (self_ty, ty) { (Type::Unit, Type::Unit) => {} (Type::Sum(al1, al2), Type::Sum(be1, be2)) | (Type::Product(al1, al2), Type::Product(be1, be2)) => { unify(al1, be1); unify(al2, be2); } (a, b) => { let self_s = match a { Type::Unit => "unit", Type::Sum(..) => "sum", Type::Product(..) => "prod", }; let b_s = match b { Type::Unit => "unit", Type::Sum(..) => "sum", Type::Product(..) => "prod", }; panic!("unification failure {} vs {}", self_s, b_s) } }, } } } fn find_root(mut node: RcVar) -> RcVar { loop { // Double-assignment needed for pre-NLL borrowck reasons let parent = match node.borrow().var { Variable::EqualTo(ref parent) => Some(parent.clone()), _ => None, }; let parent = match parent { Some(x) => x, _ => break node, }; // Extra scope for pre-NLL borrowck reasons { let parent_borr = parent.borrow(); if let Variable::EqualTo(ref grandparent) = parent_borr.var { node.borrow_mut().var = Variable::EqualTo(grandparent.clone()); } } node = parent; } } fn unify(mut alpha: RcVar, mut beta: RcVar) { alpha = find_root(alpha); beta = find_root(beta); // Already unified, done if Rc::ptr_eq(&alpha, &beta) { return; } // Adjust ranks for union-find path halving if alpha.borrow().rank < beta.borrow().rank { mem::swap(&mut alpha, &mut beta); } else if alpha.borrow().rank == beta.borrow().rank { alpha.borrow_mut().rank += 1; } // Do the unification let mut be_borr = beta.borrow_mut(); let be_var = mem::replace(&mut be_borr.var, Variable::EqualTo(alpha)); let mut al_borr = match be_borr.var { Variable::EqualTo(ref mut alpha) => alpha.borrow_mut(), _ => unreachable!(), }; match be_var { Variable::Free => {} // nothing to do Variable::Bound(be_type, _) => al_borr.bind(be_type), Variable::EqualTo(..) => unreachable!(), Variable::Finalized(..) => unreachable!(), } } #[derive(Clone)] struct UnificationArrow { source: Rc<RefCell<UnificationVar>>, target: Rc<RefCell<UnificationVar>>, } #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug)] pub struct TypedNode { pub node: Node<Arc<TypedNode>, Option<Value>>, pub index: usize, pub source_ty: Arc<FinalType>, pub target_ty: Arc<FinalType>, pub extra_cells_bound: usize, pub frame_count_bound: usize, } impl TypedNode { fn graph_print_internal(&self, drawn: &mut HashSet<usize>) { if drawn.insert(self.index) { println!( "{} [label=\"{}\\n{}\\n{}→{}\"];", self.index, match self.node { Node::Iden => "iden", Node::Unit => "unit", Node::InjL(..) => "injl", Node::InjR(..) => "injr", Node::Take(..) => "take", Node::Drop(..) => "drop", Node::Comp(..) => "comp", Node::Case(..) => "case", Node::Pair(..) => "pair", Node::Disconnect(..) => "disconnect", Node::Witness(..) => "witness", Node::Hidden(..) => "hidden", Node::Fail(..) => "fail", }, self.index, self.source_ty, self.target_ty, ); match self.node { Node::Iden | Node::Unit | Node::Witness(..) | Node::Hidden(..) | Node::Fail(..) => { } Node::InjL(ref i) | Node::InjR(ref i) | Node::Take(ref i) | Node::Drop(ref i) => { println!(" {} -> {};", self.index, i.index); i.graph_print_internal(drawn); } Node::Comp(ref i, ref j) | Node::Case(ref i, ref j) | Node::Pair(ref i, ref j) | Node::Disconnect(ref i, ref j) => { println!(" {} -> {} [color=red];", self.index, i.index); println!(" {} -> {} [color=blue];", self.index, j.index); i.graph_print_internal(drawn); j.graph_print_internal(drawn); } } } } pub fn graph_print(&self) { println!("digraph {{"); self.graph_print_internal(&mut HashSet::new()); println!("}}"); } } impl fmt::Display for TypedNode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}] ", self.index)?; match self.node { Node::Iden => f.write_str("iden")?, Node::Unit => f.write_str("unit")?, Node::InjL(ref i) => write!(f, "injl({})", i.index)?, Node::InjR(ref i) => write!(f, "injr({})", i.index)?, Node::Take(ref i) => write!(f, "take({})", i.index)?, Node::Drop(ref i) => write!(f, "drop({})", i.index)?, Node::Comp(ref i, ref j) => write!(f, "comp({}, {})", i.index, j.index)?, Node::Case(ref i, ref j) => write!(f, "case({}, {})", i.index, j.index)?, Node::Pair(ref i, ref j) => write!(f, "pair({}, {})", i.index, j.index)?, Node::Disconnect(ref i, ref j) => write!(f, "disconnect({}, {})", i.index, j.index)?, Node::Witness(..) => f.write_str("witness")?, Node::Hidden(..) => f.write_str("hidden")?, Node::Fail(..) => f.write_str("fail")?, } write!(f, ": {} → {}", self.source_ty, self.target_ty,) } } pub struct FullPrint<'a>(pub &'a TypedNode); impl<'a> fmt::Display for FullPrint<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}]", self.0.index)?; match self.0.node { Node::Iden => f.write_str("iden"), Node::Unit => f.write_str("unit"), Node::InjL(ref i) => write!(f, "injl({})", FullPrint(i)), Node::InjR(ref i) => write!(f, "injr({})", FullPrint(i)), Node::Take(ref i) => write!(f, "take({})", FullPrint(i)), Node::Drop(ref i) => write!(f, "drop({})", FullPrint(i)), Node::Comp(ref i, ref j) => write!(f, "comp({}, {})", FullPrint(i), FullPrint(j)), Node::Case(ref i, ref j) => write!(f, "case({}, {})", FullPrint(i), FullPrint(j)), Node::Pair(ref i, ref j) => write!(f, "pair({}, {})", FullPrint(i), FullPrint(j)), Node::Disconnect(ref i, ref j) => { write!(f, "disconnect({}, {})", FullPrint(i), FullPrint(j)) } Node::Witness(..) => f.write_str("witness"), Node::Hidden(..) => f.write_str("hidden"), Node::Fail(..) => f.write_str("fail"), }?; write!(f, ": {} → {}", self.0.source_ty, self.0.target_ty,) } } pub fn type_check<BitStream: Iterator<Item = bool>>( program: &[Node<usize, ()>], mut witness_iter: Option<BitStream>, ) -> Arc<TypedNode> { if program.is_empty() { panic!("cannot deal with empty program") } let mut rcs = Vec::<Rc<UnificationArrow>>::with_capacity(program.len()); let mut finals = Vec::<Arc<TypedNode>>::with_capacity(program.len()); // Compute most general unifier for all types in the DAG for k in 0..program.len() { let node = UnificationArrow { source: Rc::new(RefCell::new(UnificationVar::free())), target: Rc::new(RefCell::new(UnificationVar::free())), }; match program[k] { Node::Iden => unify(node.source.clone(), node.target.clone()), Node::Unit => node.target.borrow_mut().bind(Type::Unit), Node::InjL(i) => { unify(node.source.clone(), rcs[k - i].source.clone()); let target_type = Type::Sum( rcs[k - i].target.clone(), Rc::new(RefCell::new(UnificationVar::free())), ); node.target.borrow_mut().bind(target_type); } Node::InjR(i) => { unify(node.source.clone(), rcs[k - i].source.clone()); let target_type = Type::Sum( Rc::new(RefCell::new(UnificationVar::free())), rcs[k - i].target.clone(), ); node.target.borrow_mut().bind(target_type); } Node::Take(i) => { unify(node.target.clone(), rcs[k - i].target.clone()); let target_type = Type::Product( rcs[k - i].source.clone(), Rc::new(RefCell::new(UnificationVar::free())), ); node.source.borrow_mut().bind(target_type); } Node::Drop(i) => { unify(node.target.clone(), rcs[k - i].target.clone()); let target_type = Type::Product( Rc::new(RefCell::new(UnificationVar::free())), rcs[k - i].source.clone(), ); node.source.borrow_mut().bind(target_type); } Node::Comp(i, j) => { unify(node.source.clone(), rcs[k - i].source.clone()); unify(rcs[k - i].target.clone(), rcs[k - j].source.clone()); unify(node.target.clone(), rcs[k - j].target.clone()); } Node::Case(i, j) => { let var1 = Rc::new(RefCell::new(UnificationVar::free())); let var2 = Rc::new(RefCell::new(UnificationVar::free())); let var3 = Rc::new(RefCell::new(UnificationVar::free())); let sum_12_ty = Type::Sum(var1.clone(), var2.clone()); let mut sum12_var = UnificationVar::free(); sum12_var.bind(sum_12_ty); let sum12_var = Rc::new(RefCell::new(sum12_var)); let source_ty = Type::Product(sum12_var, var3.clone()); node.source.borrow_mut().bind(source_ty); if let Node::Hidden(..) = program[k - i] { } else { find_root(rcs[k - i].source.clone()) .borrow_mut() .bind(Type::Product(var1.clone(), var3.clone())); unify(node.target.clone(), rcs[k - i].target.clone()); } if let Node::Hidden(..) = program[k - j] { } else { find_root(rcs[k - j].source.clone()) .borrow_mut() .bind(Type::Product(var2.clone(), var3.clone())); unify(node.target.clone(), rcs[k - j].target.clone()); } } Node::Pair(i, j) => { unify(node.source.clone(), rcs[k - i].source.clone()); unify(node.source.clone(), rcs[k - j].source.clone()); node.target.borrow_mut().bind(Type::Product( rcs[k - i].target.clone(), rcs[k - j].target.clone(), )); } Node::Witness(..) => { // No type constraints } Node::Hidden(..) => { // No type constraints } ref x => unimplemented!("haven't implemented {:?}", x), }; rcs.push(Rc::new(node)); } // Finalize, setting all unconstrained types to `Unit` and doing the // occurs check for k in 0..program.len() { let source_ty = FinalType::from_var(rcs[k].source.clone()); let target_ty = FinalType::from_var(rcs[k].target.clone()); let final_node = TypedNode { node: match program[k] { Node::Iden => Node::Iden, Node::Unit => Node::Unit, Node::InjL(i) => Node::InjL(finals[k - i].clone()), Node::InjR(i) => Node::InjR(finals[k - i].clone()), Node::Take(i) => Node::Take(finals[k - i].clone()), Node::Drop(i) => Node::Drop(finals[k - i].clone()), Node::Comp(i, j) => Node::Comp(finals[k - i].clone(), finals[k - j].clone()), Node::Case(i, j) => Node::Case(finals[k - i].clone(), finals[k - j].clone()), Node::Pair(i, j) => Node::Pair(finals[k - i].clone(), finals[k - j].clone()), Node::Disconnect(i, j) => { Node::Disconnect(finals[k - i].clone(), finals[k - j].clone()) } Node::Witness(..) => { if let Some(ref mut iter) = witness_iter { Node::Witness(Some( Value::from_witness(iter, &target_ty).expect("decoding witness"), )) } else { Node::Witness(None) } } Node::Hidden(hash) => Node::Hidden(hash), ref x => unreachable!("{:?}", x), }, index: k, extra_cells_bound: match program[k] { Node::Iden => 0, Node::Unit => 0, Node::InjL(i) => finals[k - i].extra_cells_bound, Node::InjR(i) => finals[k - i].extra_cells_bound, Node::Take(i) => finals[k - i].extra_cells_bound, Node::Drop(i) => finals[k - i].extra_cells_bound, Node::Comp(i, j) => finals[k - i].target_ty.bit_width() + cmp::max( finals[k - i].extra_cells_bound, finals[k - j].extra_cells_bound, ), Node::Case(i, j) => cmp::max( finals[k - i].extra_cells_bound, finals[k - j].extra_cells_bound, ), Node::Pair(i, j) => cmp::max( finals[k - i].extra_cells_bound, finals[k - j].extra_cells_bound, ), Node::Disconnect(..) => unimplemented!(), Node::Witness(..) => target_ty.bit_width(), Node::Fail(..) => unimplemented!(), Node::Hidden(..) => 0, }, frame_count_bound: match program[k] { Node::Iden => 0, Node::Unit => 0, Node::InjL(i) => finals[k - i].frame_count_bound, Node::InjR(i) => finals[k - i].frame_count_bound, Node::Take(i) => finals[k - i].frame_count_bound, Node::Drop(i) => finals[k - i].frame_count_bound, Node::Comp(i, j) => 1 + cmp::max( finals[k - i].frame_count_bound, finals[k - j].frame_count_bound, ), Node::Case(i, j) => cmp::max( finals[k - i].frame_count_bound, finals[k - j].frame_count_bound, ), Node::Pair(i, j) => cmp::max( finals[k - i].frame_count_bound, finals[k - j].frame_count_bound, ), Node::Disconnect(..) => unimplemented!(), Node::Witness(..) => 0, Node::Fail(..) => unimplemented!(), Node::Hidden(..) => 0, }, source_ty: source_ty, target_ty: target_ty, }; finals.push(Arc::new(final_node)); } finals.pop().expect("nonempty program") }
#![allow(dead_code)] #![allow(unused_variables)] #![allow(unused_mut)] #![feature(macro_rules)] //#![feature(globs)] fn return_subslice(s: &[u8]) -> &[u8]{ s.slice(2,s.len()) } fn slice_out_first_two<T> (s: &[T]) -> &[T]{ assert!(s.len()>=2); s.slice(0,2) } fn slice_out_first_two_nested<T> (s: &[T]) -> &[T]{ slice_out_first_two(s) } fn main() { } #[cfg(test)] mod test { extern crate test; //use super::*; #[test] fn slices_1 () { let a = vec![1,2,3]; //let r = super::return_subslice(a.slice()); // error: slice() takes 2 arguments // Runtime and compile time tests for slices are really inconsistent! //let r = super::return_subslice(a.slice(0,20)); // NO compile time error! //println!("Read past bounds: {}",r[10]); // Runtime error! end <= self.len() let r = super::return_subslice(a.slice(0,a.len())); println!("Read past bounds: {}",a[2]); let r2= super::return_subslice(a.as_slice()); println!("Read past bounds: {}",a[2]); //assert_eq!(r.len(),3); } #[test] fn slices_2 () { //let a = (1,2,3); let a:(u8,u8,u8) = (1,2,3); //let r = super::return_subslice(a.as_slice()); // error: as_slice() not implemented for tuples... //let r = super::return_subslice(a.slice(0,20)); // error: slice() not implemented for tuples //let r = super::return_subslice(a); // error: types don't automatically coerce at all in rust //let r = super::return_subslice(a as Slice); // error, Slice takes 2 arguments //let r = super::return_subslice(Slice{&a[0],&a}); // error } #[test] fn slices_3 () { let a:[u8,..3] = [1,2,3]; let r = super::return_subslice(a.as_slice()); } #[test] fn slices_4 () { let a:[u8,..3] = [1,2,3]; let r = super::slice_out_first_two(a.as_slice()); println!("{}",r.len()); assert!(r.len()==2); assert!(r[0]==1); assert!(r[1]==2); } #[test] fn slices_5 () { let a:Vec<int> = vec![1,2,3]; let r = super::slice_out_first_two(a.as_slice()); println!("{}",r.len()); assert!(r.len()==2); assert!(r[0]==1); assert!(r[1]==2); let r2 = super::slice_out_first_two(r); println!("{}",r2.len()); assert!(r2.len()==2); assert!(r2[0]==1); assert!(r2[1]==2); } #[test] fn slices_nested_functions () { let a:Vec<int> = vec![1,2,3]; let r = super::slice_out_first_two_nested(a.as_slice()); println!("{}",r.len()); //assert!(r.len==2); // len is a uint, but private assert!(r.len()==2); assert!(r[0]==1); assert!(r[1]==2); } #[test] fn slices_mutable () { let mut a:Vec<int> = vec![1,2,3]; let r = super::slice_out_first_two_nested(a.as_slice()); println!("{}",r.len()); //assert!(r.len==2); // len is a uint, but private assert!(r.len()==2); assert!(r[0]==1); assert!(r[1]==2); } }
use clint::*; use log::debug; use std::thread::Builder; use tokio; use tokio::sync::mpsc::unbounded_channel; const HELP: &str = "Async Interactive client built on tokio example"; fn print_help(config: &Config) { let mut help = HELP.to_owned(); if let Some(cmd) = &config.exit_command { help = format!("{}\n- Use command \"{}\" to exit", help, cmd); } if config.exit_on_ctrl_c { help = format!("{}\n- Use CTRL+C to exit", help); } if config.exit_on_esc { help = format!("{}\n- Use Esc to exit", help); } println!("{}", help); } fn main() { // Initiate let mut config = Config::default(); let (tx, rx) = unbounded_channel(); // Reset some prompt in config config.input_prompt = Some("User>".into()); config.output_prompt = Some("Computer>".into()); print_help(&config); ClintLogger::init(tx); // Start a thread and keep printing something Builder::new() .name("handler".into()) .spawn(move || { let mut count = 0; loop { let one_second = std::time::Duration::from_secs(1); std::thread::sleep(one_second); count += 1; debug!("Started {} seconds", count); } }) .unwrap(); // Start loop let result = loop_async_tokio_blocking(config, rx, |cmd| { // "println_clint" is used to print better // println_clint(format!("Dispatcher received cmd={}", cmd)); debug!("Dispatcher received cmd={}", cmd); }); if let Err(e) = result { println!("Error: {:?}\r", e); } }
use std::{borrow::Cow, fmt, time::Duration}; use serde::Serialize; pub use crate::sdam::description::{server::ServerType, topology::TopologyType}; use crate::{ bson::DateTime, error::Error, hello::HelloCommandResponse, options::ServerAddress, sdam::ServerDescription, selection_criteria::TagSet, }; /// A description of the most up-to-date information known about a server. Further details can be /// found in the [Server Discovery and Monitoring specification](https://github.com/mongodb/specifications/blob/master/source/server-discovery-and-monitoring/server-discovery-and-monitoring.rst). #[derive(Clone)] pub struct ServerInfo<'a> { pub(crate) description: Cow<'a, ServerDescription>, } impl<'a> Serialize for ServerInfo<'a> { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { self.description.serialize(serializer) } } impl<'a> ServerInfo<'a> { pub(crate) fn new_borrowed(description: &'a ServerDescription) -> Self { Self { description: Cow::Borrowed(description), } } pub(crate) fn new_owned(description: ServerDescription) -> Self { Self { description: Cow::Owned(description), } } fn command_response_getter<T>( &'a self, f: impl Fn(&'a HelloCommandResponse) -> Option<T>, ) -> Option<T> { self.description .reply .as_ref() .ok() .and_then(|reply| reply.as_ref().and_then(|r| f(&r.command_response))) } /// Gets the address of the server. pub fn address(&self) -> &ServerAddress { &self.description.address } /// Gets the weighted average of the time it has taken for a server check to round-trip /// from the driver to the server. /// /// This is the value that the driver uses internally to determine the latency window as part of /// server selection. pub fn average_round_trip_time(&self) -> Option<Duration> { self.description.average_round_trip_time } /// Gets the last time that the driver's monitoring thread for the server updated the internal /// information about the server. pub fn last_update_time(&self) -> Option<DateTime> { self.description.last_update_time } /// Gets the maximum wire version that the server supports. pub fn max_wire_version(&self) -> Option<i32> { self.command_response_getter(|r| r.max_wire_version) } /// Gets the minimum wire version that the server supports. pub fn min_wire_version(&self) -> Option<i32> { self.command_response_getter(|r| r.min_wire_version) } /// Gets the name of the replica set that the server is part of. pub fn replica_set_name(&self) -> Option<&str> { self.command_response_getter(|r| r.set_name.as_deref()) } /// Gets the version of the replica set that the server is part of. pub fn replica_set_version(&self) -> Option<i32> { self.command_response_getter(|r| r.set_version) } /// Get the type of the server. pub fn server_type(&self) -> ServerType { self.description.server_type } /// Gets the tags associated with the server. pub fn tags(&self) -> Option<&TagSet> { self.command_response_getter(|r| r.tags.as_ref()) } /// Gets the error that caused the server's state to be transitioned to Unknown, if any. /// /// When the driver encounters certain errors during operation execution or server monitoring, /// it transitions the affected server's state to Unknown, rendering the server unusable for /// future operations until it is confirmed to be in healthy state again. pub fn error(&self) -> Option<&Error> { self.description.reply.as_ref().err() } } impl<'a> fmt::Debug for ServerInfo<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { match self.description.reply { Ok(_) => f .debug_struct("Server Description") .field("Address", self.address()) .field("Type", &self.server_type()) .field("Average RTT", &self.average_round_trip_time()) .field("Last Update Time", &self.last_update_time()) .field("Max Wire Version", &self.max_wire_version()) .field("Min Wire Version", &self.min_wire_version()) .field("Replica Set Name", &self.replica_set_name()) .field("Replica Set Version", &self.replica_set_version()) .field("Tags", &self.tags()) .field( "Compatibility Error", &self.description.compatibility_error_message(), ) .finish(), Err(ref e) => f .debug_struct("Server Description") .field("Address", self.address()) .field("Type", &self.server_type()) .field("Error", e) .finish(), } } } impl<'a> fmt::Display for ServerInfo<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> std::result::Result<(), fmt::Error> { write!( f, "{{ Address: {}, Type: {:?}", self.address(), self.server_type() )?; match self.description.reply { Ok(_) => { if let Some(avg_rtt) = self.average_round_trip_time() { write!(f, ", Average RTT: {:?}", avg_rtt)?; } if let Some(last_update_time) = self.last_update_time() { write!(f, ", Last Update Time: {}", last_update_time)?; } if let Some(max_wire_version) = self.max_wire_version() { write!(f, ", Max Wire Version: {}", max_wire_version)?; } if let Some(min_wire_version) = self.min_wire_version() { write!(f, ", Min Wire Version: {}", min_wire_version)?; } if let Some(rs_name) = self.replica_set_name() { write!(f, ", Replica Set Name: {}", rs_name)?; } if let Some(rs_version) = self.replica_set_version() { write!(f, ", Replica Set Version: {}", rs_version)?; } if let Some(tags) = self.tags() { write!(f, ", Tags: {:?}", tags)?; } if let Some(compatibility_error) = self.description.compatibility_error_message() { write!(f, ", Compatiblity Error: {}", compatibility_error)?; } } Err(ref e) => { write!(f, ", Error: {}", e)?; } } write!(f, " }}") } }
use std::collections::btree_map; use std::error::Error; use crate::table::{Chamber, Row, Table, TableSchema}; #[derive(Debug)] crate struct WhereSubcommand { // XXX TODO: starting out with supporting just a single `column = value` // condition, but should eventually expand to conj-/dis-junctions, &c. // // Use a column offset (don't want to overload the word "index") instead of // a name so that we can operate on Row directly rather than looking up the // name crate column_offset: usize, crate value: Chamber, // XXX this is a BAD design decision and I should FEEL BAD (and rework it // later) crate unconditional: bool, } crate fn column_names_to_offsets( schema: &TableSchema, column_names: &[String], ) -> Result<Vec<usize>, Box<dyn Error>> { let offsets = schema .layout .iter() .enumerate() .filter_map(|(i, column)| { if column_names.contains(&column.name) { Some(i) } else { None } }) .collect::<Vec<_>>(); if offsets.len() == column_names.len() { Ok(offsets) } else { // TODO: more precise error message Err(From::from("some column names not found")) } } impl WhereSubcommand { crate fn new_unconditional() -> Self { Self { column_offset: 0, // dummy value value: Chamber::Integer(0), // dummy value unconditional: true, } } crate fn new_column_equality( schema: &TableSchema, column_name: String, value: Chamber, ) -> Result<Self, Box<dyn Error>> { Ok(Self { column_offset: column_names_to_offsets(schema, &[column_name])?[0], value, unconditional: false, }) } crate fn operationalize(self) -> impl Fn(&Row) -> bool + 'static { move |row| { if self.unconditional { return true; } let pred = row.0[self.column_offset] == self.value; pred } } } crate struct SelectCommand<'a> { crate column_offsets: Vec<usize>, crate view: btree_map::Values<'a, usize, Row>, crate filter: Box<dyn Fn(&Row) -> bool>, } impl<'a> SelectCommand<'a> { crate fn new_table_scan( table: &'a Table, column_names: Vec<String>, where_clause: WhereSubcommand, ) -> Self { Self { column_offsets: column_names_to_offsets( &table.schema, &column_names, ).unwrap(), view: table.rows.values(), filter: Box::new(where_clause.operationalize()), } } crate fn execute(self) -> Vec<Vec<&'a Chamber>> { // XXX: `for` loops are so pedestrian // XXX: overloading the word "result"? let mut results = Vec::new(); for row in self.view { if (self.filter)(row) { let mut result = Vec::new(); for (i, chamber) in row.0.iter().enumerate() { if self.column_offsets.contains(&i) { result.push(chamber); } } results.push(result); } } results } } #[cfg(test)] mod tests { use super::*; use crate::table::*; fn example_table() -> Table { let mut schema = TableSchema::new(); schema.add_column("title".to_owned(), ColumnType::String); schema.add_column("year".to_owned(), ColumnType::Integer); let mut table = Table::new(schema); table .insert(Row(vec![ Chamber::Key(0), Chamber::String("Men Trapped In Men's Bodies".to_owned()), Chamber::Integer(2013), ])) .unwrap(); table .insert(Row(vec![ Chamber::Key(0), Chamber::String("Galileo's Middle Finger".to_owned()), Chamber::Integer(2015), ])) .unwrap(); table .insert(Row(vec![ Chamber::Key(0), Chamber::String("Thing Explainer".to_owned()), Chamber::Integer(2015), ])) .unwrap(); table } #[test] fn concerning_converting_column_names_to_offsets() { let table = example_table(); assert_eq!( column_names_to_offsets( &table.schema, &["title".to_owned(), "year".to_owned()] ).unwrap(), vec![1, 2] ); } #[test] fn concerning_select_by_primary_key() { let table = example_table(); let where_clause = WhereSubcommand::new_column_equality( &table.schema, "pk".to_owned(), Chamber::Key(2), ).unwrap(); let select_command = SelectCommand::new_table_scan( &table, vec!["title".to_owned()], where_clause, ); let result_rows = select_command.execute(); assert_eq!(result_rows.len(), 1); assert_eq!( &Chamber::String("Galileo's Middle Finger".to_owned()), result_rows[0][0], ); } #[test] fn concerning_select_by_integer() { let table = example_table(); let where_clause = WhereSubcommand::new_column_equality( &table.schema, "year".to_owned(), Chamber::Integer(2015), ).unwrap(); let select_command = SelectCommand::new_table_scan( &table, vec!["title".to_owned()], where_clause, ); let result_rows = select_command.execute(); assert_eq!(result_rows.len(), 2); assert_eq!( vec![ vec![&Chamber::String( "Galileo's Middle Finger".to_owned(), )], vec![&Chamber::String("Thing Explainer".to_owned())], ], result_rows ); } }
use crate::kernel::opcode; use crate::kernel::stream::{self, statement::StatementStream}; use crate::kernel::State; #[derive(Debug)] pub struct Statement { pub code: opcode::Statement, pub proof: Option<(usize, usize)>, } #[derive(Debug)] pub struct StatementIter { data: std::vec::IntoIter<Statement>, proofs: Option<std::vec::IntoIter<opcode::Command<opcode::Proof>>>, ps: Option<(usize, usize)>, } #[derive(Debug)] pub struct StatementOwned { data: Vec<Statement>, pub sort_indices: Vec<usize>, pub axiom_indices: Vec<usize>, pub term_indices: Vec<usize>, pub theorem_indices: Vec<usize>, idx: usize, proofs: Option<Vec<opcode::Command<opcode::Proof>>>, ps: Option<(usize, usize)>, } impl StatementIter { pub fn new(data: Vec<Statement>, proofs: Vec<opcode::Command<opcode::Proof>>) -> StatementIter { StatementIter { data: data.into_iter(), proofs: Some(proofs.into_iter()), ps: None, } } } impl StatementOwned { pub fn new( data: Vec<Statement>, proofs: Vec<opcode::Command<opcode::Proof>>, sort_indices: Vec<usize>, axiom_indices: Vec<usize>, term_indices: Vec<usize>, theorem_indices: Vec<usize>, ) -> StatementOwned { StatementOwned { data, sort_indices, axiom_indices, term_indices, theorem_indices, idx: 0, proofs: Some(proofs), ps: None, } } pub fn seek_to(&mut self, idx: usize) -> State { let mut state = State::default(); for i in self.data.iter().take(idx) { use opcode::Statement; match i.code { Statement::End => break, Statement::Sort => state.increment_current_sort(), Statement::TermDef => state.increment_current_term(), Statement::LocalDef => state.increment_current_term(), Statement::LocalTerm => state.increment_current_term(), Statement::Axiom => state.increment_current_theorem(), Statement::Thm => state.increment_current_theorem(), } } self.idx = idx; state } } impl Iterator for StatementIter { type Item = stream::statement::Opcode; fn next(&mut self) -> Option<stream::statement::Opcode> { self.ps = None; if let Some(statement) = self.data.next() { use opcode::Statement; match statement.code { Statement::End => Some(stream::statement::Opcode::End), Statement::Sort => Some(stream::statement::Opcode::Sort), Statement::TermDef => { self.ps = statement.proof; Some(stream::statement::Opcode::TermDef) } Statement::LocalDef => { self.ps = statement.proof; Some(stream::statement::Opcode::TermDef) } Statement::LocalTerm => { self.ps = statement.proof; Some(stream::statement::Opcode::TermDef) } Statement::Axiom => { self.ps = statement.proof; Some(stream::statement::Opcode::Axiom) } Statement::Thm => { self.ps = statement.proof; Some(stream::statement::Opcode::Thm) } } } else { None } } } impl Iterator for StatementOwned { type Item = stream::statement::Opcode; fn next(&mut self) -> Option<stream::statement::Opcode> { self.ps = None; if let Some(statement) = self.data.get(self.idx) { self.idx += 1; use opcode::Statement; match statement.code { Statement::End => Some(stream::statement::Opcode::End), Statement::Sort => Some(stream::statement::Opcode::Sort), Statement::TermDef => { self.ps = statement.proof; Some(stream::statement::Opcode::TermDef) } Statement::LocalDef => { self.ps = statement.proof; Some(stream::statement::Opcode::TermDef) } Statement::LocalTerm => { self.ps = statement.proof; Some(stream::statement::Opcode::TermDef) } Statement::Axiom => { self.ps = statement.proof; Some(stream::statement::Opcode::Axiom) } Statement::Thm => { self.ps = statement.proof; Some(stream::statement::Opcode::Thm) } } } else { None } } } impl StatementStream for StatementIter { type ProofStream = ProofIter; fn take_proof_stream(&mut self) -> Option<Self::ProofStream> { let len = self.ps.unwrap_or((0, 0)); let proofs = self.proofs.take()?; Some(ProofIter { proofs, max_len: (len.1 - len.0), }) } fn put_proof_stream(&mut self, proofs: Self::ProofStream) { self.proofs = Some(proofs.proofs); } } impl StatementStream for StatementOwned { type ProofStream = ProofOwned; fn take_proof_stream(&mut self) -> Option<Self::ProofStream> { let len = self.ps.unwrap_or((0, 0)); let proofs = self.proofs.take()?; Some(ProofOwned { proofs, idx: len.0, max_len: (len.1 - len.0), }) } fn put_proof_stream(&mut self, proofs: Self::ProofStream) { self.proofs = Some(proofs.proofs); } } #[derive(Debug)] pub struct ProofIter { proofs: std::vec::IntoIter<opcode::Command<opcode::Proof>>, max_len: usize, } #[derive(Debug)] pub struct ProofOwned { proofs: Vec<opcode::Command<opcode::Proof>>, idx: usize, max_len: usize, } impl Iterator for ProofIter { type Item = opcode::Command<opcode::Proof>; fn next(&mut self) -> Option<Self::Item> { if self.max_len == 0 { None } else { self.max_len -= 1; self.proofs.next() } } } impl Iterator for ProofOwned { type Item = opcode::Command<opcode::Proof>; fn next(&mut self) -> Option<Self::Item> { if self.max_len == 0 { None } else { self.max_len -= 1; let ret = self.proofs.get(self.idx); self.idx += 1; ret.copied() } } }
use equality::precise::Vector2; #[no_mangle] fn extern "C" fn vector2_new() -> Vector2 { }
//! Derive input types defined with `darling`. //! //! They parse `#[attributes(..)]` syntax in a declartive style. use darling::*; use syn::*; // pub type Data = ast::Data<VariantArgs, FieldArgs>; pub type Fields = ast::Fields<FieldArgs>; #[derive(FromDeriveInput)] #[darling(attributes(inspect), supports(struct_any, enum_any))] pub struct TypeArgs { pub ident: Ident, pub generics: Generics, pub data: ast::Data<VariantArgs, FieldArgs>, } /// Parsed from struct's or enum variant's field /// /// NOTE: `#[derive(Inspect)]` is non-recursive by default. #[derive(FromField, Clone, PartialEq)] #[darling(attributes(inspect))] pub struct FieldArgs { pub ident: Option<Ident>, pub ty: Type, /// `#[inspect(skip)]` /// /// Do not expose property info #[darling(default)] pub skip: bool, /// #[inspect(name = "<name>")] /// /// Name override for a field (default: Title Case) #[darling(default)] pub name: Option<String>, /// #[inspect(display_name = "<name>")] /// /// A human-readable name. #[darling(default)] pub display_name: Option<String>, /// #[inspect(group = "<group>")] /// /// Group override for a field (default: Common) #[darling(default)] pub group: Option<String>, /// `#[inspect(expand)]` /// /// Include the fields of the field, exclude the marked field itself. #[darling(default)] pub expand: bool, /// `#[inspect(expand_subtree)]` /// /// Include the field and the fields of the field. #[darling(default)] pub expand_subtree: bool, /// `#[inspect(read_only)]` /// /// The field is not meant to be edited. #[darling(default)] pub read_only: bool, } #[derive(FromVariant)] #[darling(attributes(inspect))] pub struct VariantArgs { pub ident: Ident, pub fields: ast::Fields<FieldArgs>, }
// import the flatbuffers runtime library extern crate flatbuffers; // import the generated code #[allow(dead_code, unused_imports, non_snake_case)] #[path = "./network_protocol_generated.rs"] mod network_protocol_generated; pub use network_protocol_generated::com::ibm::amoeba::common::network::protocol; use crate::transaction; use crate::transaction::requirements; use uuid; use crate::data; use crate::data::{DataReader, ArcDataSlice}; use crate::ida; use crate::object; use crate::store; use crate::pool; use crate::hlc; use crate::network; fn u8toi8(a: &[u8]) -> &[i8] { unsafe { std::mem::transmute::<&[u8], &[i8]>(a) } } fn i8tou8(a: &[i8]) -> &[u8] { unsafe { std::mem::transmute::<&[i8], &[u8]>(a) } } pub fn decode_uuid(o: &protocol::UUID) -> uuid::Uuid { let mut d = data::DataMut::with_capacity(16); d.put_u64_be(o.most_sig_bits() as u64); d.put_u64_be(o.least_sig_bits() as u64); uuid::Uuid::from_slice(d.finalize().as_bytes()).unwrap() } pub fn encode_uuid(o: uuid::Uuid) -> protocol::UUID { let mut d = data::RawData::new(o.as_bytes()); let msb = d.get_u64_be(); let lsb = d.get_u64_be(); protocol::UUID::new(msb as i64, lsb as i64) } pub fn decode_key_comparison(o: protocol::KeyComparison) -> requirements::KeyComparison { match o { protocol::KeyComparison::ByteArray => requirements::KeyComparison::ByteArray, protocol::KeyComparison::Integer => requirements::KeyComparison::Integer, protocol::KeyComparison::Lexical => requirements::KeyComparison::Lexical, } } pub fn encode_key_comparison(o: requirements::KeyComparison) -> protocol::KeyComparison { match o { requirements::KeyComparison::ByteArray => protocol::KeyComparison::ByteArray, requirements::KeyComparison::Integer => protocol::KeyComparison::Integer, requirements::KeyComparison::Lexical => protocol::KeyComparison::Lexical, } } pub fn decode_replication(o: &protocol::Replication) -> ida::IDA { ida::IDA::Replication { width: o.width() as u8, write_threshold: o.write_threshold() as u8 } } pub fn decode_reed_solomon(o: &protocol::ReedSolomon) -> ida::IDA { ida::IDA::ReedSolomon { width: o.width() as u8, read_threshold: o.read_threshold() as u8, write_threshold: o.write_threshold() as u8 } } pub fn decode_object_revision(o: &protocol::ObjectRevision) -> object::Revision { let mut d = data::DataMut::with_capacity(16); d.put_u64_be(o.mostSigBits() as u64); d.put_u64_be(o.leastSigBits() as u64); let u = uuid::Uuid::from_slice(d.finalize().as_bytes()).unwrap(); object::Revision(u) } pub fn encode_object_revision(o: &object::Revision) -> protocol::ObjectRevision { let mut d = data::RawData::new(o.0.as_bytes()); let msb = d.get_u64_be(); let lsb = d.get_u64_be(); protocol::ObjectRevision::new(msb as i64, lsb as i64) } pub fn decode_object_refcount(o: &protocol::ObjectRefcount) -> object::Refcount { object::Refcount { update_serial: o.update_serial() as u32, count: o.refcount() as u32 } } pub fn encode_object_refcount(o: &object::Refcount) -> protocol::ObjectRefcount { protocol::ObjectRefcount::new(o.update_serial as i32, o.count as i32) } pub fn decode_store_pointer(o: &protocol::StorePointer) -> store::Pointer { let mut v = Vec::new(); let x = match o.data() { None => None, Some(s) => { for &b in s { v.push(b as u8) } Some(&v[..]) } }; store::Pointer::new(o.store_index() as u8, x) } pub fn encode_store_pointer<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &store::Pointer) -> flatbuffers::WIPOffset<protocol::StorePointer<'bldr>> { let (pool_index, data_offset) = match o { store::Pointer::None{pool_index} => (pool_index, None), store::Pointer::Short{pool_index, nbytes, content, ..} => (pool_index, Some(builder.create_vector(u8toi8(&content[0..*nbytes as usize])))), store::Pointer::Long{pool_index, content} => (pool_index, Some(builder.create_vector(u8toi8(&content[..])))), }; protocol::StorePointer::create(builder, &protocol::StorePointerArgs { store_index: *pool_index as i8, data: data_offset }) } pub fn decode_key_revision(o: protocol::KeyRevision) -> requirements::KeyRevision { let mut v = Vec::with_capacity(o.key().unwrap().len()); if let Some(key) = o.key() { for &b in key { v.push(b as u8); } }; let key = object::Key::from_bytes(&v[..]); requirements::KeyRevision { key, revision: decode_object_revision(o.revision().unwrap()) } } pub fn encode_key_revision<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &requirements::KeyRevision) -> flatbuffers::WIPOffset<protocol::KeyRevision<'bldr>> { let key = builder.create_vector(u8toi8(&o.key.as_bytes()[..])); protocol::KeyRevision::create(builder, &protocol::KeyRevisionArgs{ key: Some(key), revision: Some(&encode_object_revision(&o.revision)) }) } pub fn decode_object_type(o: protocol::ObjectType) -> object::ObjectType { match o { protocol::ObjectType::Data => object::ObjectType::Data, protocol::ObjectType::KeyValue => object::ObjectType::KeyValue, } } pub fn encode_object_type(o: object::ObjectType) -> protocol::ObjectType { match o { object::ObjectType::Data => protocol::ObjectType::Data, object::ObjectType::KeyValue => protocol::ObjectType::KeyValue, } } pub fn decode_object_pointer(o: &protocol::ObjectPointer) -> object::Pointer { let oid = decode_uuid(o.uuid().unwrap()); let pool_id = decode_uuid(o.pool_uuid().unwrap()); let size = if o.size_() == 0 { None } else {Some(o.size_() as u32)}; let object_type = decode_object_type(o.object_type()); let ida = ida::IDA::Replication { width: o.ida_as_replication().unwrap().width() as u8, write_threshold: o.ida_as_replication().unwrap().write_threshold() as u8 }; let mut pointers:Vec<store::Pointer> = Vec::new(); if let Some(v) = o.store_pointers() { for p in v { pointers.push(decode_store_pointer(&p)); } } object::Pointer { id: object::Id(oid), pool_id: pool::Id(pool_id), size: size, ida: ida, object_type: object_type, store_pointers: pointers } } pub fn encode_object_pointer<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &object::Pointer) -> flatbuffers::WIPOffset<protocol::ObjectPointer<'bldr>> { let size = if let Some(sz) = o.size { sz } else { 0 }; let mut pointer_offsets = Vec::new(); for p in &o.store_pointers { pointer_offsets.push(encode_store_pointer(builder, &p)); } let pointers = builder.create_vector(&pointer_offsets[..]); let (ida_type, ida_offset) = match o.ida { ida::IDA::Replication{width, write_threshold} => { let offset = protocol::Replication::create(builder, &protocol::ReplicationArgs{ width: width as i32, write_threshold: write_threshold as i32 }); (protocol::IDA::Replication, offset.as_union_value()) } ida::IDA::ReedSolomon{width, read_threshold, write_threshold} => { let offset = protocol::ReedSolomon::create(builder, &protocol::ReedSolomonArgs{ width: width as i32, read_threshold: read_threshold as i32, write_threshold: write_threshold as i32 }); (protocol::IDA::ReedSolomon, offset.as_union_value()) } }; protocol::ObjectPointer::create(builder, &protocol::ObjectPointerArgs { uuid: Some(&encode_uuid(o.id.0)), pool_uuid: Some(&encode_uuid(o.pool_id.0)), size_: size as i32, store_pointers: Some(pointers), ida_type: ida_type, ida: Some(ida_offset), object_type: encode_object_type(o.object_type) }) } pub fn decode_transaction_status(o: protocol::TransactionStatus) -> transaction::Status { match o { protocol::TransactionStatus::Unresolved => transaction::Status::Unresolved, protocol::TransactionStatus::Aborted => transaction::Status::Aborted, protocol::TransactionStatus::Committed => transaction::Status::Committed } } pub fn encode_transaction_status(o: transaction::Status) -> protocol::TransactionStatus { match o { transaction::Status::Unresolved => protocol::TransactionStatus::Unresolved, transaction::Status::Aborted => protocol::TransactionStatus::Aborted, transaction::Status::Committed => protocol::TransactionStatus::Committed } } pub fn decode_transaction_disposition(o: protocol::TransactionDisposition) -> transaction::Disposition { match o { protocol::TransactionDisposition::Undetermined => transaction::Disposition::Undetermined, protocol::TransactionDisposition::VoteAbort => transaction::Disposition::VoteAbort, protocol::TransactionDisposition::VoteCommit => transaction::Disposition::VoteCommit } } pub fn encode_transaction_distposition(o: transaction::Disposition) -> protocol::TransactionDisposition { match o { transaction::Disposition::Undetermined => protocol::TransactionDisposition::Undetermined, transaction::Disposition::VoteAbort => protocol::TransactionDisposition::VoteAbort, transaction::Disposition::VoteCommit => protocol::TransactionDisposition::VoteCommit } } pub fn decode_data_update_operation(o: protocol::DataUpdateOperation) -> object::DataUpdateOperation { match o { protocol::DataUpdateOperation::Append => object::DataUpdateOperation::Append, protocol::DataUpdateOperation::Overwrite => object::DataUpdateOperation::Overwrite, } } pub fn encode_data_update_operation(o: object::DataUpdateOperation) -> protocol::DataUpdateOperation { match o { object::DataUpdateOperation::Append => protocol::DataUpdateOperation::Append, object::DataUpdateOperation::Overwrite => protocol::DataUpdateOperation::Overwrite, } } pub fn decode_key_requirement(o: &protocol::KVReq) -> requirements::KeyRequirement { let key = object::Key::from_bytes(i8tou8(o.key().unwrap())); let timestamp = hlc::Timestamp::from(o.timestamp() as u64); match o.requirement() { protocol::KeyRequirement::Exists => requirements::KeyRequirement::Exists { key }, protocol::KeyRequirement::MayExist => requirements::KeyRequirement::MayExist { key }, protocol::KeyRequirement::DoesNotExist => requirements::KeyRequirement::DoesNotExist { key }, protocol::KeyRequirement::TimestampLessThan => requirements::KeyRequirement::TimestampLessThan { key, timestamp }, protocol::KeyRequirement::TimestampGreaterThan => requirements::KeyRequirement::TimestampGreaterThan { key, timestamp }, protocol::KeyRequirement::TimestampEquals => requirements::KeyRequirement::TimestampEquals { key, timestamp }, protocol::KeyRequirement::KeyRevision => { requirements::KeyRequirement::KeyRevision { key, revision: decode_object_revision(o.revision().unwrap()) } }, protocol::KeyRequirement::KeyObjectRevision => { requirements::KeyRequirement::KeyObjectRevision { key, revision: decode_object_revision(o.revision().unwrap()) } } protocol::KeyRequirement::WithinRange => { requirements::KeyRequirement::WithinRange { key, comparison: decode_key_comparison(o.comparison()) } } } } pub fn encode_key_requirement<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &requirements::KeyRequirement) -> flatbuffers::WIPOffset<protocol::KVReq<'bldr>> { let mut arevision: protocol::ObjectRevision = encode_object_revision(&object::Revision::nil()); let mut use_revision = false; let mut args = match o { requirements::KeyRequirement::Exists{ key } => { protocol::KVReqArgs { requirement: protocol::KeyRequirement::Exists, timestamp: 0, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::MayExist{ key } => { protocol::KVReqArgs { requirement: protocol::KeyRequirement::MayExist, timestamp: 0, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::DoesNotExist{ key } => { protocol::KVReqArgs { requirement: protocol::KeyRequirement::DoesNotExist, timestamp: 0, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::TimestampLessThan{ key, timestamp } => { protocol::KVReqArgs { requirement: protocol::KeyRequirement::TimestampLessThan, timestamp: timestamp.to_u64() as i64, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::TimestampGreaterThan{ key, timestamp } => { protocol::KVReqArgs { requirement: protocol::KeyRequirement::TimestampGreaterThan, timestamp: timestamp.to_u64() as i64, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::TimestampEquals{ key, timestamp } => { protocol::KVReqArgs { requirement: protocol::KeyRequirement::TimestampEquals, timestamp: timestamp.to_u64() as i64, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::KeyRevision{ key, revision } => { arevision = encode_object_revision(revision); use_revision = true; protocol::KVReqArgs { requirement: protocol::KeyRequirement::KeyRevision, timestamp: 0, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::KeyObjectRevision{ key, revision } => { arevision = encode_object_revision(revision); use_revision = true; protocol::KVReqArgs { requirement: protocol::KeyRequirement::KeyObjectRevision, timestamp: 0, revision: None, comparison: protocol::KeyComparison::ByteArray, key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, requirements::KeyRequirement::WithinRange{ key, comparison } => { protocol::KVReqArgs { requirement: protocol::KeyRequirement::WithinRange, timestamp: 0, revision: None, comparison: encode_key_comparison(*comparison), key: Some(builder.create_vector(u8toi8(key.as_bytes()))), } }, }; if use_revision { args.revision = Some(&arevision); } protocol::KVReq::create(builder, &args) } pub fn decode_data_update(o: &protocol::DataUpdate) -> requirements::TransactionRequirement { let pointer = decode_object_pointer(&o.object_pointer().unwrap()); let required_revision = decode_object_revision(o.required_revision().unwrap()); let operation = decode_data_update_operation(o.operation()); requirements::TransactionRequirement::DataUpdate { pointer, required_revision, operation } } pub fn decode_refcount_udpate(o: &protocol::RefcountUpdate) -> requirements::TransactionRequirement { let pointer = decode_object_pointer(&o.object_pointer().unwrap()); let required_refcount = decode_object_refcount(o.required_refcount().unwrap()); let new_refcount = decode_object_refcount(o.new_refcount().unwrap()); requirements::TransactionRequirement::RefcountUpdate { pointer, required_refcount, new_refcount } } pub fn decode_version_bump(o: &protocol::VersionBump) -> requirements::TransactionRequirement { let pointer = decode_object_pointer(&o.object_pointer().unwrap()); let required_revision = decode_object_revision(o.required_revision().unwrap()); requirements::TransactionRequirement::VersionBump { pointer, required_revision, } } pub fn decode_revision_lock(o: &protocol::RevisionLock) -> requirements::TransactionRequirement { let pointer = decode_object_pointer(&o.object_pointer().unwrap()); let required_revision = decode_object_revision(o.required_revision().unwrap()); requirements::TransactionRequirement::RevisionLock { pointer, required_revision, } } pub fn decode_serialized_finalization_action(o: &protocol::SerializedFinalizationAction) -> transaction::SerializedFinalizationAction { let tid = decode_uuid(o.type_uuid().unwrap()); let slice = o.data().unwrap(); let mut v:Vec<u8> = Vec::with_capacity(slice.len()); v.extend_from_slice(i8tou8(slice)); transaction::SerializedFinalizationAction { type_uuid: tid, data: v } } pub fn encode_serialized_finalization_action<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &transaction::SerializedFinalizationAction) -> flatbuffers::WIPOffset<protocol::SerializedFinalizationAction<'bldr>> { let data = builder.create_vector(u8toi8(&o.data[..])); protocol::SerializedFinalizationAction::create(builder, &protocol::SerializedFinalizationActionArgs { type_uuid: Some(&encode_uuid(o.type_uuid)), data: Some(data) }) } pub fn decode_timestamp_requirement(o: protocol::LocalTimeRequirementEnum, timestamp:i64) -> requirements::TimestampRequirement { match o { protocol::LocalTimeRequirementEnum::GreaterThan => requirements::TimestampRequirement::GreaterThan(hlc::Timestamp::from(timestamp as u64)), protocol::LocalTimeRequirementEnum::LessThan => requirements::TimestampRequirement::LessThan(hlc::Timestamp::from(timestamp as u64)) } } pub fn encode_time_requirement(o: requirements::TimestampRequirement) -> protocol::LocalTimeRequirementEnum { match o { requirements::TimestampRequirement::Equals(_) => protocol::LocalTimeRequirementEnum::GreaterThan, requirements::TimestampRequirement::GreaterThan(_) => protocol::LocalTimeRequirementEnum::GreaterThan, requirements::TimestampRequirement::LessThan(_) => protocol::LocalTimeRequirementEnum::LessThan, } } pub fn decode_local_time_requirement(o: &protocol::LocalTimeRequirement) -> requirements::TransactionRequirement { let tr = decode_timestamp_requirement(o.requirement(), o.timestamp()); requirements::TransactionRequirement::LocalTime { requirement: tr } } pub fn encode_local_time_requirement<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &requirements::TimestampRequirement) -> flatbuffers::WIPOffset<protocol::LocalTimeRequirement<'bldr>> { let ts = match o { requirements::TimestampRequirement::Equals(ts) => ts.to_u64() as i64, requirements::TimestampRequirement::GreaterThan(ts) => ts.to_u64() as i64, requirements::TimestampRequirement::LessThan(ts) => ts.to_u64() as i64 }; protocol::LocalTimeRequirement::create(builder, &protocol::LocalTimeRequirementArgs { timestamp: ts, requirement: encode_time_requirement(*o) }) } pub fn decode_store_id(o: &protocol::StoreId) -> store::Id { let pool = decode_uuid(o.storage_pool_uuid().unwrap()); let index = o.storage_pool_index(); store::Id { pool_uuid: pool, pool_index: index as u8 } } pub fn encode_store_id<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &store::Id) -> flatbuffers::WIPOffset<protocol::StoreId<'bldr>> { protocol::StoreId::create(builder, &protocol::StoreIdArgs { storage_pool_uuid: Some(&encode_uuid(o.pool_uuid)), storage_pool_index: o.pool_index as i8 }) } pub fn decode_transaction_requirement(o: &protocol::TransactionRequirement) -> transaction::TransactionRequirement { if let Some(r) = o.data_update() { return decode_data_update(&r) } else if let Some(r) = o.refcount_update() { return decode_refcount_udpate(&r) } else if let Some(r) = o.version_bump() { return decode_version_bump(&r) } else if let Some(r) = o.revision_lock() { return decode_revision_lock(&r) } else if let Some(r) = o.kv_update() { let object_pointer = decode_object_pointer(&r.object_pointer().unwrap()); let required_revision = r.required_revision().map( |rev| decode_object_revision(&rev) ); let mut full_content_lock: Vec<requirements::KeyRevision> = Vec::new(); if let Some(v) = r.content_lock() { for kr in v { full_content_lock.push(requirements::KeyRevision { key: object::Key::from_bytes(i8tou8(kr.key().unwrap())), revision: decode_object_revision(&kr.revision().unwrap()) }); } }; let mut kv_reqs: Vec<requirements::KeyRequirement> = Vec::new(); if let Some(v) = r.requirements() { for r in v { kv_reqs.push(decode_key_requirement(&r)); } }; return transaction::TransactionRequirement::KeyValueUpdate { pointer: object_pointer, required_revision: required_revision, full_content_lock: full_content_lock, key_requirements: kv_reqs } } else { return decode_local_time_requirement(&o.localtime().unwrap()) } } pub fn encode_transaction_requirement<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &requirements::TransactionRequirement) -> flatbuffers::WIPOffset<protocol::TransactionRequirement<'bldr>> { let tr_builder = match o { requirements::TransactionRequirement::DataUpdate {pointer, required_revision, operation} => { let op = encode_object_pointer(builder, &pointer); let wip = protocol::DataUpdate::create(builder, &protocol::DataUpdateArgs { object_pointer: Some(op), required_revision: Some(&encode_object_revision(&required_revision)), operation: encode_data_update_operation(*operation) }); let mut tr_builder = protocol::TransactionRequirementBuilder::new(builder); tr_builder.add_data_update(wip); tr_builder }, requirements::TransactionRequirement::RefcountUpdate {pointer, required_refcount, new_refcount} => { let op = encode_object_pointer(builder, &pointer); let wip = protocol::RefcountUpdate::create(builder, &protocol::RefcountUpdateArgs { object_pointer: Some(op), required_refcount: Some(&encode_object_refcount(&required_refcount)), new_refcount: Some(&encode_object_refcount(&new_refcount)) }); let mut tr_builder = protocol::TransactionRequirementBuilder::new(builder); tr_builder.add_refcount_update(wip); tr_builder }, requirements::TransactionRequirement::VersionBump {pointer, required_revision} => { let op = encode_object_pointer(builder, &pointer); let wip = protocol::VersionBump::create(builder, &protocol::VersionBumpArgs { object_pointer: Some(op), required_revision: Some(&encode_object_revision(&required_revision)), }); let mut tr_builder = protocol::TransactionRequirementBuilder::new(builder); tr_builder.add_version_bump(wip); tr_builder }, requirements::TransactionRequirement::RevisionLock {pointer, required_revision} => { let op = encode_object_pointer(builder, &pointer); let wip = protocol::RevisionLock::create(builder, &protocol::RevisionLockArgs { object_pointer: Some(op), required_revision: Some(&encode_object_revision(&required_revision)), }); let mut tr_builder = protocol::TransactionRequirementBuilder::new(builder); tr_builder.add_revision_lock(wip); tr_builder }, requirements::TransactionRequirement::LocalTime {requirement} => { let wip = encode_local_time_requirement(builder, requirement); let mut tr_builder = protocol::TransactionRequirementBuilder::new(builder); tr_builder.add_localtime(wip); tr_builder }, requirements::TransactionRequirement::KeyValueUpdate {pointer, required_revision, full_content_lock, key_requirements} => { let mut fcontent_offsets = Vec::new(); for kr in full_content_lock { fcontent_offsets.push(encode_key_revision(builder, &kr)); } let content_lock_vec = builder.create_vector(&fcontent_offsets[..]); let mut req_offsets = Vec::new(); for r in key_requirements { req_offsets.push(encode_key_requirement(builder, r)); } let req_vec = builder.create_vector(&req_offsets[..]); let op = encode_object_pointer(builder, &pointer); let rev = match required_revision { None => encode_object_revision(&object::Revision::nil()), Some(r) => encode_object_revision(&r) }; let wip = protocol::KeyValueUpdate::create(builder, &protocol::KeyValueUpdateArgs { object_pointer: Some(op), required_revision: required_revision.map( |_| &rev ), content_lock: Some(content_lock_vec), requirements: Some(req_vec) }); let mut tr_builder = protocol::TransactionRequirementBuilder::new(builder); tr_builder.add_kv_update(wip); tr_builder }, }; tr_builder.finish() } pub fn deserialize_transaction_description(encoded: &ArcDataSlice) -> transaction::TransactionDescription { let proto = flatbuffers::get_root::<protocol::TransactionDescription>(encoded.as_bytes()); decode_transaction_description(&proto) } pub fn decode_transaction_description(o: &protocol::TransactionDescription) -> transaction::TransactionDescription { let txid = transaction::Id(decode_uuid(o.transaction_uuid().unwrap())); let start_ts = hlc::Timestamp::from(o.start_timestamp() as u64); let primary_object = decode_object_pointer(&o.primary_object().unwrap()); let designated_leader = o.designated_leader_uid(); let originating_client = o.originating_client().map(|c| network::ClientId(decode_uuid(c))); let mut notify_on_resolution:Vec<store::Id> = Vec::new(); if let Some(v) = o.notify_on_resolution() { for p in v { notify_on_resolution.push(decode_store_id(&p)); } }; let mut finalization_actions:Vec<transaction::SerializedFinalizationAction> = Vec::new(); if let Some(v) = o.finalization_actions() { for p in v { finalization_actions.push(decode_serialized_finalization_action(&p)); } }; let notes = String::from_utf8_lossy(i8tou8(o.notes().unwrap())); let mut transaction_requirements: Vec<requirements::TransactionRequirement> = Vec::new(); if let Some(v) = o.requirements() { for p in v { transaction_requirements.push(decode_transaction_requirement(&p)); } } transaction::TransactionDescription::new( txid, start_ts, primary_object, designated_leader as u8, transaction_requirements, finalization_actions, originating_client, notify_on_resolution, vec![String::from(notes)] ) } pub fn encode_transaction_description<'bldr, 'mut_bldr>(builder: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr>, o: &transaction::TransactionDescription) -> flatbuffers::WIPOffset<protocol::TransactionDescription<'bldr>> { let mut rv = Vec::new(); for r in &o.requirements { rv.push(encode_transaction_requirement(builder, &r)); } let requirements = builder.create_vector(&rv[..]); let mut fa = Vec::new(); for f in &o.finalization_actions { fa.push(encode_serialized_finalization_action(builder, &f)); } let serialized_fa = builder.create_vector(&fa[..]); let mut n = Vec::new(); for st in &o.notify_on_resolution { n.push(encode_store_id(builder, &st)); } let notify = builder.create_vector(&n[..]); let mut notes_str = String::new(); for note in &o.notes { notes_str.push_str(&note); } let notes = builder.create_vector(u8toi8(notes_str.as_bytes())); let op = encode_object_pointer(builder, &o.primary_object); let orig_client = match o.originating_client { None => encode_uuid(uuid::Uuid::nil()), Some(c) => encode_uuid(c.0) }; protocol::TransactionDescription::create(builder, &protocol::TransactionDescriptionArgs { transaction_uuid: Some(&encode_uuid(o.id.0)), start_timestamp: o.start_timestamp.to_u64() as i64, primary_object: Some(op), designated_leader_uid: o.designated_leader as i8, requirements: Some(requirements), finalization_actions: Some(serialized_fa), originating_client: o.originating_client.map(|_| &orig_client), notify_on_resolution: Some(notify), notes: Some(notes) }) }
use std::fs::File; use std::io; use std::io::prelude::*; static mut FIRST_RUN: bool = true; fn main() { unsafe { if FIRST_RUN { FIRST_RUN = false; println!("SMD Fixer v2.0.8 by Ali Deym\n"); } } println!("Enter file name (or exit): "); let mut filename = String::new(); io::stdin().read_line(&mut filename).unwrap(); filename = String::from(filename.trim_end()); if filename.trim_end() == "exit" { return; } let content = std::fs::read_to_string(&filename).unwrap(); let iter = content.split("\n"); let iter_clone = iter.clone(); for item in iter_clone { let firstword = item.split_ascii_whitespace().next().unwrap_or(""); let n = firstword.parse::<i32>().unwrap_or(-1); if n >= 0 { println!("{}", item); } else if firstword.trim_end().eq_ignore_ascii_case("end") { break; } } let mut bone_num = String::new(); let mut bone = Vec::new(); while bone_num.trim_end() != "end" { bone_num.clear(); println!("Enter bone(s) number or end to finish: "); io::stdin().read_line(&mut bone_num).unwrap(); let bn = bone_num.trim_end().parse::<i32>().unwrap_or(-1); if bn >= 0 { bone.push(bn); } } let mut new_content = Vec::new(); let mut on_frame = false; for item in iter { if item.trim().is_empty() { continue; } if item.to_lowercase().starts_with("time ") { on_frame = true; new_content.push(item.trim_end().replace("\r", "").replace("\n", "")); continue; } let firstword = item.split_ascii_whitespace().next().unwrap_or(""); let n = firstword.parse::<i32>().unwrap_or(-1); if bone.contains(&n) { new_content.push(item.trim_end().replace("\r", "").replace("\n", "")); } if !on_frame && n < 0 { new_content.push(item.trim_end().replace("\r", "").replace("\n", "")); } } new_content.push(String::from("end")); { std::fs::remove_file(&filename).unwrap(); let mut f = File::create(&filename).unwrap(); let joined = new_content.join("\r\n"); f.write_all(joined.as_bytes()).unwrap(); f.flush().unwrap(); } main(); }
use std::cmp::{Ordering}; #[derive(PartialEq, Eq)] pub enum LinkLayerType { Novell8023, Ethernet2, } #[derive(PartialEq, Eq)] pub enum NetworkLayerType { ARP, IPv4, IPv6, Other, } #[derive(PartialEq, Eq)] pub enum TransportLayerType { ICMP, TCP, UDP, Other, } #[derive(PartialEq, Eq)] pub struct PacketTypes { pub link_layer_type: LinkLayerType, pub network_layer_type: NetworkLayerType, pub transport_layer_type: TransportLayerType, pub packet_length: u32, pub source_mac: [u8; 6], pub dest_mac: [u8; 6], pub source_ip: [u8; 16], pub dest_ip: [u8; 16], pub source_port: u16, pub dest_port: u16, pub is_syn: bool, pub is_fin: bool, pub is_frag: bool, } impl PacketTypes { pub fn new(data: &[u8], len: u32) -> Self { let mut frame_type = LinkLayerType::Novell8023; let mut network_type = NetworkLayerType::Other; let mut transport_type = TransportLayerType::Other; let mut source_ip: [u8; 16] = [0; 16]; let mut dest_ip: [u8; 16] = [0; 16]; let mut source_port = 0; let mut dest_port = 0; let mut is_syn = false; let mut is_fin = false; let mut is_frag = false; let ethertype = ((data[12] as u16) << 8) | (data[13] as u16); if ethertype >= 1536 { frame_type = LinkLayerType::Ethernet2; if ethertype == 0x0800 { network_type = NetworkLayerType::IPv4; source_ip[0] = data[26]; source_ip[1] = data[27]; source_ip[2] = data[28]; source_ip[3] = data[29]; dest_ip[0] = data[30]; dest_ip[1] = data[31]; dest_ip[2] = data[32]; dest_ip[3] = data[33]; } else if ethertype == 0x0806 { network_type = NetworkLayerType::ARP; source_ip[0] = data[29]; source_ip[1] = data[30]; source_ip[2] = data[31]; source_ip[3] = data[32]; dest_ip[0] = data[38]; dest_ip[1] = data[39]; dest_ip[2] = data[40]; dest_ip[3] = data[41]; } else if ethertype == 0x86DD { network_type = NetworkLayerType::IPv6; source_ip.clone_from_slice(&data[21..37]); dest_ip.clone_from_slice(&data[38..54]); } match network_type { NetworkLayerType::IPv4 => { let protocol_code = data[23]; transport_type = get_trans_type(protocol_code); let frag_bits = (data[20] << 2 as u8) >> 7; if frag_bits == 1 { is_frag = true; } }, NetworkLayerType::IPv6 => { let protocol_code = data[20]; transport_type = get_trans_type(protocol_code); }, _ => transport_type = TransportLayerType::Other, } match transport_type { TransportLayerType::TCP => { source_port = ((data[34] as u16) << 8) | (data[35] as u16); dest_port = ((data[36] as u16) << 8) | (data[37] as u16); let fin_bit = (data[47] << 7 as u8) >> 7; let syn_bit = (data[47] << 6 as u8) >> 7; if fin_bit == 1 { is_fin = true; } if syn_bit == 1 { is_syn = true; } }, TransportLayerType::UDP => { source_port = ((data[34] as u16) << 8) | (data[35] as u16); dest_port = ((data[36] as u16) << 8) | (data[37] as u16); }, _ => {}, } } PacketTypes { link_layer_type: frame_type, network_layer_type: network_type, transport_layer_type: transport_type, packet_length: len, source_mac: [data[0], data[1], data[2], data[3], data[4], data[5]], dest_mac: [data[6], data[7], data[8], data[9], data[10], data[11]], source_ip: source_ip, dest_ip: dest_ip, source_port: source_port, dest_port: dest_port, is_syn: is_syn, is_fin: is_fin, is_frag: is_frag, } } } impl PartialOrd for PacketTypes { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for PacketTypes { fn cmp(&self, other: &Self) -> Ordering { if self.packet_length < other.packet_length { return Ordering::Less } else if self.packet_length > other.packet_length { return Ordering::Greater } else { return Ordering::Equal } } } fn get_trans_type(protocol_code: u8) -> TransportLayerType { match protocol_code { 1 => return TransportLayerType::ICMP, 6 => TransportLayerType::TCP, 17 => TransportLayerType::UDP, _ => return TransportLayerType::Other, } }
use super::{ENDPOINT, USERNAME}; use crate::client::{Claims, Jwt, UnauthorizedClient}; use crate::{CLIENT_CERT, CLIENT_KEY, SERVER_CA_CERT}; use anyhow::Result; use serial_test::serial; use server::server; use std::collections::HashMap; use tonic::transport::{Certificate, Identity}; #[tokio::test] #[serial] async fn success() { async fn test() -> Result<()> { tokio::spawn(server::serve()); let mut client = crate::init_client(USERNAME.into(), ENDPOINT).await?; client .spawn( "/bin/bash".into(), ".".into(), vec!["-c".into(), "echo hi".into()], HashMap::new(), ) .await?; Ok(()) } test().await.unwrap() } #[tokio::test] #[should_panic] #[serial] async fn invalid_jwt_signature() { async fn test() -> Result<()> { const FAKE_JWT: &str = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"; let token = Jwt(FAKE_JWT.into()); tokio::spawn(server::serve()); let identity = Identity::from_pem(CLIENT_CERT, CLIENT_KEY); let server_ca_cert = Certificate::from_pem(SERVER_CA_CERT); let mut client = UnauthorizedClient::connect(ENDPOINT, identity, server_ca_cert) .await? .with_token(token)?; client .spawn( "/bin/bash".into(), ".".into(), vec!["-c".into(), "echo hi".into()], HashMap::new(), ) .await?; Ok(()) } test().await.unwrap() } #[tokio::test] #[should_panic] #[serial] async fn missing_privileges() { async fn test() -> Result<()> { tokio::spawn(server::serve()); let identity = Identity::from_pem(CLIENT_CERT, CLIENT_KEY); let server_ca_cert = Certificate::from_pem(SERVER_CA_CERT); let mut unauthorized_client = UnauthorizedClient::connect(ENDPOINT, identity, server_ca_cert).await?; let claims = Claims { username: USERNAME.into(), spawn: false, stop: true, status: true, stream_log: true, }; let token = unauthorized_client.issue_jwt(claims).await?; let mut client = unauthorized_client.with_token(token)?; client .spawn( "/bin/bash".into(), ".".into(), vec!["-c".into(), "echo hi".into()], HashMap::new(), ) .await?; Ok(()) } test().await.unwrap() }
fn main() { let _a: i16 = -150; let _b = -150 as i16; let _c = -150 + _b - _b; let _d = -150i16; }
trait AbstractDisplay { fn open(&self); fn print(&self); fn close(&self); fn display(&self) { self.open(); for i in 1..5 { self.print(); } self.close(); } } struct CharDisplay { ch: char, } impl CharDisplay { fn new(ch: char) -> CharDisplay { CharDisplay{ ch: ch } } } impl AbstractDisplay for CharDisplay { fn open(&self) { print!("<<"); } fn print(&self) { let mut s = String::new(); s.push(self.ch); print!("{}", s); } fn close(&self) { println!(">>"); } } struct StringDisplay { string : String, width : usize, } impl StringDisplay { fn new(string: String) -> StringDisplay { let bytes_len = string.len(); let chars_len = string.chars().count(); if bytes_len == chars_len { StringDisplay { string: string.clone(), width: string.len() } } else { StringDisplay { string: string.clone(), width: 2 * string.chars().count() } } } fn print_line(&self) { print!("+"); for i in 0..self.width { print!("-"); } println!("+"); } } impl AbstractDisplay for StringDisplay { fn open(&self) { self.print_line(); } fn print(&self) { println!("|{}|", self.string); } fn close(&self) { self.print_line(); } } fn main() { let d1 = CharDisplay::new('H'); let d2 = StringDisplay::new("Hello, world.".to_string()); let d3 = StringDisplay::new("こんにちは".to_string()); d1.display(); d2.display(); d3.display(); }
use serde::{Deserialize, Serialize}; use specs::error::NoError; use specs::prelude::*; use specs::saveload::{ConvertSaveload, Marker}; use specs_derive::*; // Helper for serializing entities in serde pub struct EntityMarker; #[derive(Component, ConvertSaveload, Copy, Clone)] pub struct FPSTracker { pub for_time: u64, pub seen_frames: u16, pub prev_fps: u16, } #[derive(Component, ConvertSaveload, Clone)] pub struct Location { pub x: i32, pub y: i32, } #[derive(Component, ConvertSaveload, Clone)] pub struct PlayerInfo { pub id: String, } #[derive(Component, ConvertSaveload, Clone)] pub struct Renderable { pub render_order: i32, } #[derive(Component, ConvertSaveload, Clone)] pub struct TextRenderable { pub text: String, pub font_size: f64, pub offset_x: f64, pub offset_y: f64, } #[derive(Component, ConvertSaveload, Clone)] pub struct ChatRenderable { pub text: String, pub offset_x: f64, pub offset_y: f64, } #[derive(Component, ConvertSaveload, Clone)] pub struct GraphicRenderable { pub image_name: String, pub offset_x: f64, pub offset_y: f64, } #[derive(Component, ConvertSaveload, Clone)] pub struct GraphicAnimatable { pub image_names: Vec<String>, pub tick_interval: i16, pub ticks: i16, } #[derive(Component, ConvertSaveload, Clone)] pub struct WantsToMoveTo { pub x: i32, pub y: i32, pub speed: i16, } #[derive(Component, ConvertSaveload, Clone)] pub struct Disappearing { pub total_ticks: u32, pub ticks_left: u32, } #[derive(Component, ConvertSaveload, Clone)] pub struct CarriedBy { pub owner: Entity, } #[derive(PartialEq, Copy, Clone, Deserialize, Serialize)] pub enum CrabAIState { WalkingRight, SleepingRight, WalkingLeft, SleepingLeft, } #[derive(Component, ConvertSaveload, Clone)] pub struct CrabAI { pub crab_state: CrabAIState, pub tick_interval: i16, pub ticks: i16, pub walk_speed: i16, pub sleep_duration: i16, } #[derive(Component, Clone, Deserialize, Serialize)] pub struct WantsToBePickedUp {} #[derive(Component, Clone, Deserialize, Serialize)] pub struct WantsToStab {}
use ncurses::{ACS_BLOCK, WINDOW, box_, mvwaddch, wrefresh}; use crate::chip8::{CHIP_WIDTH, CHIP_HEIGHT}; pub struct Screen { window: WINDOW } impl Screen { pub fn new(window: WINDOW) -> Self { Screen { window: window } } pub fn update(&self, vram: [[bool; CHIP_WIDTH]; CHIP_HEIGHT]) { for x in 0..CHIP_WIDTH { for y in 0..CHIP_HEIGHT { let ch = match vram[y][x] { false => ' ' as u32, true => ACS_BLOCK() }; mvwaddch(self.window, (y + 1) as i32, (x + 1) as i32, ch); } } box_(self.window, 0, 0); wrefresh(self.window); } }
// Copyright 2017 The Grin Developers // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /// Tests exercising the loading and unloading of plugins, as well as the /// existence and correct functionality of each plugin function mod common; extern crate rand; extern crate cuckoo_miner as cuckoo; use cuckoo::{PluginConfig}; use common::mine_async_for_duration; #[test] fn mine_cuckatoo_mean_compat_cpu_19() { let mut config = PluginConfig::new("cuckatoo_mean_compat_cpu_19").unwrap(); config.params.nthreads = 4; mine_async_for_duration(&vec![config], 20); } #[test] fn mine_cuckatoo_mean_compat_cpu_29() { let mut config = PluginConfig::new("cuckatoo_mean_compat_cpu_29").unwrap(); config.params.nthreads = 4; mine_async_for_duration(&vec![config], 20); } #[ignore] #[test] fn mine_cuckatoo_mean_compat_cpu_30() { let mut config = PluginConfig::new("cuckatoo_mean_compat_cpu_30").unwrap(); config.params.nthreads = 4; mine_async_for_duration(&vec![config], 20); } #[cfg(feature="build-mean-avx2")] #[test] fn mine_cuckatoo_mean_avx2_cpu_29() { let mut config = PluginConfig::new("cuckatoo_mean_avx2_cpu_29").unwrap(); config.params.nthreads = 4; mine_async_for_duration(&vec![config], 20); } #[ignore] #[cfg(feature="build-mean-avx2")] #[test] fn mine_cuckatoo_mean_avx2_cpu_30() { let mut config = PluginConfig::new("cuckatoo_mean_avx2_cpu_30").unwrap(); config.params.nthreads = 4; mine_async_for_duration(&vec![config], 20); } #[test] fn mine_cuckatoo_lean_cpu_19() { let mut config = PluginConfig::new("cuckatoo_lean_cpu_19").unwrap(); config.params.nthreads = 4; mine_async_for_duration(&vec![config], 20); } #[test] fn mine_cuckatoo_lean_cpu_29() { let mut config = PluginConfig::new("cuckatoo_lean_cpu_29").unwrap(); config.params.nthreads = 4; mine_async_for_duration(&vec![config], 20); } #[cfg(feature="build-cuda-plugins")] #[test] fn mine_cuckatoo_mean_cuda_29() { let mut config = PluginConfig::new("cuckatoo_mean_cuda_29").unwrap(); config.params.expand = 1; mine_async_for_duration(&vec![config], 20); } #[cfg(feature="build-cuda-plugins")] #[test] fn mine_cuckatoo_lean_cuda_29() { let config = PluginConfig::new("cuckatoo_lean_cuda_29").unwrap(); mine_async_for_duration(&vec![config], 20); }
#![warn(clippy::pedantic)] use libcnb_test::{assert_contains, BuildConfig, ContainerConfig, ContainerContext, TestRunner}; use std::time::Duration; const PORT: u16 = 8080; fn test_node(fixture: &str, builder: &str, expect_lines: &[&str]) { TestRunner::default().build( BuildConfig::new(builder, format!("../../test/fixtures/{fixture}")), |ctx| { for expect_line in expect_lines { assert_contains!(ctx.pack_stdout, expect_line); } ctx.start_container(ContainerConfig::new().expose_port(PORT), |container| { test_response(&container, fixture); }); }, ); } fn test_response(container: &ContainerContext, text: &str) { std::thread::sleep(Duration::from_secs(1)); let addr = container .address_for_port(PORT) .expect("couldn't get container address"); let resp = ureq::get(&format!("http://{addr}")) .call() .expect("request to container failed") .into_string() .expect("response read error"); assert_contains!(resp, text); } #[test] #[ignore] fn simple_indexjs_heroku20() { test_node( "node-with-indexjs", "heroku/buildpacks:20", &["Detected Node.js version range: *", "Installing Node.js"], ); } #[test] #[ignore] fn simple_indexjs_heroku22() { test_node( "node-with-indexjs", "heroku/builder:22", &["Detected Node.js version range: *", "Installing Node.js"], ); } #[test] #[ignore] fn simple_serverjs_heroku20() { test_node( "node-with-serverjs", "heroku/buildpacks:20", &["Installing Node.js 16.0.0"], ); } #[test] #[ignore] fn simple_serverjs_heroku22() { test_node( "node-with-serverjs", "heroku/builder:22", &["Installing Node.js 16.0.0"], ); } #[test] #[ignore] fn upgrade_simple_indexjs_from_heroku20_to_heroku22() { TestRunner::default().build( BuildConfig::new( "heroku/buildpacks:20", "../../test/fixtures/node-with-indexjs", ), |initial_ctx| { assert_contains!(initial_ctx.pack_stdout, "Installing Node.js"); initial_ctx.rebuild( BuildConfig::new("heroku/builder:22", "../../test/fixtures/node-with-indexjs"), |upgrade_ctx| { assert_contains!(upgrade_ctx.pack_stdout, "Installing Node.js"); let port = 8080; upgrade_ctx.start_container( ContainerConfig::new().expose_port(port), |container| { test_response(&container, "node-with-index"); }, ); }, ); }, ); }
#[derive(Debug, Deserialize, PartialEq, Eq, Clone)] pub struct FilterOutput { pub stream_label: String, }
use eyre::eyre; use eyre::Result; use hotwatch::Event; use lazy_static::lazy_static; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; use serde::Serialize; use std::collections::BTreeMap; use std::collections::HashMap; use std::collections::HashSet; use std::fmt::Debug; use std::fs; use std::path::PathBuf; use tera::{Context, Tera}; use tracing::{debug, error, info, warn}; use url::Url; use crate::content::load_drafts; use crate::content::load_series; use crate::content::set_post_prev_next; use crate::content::DraftRef; use crate::content::PostRef; use crate::content::SeriesArchiveItem; use crate::content::SeriesItem; use crate::content::SeriesRef; use crate::feed::SiteFeed; use crate::item::Item; use crate::paths::AbsPath; use crate::paths::FilePath; use crate::paths::RelPath; use crate::{ content::{ load_posts, load_standalones, post_archives, tags_archives, ArchiveItem, DraftArchiveItem, DraftItem, HomepageItem, PostItem, ProjectsItem, Sass, StandaloneItem, Tag, TagListItem, }, item::RenderContext, site_url::SiteUrl, util::{self, load_templates}, }; lazy_static! { pub static ref BASE_SITE_URL: Url = Url::parse("https://jonashietala.se").unwrap(); } #[derive(Debug)] pub struct SiteOptions { pub input_dir: AbsPath, pub output_dir: AbsPath, pub clear_output_dir: bool, pub include_drafts: bool, } pub struct SiteContent { pub homepage: HomepageItem, pub projects: ProjectsItem, pub posts: BTreeMap<PostRef, PostItem>, pub series: BTreeMap<SeriesRef, SeriesItem>, pub drafts: Option<BTreeMap<DraftRef, DraftItem>>, pub standalones: HashSet<StandaloneItem>, } impl SiteContent { fn load(opts: &SiteOptions) -> Result<Self> { let mut posts = load_posts(opts.input_dir.join("posts"))?; let series = load_series(opts.input_dir.join("series"), &mut posts)?; let standalones = load_standalones(opts.input_dir.join("static"))?; let drafts = if opts.include_drafts { let drafts = load_drafts(opts.input_dir.join("drafts"))?; Some(drafts) } else { None }; println!( "posts: {} series: {} standalones: {} drafts: {:?}", posts.len(), series.len(), standalones.len(), drafts.as_ref().map(|x| x.len()) ); let homepage = HomepageItem::new(&opts.input_dir, &posts)?; let projects = ProjectsItem::new(&opts.input_dir)?; Ok(Self { posts, series, standalones, drafts, homepage, projects, }) } #[allow(dead_code)] pub fn find_post<'a>(&'a self, file_name: &str) -> Option<&'a PostItem> { self.posts .values() .find(|post| post.path.file_name() == Some(file_name)) } #[allow(dead_code)] pub fn find_series<'a>(&'a self, file_name: &str) -> Option<&'a SeriesItem> { self.series .values() .find(|series| series.path.file_name() == Some(file_name)) } pub fn insert_post(&mut self, post: PostItem) -> Option<PostItem> { let post_ref = post.post_ref(); let prev_post = self.posts.insert(post_ref.clone(), post); set_post_prev_next(&mut self.posts); self.update_homepage(); prev_post } pub fn insert_draft(&mut self, draft: DraftItem) -> Option<DraftItem> { let draft_ref = draft.draft_ref(); let prev_draft = self .drafts .as_mut() .unwrap() .insert(draft_ref.clone(), draft); prev_draft } pub fn update_homepage(&mut self) { self.homepage.update_posts(&self.posts) } pub fn get_post(&self, post_ref: &PostRef) -> Option<&PostItem> { self.posts.get(post_ref) } pub fn get_series(&self, series_ref: &SeriesRef) -> Option<&SeriesItem> { self.series.get(series_ref) } } pub struct SiteLookup { pub tags: HashMap<Tag, Vec<PostRef>>, } impl SiteLookup { fn from_content(content: &SiteContent) -> Self { let mut tags: HashMap<Tag, Vec<PostRef>> = HashMap::new(); for (post_ref, post) in &content.posts { for tag in &post.tags { tags.entry(tag.clone()) .or_insert_with(Vec::new) .push(post_ref.clone()); } } Self { tags } } } pub struct Site { pub content: SiteContent, pub lookup: SiteLookup, pub templates: Tera, // Generation options pub opts: SiteOptions, // Cached rendering context context: Context, } #[derive(Default)] struct SiteRenderOpts<'a> { all_posts: bool, all_standalones: bool, all_drafts: bool, draft_archive: bool, post_archives: bool, tags_archives: bool, series_archive: bool, tags_list: bool, homepage: bool, projects: bool, series: bool, sass: bool, copy_files: bool, feed: bool, extra_render: Vec<&'a dyn Item>, } impl SiteRenderOpts<'_> { fn all() -> Self { Self { all_posts: true, all_standalones: true, all_drafts: true, draft_archive: true, post_archives: true, tags_archives: true, series_archive: true, tags_list: true, homepage: true, projects: true, series: true, sass: true, copy_files: true, feed: true, extra_render: vec![], } } fn post_created<'a>(post: &'a PostItem) -> SiteRenderOpts<'a> { let has_series = post.series.is_some(); let has_tags = !post.tags.is_empty(); SiteRenderOpts { all_posts: true, tags_archives: has_tags, tags_list: has_tags, post_archives: true, series_archive: has_series, series: has_series, homepage: true, extra_render: vec![post], feed: true, ..Default::default() } } fn post_updated<'a>(old: &PostItem, new: &'a PostItem) -> SiteRenderOpts<'a> { let title_changed = new.title != old.title; let tags_changed = new.tags != old.tags; let series_changed = new.series.is_some() || new.series != old.series; let recommended_changed = new.recommended != old.recommended; SiteRenderOpts { // NOTE // It's excessive to re-render ALL posts, just next/prev + in series should be enough. // It's excessive to re-render ALL tags, just affected tags should be enough. // It's excessive to re-render ALL series, just affected should be enough. all_posts: title_changed || series_changed, tags_archives: title_changed || tags_changed, tags_list: tags_changed, post_archives: title_changed, series_archive: title_changed || series_changed, series: title_changed || series_changed, homepage: title_changed || recommended_changed, extra_render: vec![new], feed: true, ..Default::default() } } fn draft_created<'a>(draft: &'a DraftItem) -> SiteRenderOpts<'a> { SiteRenderOpts { draft_archive: true, extra_render: vec![draft], ..Default::default() } } fn draft_updated<'a>(old: &DraftItem, new: &'a DraftItem) -> SiteRenderOpts<'a> { SiteRenderOpts { draft_archive: new.title != old.title, extra_render: vec![new], ..Default::default() } } } struct SiteRenderExtra<'a> { post_archives: Option<Vec<ArchiveItem>>, series_archive: Option<SeriesArchiveItem>, tags_archives: Option<Vec<ArchiveItem>>, tags_list: Option<TagListItem<'a>>, draft_archive: Option<DraftArchiveItem<'a>>, } impl<'a> SiteRenderExtra<'a> { fn new(opts: &SiteRenderOpts, site: &'a Site) -> SiteRenderExtra<'a> { let post_archives = if opts.post_archives { Some(post_archives(&site.content.posts)) } else { None }; let tags_archives = if opts.tags_archives { Some(tags_archives(&site.lookup.tags)) } else { None }; let series_archive = if opts.series_archive { Some(SeriesArchiveItem::new(&site.content.series)) } else { None }; let tags_list = if opts.tags_list { Some(TagListItem::new(&site.lookup.tags)) } else { None }; let draft_archive = if opts.draft_archive { site.draft_archive() } else { None }; SiteRenderExtra { post_archives, series_archive, tags_archives, tags_list, draft_archive, } } } enum PathEvent { SourceFile, Css, Post, Static, Draft, Series, Template, Font, Image, Homepage, Project, Unknown, Ignore, } impl PathEvent { pub fn from_path(path: &FilePath) -> Self { if path.rel_path.0.extension() == Some("rs") { Self::SourceFile } else if path.rel_path.starts_with("css/") { Self::Css } else if path.rel_path.starts_with("posts/") { Self::Post } else if path.rel_path.starts_with("static/") { Self::Static } else if path.rel_path.starts_with("drafts/") { Self::Draft } else if path.rel_path.starts_with("series/") { Self::Series } else if path.rel_path.starts_with("templates/") { Self::Template } else if path.rel_path.starts_with("fonts/") || path.rel_path.starts_with("images/") { Self::Font } else if path.rel_path.starts_with("images/") { Self::Image } else if path.rel_path == "about.markdown" { Self::Homepage } else if path.rel_path == "projects.markdown" || path.rel_path.starts_with("projects/") { Self::Project } else if unknown_change_msg(&path.rel_path) { Self::Unknown } else { Self::Ignore } } } impl Site { pub fn load_content(opts: SiteOptions) -> Result<Self> { let content = SiteContent::load(&opts)?; Self::with_content(content, opts) } pub fn with_content(content: SiteContent, opts: SiteOptions) -> Result<Self> { let lookup = SiteLookup::from_content(&content); let templates = load_templates("templates/*.html")?; let context = Context::from_serialize(SiteContext::new(opts.include_drafts)).unwrap(); Ok(Self { opts, templates, content, lookup, context, }) } fn draft_archive(&self) -> Option<DraftArchiveItem> { self.content.drafts.as_ref().map(|drafts| DraftArchiveItem { drafts: drafts.values().collect(), url: SiteUrl::parse("/drafts").unwrap(), title: "Drafts".to_string(), }) } fn copy_archive(&self) -> Result<()> { util::copy_file( &self.opts.output_dir.join("blog/index.html"), &self.opts.output_dir.join("archive/index.html"), ) } pub fn render_all(&self) -> Result<()> { if self.opts.clear_output_dir && self.opts.output_dir.exists() { debug!("Removing {}", self.opts.clear_output_dir); fs::remove_dir_all(&self.opts.output_dir)?; } self.render(SiteRenderOpts::all()) } fn render(&self, opts: SiteRenderOpts<'_>) -> Result<()> { let ctx = self.render_ctx(); let extra = SiteRenderExtra::new(&opts, self); let mut items = opts.extra_render; if opts.all_posts { info!("Rebuilding all posts"); for post in self.content.posts.values() { items.push(post); } } if opts.all_standalones { info!("Rebuilding all standalones"); for standalone in &self.content.standalones { items.push(standalone); } } if opts.all_drafts { info!("Rebuilding all drafts"); if let Some(ref drafts) = self.content.drafts { for draft in drafts.values() { items.push(draft); } } } if opts.homepage { info!("Rebuilding homepage"); items.push(&self.content.homepage); } if opts.projects { info!("Rebuilding projects"); items.push(&self.content.projects); } if opts.series { info!("Rebuilding series"); for serie in self.content.series.values() { items.push(serie); } } if let Some(ref post_archives) = extra.post_archives { info!("Rebuilding post archives"); for i in post_archives { items.push(i); } } if let Some(ref series_archive) = extra.series_archive { info!("Rebuilding series archives"); items.push(series_archive); } if let Some(ref tags_archives) = extra.tags_archives { info!("Rebuilding tags archives"); for i in tags_archives { items.push(i); } } if let Some(ref tags_list) = extra.tags_list { info!("Rebuilding tags list"); items.push(tags_list); } if let Some(ref draft_archive) = extra.draft_archive { info!("Rebuilding draft archive"); items.push(draft_archive); } let sass = Sass; if opts.sass { info!("Rebuilding css"); items.push(&sass); } let feed = SiteFeed; if opts.feed { info!("Rebuilding feed"); items.push(&feed); } render_items(&items, &ctx)?; if opts.post_archives { self.copy_archive()?; } if opts.copy_files { util::copy_files_keep_dirs("fonts/*", &self.opts.input_dir, &self.opts.output_dir)?; util::copy_files_keep_dirs("images/**/*", &self.opts.input_dir, &self.opts.output_dir)?; util::copy_files_to( self.opts.input_dir.join("static/*.txt").as_str(), &self.opts.output_dir, )?; } Ok(()) } fn render_ctx(&self) -> RenderContext { RenderContext { parent_context: &self.context, tera: &self.templates, output_dir: &self.opts.output_dir, content: &self.content, } } fn render_item<T: Item + ?Sized>(&self, item: &T) -> Result<()> { item.render(&self.render_ctx()) } pub fn file_changed(&mut self, event: Event) -> Result<()> { match event { Event::Write(path) => { self.write_event(path)?; } Event::Create(path) => { self.create_event(path)?; } Event::Rename(from, to) => { self.rename_event(from, to)?; } Event::Remove(path) => { self.remove_event(path)?; } Event::Rescan => { self.rebuild_all()?; } Event::Error(err, path) => { return Err(eyre!("{err} {path:?}")); } _ => {} } Ok(()) } fn write_event(&mut self, path: PathBuf) -> Result<()> { let path = self.file_path(path)?; match PathEvent::from_path(&path) { PathEvent::SourceFile => error!("Source file changed `{path}`, please rebuild"), PathEvent::Css => self.rebuild_css()?, PathEvent::Post => self.rebuild_post(path.abs_path())?, PathEvent::Static => self.rebuild_standalone(path.abs_path())?, PathEvent::Draft => self.rebuild_draft(path.abs_path())?, PathEvent::Series => self.rebuild_series(path.abs_path())?, PathEvent::Template => self.rebuild_template(path.abs_path())?, PathEvent::Font | PathEvent::Image => self.rebuild_copy(path)?, PathEvent::Homepage => self.rebuild_homepage()?, PathEvent::Project => self.rebuild_projects(path.abs_path())?, PathEvent::Unknown => warn!("Unknown write: {path}"), PathEvent::Ignore => (), } Ok(()) } fn create_event(&mut self, path: PathBuf) -> Result<()> { let path = self.file_path(path)?; match PathEvent::from_path(&path) { PathEvent::SourceFile => error!("Source file changed `{path}`, please rebuild"), PathEvent::Css => self.rebuild_css()?, PathEvent::Static => self.rebuild_standalone(path.abs_path())?, PathEvent::Draft => self.rebuild_draft(path.abs_path())?, PathEvent::Font | PathEvent::Image => self.rebuild_copy(path)?, PathEvent::Homepage => self.rebuild_homepage()?, PathEvent::Project => self.rebuild_projects(path.abs_path())?, PathEvent::Post => self.rebuild_all()?, PathEvent::Series => self.rebuild_all()?, PathEvent::Template => self.rebuild_all()?, PathEvent::Ignore => (), PathEvent::Unknown => warn!("Unknown create: {path}"), } Ok(()) } fn rename_event(&mut self, from: PathBuf, to: PathBuf) -> Result<()> { let from = self.file_path(from)?; let to = self.file_path(to)?; // Could be made more efficient, but this is easier and good for consistency. // Rebuild all is still quite fast and this is uncommon, so it's fine for now... match (PathEvent::from_path(&from), PathEvent::from_path(&to)) { (PathEvent::SourceFile, _) | (_, PathEvent::SourceFile) => { error!("Source file removed `{from} -> {to}`, please rebuild") } (PathEvent::Unknown, _) | (_, PathEvent::Unknown) => { warn!("Unknown rename: {from} -> {to}") } (PathEvent::Ignore, PathEvent::Ignore) => (), _ => self.rebuild_all()?, } Ok(()) } fn remove_event(&mut self, path: PathBuf) -> Result<()> { let path = self.file_path(path)?; match PathEvent::from_path(&path) { PathEvent::SourceFile => error!("Source file removed `{path}`, please rebuild"), PathEvent::Css => self.rebuild_css()?, PathEvent::Font | PathEvent::Image => self.remove_output(path)?, PathEvent::Homepage => self.rebuild_homepage()?, PathEvent::Project => self.rebuild_projects(path.abs_path())?, PathEvent::Unknown => warn!("Unknown remove: {path}"), PathEvent::Ignore => (), // Not efficient, but it's much easier to get consistency. // Rebuild all is still quite fast and this is uncommon, so it's fine for now... _ => self.rebuild_all()?, } Ok(()) } fn rebuild_css(&self) -> Result<()> { info!("Rebuilding css"); self.render_item(&Sass {}) } fn rebuild_post(&mut self, path: AbsPath) -> Result<()> { info!("Post changed: {path}"); let updated = PostItem::from_file(path.clone())?; let post_ref = updated.post_ref(); let prev_post = self.content.insert_post(updated); let updated = self.content.posts.get(&post_ref).unwrap(); let render_opts = match prev_post { Some(old) => SiteRenderOpts::post_updated(&old, &updated), None => SiteRenderOpts::post_created(&updated), }; self.render(render_opts) } fn rebuild_standalone(&mut self, path: AbsPath) -> Result<()> { info!("Standalone changed: {path}"); let updated = StandaloneItem::from_file(path)?; self.render_item(&updated)?; self.content.standalones.insert(updated); Ok(()) } fn rebuild_draft(&mut self, path: AbsPath) -> Result<()> { if !self.opts.include_drafts { return Ok(()); } info!("Draft changed: {path}"); let updated = DraftItem::from_file(path.clone())?; let draft_ref = updated.draft_ref(); let prev_draft = self.content.insert_draft(updated); let drafts = &self.content.drafts.as_ref().unwrap(); let updated = drafts.get(&draft_ref).unwrap(); let render_opts = match prev_draft { Some(old) => SiteRenderOpts::draft_updated(&old, &updated), None => SiteRenderOpts::draft_created(&updated), }; self.render(render_opts) } fn rebuild_series(&mut self, path: AbsPath) -> Result<()> { info!("Series changed: {path}"); let mut updated = SeriesItem::from_file(path.clone())?; // We need to loop as we can't build a SeriesRef without having the last updated field. let old_ref = self .content .series .iter() .find(|x| x.0.id == updated.id) .map(|x| x.0.clone()) .ok_or_else(|| eyre!("Nonexistent series: {}", path))?; let old = self .content .series .remove(&old_ref) .ok_or_else(|| eyre!("Nonexistent series: {}", path))?; updated.posts = old.posts; // We need series here for posts to render. let series_ref = updated.series_ref(); self.content.series.insert(series_ref.clone(), updated); let updated = self.content.series.get(&series_ref).unwrap(); let title_changed = updated.title != old.title; let note_changed = updated.post_note != old.post_note; self.render(SiteRenderOpts { all_posts: title_changed || note_changed, series_archive: true, extra_render: vec![updated], ..Default::default() }) } fn rebuild_homepage(&mut self) -> Result<()> { self.content.homepage = HomepageItem::new(&self.opts.input_dir, &self.content.posts)?; self.render(SiteRenderOpts { projects: true, ..Default::default() }) } fn rebuild_projects(&mut self, path: AbsPath) -> Result<()> { info!("Projects changed: {path}"); self.content.projects = ProjectsItem::new(&self.opts.input_dir)?; self.render(SiteRenderOpts { projects: true, ..Default::default() }) } fn rebuild_template(&mut self, path: AbsPath) -> Result<()> { info!("Template changed: {path}"); let template = if let Some(name) = path.file_name() { name } else { return Ok(()); }; self.templates.full_reload()?; let opts = match template { "site.html" => SiteRenderOpts { all_posts: true, all_standalones: true, all_drafts: true, draft_archive: true, post_archives: true, tags_archives: true, tags_list: true, homepage: true, projects: true, ..Default::default() }, "archive.html" => SiteRenderOpts { draft_archive: true, post_archives: true, tags_archives: true, ..Default::default() }, "post.html" => SiteRenderOpts { all_posts: true, all_drafts: true, ..Default::default() }, "static.html" => SiteRenderOpts { all_standalones: true, ..Default::default() }, "tags.html" => SiteRenderOpts { tags_list: true, ..Default::default() }, "homepage.html" => SiteRenderOpts { homepage: true, ..Default::default() }, "projects.html" => SiteRenderOpts { projects: true, ..Default::default() }, "series.html" => SiteRenderOpts { series: true, ..Default::default() }, "series_archive.html" => SiteRenderOpts { series_archive: true, ..Default::default() }, _ => { error!("Unknown template {template}"); SiteRenderOpts::all() } }; self.render(opts) } fn remove_output(&mut self, path: FilePath) -> Result<()> { info!("File removed: {path}"); std::fs::remove_file(&self.opts.output_dir.join(&path.rel_path.0))?; Ok(()) } fn rebuild_copy(&mut self, path: FilePath) -> Result<()> { info!("Copy changed: {path}"); util::copy_file( &path.abs_path(), &self.opts.output_dir.join(&path.rel_path.0), ) } fn rebuild_all(&mut self) -> Result<()> { self.templates.full_reload()?; self.content = SiteContent::load(&self.opts)?; self.lookup = SiteLookup::from_content(&self.content); self.render_all() } fn file_path(&self, path: PathBuf) -> Result<FilePath> { FilePath::from_std_path(&self.opts.input_dir, path) } } fn render_items(items: &[&dyn Item], ctx: &RenderContext) -> Result<()> { items.par_iter().try_for_each(|item| item.render(ctx)) } fn unknown_change_msg(path: &RelPath) -> bool { #[allow(clippy::if_same_then_else)] if path.starts_with("target") { false } else if path.starts_with("test-site/") { false } else if path.starts_with("itemref-derive/") { false } else if path == "Cargo.toml" { false } else if path == "Cargo.lock" { false } else if path == "TODO.md" { false } else if path == "README.md" { false } else { !path.starts_with(".") } } #[derive(Debug, Clone, Serialize)] pub struct SiteContext { mail: &'static str, meta_keywords: Vec<String>, include_drafts: bool, } impl SiteContext { pub fn new(include_drafts: bool) -> Self { Self { mail: "mail@jonashietala.se", meta_keywords: vec![], include_drafts, } } } #[cfg(test)] mod tests { use super::*; use crate::item::TeraItem; use crate::tests::*; use crate::util::{parse_html_files, ParsedFiles}; use camino::Utf8Path; use camino::Utf8PathBuf; use colored::Colorize; #[allow(dead_code)] fn enable_trace() { use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; tracing_subscriber::registry() .with(tracing_subscriber::EnvFilter::new( "jonashietala_se=debug,tower_http=debug", )) .with(tracing_subscriber::fmt::layer()) .init(); } #[test] fn test_render_and_check_site() -> Result<()> { let (_output_dir, output_path) = AbsPath::new_tempdir()?; // let temp_dir = tempfile::tempdir().unwrap(); // let output_dir = Utf8PathBuf::from_path_buf(temp_dir.path().to_owned()).unwrap(); let site = Site::load_content(SiteOptions { output_dir: output_path.clone(), input_dir: AbsPath::current_dir().unwrap(), clear_output_dir: false, include_drafts: true, })?; site.render_all()?; assert!(!site.content.posts.is_empty()); for post in site.content.posts.values() { let output_file = post.output_file(&output_path); assert!(output_file.exists()); } if let Some(ref drafts) = site.content.drafts { assert!(!drafts.is_empty()); for draft in drafts.values() { let output_file = draft.output_file(&output_path); assert!(output_file.exists()); } } let rel_path = |path| { let mut res = output_path.0.clone(); res.push(path); res }; assert!(output_path.exists()); assert!(rel_path("blog/2009/07/21/the_first_worst_post/index.html").exists()); assert!(rel_path("blog/index.html").exists()); assert!(rel_path("blog/2022/index.html").exists()); assert!(rel_path("blog/2022/01/index.html").exists()); assert!(rel_path("blog/2022/01/10/2021_in_review/index.html").exists()); assert!(rel_path("blog/tags/index.html").exists()); assert!(rel_path("blog/tags/why_cryptocurrencies/index.html").exists()); assert!(rel_path("archive/index.html").exists()); assert!(rel_path("series/index.html").exists()); assert!(rel_path("series/t-34/index.html").exists()); assert!(rel_path("css/main.css").exists()); assert!(rel_path("404/index.html").exists()); assert!(rel_path("index.html").exists()); if site.content.drafts.is_some() { assert!(rel_path("drafts/index.html").exists()); } assert!(rel_path("encrmsg01.txt").exists()); assert!(rel_path("feed.xml").exists()); let files = parse_html_files(&output_path)?; let file_errors = check_files(&files, &output_path); let mut file_error_count = 0; for (path, errors) in file_errors { // Drafts shouldn't generate hard errors, but output warnings if we run // the test with -- --nocapture or if the test fails for other reasons. let is_draft = path.as_str().contains("/drafts/"); if !is_draft { file_error_count += errors.len(); } if !errors.is_empty() { if is_draft { print!("{}", "Warnings".yellow()); } else { print!("{}", "Errors".red()); } println!(" while checking {}", path.as_str().magenta()); for error in &errors { println!(" {}", error); } } } assert_eq!(file_error_count, 0); Ok(()) } #[test] fn test_hide_drafts() -> Result<()> { let test_site = TestSiteBuilder { include_drafts: false, } .build()?; assert!(!test_site.output_path("drafts/index.html").exists()); assert!(!test_site.output_path("drafts/a_draft/index.html").exists()); assert!(!test_site .read_file_to_string("index.html")? .contains("Drafts")); assert!(!test_site .find_post("2022-01-31-test_post.markdown") .unwrap() .raw_content .contains("Drafts")); Ok(()) } #[test] fn test_site_file_create() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: true, } .build()?; assert!(test_site .find_post("posts/2023-01-31-new_post.markdown") .is_none()); test_site.create_file( "posts/2023-01-31-new_post.markdown", r#" --- title: "New post title" tags: Tag1 --- My created post "#, )?; assert!(test_site .find_post("2023-01-31-new_post.markdown") .unwrap() .raw_content .contains("My created post")); let homepage = test_site.output_content("index.html")?; assert!(homepage.contains("New post title")); test_site.create_file( "drafts/my_draft.markdown", r#" --- title: "New draft title" tags: Tag1 --- My created draft "#, )?; assert!(test_site .output_content("drafts/index.html")? .contains("New draft title")); assert!(test_site .output_content("drafts/my_draft/index.html")? .contains("My created draft")); test_site.create_file( "static/my_static.markdown", r#" --- title: "Some static page" --- My created static "#, )?; let draft = test_site.output_content("my_static/index.html")?; assert!(draft.contains("My created static")); Ok(()) } #[test] fn test_post_removed() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: false, } .build()?; assert!(test_site .output_content("blog/2022/01/31/test_post/index.html") .is_ok()); test_site.remove_file("posts/2022-01-31-test_post.markdown")?; assert!(test_site .output_content("blog/2022/01/31/test_post/index.html") .is_err()); Ok(()) } #[test] fn test_draft_promoted() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: true, } .build()?; assert!(test_site .output_content("drafts/a_draft/index.html")? .contains("My draft text")); test_site.rename_file( "drafts/a_draft.markdown", "posts/2023-01-31-now_post.markdown", )?; assert!(test_site .output_content("drafts/a_draft/index.html") .is_err()); assert!(test_site .output_content("blog/2023/01/31/now_post/index.html")? .contains("My draft text")); Ok(()) } #[test] fn test_post_demoted() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: true, } .build()?; assert!(test_site .output_content("blog/2022/01/31/test_post/index.html")? .contains("☃︎")); test_site.rename_file( "posts/2022-01-31-test_post.markdown", "drafts/new_draft.markdown", )?; assert!(test_site .output_content("blog/2022/01/31/test_post/index.html") .is_err()); assert!(test_site .output_content("drafts/new_draft/index.html")? .contains("☃︎")); Ok(()) } #[test] fn test_post_content_change() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: false, } .build()?; assert!(test_site .find_post("2022-01-31-test_post.markdown") .unwrap() .raw_content .contains("☃︎")); test_site.change_file("posts/2022-01-31-test_post.markdown", "☃︎", "💩")?; assert!(test_site .find_post("2022-01-31-test_post.markdown") .unwrap() .raw_content .contains('💩')); Ok(()) } #[test] fn test_draft_content_change() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: true, } .build()?; assert!(test_site .output_content("drafts/a_draft/index.html")? .contains("My draft text")); test_site.change_file("drafts/a_draft.markdown", "My draft text", "DRAFT TEXT")?; assert!(test_site .output_content("drafts/a_draft/index.html")? .contains("DRAFT TEXT")); Ok(()) } #[test] fn test_post_title_change() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: false, } .build()?; let myseries = test_site.find_series("myseries.markdown").unwrap(); assert_eq!(myseries.posts.len(), 2); let myseries_content = test_site.output_content("series/myseries/index.html")?; assert!(myseries_content.contains("Feb post 1")); assert!(myseries_content.contains("Feb post 2")); test_site.change_file( "posts/2022-02-01-feb_post.markdown", "Feb post 1", "First series post", )?; assert!(test_site .output_content("archive/index.html")? .contains("First series post")); let myseries_content = test_site.output_content("series/myseries/index.html")?; assert!(!myseries_content.contains("Feb post 1")); assert!(myseries_content.contains("First series post")); assert!(myseries_content.contains("Feb post 2")); Ok(()) } #[test] fn test_series_title_change() -> Result<()> { let mut test_site = TestSiteBuilder { include_drafts: true, } .build()?; assert!(test_site .output_content("series/index.html")? .contains("My series")); assert!(test_site .output_content("blog/2022/02/01/feb_post/index.html")? .contains("My series")); assert!(test_site .output_content("blog/2022/02/02/feb_post2/index.html")? .contains("My series")); test_site.change_file("series/myseries.markdown", "My series", "New series title")?; assert!(test_site .output_content("series/index.html")? .contains("New series title")); assert!(test_site .output_content("blog/2022/02/01/feb_post/index.html")? .contains("New series title")); assert!(test_site .output_content("blog/2022/02/02/feb_post2/index.html")? .contains("New series title")); Ok(()) } fn check_files<'a>( files: &'a ParsedFiles, output_dir: &Utf8Path, ) -> HashMap<Utf8PathBuf, Vec<GeneratedFileError<'a>>> { files .values() .filter_map(|file| { let errors = check_file(file, files, output_dir); if errors.is_empty() { None } else { Some((file.path.clone(), errors)) } }) .collect() } }
use std::process::Child; use crate::units::Second; pub mod wallclocktimer; #[cfg(windows)] mod windows_timer; #[cfg(windows)] pub use self::windows_timer::get_cpu_timer; #[cfg(not(windows))] mod unix_timer; #[cfg(not(windows))] pub use self::unix_timer::get_cpu_timer; /// Defines start functionality of a timer. pub trait TimerStart { fn start() -> Self; fn start_for_process(process: &Child) -> Self; } /// Defines stop functionality of a timer. pub trait TimerStop { type Result; fn stop(&self) -> Self::Result; } #[derive(Debug, Copy, Clone)] pub struct CPUTimes { /// Total amount of time spent executing in user mode pub user_usec: i64, /// Total amount of time spent executing in kernel mode pub system_usec: i64, } #[derive(Debug, Copy, Clone)] pub struct CPUInterval { /// Total amount of time spent executing in user mode pub user: Second, /// Total amount of time spent executing in kernel mode pub system: Second, }
// Iterator trait: https://doc.rust-lang.org/std/iter/trait.Iterator.html // General information, including how to implement an iterator: https://doc.rust-lang.org/std/iter/index.html fn main() { } #[test] fn consuming() { let v1 = vec![1, 2, 3]; let v1_iter = v1.iter(); // this consumes // `sum` takes ownership of the iterator; "consumes" it // because it repeatedly calls "next" on it. The consumed // iterator cannot be used afterwards, because `sum` // "swallowed" it (took ownership, didn't return it) // TO_GROK: why can't the type be inferred ? let total: i32 = v1_iter.sum(); assert_eq!(total, 6); } #[test] fn iterator_adaptors() { let v1 = vec![1, 2, 3]; // iterators are lazy; this will not do anything: v1.iter().map(|x| x + 1); // one way of actually invoking the iterator is `collect`: // TO_GROK: again, type not inferred, ugly... // https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.collect let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); assert_eq!(v2, vec![2, 3, 4]); }
pub struct SQLParser {} impl SQLParser { pub fn new() -> SQLParser { let sm = SQLParser {}; sm } }
pub mod hittable; pub mod material; pub mod sphere;
extern crate chrono; mod settings; use structopt::StructOpt; use sustl::sustenance::*; use sustl::sustenance_type::*; use toduitl::journal::Journal; use std::str::FromStr; use settings::*; #[derive(StructOpt)] struct Cli { #[structopt(subcommand)] action: Action, } #[derive(StructOpt)] enum Action { Create { food_name: String, sustenance_type: String, quantity: i32, }, AddJournal, } fn main() { let args = Cli::from_args(); Settings::new(); match args.action { Action::Create { food_name, sustenance_type, quantity, } => { let stype = SustenanceType::from_str(&sustenance_type).unwrap(); let sustenance = Sustenance::new(&food_name, stype, quantity as f32); sustenance.save().expect("unable to save sustenance"); }, Action::AddJournal => { let journal_file = Journal::new("current", "journal").expect("could not create journal"); let relative_path = settings::get_relative_health_journal_folder(); journal_file.add_link_to_journal(&"Health Journal".to_string(), &relative_path) .expect("could not add health journal to journal"); } } }
use crate::headers; use azure_core::AddAsHeader; use http::request::Builder; /// A collection of keys to partition on /// /// You can learn more about partitioning [here](https://docs.microsoft.com/en-us/azure/cosmos-db/partitioning-overview) pub type PartitionKeys = crate::to_json_vector::ToJsonVector; impl AddAsHeader for &'_ PartitionKeys { fn add_as_header(&self, builder: Builder) -> Builder { headers::add_partition_keys_header(self, builder) } }
/// Replicates the Fn traits for stable build pub trait StableFnOnce<Input> { type Output; fn stable_call_once(self,args:Input) -> Self::Output; } /// Replicates the Fn traits for stable build pub trait StableFnMut<Input>: StableFnOnce<Input> { fn stable_call_mut(&mut self,args:Input) -> Self::Output; } /// Replicates the Fn traits for stable build pub trait StableFn<Input>:StableFnMut<Input> { fn stable_call(&self,args:Input) -> Self::Output; } pub fn as_cloning_stable_fn<Input,Output>(f: impl StableFnOnce<Input,Output=Output> + Clone) -> impl StableFn<Input,Output=Output> { struct Wrapper<T>(T); impl<Input,Output,T> StableFnOnce<Input> for Wrapper<T> where T: StableFnOnce<Input,Output=Output> { type Output = Output; fn stable_call_once(self, args:Input) -> Output { let Wrapper(t) = self; t.stable_call_once(args) } } impl<Input,Output,T> StableFnMut<Input> for Wrapper<T> where T: StableFnOnce<Input,Output=Output> + Clone { fn stable_call_mut(&mut self, args:Input) -> Output { let Wrapper(t) = self; t.clone().stable_call_once(args) } } impl<Input,Output,T> StableFn<Input> for Wrapper<T> where T: StableFnOnce<Input,Output=Output> + Clone { fn stable_call(&self, args:Input) -> Output { let Wrapper(t) = self; t.clone().stable_call_once(args) } } Wrapper(f) } #[cfg(feature="nightly")] pub fn as_cloning_fn<Input,Output>(f: impl FnOnce<Input,Output=Output> + Clone) -> impl Fn<Input,Output=Output> { struct Wrapper<T>(T); impl<Input,Output,T> FnOnce<Input> for Wrapper<T> where T: FnOnce<Input,Output=Output> { type Output = Output; extern "rust-call" fn call_once(self, args:Input) -> Output { let Wrapper(t) = self; t.call_once(args) } } impl<Input,Output,T> FnMut<Input> for Wrapper<T> where T: FnOnce<Input,Output=Output> + Clone { extern "rust-call" fn call_mut(&mut self, args:Input) -> Output { let Wrapper(t) = self; t.clone().call_once(args) } } impl<Input,Output,T> StableFn<Input> for Wrapper<T> where T: StableFnOnce<Input,Output=Output> + Clone { extern "rust-call" fn call(&self, args:Input) -> Output { let Wrapper(t) = self; t.clone().call_once(args) } } Wrapper(f) }
use std::path::Path; use protobuf::stream::CodedInputStream; use misc::*; use zbackup::data::*; use zbackup::disk_format::*; use zbackup::disk_format::protobuf_types as raw; pub struct DiskBackupInfo { raw: raw::BackupInfo, } impl DiskBackupInfo { pub fn read ( coded_input_stream: & mut CodedInputStream, ) -> Result <DiskBackupInfo, String> { Ok (DiskBackupInfo { raw: protobuf_message_read ( coded_input_stream, || format! ( "backup info"), ) ?, }) } pub fn sha256 (& self) -> [u8; 32] { to_array_32 (self.raw.get_sha256 ()) } pub fn backup_data (& self) -> & [u8] { & self.raw.get_backup_data () } pub fn iterations (& self) -> u32 { self.raw.get_iterations () } } #[ inline ] pub fn backup_read_path < BackupPath: AsRef <Path>, > ( backup_path: BackupPath, encryption_key: Option <EncryptionKey>, ) -> Result <DiskBackupInfo, String> { backup_read_path_impl ( backup_path.as_ref (), encryption_key, ) } pub fn backup_read_path_impl ( backup_path: & Path, encryption_key: Option <[u8; KEY_SIZE]>, ) -> Result <DiskBackupInfo, String> { let backup_info: DiskBackupInfo; // open file let mut source = io_result_with_prefix ( || format! ( "Error reading {}: ", backup_path.to_string_lossy ()), file_open_with_crypto_and_adler ( backup_path, encryption_key), ) ?; { let mut coded_input_stream = CodedInputStream::from_buffered_reader ( & mut source); // read file header let file_header: DiskFileHeader = DiskFileHeader::read ( & mut coded_input_stream, ) ?; if file_header.version () != 1 { panic! ( "Unsupported backup version {}", file_header.version ()); } // read backup info backup_info = DiskBackupInfo::read ( & mut coded_input_stream, ) ?; } // verify checksum adler_verify_hash_and_eof ( || format! ( "Error reading {}: ", backup_path.to_string_lossy ()), source, ) ?; // return Ok (backup_info) } // ex: noet ts=4 filetype=rust
#![allow(dead_code)] use std::marker::PhantomData; use expr::*; use fun::*; use symbol::*; pub struct Nil{} impl Expr for Nil { fn to_string() -> String { "nil".to_string() } } pub struct ConsCell<T1: Expr, T2: Expr> { p1: PhantomData<T1>, p2: PhantomData<T2>, } impl <T1: Expr, T2: Expr> Expr for ConsCell<T1, T2>{ fn to_string() -> String { format!("({} . {})", T1::to_string(), T2::to_string()) } } #[macro_export] macro_rules! list { () => { $crate::cons::Nil }; (,) => { $crate::cons::Nil }; (, $t: ty $(, $tys: ty)*) => { $crate::cons::ConsCell<$t , list!($(, $tys)*)> }; ($t: ty $(, $tys: ty)*) => { $crate::cons::ConsCell<$t , list!($(, $tys)*)> }; } pub type Cons = symbol!(C O N S); pub type Car = symbol!(C A R); pub type Cdr = symbol!(C D R); impl <T1: Expr, T2: Expr> Fun2<T1, T2> for Cons { type Out = ConsCell<T1, T2>; } impl <T1: Expr, T2: Expr> Fun1<ConsCell<T1, T2>> for Car { type Out = T1; } impl <T1: Expr, T2: Expr> Fun1<ConsCell<T1, T2>> for Cdr { type Out = T2; }
use crate::hash; use anyhow::{anyhow, Result}; use serde::{Deserialize, Serialize}; use std::env; use sysinfo::{CpuExt, System, SystemExt}; /// Describes a fingerprinted system. /// /// ``` /// # use sightglass_fingerprint::Machine; /// println!("Current machine fingerprint: {:?}", Machine::fingerprint()); /// ``` #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct Machine { /// A unique identifier hashed from all other properties. pub id: String, /// The host name of the machine. pub name: String, /// The long version of the system OS; e.g., Linux 35 Fedora Linux. pub os: String, /// The system's kernel version; e.g., 5.15.14 pub kernel: String, /// The system's CPU architecture. pub arch: String, /// The CPU brand string; e.g., like `lscpu`'s model name. pub cpu: String, /// The amount of system memory in a human-readable string; e.g. 4 GiB. pub memory: String, } impl Machine { /// Detect system information for the currently machine running Sightglass. pub fn fingerprint() -> Result<Self> { // Gather the host name. let name = hostname::get() .expect("must be able to detect the system hostname") .to_string_lossy() .to_string(); // Gather the OS information. let mut sys = System::new(); let os = sys .long_os_version() .ok_or(anyhow!("must be able to detect the system OS"))?; let kernel = sys .kernel_version() .ok_or(anyhow!("must be able to detect the system kernel version"))?; // Gather some CPU information. let arch = std::env::consts::ARCH.to_string(); sys.refresh_cpu(); let cpu = sys.global_cpu_info().brand().to_string(); // Gather the memory information. The expected result should be in GiB (the 1024-base SI // measurement commonly used for memory) but it is unclear whether `sysinfo` is returning KB // or KiB. sys.refresh_memory(); let memory_total_kb = sys.total_memory(); let memory = bytesize::to_string(bytesize::ByteSize::kib(memory_total_kb).0, true); // Hash all properties into a unique identifier. let hash = hash::string(&format!( "{}\n{}\n{}\n{}\n{}\n{}", name, arch, os, kernel, cpu, memory )); let id = format!( "{}-{}-{}", env::consts::ARCH, env::consts::OS, hash::slug(&hash) ); Ok(Self { id, name, arch, os, kernel, cpu, memory, }) } }
#[cfg(test)] mod file_tests { #[test] fn it_counts_points_in_file() { laszip::load_laszip_library(); let laz = laszip::LazReader::from_file("../data/building.laz"); assert_eq!(1473, laz.unwrap().get_number_of_points().unwrap()); } }
#[macro_use] extern crate diesel; #[macro_use] extern crate serde_derive; extern crate actix; extern crate actix_web; extern crate chrono; extern crate dotenv; extern crate env_logger; extern crate futures; extern crate num_cpus; extern crate rand; extern crate serde; extern crate serde_json; use actix::*; use actix_web::{http::{header, Method}, middleware, middleware::cors::Cors, server, App}; use diesel::prelude::PgConnection; use diesel::r2d2::{ConnectionManager, Pool}; mod controller; mod db; mod model; mod schema; mod view; mod ws_server; use controller::person::{person_list, ws}; use db::ConnDsl; use ws_server::WsServer; pub struct AppState { db: Addr<Syn, ConnDsl>, ws: Addr<Syn, WsServer>, } fn main() { ::std::env::set_var("RUST_LOG", "actix_web=debug"); ::std::env::set_var("RUST_BACKTRACE", "1"); env_logger::init(); let sys = actix::System::new("vote"); let db_url = dotenv::var("DATABASE_URL").expect("DATABASE_URL must be set"); let manager = ConnectionManager::<PgConnection>::new(db_url); let conn = Pool::builder() .build(manager) .expect("failed to create pool."); let addr = SyncArbiter::start(num_cpus::get() * 4, move || ConnDsl(conn.clone())); let _ws = Arbiter::start(|_| ws_server::WsServer::default()); server::new(move || { App::with_state(AppState { db: addr.clone(), ws: _ws.clone(), }).middleware(middleware::Logger::default()) .configure(|app| { Cors::for_app(app) .allowed_methods(vec!["GET", "POST"]) .allowed_header(header::CONTENT_TYPE) .max_age(3600) .resource("/api/person/list", |r| { r.method(Method::GET).with(person_list) }) //.resource("/api/person/update", |r| { r.method(Method::POST).with2(person_update) }) .resource("/person/ws", |r| r.route().f(ws)) .register() }) }).bind("0.0.0.0:8080") .unwrap() .shutdown_timeout(2) .start(); sys.run(); }
use crate::metrics::MixMetric; use reqwest::Response; pub struct Request { base_url: String, path: String, } pub trait MetricsMixPoster { fn new(base_url: String) -> Self; fn post(&self, metric: &MixMetric) -> Result<Response, reqwest::Error>; } impl MetricsMixPoster for Request { fn new(base_url: String) -> Self { Request { base_url, path: "/api/metrics/mixes".to_string(), } } fn post(&self, metric: &MixMetric) -> Result<Response, reqwest::Error> { let url = format!("{}{}", self.base_url, self.path); let client = reqwest::Client::new(); let mix_metric_vec = client.post(&url).json(&metric).send()?; Ok(mix_metric_vec) } } #[cfg(test)] mod metrics_get_request { use super::*; #[cfg(test)] use mockito::mock; #[cfg(test)] mod on_a_400_status { use super::*; #[test] fn it_returns_an_error() { let _m = mock("POST", "/api/metrics/mixes").with_status(400).create(); let req = Request::new(mockito::server_url()); let metric = fixtures::new_metric(); let result = req.post(&metric); assert_eq!(400, result.unwrap().status()); _m.assert(); } } #[cfg(test)] mod on_a_200 { use super::*; #[test] fn it_returns_a_response_with_200() { let json = fixtures::mix_metrics_response_json(); let _m = mock("POST", "/api/metrics/mixes") .with_status(201) .with_body(json) .create(); let req = Request::new(mockito::server_url()); let metric = fixtures::new_metric(); let result = req.post(&metric); assert_eq!(true, result.is_ok()); _m.assert(); } } #[cfg(test)] mod fixtures { use crate::metrics::MixMetric; pub fn new_metric() -> MixMetric { MixMetric { pub_key: "abc".to_string(), received: 666, sent: Default::default(), } } #[cfg(test)] pub fn mix_metrics_response_json() -> String { r#" { "pubKey": "OwOqwWjh_IlnaWS2PxO6odnhNahOYpRCkju50beQCTA=", "sent": { "35.178.213.77:1789": 1, "52.56.99.196:1789": 2 }, "received": 10, "timestamp": 1576061080635800000 } "# .to_string() } } }
//! MetroBus route related enum and methods. use crate::{ bus::{client::responses, traits::NeedsRoute}, date::Date, error::Error, location::RadiusAtLatLong, requests::Fetch, }; use serde::{ de::{Deserializer, Error as SerdeError}, Deserialize, }; use std::{error, fmt, str::FromStr}; /// All MetroBus routes. /// # Note /// Some routes' name begins with a number (i.e. 10A). This is not allowed /// by Rust naming conventions. As a fix, the first number of the route /// has been replaced by a word. So, `10A` => `One0A`. This is unfortunate. #[derive(Debug, Copy, Clone, PartialEq)] pub enum Route { One0A, One0B, One0E, One0N, One1Y, One1Yv1, One1Yv2, One5K, One5Kv1, One6A, One6C, One6Cv1, One6E, One6G, One6Gv1, One6H, One6L, One6Y, One6Yv1, One7B, One7G, One7H, One7K, One7L, One7M, One8G, One8H, One8J, One8P, One8Pv1, One8Pv2, OneA, OneB, OneC, OneCv1, OneCv2, OneCv3, OneCv4, Two1A, Two1D, Two2A, Two2Av1, Two2C, Two2F, Two3A, Two3B, Two3Bv1, Two3T, Two5B, Two5Bv1, Two5Bv2, Two5Bv3, Two6A, Two8A, Two8Av1, Two8F, Two8G, Two9C, Two9G, Two9K, Two9Kv1, Two9N, Two9Nv1, Two9W, TwoA, TwoB, TwoBv1, TwoBv2, TwoBv3, Three0N, Three0S, Three1, Three2, Three2v1, Three3, Three4, Three6, Three7, Three8B, Three8Bv1, Three8Bv2, Three9, ThreeA, ThreeAv1, ThreeT, ThreeTv1, ThreeY, Four2, Four3, FourA, FourB, Five2, Five2v1, Five2v2, Five4, Five4v1, Five4v2, Five4v3, Five9, FiveA, Six0, Six2, Six2v1, Six3, Six4, Six4v1, Seven0, Seven0v1, Seven4, Seven9, SevenA, SevenAv1, SevenAv2, SevenAv3, SevenC, SevenF, SevenFv1, SevenM, SevenMv1, SevenP, SevenW, SevenY, SevenYv1, Eight0, Eight0v1, Eight0v2, Eight0v3, Eight3, Eight3v1, Eight3v2, Eight3v3, Eight3v4, Eight6, Eight6v1, Eight6v2, Eight7, Eight7v1, Eight7v2, Eight7v3, Eight7v4, Eight7v5, Eight9, Eight9v1, Eight9M, EightS, EightW, EightZ, Nine0, Nine0v1, Nine0v2, Nine2, Nine2v1, Nine2v2, Nine6, Nine6v1, Nine6v2, Nine6v3, Nine6v4, Nine6v5, Nine7, Nine7v1, A12, A12v1, A12v2, A12v3, A2, A2v1, A2v2, A2v3, A31, A32, A33, A4, A4v1, A4v2, A4v3, A4v4, A4v5, A6, A6v1, A7, A8, A8v1, A9, B2, B2v1, B2v2, B2v3, B2v4, B21, B22, B22v1, B24, B24v1, B27, B29, B29v1, B29v2, B30, B8, B8v1, B8v2, B9, B98, B99, C11, C12, C13, C14, C2, C2v1, C2v2, C2v3, C21, C21v1, C21v2, C22, C22v1, C26, C26v1, C28, C28v1, C29, C29_1, C29_2, C29_4, C290, C4, C4v1, C4v2, C4v3, C8, C8v1, C8v2, C8v3, D1, D12, D12v1, D12v2, D13, D13v1, D14, D14v1, D14v2, D2, D2v1, D31, D32, D33, D34, D4, D4v1, D4v2, D5, D51, D6, D6v1, D6v2, D6v3, D8, D8v1, E2, E4, E4v1, E4v2, E6, F1, F12, F12v1, F13, F13v1, F13v2, F13v3, F14, F14v1, F2, F2v1, F2v2, F4, F4v1, F4v2, F6, F6v1, F6v2, F8, F99, G12, G12v1, G12v2, G14, G14v1, G14v2, G2, G2v1, G8, G8v1, G8v2, G8v3, G9, G9v1, H1, H11, H12, H12v1, H13, H2, H3, H4, H4v1, H6, H6v1, H8, H9, J1, J1v1, J12, J12v1, J2, J2v1, J2v2, J4, K12, K12v1, K12v2, K2, K6, K6v1, K9, K9v1, L1, L2, L2v1, L2v2, L99, L8, M4, M4v1, M4v2, M6, M6v1, MW1, M99, N2, N4, N4v1, N6, NH1, NH2, P12, P12v1, P12v2, P18, P19, P6, P6v1, P6v2, P6v3, P6v4, P99, Q1, Q2, Q2v1, Q2v2, Q4, Q4v1, Q5, Q6, Q6v1, R1, R12, R12v1, R2, R2v1, R2v2, R4, REX, REXv1, REXv2, REXv3, REXv4, S1, S2, S2v1, S35, S4, S41, S80, S80v1, S80v2, S9, S9v1, S91, S91v1, SH99, T14, T14v1, T18, T18v1, T2, U4, U4v1, U4v2, U5, U6, U6v1, U6v2, U7, U7v1, U7v2, U7v3, U7v4, V1, V12, V14, V14v1, V2, V2v1, V4, V4v1, V7, V8, W1, W14, W14v1, W14v2, W2, W2v1, W2v2, W2v3, W2v4, W2v5, W2v6, W2v7, W3, W3v1, W4, W4v1, W4v2, W45, W47, W5, W6, W6v1, W8, W8v1, W8v2, X1, X2, X2v1, X2v2, X2v3, X3, X3v1, X8, X9, X9v1, X9v2, Y2, Y7, Y8, Z11, Z11v1, Z2, Z2v1, Z2v2, Z2v3, Z6, Z6v1, Z6v2, Z7, Z7v1, Z8, Z8v1, Z8v2, Z8v3, Z8v4, Z8v5, Z8v6, } impl Route { pub fn new(s: &str) -> Result<Self, StringIsNotRouteError> { s.parse() } } impl Fetch for Route {} impl NeedsRoute for Route {} // Overwrite NeedsRoute methods impl Route { /// Bus positions for this route around a given lat/long. /// [WMATA Documentation](https://developer.wmata.com/docs/services/54763629281d83086473f231/operations/5476362a281d830c946a3d68?) /// /// # Example /// ``` /// use wmata::{Route, RadiusAtLatLong}; /// use tokio_test::block_on; /// /// let route = Route::A2; /// let positions = block_on(async { /// route.positions( /// Some(RadiusAtLatLong::new(1000, 38.8817596, -77.0166426)), /// "9e38c3eab34c4e6c990828002828f5ed" /// ).await /// }); /// /// assert!(positions.is_ok()); /// ``` pub async fn positions( self, radius_at_lat_long: Option<RadiusAtLatLong>, api_key: &str, ) -> Result<responses::BusPositions, Error> { self.positions_along(Some(self), radius_at_lat_long, api_key) .await } /// Reported bus incidents/delays for this route. /// [WMATA Documentation](https://developer.wmata.com/docs/services/54763641281d83086473f232/operations/54763641281d830c946a3d75) /// /// # Examples /// ``` /// use wmata::Route; /// use tokio_test::block_on; /// /// let incidents = block_on(async { Route::A2.incidents("9e38c3eab34c4e6c990828002828f5ed").await }); /// assert!(incidents.is_ok()); /// ``` pub async fn incidents(self, api_key: &str) -> Result<responses::Incidents, Error> { self.incidents_along(Some(self), api_key).await } /// For an optional given date, returns the set of ordered latitude/longitude /// points along this route along with the list of stops served. /// [WMATA Documentation](https://developer.wmata.com/docs/services/54763629281d83086473f231/operations/5476362a281d830c946a3d69?) /// /// # Date /// Omit date for current date /// /// # Examples /// ``` /// use wmata::Route; /// use tokio_test::block_on; /// /// let path = block_on(async { Route::A2.path(None, "9e38c3eab34c4e6c990828002828f5ed").await }); /// assert!(path.is_ok()); /// ``` /// With a date /// ``` /// use wmata::{Route, Date}; /// use tokio_test::block_on; /// /// let path = block_on(async { Route::A2.path(Some(Date::new(2019, 10, 2)), "9e38c3eab34c4e6c990828002828f5ed").await }); /// assert!(path.is_ok()); /// ``` pub async fn path( self, date: Option<Date>, api_key: &str, ) -> Result<responses::PathDetails, Error> { <Self as NeedsRoute>::path(&self, self, date, api_key).await } /// Schedules for this route for an optional given date. /// [WMATA Documentation](https://developer.wmata.com/docs/services/54763629281d83086473f231/operations/5476362a281d830c946a3d6b?) /// /// # Date /// Omit date for current date /// /// # Variations /// Whether or not to include variations if a base route is specified in Route. /// For example, if B30 is specified and IncludingVariations is set to true, /// data for all variations of B30 such as B30v1, B30v2, etc. will be returned. /// /// # Examples /// ``` /// use wmata::Route; /// use tokio_test::block_on; /// /// let schedule = block_on(async { Route::A2.schedule(None, false, "9e38c3eab34c4e6c990828002828f5ed").await }); /// assert!(schedule.is_ok()); /// ``` /// /// with date and variations /// ``` /// use wmata::{Route, Date}; /// use tokio_test::block_on; /// /// let schedule = block_on(async { Route::A2.schedule(Some(Date::new(2019, 10, 2)), true, "9e38c3eab34c4e6c990828002828f5ed").await }); /// assert!(schedule.is_ok()); /// ``` pub async fn schedule( self, date: Option<Date>, including_variations: bool, api_key: &str, ) -> Result<responses::RouteSchedule, Error> { self.route_schedule(self, date, including_variations, api_key) .await } } impl<'de> Deserialize<'de> for Route { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { let route = String::deserialize(deserializer)?; Route::from_str(&route).map_err(SerdeError::custom) } } impl ToString for Route { fn to_string(&self) -> String { match self { Route::One0A => "10A".to_string(), Route::One0B => "10B".to_string(), Route::One0E => "10E".to_string(), Route::One0N => "10N".to_string(), Route::One1Y => "11Y".to_string(), Route::One1Yv1 => "11Yv1".to_string(), Route::One1Yv2 => "11Yv2".to_string(), Route::One5K => "15K".to_string(), Route::One5Kv1 => "15Kv1".to_string(), Route::One6A => "16A".to_string(), Route::One6C => "16C".to_string(), Route::One6Cv1 => "16Cv1".to_string(), Route::One6E => "16E".to_string(), Route::One6G => "16G".to_string(), Route::One6Gv1 => "16Gv1".to_string(), Route::One6H => "16H".to_string(), Route::One6L => "16L".to_string(), Route::One6Y => "16Y".to_string(), Route::One6Yv1 => "16Yv1".to_string(), Route::One7B => "17B".to_string(), Route::One7G => "17G".to_string(), Route::One7H => "17H".to_string(), Route::One7K => "17K".to_string(), Route::One7L => "17L".to_string(), Route::One7M => "17M".to_string(), Route::One8G => "18G".to_string(), Route::One8H => "18H".to_string(), Route::One8J => "18J".to_string(), Route::One8P => "18P".to_string(), Route::One8Pv1 => "18Pv1".to_string(), Route::One8Pv2 => "18Pv2".to_string(), Route::OneA => "1A".to_string(), Route::OneB => "1B".to_string(), Route::OneC => "1C".to_string(), Route::OneCv1 => "1Cv1".to_string(), Route::OneCv2 => "1Cv2".to_string(), Route::OneCv3 => "1Cv3".to_string(), Route::OneCv4 => "1Cv4".to_string(), Route::Two1A => "21A".to_string(), Route::Two1D => "21D".to_string(), Route::Two2A => "22A".to_string(), Route::Two2Av1 => "22Av1".to_string(), Route::Two2C => "22C".to_string(), Route::Two2F => "22F".to_string(), Route::Two3A => "23A".to_string(), Route::Two3B => "23B".to_string(), Route::Two3Bv1 => "23Bv1".to_string(), Route::Two3T => "23T".to_string(), Route::Two5B => "25B".to_string(), Route::Two5Bv1 => "25Bv1".to_string(), Route::Two5Bv2 => "25Bv2".to_string(), Route::Two5Bv3 => "25Bv3".to_string(), Route::Two6A => "26A".to_string(), Route::Two8A => "28A".to_string(), Route::Two8Av1 => "28Av1".to_string(), Route::Two8F => "28F".to_string(), Route::Two8G => "28G".to_string(), Route::Two9C => "29C".to_string(), Route::Two9G => "29G".to_string(), Route::Two9K => "29K".to_string(), Route::Two9Kv1 => "29Kv1".to_string(), Route::Two9N => "29N".to_string(), Route::Two9Nv1 => "29Nv1".to_string(), Route::Two9W => "29W".to_string(), Route::TwoA => "2A".to_string(), Route::TwoB => "2B".to_string(), Route::TwoBv1 => "2Bv1".to_string(), Route::TwoBv2 => "2Bv2".to_string(), Route::TwoBv3 => "2Bv3".to_string(), Route::Three0N => "30N".to_string(), Route::Three0S => "30S".to_string(), Route::Three1 => "31".to_string(), Route::Three2 => "32".to_string(), Route::Three2v1 => "32v1".to_string(), Route::Three3 => "33".to_string(), Route::Three4 => "34".to_string(), Route::Three6 => "36".to_string(), Route::Three7 => "37".to_string(), Route::Three8B => "38B".to_string(), Route::Three8Bv1 => "38Bv1".to_string(), Route::Three8Bv2 => "38Bv2".to_string(), Route::Three9 => "39".to_string(), Route::ThreeA => "3A".to_string(), Route::ThreeAv1 => "3Av1".to_string(), Route::ThreeT => "3T".to_string(), Route::ThreeTv1 => "3Tv1".to_string(), Route::ThreeY => "3Y".to_string(), Route::Four2 => "42".to_string(), Route::Four3 => "43".to_string(), Route::FourA => "4A".to_string(), Route::FourB => "4B".to_string(), Route::Five2 => "52".to_string(), Route::Five2v1 => "52v1".to_string(), Route::Five2v2 => "52v2".to_string(), Route::Five4 => "54".to_string(), Route::Five4v1 => "54v1".to_string(), Route::Five4v2 => "54v2".to_string(), Route::Five4v3 => "54v3".to_string(), Route::Five9 => "59".to_string(), Route::FiveA => "5A".to_string(), Route::Six0 => "60".to_string(), Route::Six2 => "62".to_string(), Route::Six2v1 => "62v1".to_string(), Route::Six3 => "63".to_string(), Route::Six4 => "64".to_string(), Route::Six4v1 => "64v1".to_string(), Route::Seven0 => "70".to_string(), Route::Seven0v1 => "70v1".to_string(), Route::Seven4 => "74".to_string(), Route::Seven9 => "79".to_string(), Route::SevenA => "7A".to_string(), Route::SevenAv1 => "7Av1".to_string(), Route::SevenAv2 => "7Av2".to_string(), Route::SevenAv3 => "7Av3".to_string(), Route::SevenC => "7C".to_string(), Route::SevenF => "7F".to_string(), Route::SevenFv1 => "7Fv1".to_string(), Route::SevenM => "7M".to_string(), Route::SevenMv1 => "7Mv1".to_string(), Route::SevenP => "7P".to_string(), Route::SevenW => "7W".to_string(), Route::SevenY => "7Y".to_string(), Route::SevenYv1 => "7Yv1".to_string(), Route::Eight0 => "80".to_string(), Route::Eight0v1 => "80v1".to_string(), Route::Eight0v2 => "80v2".to_string(), Route::Eight0v3 => "80v3".to_string(), Route::Eight3 => "83".to_string(), Route::Eight3v1 => "83v1".to_string(), Route::Eight3v2 => "83v2".to_string(), Route::Eight3v3 => "83v3".to_string(), Route::Eight3v4 => "83v4".to_string(), Route::Eight6 => "86".to_string(), Route::Eight6v1 => "86v1".to_string(), Route::Eight6v2 => "86v2".to_string(), Route::Eight7 => "87".to_string(), Route::Eight7v1 => "87v1".to_string(), Route::Eight7v2 => "87v2".to_string(), Route::Eight7v3 => "87v3".to_string(), Route::Eight7v4 => "87v4".to_string(), Route::Eight7v5 => "87v5".to_string(), Route::Eight9 => "89".to_string(), Route::Eight9v1 => "89v1".to_string(), Route::Eight9M => "89M".to_string(), Route::EightS => "8S".to_string(), Route::EightW => "8W".to_string(), Route::EightZ => "8Z".to_string(), Route::Nine0 => "90".to_string(), Route::Nine0v1 => "90v1".to_string(), Route::Nine0v2 => "90v2".to_string(), Route::Nine2 => "92".to_string(), Route::Nine2v1 => "92v1".to_string(), Route::Nine2v2 => "92v2".to_string(), Route::Nine6 => "96".to_string(), Route::Nine6v1 => "96v1".to_string(), Route::Nine6v2 => "96v2".to_string(), Route::Nine6v3 => "96v3".to_string(), Route::Nine6v4 => "96v4".to_string(), Route::Nine6v5 => "96v5".to_string(), Route::Nine7 => "97".to_string(), Route::Nine7v1 => "97v1".to_string(), Route::A12 => "A12".to_string(), Route::A12v1 => "A12v1".to_string(), Route::A12v2 => "A12v2".to_string(), Route::A12v3 => "A12v3".to_string(), Route::A2 => "A2".to_string(), Route::A2v1 => "A2v1".to_string(), Route::A2v2 => "A2v2".to_string(), Route::A2v3 => "A2v3".to_string(), Route::A31 => "A31".to_string(), Route::A32 => "A32".to_string(), Route::A33 => "A33".to_string(), Route::A4 => "A4".to_string(), Route::A4v1 => "A4v1".to_string(), Route::A4v2 => "A4v2".to_string(), Route::A4v3 => "A4v3".to_string(), Route::A4v4 => "A4v4".to_string(), Route::A4v5 => "A4v5".to_string(), Route::A6 => "A6".to_string(), Route::A6v1 => "A6v1".to_string(), Route::A7 => "A7".to_string(), Route::A8 => "A8".to_string(), Route::A8v1 => "A8v1".to_string(), Route::A9 => "A9".to_string(), Route::B2 => "B2".to_string(), Route::B2v1 => "B2v1".to_string(), Route::B2v2 => "B2v2".to_string(), Route::B2v3 => "B2v3".to_string(), Route::B2v4 => "B2v4".to_string(), Route::B21 => "B21".to_string(), Route::B22 => "B22".to_string(), Route::B22v1 => "B22v1".to_string(), Route::B24 => "B24".to_string(), Route::B24v1 => "B24v1".to_string(), Route::B27 => "B27".to_string(), Route::B29 => "B29".to_string(), Route::B29v1 => "B29v1".to_string(), Route::B29v2 => "B29v2".to_string(), Route::B30 => "B30".to_string(), Route::B8 => "B8".to_string(), Route::B8v1 => "B8v1".to_string(), Route::B8v2 => "B8v2".to_string(), Route::B9 => "B9".to_string(), Route::B98 => "B98".to_string(), Route::B99 => "B99".to_string(), Route::C11 => "C11".to_string(), Route::C12 => "C12".to_string(), Route::C13 => "C13".to_string(), Route::C14 => "C14".to_string(), Route::C2 => "C2".to_string(), Route::C2v1 => "C2v1".to_string(), Route::C2v2 => "C2v2".to_string(), Route::C2v3 => "C2v3".to_string(), Route::C21 => "C21".to_string(), Route::C21v1 => "C21v1".to_string(), Route::C21v2 => "C21v2".to_string(), Route::C22 => "C22".to_string(), Route::C22v1 => "C22v1".to_string(), Route::C26 => "C26".to_string(), Route::C26v1 => "C26v1".to_string(), Route::C28 => "C28".to_string(), Route::C28v1 => "C28v1".to_string(), Route::C29 => "C29".to_string(), Route::C29_1 => "C29*1".to_string(), Route::C29_2 => "C29*2".to_string(), Route::C29_4 => "C29*4".to_string(), Route::C290 => "C29/".to_string(), Route::C4 => "C4".to_string(), Route::C4v1 => "C4v1".to_string(), Route::C4v2 => "C4v2".to_string(), Route::C4v3 => "C4v3".to_string(), Route::C8 => "C8".to_string(), Route::C8v1 => "C8v1".to_string(), Route::C8v2 => "C8v2".to_string(), Route::C8v3 => "C8v3".to_string(), Route::D1 => "D1".to_string(), Route::D12 => "D12".to_string(), Route::D12v1 => "D12v1".to_string(), Route::D12v2 => "D12v2".to_string(), Route::D13 => "D13".to_string(), Route::D13v1 => "D13v1".to_string(), Route::D14 => "D14".to_string(), Route::D14v1 => "D14v1".to_string(), Route::D14v2 => "D14v2".to_string(), Route::D2 => "D2".to_string(), Route::D2v1 => "D2v1".to_string(), Route::D31 => "D31".to_string(), Route::D32 => "D32".to_string(), Route::D33 => "D33".to_string(), Route::D34 => "D34".to_string(), Route::D4 => "D4".to_string(), Route::D4v1 => "D4v1".to_string(), Route::D4v2 => "D4v2".to_string(), Route::D5 => "D5".to_string(), Route::D51 => "D51".to_string(), Route::D6 => "D6".to_string(), Route::D6v1 => "D6v1".to_string(), Route::D6v2 => "D6v2".to_string(), Route::D6v3 => "D6v3".to_string(), Route::D8 => "D8".to_string(), Route::D8v1 => "D8v1".to_string(), Route::E2 => "E2".to_string(), Route::E4 => "E4".to_string(), Route::E4v1 => "E4v1".to_string(), Route::E4v2 => "E4v2".to_string(), Route::E6 => "E6".to_string(), Route::F1 => "F1".to_string(), Route::F12 => "F12".to_string(), Route::F12v1 => "F12v1".to_string(), Route::F13 => "F13".to_string(), Route::F13v1 => "F13v1".to_string(), Route::F13v2 => "F13v2".to_string(), Route::F13v3 => "F13v3".to_string(), Route::F14 => "F14".to_string(), Route::F14v1 => "F14v1".to_string(), Route::F2 => "F2".to_string(), Route::F2v1 => "F2v1".to_string(), Route::F2v2 => "F2v2".to_string(), Route::F4 => "F4".to_string(), Route::F4v1 => "F4v1".to_string(), Route::F4v2 => "F4v2".to_string(), Route::F6 => "F6".to_string(), Route::F6v1 => "F6v1".to_string(), Route::F6v2 => "F6v2".to_string(), Route::F8 => "F8".to_string(), Route::F99 => "F99".to_string(), Route::G12 => "G12".to_string(), Route::G12v1 => "G12v1".to_string(), Route::G12v2 => "G12v2".to_string(), Route::G14 => "G14".to_string(), Route::G14v1 => "G14v1".to_string(), Route::G14v2 => "G14v2".to_string(), Route::G2 => "G2".to_string(), Route::G2v1 => "G2v1".to_string(), Route::G8 => "G8".to_string(), Route::G8v1 => "G8v1".to_string(), Route::G8v2 => "G8v2".to_string(), Route::G8v3 => "G8v3".to_string(), Route::G9 => "G9".to_string(), Route::G9v1 => "G9v1".to_string(), Route::H1 => "H1".to_string(), Route::H11 => "H11".to_string(), Route::H12 => "H12".to_string(), Route::H12v1 => "H12v1".to_string(), Route::H13 => "H13".to_string(), Route::H2 => "H2".to_string(), Route::H3 => "H3".to_string(), Route::H4 => "H4".to_string(), Route::H4v1 => "H4v1".to_string(), Route::H6 => "H6".to_string(), Route::H6v1 => "H6v1".to_string(), Route::H8 => "H8".to_string(), Route::H9 => "H9".to_string(), Route::J1 => "J1".to_string(), Route::J1v1 => "J1v1".to_string(), Route::J12 => "J12".to_string(), Route::J12v1 => "J12v1".to_string(), Route::J2 => "J2".to_string(), Route::J2v1 => "J2v1".to_string(), Route::J2v2 => "J2v2".to_string(), Route::J4 => "J4".to_string(), Route::K12 => "K12".to_string(), Route::K12v1 => "K12v1".to_string(), Route::K12v2 => "K12v2".to_string(), Route::K2 => "K2".to_string(), Route::K6 => "K6".to_string(), Route::K6v1 => "K6v1".to_string(), Route::K9 => "K9".to_string(), Route::K9v1 => "K9v1".to_string(), Route::L1 => "L1".to_string(), Route::L2 => "L2".to_string(), Route::L2v1 => "L2v1".to_string(), Route::L2v2 => "L2v2".to_string(), Route::L99 => "L99".to_string(), Route::L8 => "L8".to_string(), Route::M4 => "M4".to_string(), Route::M4v1 => "M4v1".to_string(), Route::M4v2 => "M4v2".to_string(), Route::M6 => "M6".to_string(), Route::M6v1 => "M6v1".to_string(), Route::MW1 => "MW1".to_string(), Route::M99 => "M99".to_string(), Route::N2 => "N2".to_string(), Route::N4 => "N4".to_string(), Route::N4v1 => "N4v1".to_string(), Route::N6 => "N6".to_string(), Route::NH1 => "NH1".to_string(), Route::NH2 => "NH2".to_string(), Route::P12 => "P12".to_string(), Route::P12v1 => "P12v1".to_string(), Route::P12v2 => "P12v2".to_string(), Route::P18 => "P18".to_string(), Route::P19 => "P19".to_string(), Route::P6 => "P6".to_string(), Route::P6v1 => "P6v1".to_string(), Route::P6v2 => "P6v2".to_string(), Route::P6v3 => "P6v3".to_string(), Route::P6v4 => "P6v4".to_string(), Route::P99 => "P99".to_string(), Route::Q1 => "Q1".to_string(), Route::Q2 => "Q2".to_string(), Route::Q2v1 => "Q2v1".to_string(), Route::Q2v2 => "Q2v2".to_string(), Route::Q4 => "Q4".to_string(), Route::Q4v1 => "Q4v1".to_string(), Route::Q5 => "Q5".to_string(), Route::Q6 => "Q6".to_string(), Route::Q6v1 => "Q6v1".to_string(), Route::R1 => "R1".to_string(), Route::R12 => "R12".to_string(), Route::R12v1 => "R12v1".to_string(), Route::R2 => "R2".to_string(), Route::R2v1 => "R2v1".to_string(), Route::R2v2 => "R2v2".to_string(), Route::R4 => "R4".to_string(), Route::REX => "REX".to_string(), Route::REXv1 => "REXv1".to_string(), Route::REXv2 => "REXv2".to_string(), Route::REXv3 => "REXv3".to_string(), Route::REXv4 => "REXv4".to_string(), Route::S1 => "S1".to_string(), Route::S2 => "S2".to_string(), Route::S2v1 => "S2v1".to_string(), Route::S35 => "S35".to_string(), Route::S4 => "S4".to_string(), Route::S41 => "S41".to_string(), Route::S80 => "S80".to_string(), Route::S80v1 => "S80v1".to_string(), Route::S80v2 => "S80v2".to_string(), Route::S9 => "S9".to_string(), Route::S9v1 => "S9v1".to_string(), Route::S91 => "S91".to_string(), Route::S91v1 => "S91v1".to_string(), Route::SH99 => "SH99".to_string(), Route::T14 => "T14".to_string(), Route::T14v1 => "T14v1".to_string(), Route::T18 => "T18".to_string(), Route::T18v1 => "T18v1".to_string(), Route::T2 => "T2".to_string(), Route::U4 => "U4".to_string(), Route::U4v1 => "U4v1".to_string(), Route::U4v2 => "U4v2".to_string(), Route::U5 => "U5".to_string(), Route::U6 => "U6".to_string(), Route::U6v1 => "U6v1".to_string(), Route::U6v2 => "U6v2".to_string(), Route::U7 => "U7".to_string(), Route::U7v1 => "U7v1".to_string(), Route::U7v2 => "U7v2".to_string(), Route::U7v3 => "U7v3".to_string(), Route::U7v4 => "U7v4".to_string(), Route::V1 => "V1".to_string(), Route::V12 => "V12".to_string(), Route::V14 => "V14".to_string(), Route::V14v1 => "V14v1".to_string(), Route::V2 => "V2".to_string(), Route::V2v1 => "V2v1".to_string(), Route::V4 => "V4".to_string(), Route::V4v1 => "V4v1".to_string(), Route::V7 => "V7".to_string(), Route::V8 => "V8".to_string(), Route::W1 => "W1".to_string(), Route::W14 => "W14".to_string(), Route::W14v1 => "W14v1".to_string(), Route::W14v2 => "W14v2".to_string(), Route::W2 => "W2".to_string(), Route::W2v1 => "W2v1".to_string(), Route::W2v2 => "W2v2".to_string(), Route::W2v3 => "W2v3".to_string(), Route::W2v4 => "W2v4".to_string(), Route::W2v5 => "W2v5".to_string(), Route::W2v6 => "W2v6".to_string(), Route::W2v7 => "W2v7".to_string(), Route::W3 => "W3".to_string(), Route::W3v1 => "W3v1".to_string(), Route::W4 => "W4".to_string(), Route::W4v1 => "W4v1".to_string(), Route::W4v2 => "W4v2".to_string(), Route::W45 => "W45".to_string(), Route::W47 => "W47".to_string(), Route::W5 => "W5".to_string(), Route::W6 => "W6".to_string(), Route::W6v1 => "W6v1".to_string(), Route::W8 => "W8".to_string(), Route::W8v1 => "W8v1".to_string(), Route::W8v2 => "W8v2".to_string(), Route::X1 => "X1".to_string(), Route::X2 => "X2".to_string(), Route::X2v1 => "X2v1".to_string(), Route::X2v2 => "X2v2".to_string(), Route::X2v3 => "X2v3".to_string(), Route::X3 => "X3".to_string(), Route::X3v1 => "X3v1".to_string(), Route::X8 => "X8".to_string(), Route::X9 => "X9".to_string(), Route::X9v1 => "X9v1".to_string(), Route::X9v2 => "X9v2".to_string(), Route::Y2 => "Y2".to_string(), Route::Y7 => "Y7".to_string(), Route::Y8 => "Y8".to_string(), Route::Z11 => "Z11".to_string(), Route::Z11v1 => "Z11v1".to_string(), Route::Z2 => "Z2".to_string(), Route::Z2v1 => "Z2v1".to_string(), Route::Z2v2 => "Z2v2".to_string(), Route::Z2v3 => "Z2v3".to_string(), Route::Z6 => "Z6".to_string(), Route::Z6v1 => "Z6v1".to_string(), Route::Z6v2 => "Z6v2".to_string(), Route::Z7 => "Z7".to_string(), Route::Z7v1 => "Z7v1".to_string(), Route::Z8 => "Z8".to_string(), Route::Z8v1 => "Z8v1".to_string(), Route::Z8v2 => "Z8v2".to_string(), Route::Z8v3 => "Z8v3".to_string(), Route::Z8v4 => "Z8v4".to_string(), Route::Z8v5 => "Z8v5".to_string(), Route::Z8v6 => "Z8v6".to_string(), } } } impl FromStr for Route { type Err = StringIsNotRouteError; /// Convert a string into a Route. /// /// # Examples /// ``` /// use wmata::Route; /// /// let route_id: Route = "10A".parse().unwrap(); /// /// assert_eq!(route_id, Route::One0A); /// ``` fn from_str(s: &str) -> Result<Self, Self::Err> { match s { "10A" => Ok(Route::One0A), "10B" => Ok(Route::One0B), "10E" => Ok(Route::One0E), "10N" => Ok(Route::One0N), "11Y" => Ok(Route::One1Y), "11Yv1" => Ok(Route::One1Yv1), "11Yv2" => Ok(Route::One1Yv2), "15K" => Ok(Route::One5K), "15Kv1" => Ok(Route::One5Kv1), "16A" => Ok(Route::One6A), "16C" => Ok(Route::One6C), "16Cv1" => Ok(Route::One6Cv1), "16E" => Ok(Route::One6E), "16G" => Ok(Route::One6G), "16Gv1" => Ok(Route::One6Gv1), "16H" => Ok(Route::One6H), "16L" => Ok(Route::One6L), "16Y" => Ok(Route::One6Y), "16Yv1" => Ok(Route::One6Yv1), "17B" => Ok(Route::One7B), "17G" => Ok(Route::One7G), "17H" => Ok(Route::One7H), "17K" => Ok(Route::One7K), "17L" => Ok(Route::One7L), "17M" => Ok(Route::One7M), "18G" => Ok(Route::One8G), "18H" => Ok(Route::One8H), "18J" => Ok(Route::One8J), "18P" => Ok(Route::One8P), "18Pv1" => Ok(Route::One8Pv1), "18Pv2" => Ok(Route::One8Pv2), "1A" => Ok(Route::OneA), "1B" => Ok(Route::OneB), "1C" => Ok(Route::OneC), "1Cv1" => Ok(Route::OneCv1), "1Cv2" => Ok(Route::OneCv2), "1Cv3" => Ok(Route::OneCv3), "1Cv4" => Ok(Route::OneCv4), "21A" => Ok(Route::Two1A), "21D" => Ok(Route::Two1D), "22A" => Ok(Route::Two2A), "22Av1" => Ok(Route::Two2Av1), "22C" => Ok(Route::Two2C), "22F" => Ok(Route::Two2F), "23A" => Ok(Route::Two3A), "23B" => Ok(Route::Two3B), "23Bv1" => Ok(Route::Two3Bv1), "23T" => Ok(Route::Two3T), "25B" => Ok(Route::Two5B), "25Bv1" => Ok(Route::Two5Bv1), "25Bv2" => Ok(Route::Two5Bv2), "25Bv3" => Ok(Route::Two5Bv3), "26A" => Ok(Route::Two6A), "28A" => Ok(Route::Two8A), "28Av1" => Ok(Route::Two8Av1), "28F" => Ok(Route::Two8F), "28G" => Ok(Route::Two8G), "29C" => Ok(Route::Two9C), "29G" => Ok(Route::Two9G), "29K" => Ok(Route::Two9K), "29Kv1" => Ok(Route::Two9Kv1), "29N" => Ok(Route::Two9N), "29Nv1" => Ok(Route::Two9Nv1), "29W" => Ok(Route::Two9W), "2A" => Ok(Route::TwoA), "2B" => Ok(Route::TwoB), "2Bv1" => Ok(Route::TwoBv1), "2Bv2" => Ok(Route::TwoBv2), "2Bv3" => Ok(Route::TwoBv3), "30N" => Ok(Route::Three0N), "30S" => Ok(Route::Three0S), "31" => Ok(Route::Three1), "32" => Ok(Route::Three2), "32v1" => Ok(Route::Three2v1), "33" => Ok(Route::Three3), "34" => Ok(Route::Three4), "36" => Ok(Route::Three6), "37" => Ok(Route::Three7), "38B" => Ok(Route::Three8B), "38Bv1" => Ok(Route::Three8Bv1), "38Bv2" => Ok(Route::Three8Bv2), "39" => Ok(Route::Three9), "3A" => Ok(Route::ThreeA), "3Av1" => Ok(Route::ThreeAv1), "3T" => Ok(Route::ThreeT), "3Tv1" => Ok(Route::ThreeTv1), "3Y" => Ok(Route::ThreeY), "42" => Ok(Route::Four2), "43" => Ok(Route::Four3), "4A" => Ok(Route::FourA), "4B" => Ok(Route::FourB), "52" => Ok(Route::Five2), "52v1" => Ok(Route::Five2v1), "52v2" => Ok(Route::Five2v2), "54" => Ok(Route::Five4), "54v1" => Ok(Route::Five4v1), "54v2" => Ok(Route::Five4v2), "54v3" => Ok(Route::Five4v3), "59" => Ok(Route::Five9), "5A" => Ok(Route::FiveA), "60" => Ok(Route::Six0), "62" => Ok(Route::Six2), "62v1" => Ok(Route::Six2v1), "63" => Ok(Route::Six3), "64" => Ok(Route::Six4), "64v1" => Ok(Route::Six4v1), "70" => Ok(Route::Seven0), "70v1" => Ok(Route::Seven0v1), "74" => Ok(Route::Seven4), "79" => Ok(Route::Seven9), "7A" => Ok(Route::SevenA), "7Av1" => Ok(Route::SevenAv1), "7Av2" => Ok(Route::SevenAv2), "7Av3" => Ok(Route::SevenAv3), "7C" => Ok(Route::SevenC), "7F" => Ok(Route::SevenF), "7Fv1" => Ok(Route::SevenFv1), "7M" => Ok(Route::SevenM), "7Mv1" => Ok(Route::SevenMv1), "7P" => Ok(Route::SevenP), "7W" => Ok(Route::SevenW), "7Y" => Ok(Route::SevenY), "7Yv1" => Ok(Route::SevenYv1), "80" => Ok(Route::Eight0), "80v1" => Ok(Route::Eight0v1), "80v2" => Ok(Route::Eight0v2), "80v3" => Ok(Route::Eight0v3), "83" => Ok(Route::Eight3), "83v1" => Ok(Route::Eight3v1), "83v2" => Ok(Route::Eight3v2), "83v3" => Ok(Route::Eight3v3), "83v4" => Ok(Route::Eight3v4), "86" => Ok(Route::Eight6), "86v1" => Ok(Route::Eight6v1), "86v2" => Ok(Route::Eight6v2), "87" => Ok(Route::Eight7), "87v1" => Ok(Route::Eight7v1), "87v2" => Ok(Route::Eight7v2), "87v3" => Ok(Route::Eight7v3), "87v4" => Ok(Route::Eight7v4), "87v5" => Ok(Route::Eight7v5), "89" => Ok(Route::Eight9), "89v1" => Ok(Route::Eight9v1), "89M" => Ok(Route::Eight9M), "8S" => Ok(Route::EightS), "8W" => Ok(Route::EightW), "8Z" => Ok(Route::EightZ), "90" => Ok(Route::Nine0), "90v1" => Ok(Route::Nine0v1), "90v2" => Ok(Route::Nine0v2), "92" => Ok(Route::Nine2), "92v1" => Ok(Route::Nine2v1), "92v2" => Ok(Route::Nine2v2), "96" => Ok(Route::Nine6), "96v1" => Ok(Route::Nine6v1), "96v2" => Ok(Route::Nine6v2), "96v3" => Ok(Route::Nine6v3), "96v4" => Ok(Route::Nine6v4), "96v5" => Ok(Route::Nine6v5), "97" => Ok(Route::Nine7), "97v1" => Ok(Route::Nine7v1), "A12" => Ok(Route::A12), "A12v1" => Ok(Route::A12v1), "A12v2" => Ok(Route::A12v2), "A12v3" => Ok(Route::A12v3), "A2" => Ok(Route::A2), "A2v1" => Ok(Route::A2v1), "A2v2" => Ok(Route::A2v2), "A2v3" => Ok(Route::A2v3), "A31" => Ok(Route::A31), "A32" => Ok(Route::A32), "A33" => Ok(Route::A33), "A4" => Ok(Route::A4), "A4v1" => Ok(Route::A4v1), "A4v2" => Ok(Route::A4v2), "A4v3" => Ok(Route::A4v3), "A4v4" => Ok(Route::A4v4), "A4v5" => Ok(Route::A4v5), "A6" => Ok(Route::A6), "A6v1" => Ok(Route::A6v1), "A7" => Ok(Route::A7), "A8" => Ok(Route::A8), "A8v1" => Ok(Route::A8v1), "A9" => Ok(Route::A9), "B2" => Ok(Route::B2), "B2v1" => Ok(Route::B2v1), "B2v2" => Ok(Route::B2v2), "B2v3" => Ok(Route::B2v3), "B2v4" => Ok(Route::B2v4), "B21" => Ok(Route::B21), "B22" => Ok(Route::B22), "B22v1" => Ok(Route::B22v1), "B24" => Ok(Route::B24), "B24v1" => Ok(Route::B24v1), "B27" => Ok(Route::B27), "B29" => Ok(Route::B29), "B29v1" => Ok(Route::B29v1), "B29v2" => Ok(Route::B29v2), "B30" => Ok(Route::B30), "B8" => Ok(Route::B8), "B8v1" => Ok(Route::B8v1), "B8v2" => Ok(Route::B8v2), "B9" => Ok(Route::B9), "B98" => Ok(Route::B98), "B99" => Ok(Route::B99), "C11" => Ok(Route::C11), "C12" => Ok(Route::C12), "C13" => Ok(Route::C13), "C14" => Ok(Route::C14), "C2" => Ok(Route::C2), "C2v1" => Ok(Route::C2v1), "C2v2" => Ok(Route::C2v2), "C2v3" => Ok(Route::C2v3), "C21" => Ok(Route::C21), "C21v1" => Ok(Route::C21v1), "C21v2" => Ok(Route::C21v2), "C22" => Ok(Route::C22), "C22v1" => Ok(Route::C22v1), "C26" => Ok(Route::C26), "C26v1" => Ok(Route::C26v1), "C28" => Ok(Route::C28), "C29" => Ok(Route::C29), "C28v1" => Ok(Route::C28v1), "C29*1" => Ok(Route::C29_1), "C29*2" => Ok(Route::C29_2), "C29*4" => Ok(Route::C29_4), "C29/" => Ok(Route::C290), "C4" => Ok(Route::C4), "C4v1" => Ok(Route::C4v1), "C4v2" => Ok(Route::C4v2), "C4v3" => Ok(Route::C4v3), "C8" => Ok(Route::C8), "C8v1" => Ok(Route::C8v1), "C8v2" => Ok(Route::C8v2), "C8v3" => Ok(Route::C8v3), "D1" => Ok(Route::D1), "D12" => Ok(Route::D12), "D12v1" => Ok(Route::D12v1), "D12v2" => Ok(Route::D12v2), "D13" => Ok(Route::D13), "D13v1" => Ok(Route::D13v1), "D14" => Ok(Route::D14), "D14v1" => Ok(Route::D14v1), "D14v2" => Ok(Route::D14v2), "D2" => Ok(Route::D2), "D2v1" => Ok(Route::D2v1), "D31" => Ok(Route::D31), "D32" => Ok(Route::D32), "D33" => Ok(Route::D33), "D34" => Ok(Route::D34), "D4" => Ok(Route::D4), "D4v1" => Ok(Route::D4v1), "D4v2" => Ok(Route::D4v2), "D5" => Ok(Route::D5), "D51" => Ok(Route::D51), "D6" => Ok(Route::D6), "D6v1" => Ok(Route::D6v1), "D6v2" => Ok(Route::D6v2), "D6v3" => Ok(Route::D6v3), "D8" => Ok(Route::D8), "D8v1" => Ok(Route::D8v1), "E2" => Ok(Route::E2), "E4" => Ok(Route::E4), "E4v1" => Ok(Route::E4v1), "E4v2" => Ok(Route::E4v2), "E6" => Ok(Route::E6), "F1" => Ok(Route::F1), "F12" => Ok(Route::F12), "F12v1" => Ok(Route::F12v1), "F13" => Ok(Route::F13), "F13v1" => Ok(Route::F13v1), "F13v2" => Ok(Route::F13v2), "F13v3" => Ok(Route::F13v3), "F14" => Ok(Route::F14), "F14v1" => Ok(Route::F14v1), "F2" => Ok(Route::F2), "F2v1" => Ok(Route::F2v1), "F2v2" => Ok(Route::F2v2), "F4" => Ok(Route::F4), "F4v1" => Ok(Route::F4v1), "F4v2" => Ok(Route::F4v2), "F6" => Ok(Route::F6), "F6v1" => Ok(Route::F6v1), "F6v2" => Ok(Route::F6v2), "F8" => Ok(Route::F8), "F99" => Ok(Route::F99), "G12" => Ok(Route::G12), "G12v1" => Ok(Route::G12v1), "G12v2" => Ok(Route::G12v2), "G14" => Ok(Route::G14), "G14v1" => Ok(Route::G14v1), "G14v2" => Ok(Route::G14v2), "G2" => Ok(Route::G2), "G2v1" => Ok(Route::G2v1), "G8" => Ok(Route::G8), "G8v1" => Ok(Route::G8v1), "G8v2" => Ok(Route::G8v2), "G8v3" => Ok(Route::G8v3), "G9" => Ok(Route::G9), "G9v1" => Ok(Route::G9v1), "H1" => Ok(Route::H1), "H11" => Ok(Route::H11), "H12" => Ok(Route::H12), "H12v1" => Ok(Route::H12v1), "H13" => Ok(Route::H13), "H2" => Ok(Route::H2), "H3" => Ok(Route::H3), "H4" => Ok(Route::H4), "H4v1" => Ok(Route::H4v1), "H6" => Ok(Route::H6), "H6v1" => Ok(Route::H6v1), "H8" => Ok(Route::H8), "H9" => Ok(Route::H9), "J1" => Ok(Route::J1), "J1v1" => Ok(Route::J1v1), "J12" => Ok(Route::J12), "J12v1" => Ok(Route::J12v1), "J2" => Ok(Route::J2), "J2v1" => Ok(Route::J2v1), "J2v2" => Ok(Route::J2v2), "J4" => Ok(Route::J4), "K12" => Ok(Route::K12), "K12v1" => Ok(Route::K12v1), "K12v2" => Ok(Route::K12v2), "K2" => Ok(Route::K2), "K6" => Ok(Route::K6), "K6v1" => Ok(Route::K6v1), "K9" => Ok(Route::K9), "K9v1" => Ok(Route::K9v1), "L1" => Ok(Route::L1), "L2" => Ok(Route::L2), "L2v1" => Ok(Route::L2v1), "L2v2" => Ok(Route::L2v2), "L8" => Ok(Route::L8), "L99" => Ok(Route::L99), "M4" => Ok(Route::M4), "M4v1" => Ok(Route::M4v1), "M4v2" => Ok(Route::M4v2), "M6" => Ok(Route::M6), "M6v1" => Ok(Route::M6v1), "MW1" => Ok(Route::MW1), "M99" => Ok(Route::M99), "N2" => Ok(Route::N2), "N4" => Ok(Route::N4), "N4v1" => Ok(Route::N4v1), "N6" => Ok(Route::N6), "NH1" => Ok(Route::NH1), "NH2" => Ok(Route::NH2), "P12" => Ok(Route::P12), "P12v1" => Ok(Route::P12v1), "P12v2" => Ok(Route::P12v2), "P18" => Ok(Route::P18), "P19" => Ok(Route::P19), "P6" => Ok(Route::P6), "P6v1" => Ok(Route::P6v1), "P6v2" => Ok(Route::P6v2), "P6v3" => Ok(Route::P6v3), "P6v4" => Ok(Route::P6v4), "P99" => Ok(Route::P99), "Q1" => Ok(Route::Q1), "Q2" => Ok(Route::Q2), "Q2v1" => Ok(Route::Q2v1), "Q2v2" => Ok(Route::Q2v2), "Q4" => Ok(Route::Q4), "Q4v1" => Ok(Route::Q4v1), "Q5" => Ok(Route::Q5), "Q6" => Ok(Route::Q6), "Q6v1" => Ok(Route::Q6v1), "R1" => Ok(Route::R1), "R12" => Ok(Route::R12), "R12v1" => Ok(Route::R12v1), "R2" => Ok(Route::R2), "R2v1" => Ok(Route::R2v1), "R2v2" => Ok(Route::R2v2), "R4" => Ok(Route::R4), "REX" => Ok(Route::REX), "REXv1" => Ok(Route::REXv1), "REXv2" => Ok(Route::REXv2), "REXv3" => Ok(Route::REXv3), "REXv4" => Ok(Route::REXv4), "S1" => Ok(Route::S1), "S2" => Ok(Route::S2), "S2v1" => Ok(Route::S2v1), "S35" => Ok(Route::S35), "S4" => Ok(Route::S4), "S41" => Ok(Route::S41), "S80" => Ok(Route::S80), "S80v1" => Ok(Route::S80v1), "S80v2" => Ok(Route::S80v2), "S9" => Ok(Route::S9), "S9v1" => Ok(Route::S9v1), "S91" => Ok(Route::S91), "S91v1" => Ok(Route::S91v1), "SH99" => Ok(Route::SH99), "T14" => Ok(Route::T14), "T14v1" => Ok(Route::T14v1), "T18" => Ok(Route::T18), "T18v1" => Ok(Route::T18v1), "T2" => Ok(Route::T2), "U4" => Ok(Route::U4), "U4v1" => Ok(Route::U4v1), "U4v2" => Ok(Route::U4v2), "U5" => Ok(Route::U5), "U6" => Ok(Route::U6), "U6v1" => Ok(Route::U6v1), "U6v2" => Ok(Route::U6v2), "U7" => Ok(Route::U7), "U7v1" => Ok(Route::U7v1), "U7v2" => Ok(Route::U7v2), "U7v3" => Ok(Route::U7v3), "U7v4" => Ok(Route::U7v4), "V1" => Ok(Route::V1), "V12" => Ok(Route::V12), "V14" => Ok(Route::V14), "V14v1" => Ok(Route::V14v1), "V2" => Ok(Route::V2), "V2v1" => Ok(Route::V2v1), "V4" => Ok(Route::V4), "V4v1" => Ok(Route::V4v1), "V7" => Ok(Route::V7), "V8" => Ok(Route::V8), "W1" => Ok(Route::W1), "W14" => Ok(Route::W14), "W14v1" => Ok(Route::W14v1), "W14v2" => Ok(Route::W14v2), "W2" => Ok(Route::W2), "W2v1" => Ok(Route::W2v1), "W2v2" => Ok(Route::W2v2), "W2v3" => Ok(Route::W2v3), "W2v4" => Ok(Route::W2v4), "W2v5" => Ok(Route::W2v5), "W2v6" => Ok(Route::W2v6), "W2v7" => Ok(Route::W2v7), "W3" => Ok(Route::W3), "W3v1" => Ok(Route::W3v1), "W4" => Ok(Route::W4), "W4v1" => Ok(Route::W4v1), "W4v2" => Ok(Route::W4v2), "W45" => Ok(Route::W45), "W47" => Ok(Route::W47), "W5" => Ok(Route::W5), "W6" => Ok(Route::W6), "W6v1" => Ok(Route::W6v1), "W8" => Ok(Route::W8), "W8v1" => Ok(Route::W8v1), "W8v2" => Ok(Route::W8v2), "X1" => Ok(Route::X1), "X2" => Ok(Route::X2), "X2v1" => Ok(Route::X2v1), "X2v2" => Ok(Route::X2v2), "X2v3" => Ok(Route::X2v3), "X3" => Ok(Route::X3), "X3v1" => Ok(Route::X3v1), "X8" => Ok(Route::X8), "X9" => Ok(Route::X9), "X9v1" => Ok(Route::X9v1), "X9v2" => Ok(Route::X9v2), "Y2" => Ok(Route::Y2), "Y7" => Ok(Route::Y7), "Y8" => Ok(Route::Y8), "Z11" => Ok(Route::Z11), "Z11v1" => Ok(Route::Z11v1), "Z2" => Ok(Route::Z2), "Z2v1" => Ok(Route::Z2v1), "Z2v2" => Ok(Route::Z2v2), "Z2v3" => Ok(Route::Z2v3), "Z6" => Ok(Route::Z6), "Z6v1" => Ok(Route::Z6v1), "Z6v2" => Ok(Route::Z6v2), "Z7" => Ok(Route::Z7), "Z7v1" => Ok(Route::Z7v1), "Z8" => Ok(Route::Z8), "Z8v1" => Ok(Route::Z8v1), "Z8v2" => Ok(Route::Z8v2), "Z8v3" => Ok(Route::Z8v3), "Z8v4" => Ok(Route::Z8v4), "Z8v5" => Ok(Route::Z8v5), "Z8v6" => Ok(Route::Z8v6), _ => Err(StringIsNotRouteError(s.to_string())), } } } #[derive(Debug, Clone)] pub struct StringIsNotRouteError(pub String); impl fmt::Display for StringIsNotRouteError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} is not a valid Route ID.", self.0) } } impl error::Error for StringIsNotRouteError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { None } }
#![recursion_limit = "128"] #[macro_use] extern crate helix; extern crate chrono; use chrono::{DateTime, NaiveDateTime, TimeZone, Utc}; use evtx::{EvtxParser, ParserSettings}; use std::path::PathBuf; use std::time::SystemTime; ruby! { class EventAfter { struct { ts: i64, rn: Option<u64> } def initialize(helix, ts: i64, rn: Option<u64>) { Self { helix, ts, rn } } def timestamp(&self) -> i64 { self.ts } def record_number(&self) -> Option<u64> { self.rn } } class EvtxLoader { struct { file_path: String, pb: std::path::PathBuf, events: Vec<String>, total: u64, modified_time: DateTime<Utc>, oldest_time: DateTime<Utc>, oldest_rn: u64 } def initialize(helix, path: String) { let default = DateTime::<Utc>::from_utc(NaiveDateTime::from_timestamp(0, 0), Utc); Self { helix: helix, file_path: path.clone(), events: vec![], oldest_time: default, modified_time: default, oldest_rn: 0, total: 0, pb: PathBuf::from(path) } } def oldest_record_number(&self) -> u64 { self.oldest_rn } def oldest_timestamp(&self) -> i64 { self.oldest_time.timestamp() } def total_records(&self) -> u64 { self.total } def events(&mut self) -> Vec<String> { let settings = ParserSettings::default().indent(false); let mut total_records: u64 = 0; let mut output: Vec<String> = Vec::new(); let mut parser = EvtxParser::from_path(&self.pb). unwrap(). with_configuration(settings); for record in parser.records_json() { match record { Ok(r) => { output.push(r.data.to_string()); if r.timestamp > self.oldest_time { self.oldest_rn = r.event_record_id; self.oldest_time = r.timestamp; } total_records += 1; }, Err(e) => eprintln!("{}", e), } } self.total = total_records; self.modified_time = Utc.timestamp(self.file_modified_time(), 0); output } def file_modified_time(&self) -> i64 { (std::fs::metadata(&self.file_path). unwrap(). modified(). unwrap(). duration_since(SystemTime::UNIX_EPOCH). unwrap(). as_secs()) as i64 } def was_modified(&self) -> bool { if self.modified_time.timestamp() < self.file_modified_time() { return true; } false } } }
use std::cmp; use crate::error::ReturnError; use crate::traits::{self, MakingUrlFormat}; #[cfg(feature = "async_mode")] use crate::request_async; #[cfg(feature = "sync_mode")] use crate::request_sync; /// provides users an option menu to choose one of the return format. /// /// Users are expected to use appropriate format for related request. pub(crate) enum ReturnFormat { /// Comma Separated Values format. Csv, /// Java Script Object Notation format. Json, /// Extensible Markup Language format. Xml, } impl ToString for ReturnFormat { /// returns stringified version of return format option that is appropriate for url usage. fn to_string(&self) -> String { match self { &Self::Csv => String::from("csv"), &Self::Json => String::from("json"), &Self::Xml => String::from("xml"), } } } impl traits::MakingUrlFormat for ReturnFormat { /// generates required url representation of return format. fn generate_url_format(&self) -> String { format!("type={}", self.to_string()) } } /// is the container of the api key validated. /// /// To check validity of the given api key, users need to create an api key variable via /// [`ApiKey::from`](fn@ApiKey::from). #[derive(Debug)] pub(crate) struct ApiKey(String); impl<'a> ApiKey { fn change(&mut self, new_key: &'a str) -> Result<(), ReturnError> { let api_key = ApiKey(new_key.to_string()); api_key.is_api_key_valid()?; self.0 = new_key.to_string(); Ok(()) } #[cfg(feature = "async_mode")] fn check_api_key_validity_async(reference_url: String) -> Result<(), ReturnError> { match request_async::do_request(&reference_url) { Ok(_) => Ok(()), Err(_) => Err(ReturnError::InvalidApiKeyOrBadInternetConnection), } } #[cfg(feature = "sync_mode")] fn check_api_key_validity_sync(reference_url: String) -> Result<(), ReturnError> { match request_sync::do_request(&reference_url) { Ok(_) => Ok(()), Err(_) => Err(ReturnError::InvalidApiKeyOrBadInternetConnection), } } fn is_api_key_valid(&self) -> Result<(), ReturnError> { // The string below is divided into two due to the convention of horizontal width which is 120 characters. let reference_url = format!( "https://evds2.tcmb.gov.tr/service/evds/series=TP.DK.USD.S.YTL{}&key={}", "&startDate=13-12-2011&endDate=13-12-2011&type=json", self.0, ); #[cfg(feature = "async_mode")] return ApiKey::check_api_key_validity_async(reference_url); #[cfg(feature = "sync_mode")] return ApiKey::check_api_key_validity_sync(reference_url); } fn get(&self) -> &str { &self.0 } /// is needed to automatically check validation of api key for new instance. /// /// The internet connection is required to achieve the task. /// /// # Error /// /// The function will return error if given api key is invalid or there is a bad internet connection. /// /// # Examples /// /// ``` /// use tcmb_evds_c::common::ApiKey; /// use tcmb_evds_c::error::ReturnError; /// /// /// // If user key entered is valid, the function creates api_key variable. /// // Otherwise, returns one of ReturnError options. /// // The function returns an error unless users write their own valid api key. /// let result = ApiKey::from("users_key".to_string()); /// /// /// // Users can handle error in a different way. /// let api_key = match result { /// Err(return_error) => { /// println!("{}", return_error.to_string()); /// return; /// }, /// Ok(api_key) => api_key, /// }; /// ``` pub(crate) fn from(key: String) -> Result<ApiKey, ReturnError> { let api_key = ApiKey(key); api_key.is_api_key_valid()?; Ok(api_key) } } impl cmp::PartialEq for ApiKey { fn eq(&self, other: &Self) -> bool { self.get() == other.get() } } impl traits::MakingUrlFormat for ApiKey { fn generate_url_format(&self) -> String { format!("key={}", self.0) } } /// is composed of created [`ApiKey`](struct@ApiKey) and [`ReturnFormat`](crate::common::ReturnFormat) variables. /// /// This struct is common for each function that this crate provides. pub(crate) struct Evds { api_key: ApiKey, return_format: ReturnFormat, } impl<'a> Evds { /// creates an Evds object from given [`ApiKey`](struct@ApiKey) and [`ReturnFormat`](enum@ReturnFormat). /// /// # Examples /// /// ``` /// # use tcmb_evds_c::error::ReturnError; /// # use tcmb_evds_c::common::{ApiKey, ReturnFormat}; /// use tcmb_evds_c::common::Evds; /// # /// # // If user key entered is valid, the function creates api_key variable. /// # // Otherwise, returns one of ReturnError. /// # // The function returns an error unless users write their own api key valid. /// # let result = ApiKey::from("users_key".to_string()); /// # /// # /// # // Users can handle error in a different way. /// # let api_key = match result { /// # Err(return_error) => { /// # println!("{}", return_error.to_string()); /// # return; /// # }, /// # Ok(api_key) => api_key, /// # }; /// /// /// // Valid api_key is required. /// let evds = Evds::from(api_key, ReturnFormat::Json); /// ``` pub(crate) fn from(api_key: ApiKey, return_format: ReturnFormat) -> Evds { Evds { api_key, return_format, } } /// changes api key contained in Evds object if and only if the given key is valid. /// /// The internet connection is required to achieve the task. /// /// # Error /// /// The function will return error if given api key is invalid or there is a bad internet connection. /// /// # Examples /// /// ``` /// # use std::error::Error; /// # use tcmb_evds_c::error::ReturnError; /// use tcmb_evds_c::common::{ApiKey, ReturnFormat, Evds}; /// /// /// # fn main() -> Result<(), Box<dyn Error>> { /// # /// # let api_key = ApiKey::from("users_key")?; /// let mut evds = Evds::from(api_key, ReturnFormat::Json); /// /// /// evds.change_api_key("user's_new_key")?; /// # Ok(()) /// # } /// ``` pub(crate) fn change_api_key(&mut self, api_key: &str) -> Result<(), ReturnError> { self.api_key.change(api_key)?; Ok(()) } /// changes return format inside of an [`Evds`](struct@Evds) variable. /// /// # Examples /// /// ``` /// # use tcmb_evds_c::error::ReturnError; /// # use tcmb_evds_c::common::{ApiKey, ReturnFormat}; /// use tcmb_evds_c::common::Evds; /// # let result = ApiKey::from("users_key".to_string()); /// # /// # if let Err(_) = result { /// # return; /// # } /// # /// # let api_key = result.unwrap(); /// # /// # /// # let mut evds = Evds::from(api_key, ReturnFormat::Json); /// /// /// evds.change_return_format(ReturnFormat::Xml); /// ``` pub(crate) fn change_return_format(&mut self, return_format: ReturnFormat) { self.return_format = return_format; } /// generates url format of api key. pub(crate) fn get_api_key_as_url(&self) -> String { self.api_key.generate_url_format() } /// generates url format of return format. pub(crate) fn get_return_format_as_url(&self) -> String { self.return_format.generate_url_format() } } #[cfg(test)] mod tests { use super::*; #[test] fn api_functionality_should_work() { let mut api_key = match ApiKey::from("abc".to_string()) { Ok(api_key) => api_key, Err(message) => { println!("{}", message.to_string()); ApiKey("abc".to_string()) }, }; if let Err(message) = api_key.change("new_key") { println!("{}", message.to_string()); }; } #[test] fn should_change_api_key() { let api_key = match ApiKey::from("abc".to_string()) { Ok(api_key) => api_key, Err(message) => { println!("{}", message.to_string()); ApiKey("abc".to_string()) }, }; let mut evds = Evds::from(api_key, ReturnFormat::Csv); if let Err(message) = evds.change_api_key("VALID_API_KEY") { println!("{}", message.to_string()); } } #[test] fn evds_functionalities_should_work() { let api_key = match ApiKey::from("abc".to_string()) { Ok(api_key) => api_key, Err(message) => { println!("{}", message.to_string()); ApiKey("abc".to_string()) }, }; let mut evds = Evds::from(api_key, ReturnFormat::Csv); println!("{}", &evds.return_format.to_string()); evds.change_return_format(ReturnFormat::Json); println!("{}", &evds.return_format.to_string()); println!("\n\n{}\n{}\n", evds.return_format.generate_url_format(), evds.api_key.generate_url_format()); evds.return_format = ReturnFormat::Csv; println!("\n\n{}\n{}\n", evds.return_format.generate_url_format(), evds.api_key.generate_url_format()); evds.return_format = ReturnFormat::Xml; println!("\n\n{}\n{}\n", evds.return_format.generate_url_format(), evds.api_key.generate_url_format()); } }
tonic::include_proto!("as/api");
use super::*; #[derive(Debug, Clone, PartialEq)] pub struct VocabularyVec<IndexT: ToFromUsize, CountT: ToFromUsize> { pub ids: Vec<IndexT>, pub vocabulary: Vocabulary<IndexT>, pub counts: Vec<CountT>, } impl<IndexT: ToFromUsize, CountT: ToFromUsize> VocabularyVec<IndexT, CountT> { pub fn default() -> VocabularyVec<IndexT, CountT> { VocabularyVec { ids: Vec::new(), vocabulary: Vocabulary::default(), counts: Vec::new(), } } pub fn from_structs( ids: Vec<IndexT>, vocabulary: Option<Vocabulary<IndexT>>, ) -> Option<VocabularyVec<IndexT, CountT>> { match vocabulary { Some(vocab) => { let mut vocabvec = VocabularyVec { ids, vocabulary: vocab, counts: Vec::new(), }; vocabvec.build_counts(); Some(vocabvec) } None => None, } } pub fn build_counts(&mut self) { self.counts = vec![CountT::from_usize(0); self.vocabulary.len()]; for index in self.ids.iter() { self.counts[IndexT::to_usize(*index)] += CountT::from_usize(1); } } pub fn build_reverse_mapping(&mut self) -> Result<(), String> { self.vocabulary.build_reverse_mapping() } /// Returns id of given value inserted. /// /// # Arguments /// /// * `value`: String - The value to be inserted. pub fn insert(&mut self, value: String) -> Result<IndexT, String> { self.vocabulary.insert(value.clone())?; let id = *self.get(&value).unwrap(); self.ids.push(id); Ok(id) } /// Returns wethever the value is empty or not. pub fn is_empty(&self) -> bool { self.vocabulary.is_empty() } /// Returns string name of given id. /// /// # Arguments /// /// * `id`: IndexT - Id to be translated. pub fn translate(&self, id: IndexT) -> &str { self.vocabulary.translate(id) } /// Return the id of given key. /// /// # Arguments /// /// * `key`: &str - the key whose Id is to be retrieved. pub fn get(&self, key: &str) -> Option<&IndexT> { self.vocabulary.get(key) } /// Return vector of keys of the map. pub fn keys(&self) -> Vec<String> { self.vocabulary.keys() } /// Return length of the vocabulary. pub fn len(&self) -> usize { self.counts.len() } /// Return boolean representing if values are numeric. pub fn has_numeric_ids(&self) -> bool { self.vocabulary.has_numeric_ids() } /// Set wether to load IDs as numeric. /// /// # Arguments /// * numeric_ids: bool - Wether to load the IDs as numeric /// pub fn set_numeric_ids(mut self, numeric_ids: bool) -> VocabularyVec<IndexT, CountT> { self.vocabulary = self.vocabulary.set_numeric_ids(numeric_ids); self } }
use core::ptr; // TODO: This SPI driver needs more testing... pub struct Spi<'a> { _lease: lease_ty!('a, SpiLease), base_reg: u32, } bf!(SpiFifoCntReg[u32] { baudrate: 0:5, dev_select: 6:7, is_outgoing: 13:13, busy: 15:15 }); #[derive(Clone, Copy)] #[allow(non_camel_case_types)] enum Reg { FIFO_CNT = 0x800, FIFO_DONE = 0x804, FIFO_BLKLEN = 0x808, FIFO_DATA = 0x80C, FIFO_STATUS = 0x810, } impl<'a> Spi<'a> { pub fn new(lease: lease_ty!('a, SpiLease)) -> Spi { let idx = lease.idx; Spi { _lease: lease, base_reg: match idx { 0 => 0x10160000, _ => unimplemented!() }, } } #[inline(never)] fn read_reg(&mut self, reg: Reg) -> u32 { unsafe { ptr::read_volatile((self.base_reg + reg as u32) as *const u32) } } fn write_reg(&mut self, reg: Reg, val: u32) { unsafe { ptr::write_volatile((self.base_reg + reg as u32) as *mut u32, val); } } pub fn chipselect(&mut self, device_id: u32) { let dev_select = device_id % 3; let baudrate = match device_id { 0 => 2, 3 => 5, _ => unimplemented!() }; let mut fifo_cnt = SpiFifoCntReg::new(0); fifo_cnt.baudrate.set(baudrate); fifo_cnt.dev_select.set(dev_select); self.write_reg(Reg::FIFO_CNT, fifo_cnt.val); } pub fn write(&mut self, bytes: &[u8]) { let mut fifo_cnt_raw = self.read_reg(Reg::FIFO_CNT); { let fifo_cnt = SpiFifoCntReg::alias_mut(&mut fifo_cnt_raw); fifo_cnt.is_outgoing.set(1); fifo_cnt.busy.set(1); } self.write_reg(Reg::FIFO_BLKLEN, bytes.len() as u32); self.write_reg(Reg::FIFO_CNT, fifo_cnt_raw); for chunk in bytes.chunks(4) { let mut word: u32 = 0; for byte in chunk.iter().rev() { word <<= 8; word |= *byte as u32; } self.write_reg(Reg::FIFO_DATA, word); while self.read_reg(Reg::FIFO_STATUS) & 0 == 1 {} } self.write_reg(Reg::FIFO_DONE, 0); } pub fn read(&mut self, bytes: &mut [u8]) { let mut fifo_cnt_raw = self.read_reg(Reg::FIFO_CNT); { let fifo_cnt = SpiFifoCntReg::alias_mut(&mut fifo_cnt_raw); fifo_cnt.is_outgoing.set(0); fifo_cnt.busy.set(1); } self.write_reg(Reg::FIFO_BLKLEN, bytes.len() as u32); self.write_reg(Reg::FIFO_CNT, fifo_cnt_raw); for chunk in bytes.chunks_mut(4) { let mut word: u32 = self.read_reg(Reg::FIFO_DATA); for byte in chunk.iter_mut() { *byte = word as u8; word >>= 8; } while self.read_reg(Reg::FIFO_STATUS) & 0 == 1 {} } } pub fn deselect(&mut self) { self.write_reg(Reg::FIFO_DONE, 0); } }
//! Serde deserialize for password hashes //! //! The output from a hashing algorithm typically includes: the hash itself, //! the salt, and the parameters used in the hashing. //! This allows us to store the output in an unambigous fashion. //! //! However, not all algorithms had this foresight, and many instead wrote //! simple formats which simply included the hash output and salt concatenated. //! //! This module attempts to deserialize various formats into the `libpasta` //! supported form. use hashing::{Algorithm, Output}; use primitives::Primitive; use serde::de::Error; use serde::de::{self, Visitor}; use serde::{Deserialize, Deserializer}; use serde_mcf; use serde_mcf::{base64, base64bcrypt, Hashes}; use std::fmt; /// Currently supported hashing variants. /// /// `Bcrypt`: `$(2a|2b|2x|2y)$<cost>$<salthash>` /// where salthash is a non-standard base64 encoding. /// `Mcf`: `$<alg-id>$<params map>$<salt>$<hash>` /// `Pasta`: `$<MCF-hash>` or `$!<Pasta-hash>` (recursively) #[derive(Debug, PartialEq)] enum SupportedVariants { Bcrypt(Hashes), Mcf(Hashes), Pasta(PastaVariants), } /// A Pasta hash is either a sing hash parameterisation, or a recursive /// structure, containing many hash parameters. #[derive(Debug, PartialEq)] enum PastaVariants { Single, Nested, } static VAR_STRUCT: [&str; 2] = ["variant", "remaining"]; // The *Fields structs define the layout of the various supported variants, // as detailed above. After parsing the algorithm identifier, one of these // structs are used to attempt to deserialize. #[derive(Deserialize)] struct BcryptFields { cost: u32, #[serde(with = "base64bcrypt")] salthash: (Vec<u8>, Vec<u8>), } #[derive(Deserialize)] struct McfFields { params: serde_mcf::Map<String, serde_mcf::Value>, #[serde(with = "base64")] pub salt: Vec<u8>, #[serde(with = "base64")] pub hash: Vec<u8>, } /// The nested Pasta format is specified by a $<id>$<params> parameterising the /// outer layer hash algorithm, followed by another set of algorithm parameters. /// This inner hash may also a further layer of nested params. #[derive(Deserialize)] struct PastaNest { outer_id: Hashes, outer_params: serde_mcf::Map<String, serde_mcf::Value>, inner: Output, } // Deserialize Output using OutputVisitor impl<'de> Deserialize<'de> for Output { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_struct("var_container", &VAR_STRUCT, OutputVisitor) } } /// `OutputVisitor` does most of the heavy lifting of the deserializing. /// First, we use the `SupportedVariants` enum to identify which type of hash /// we are dealing with. /// Second, the remaining values are deserialized into the suitable *Field struct. /// Finally, the fields are unified into the `Output` struct and returned. struct OutputVisitor; impl<'de> Visitor<'de> for OutputVisitor { type Value = Output; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an identifier") } fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error> where V: de::MapAccess<'de>, { // The first step is to detect which variant we are dealing with. let _: Option<String> = map.next_key()?; let var: SupportedVariants = map.next_value()?; match var { // Deserialize each variant using specific format. // Note that let fields: SomeFields = map.next_value()?; // is automatically calling the deserializer for SomeFields. SupportedVariants::Bcrypt(_) => { let _: Option<String> = map.next_key()?; let fields: BcryptFields = map.next_value()?; let prim = ::primitives::Bcrypt::new(fields.cost); if prim == ::primitives::Poisoned.into() { return Err(V::Error::custom(format!( "failed to deserialize as {:?}", var ))); } Ok(Output { alg: Algorithm::Single(prim), salt: fields.salthash.0, hash: fields.salthash.1, }) } SupportedVariants::Mcf(var) => { let _: Option<String> = map.next_key()?; let fields: McfFields = map.next_value()?; let prim = ::primitives::Primitive::from((&var, &fields.params)); if prim == ::primitives::Poisoned.into() { return Err(V::Error::custom(format!( "failed to deserialize as {:?}", var ))); } Ok(Output { alg: Algorithm::Single(prim), salt: fields.salt, hash: fields.hash, }) } SupportedVariants::Pasta(var) => { match var { PastaVariants::Single => { let _: Option<String> = map.next_key()?; let output: serde_mcf::McfHash = map.next_value()?; let prim = ::primitives::Primitive::from((&output.algorithm, &output.parameters)); if prim == ::primitives::Poisoned.into() { return Err(V::Error::custom(format!( "failed to deserialize as {:?}", var ))); } Ok(Output { alg: Algorithm::Single(prim), salt: output.salt, hash: output.hash, }) } PastaVariants::Nested => { let _: Option<String> = map.next_key()?; // Note that in this case, PastaNest deserializer is // recursively deserializing PastaVariants until // reaching the end. let fields: PastaNest = map.next_value()?; let prim = ::primitives::Primitive::from((&fields.outer_id, &fields.outer_params)); if prim == ::primitives::Poisoned.into() { return Err(V::Error::custom(format!( "failed to deserialize as {:?}", var ))); } Ok(Output { alg: Algorithm::Nested { outer: prim, inner: Box::new(fields.inner.alg.clone()), }, salt: fields.inner.salt, hash: fields.inner.hash, }) } } } } } } impl<'de> Deserialize<'de> for SupportedVariants { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_identifier(VariantVisitor) } } /// Visitor to deserialize the `SupportedVariants` enum. /// Currently is able to detect the variant by how the string starts. /// For example, `$$` or `$!$` indicates a Pasta variant, whereas `$2a` would /// be a regular `Bcrypt` hash. struct VariantVisitor; impl<'de> Visitor<'de> for VariantVisitor { type Value = SupportedVariants; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("an identifier") } fn visit_borrowed_str<E>(self, val: &str) -> Result<Self::Value, E> where E: Error, { let variant = match val { "" => SupportedVariants::Pasta(PastaVariants::Single), "!" => SupportedVariants::Pasta(PastaVariants::Nested), other => { let variant = Hashes::from_id(other) .ok_or_else(|| E::custom(format!("unknown MCF variant: {}", other)))?; match variant { Hashes::Bcrypt | Hashes::Bcrypta | Hashes::Bcryptx | Hashes::Bcrypty | Hashes::Bcryptb => SupportedVariants::Bcrypt(variant), _ => SupportedVariants::Mcf(variant), } } }; Ok(variant) } } // The deserializing of a `Primitive` is used in the nested `Pasta` variants. impl<'de> Deserialize<'de> for Primitive { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { #[derive(Deserialize)] struct PrimitiveStruct { id: Hashes, params: serde_mcf::Map<String, serde_mcf::Value>, } let prim = PrimitiveStruct::deserialize(deserializer)?; let prim = (&prim.id, &prim.params).into(); if prim == ::primitives::Poisoned.into() { return Err(D::Error::custom("failed to deserialize")); } Ok(prim) } } #[cfg(test)] mod test { #![allow(clippy::clippy::shadow_unrelated)] use super::*; use serde_mcf; use serde_yaml; #[test] fn variant_tests() { let variant = "$argon2i"; assert_eq!( serde_mcf::from_str::<SupportedVariants>(variant).unwrap(), SupportedVariants::Mcf(Hashes::Argon2i) ); let not_a_variant = "12"; assert!(serde_yaml::from_str::<SupportedVariants>(not_a_variant).is_err()); } #[test] fn hash_tests() { let hash = "$$non-existant$$$"; assert!(serde_mcf::from_str::<Output>(hash).is_err()); let hash = "$argon2i$fake_map=12$salt$hash"; assert!(serde_mcf::from_str::<Output>(hash).is_err()); } #[test] fn de_bcrypt() { let hash = "$2a$10$175ikf/E6E.73e83.fJRbODnYWBwmfS0ENdzUBZbedUNGO.99wJfa"; assert!(serde_mcf::from_str::<Output>(hash).is_ok()); let broken_hash = "$2a$purple$175ikf/E6E.73e83.fJRbODnYWBwmfS0ENdzUBZbedUNGO.99wJfa"; assert!(serde_mcf::from_str::<Output>(broken_hash).is_err()); } }
use crate::schema::persons; use chrono::NaiveDateTime; use serde::{Deserialize, Serialize}; #[derive(GraphQLObject, PartialEq, Queryable, Debug, Serialize, Deserialize)] pub struct Person { pub id: i32, pub name: String, pub email: Option<String>, pub phone: Option<String>, pub tags: Vec<String>, pub added: NaiveDateTime, pub changed: Option<NaiveDateTime>, } #[derive(Insertable)] #[table_name = "persons"] pub struct NewPerson { pub name: String, pub email: Option<String>, pub phone: Option<String>, pub tags: Vec<String>, pub added: NaiveDateTime, pub changed: Option<NaiveDateTime>, } impl NewPerson { pub fn from_input(input: InputPerson) -> Self { Self { name: input.name, email: input.email.clone(), phone: input.phone.clone(), tags: input.tags, added: chrono::Utc::now().naive_utc(), changed: None, } } } #[derive(GraphQLInputObject, Debug, Deserialize)] pub struct InputPerson { pub name: String, pub email: Option<String>, pub phone: Option<String>, pub tags: Vec<String>, } #[derive(Debug, AsChangeset)] #[table_name = "persons"] pub struct UpdatePerson { pub name: Option<String>, pub email: Option<String>, pub phone: Option<String>, pub tags: Option<Vec<String>>, pub changed: Option<NaiveDateTime>, } impl UpdatePerson { pub fn from_input(input: InputUpdatePerson) -> Self { Self { name: input.name, email: input.email.clone(), phone: input.phone.clone(), tags: input.tags, changed: Some(chrono::Utc::now().naive_utc()), } } } #[derive(GraphQLInputObject, Debug, Deserialize)] pub struct InputUpdatePerson { pub name: Option<String>, pub email: Option<String>, pub phone: Option<String>, pub tags: Option<Vec<String>>, } #[derive(Queryable, Debug, Deserialize)] pub struct QueryPerson { pub name: Option<String>, pub tags: Option<Vec<String>>, }
use crate::types::{Face, Vertex}; pub fn rect() -> (Vec<Vertex>, Vec<Face>) { let normal = [0., 0., 1.]; let tangent = [1., 0., 0.]; let v = vec![ Vertex { position: [-0.5, 0.5, 0.], normal, uv: [0., 1.], tangent, }, Vertex { position: [0.5, 0.5, 0.], normal, uv: [1., 1.], tangent, }, Vertex { position: [0.5, -0.5, 0.], normal, uv: [1., 0.], tangent, }, Vertex { position: [-0.5, -0.5, 0.], normal, uv: [0., 0.], tangent, }, ]; let f = vec![[0, 2, 1], [0, 3, 2]]; (v, f) }
use std::fs::File; use std::io::prelude::*; use serde_json::{Value, Error}; use serde_json; use models::Observables; #[derive(Serialize, Deserialize, Debug, Clone)] pub struct CartesianPoint { pub x: Option<f64>, pub y: Option<f64>, pub z: f64, } #[derive(Serialize, Deserialize, Debug)] pub enum PlotType { VectorField, } impl PlotType { pub fn as_str(&self) -> &str { match self { &PlotType::VectorField => "vector_field", } } } #[derive(Serialize, Deserialize, Debug)] pub struct Chart { pub data: Vec<CartesianPoint>, pub plot_type: PlotType, pub name: String, } pub fn write_plot(charts: Vec<Chart>) { for chart in charts { let mut file = File::create(format!("web/{}.json", chart.name)).unwrap(); write!(file, "{}", serde_json::to_string(&chart).unwrap()); } }
use std::num::ParseIntError; use std::convert; use std::fmt; use std::error::Error; #[derive(Debug)] struct AppError(String); macro_rules! to_apperr { ($e:ident, $m:expr) => { impl convert::From<$e> for AppError { fn from(error: $e) -> AppError { AppError(format!($m, error.description().to_string())) } } } } impl Error for AppError { fn description(&self) -> &str { &self.0 } } impl fmt::Display for AppError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(&self.0) } } // impl convert::From<num::ParseIntError> for AppError { // fn from(error: num::ParseIntError) -> AppError { // AppError(format!("Unable to parse values: {}", error.description().to_string())) // } // } to_apperr!(ParseIntError, "Unable to parse values: {}"); fn main() { match read_values() { Ok(values) => println!("{}", avg(&values)), Err(e) => println!("{}", e.description()), } } fn avg(values: &[u32]) -> u32 { let (sum, count) = values.iter().fold((0,0), |(s,c), n| (s+n, c+1)); (sum as f32 / count as f32) as u32 } fn read_values() -> Result<Vec<u32>, AppError> { let mut values = Vec::new(); for arg in std::env::args().skip(1) { values.push(try!(arg.parse())); // values.push(match arg.parse::<u32>() { // Ok(n) => n, // Err(e) => return AppError(e.description().to_string()), // }); } Ok(values) }
//multi return value pub fn func_mult_return(x: i32, y: i32) -> (i32, i32) { println!("{}", "-------------------------------"); println!("{}", x + y); println!("{}", "-------------------------------"); (y, x) } //..会产生一个iterator ,它包含左边的数,排除在右边的数。 // 为了得到一个包含两端的范围的iterator,使用...符号 pub fn for_func() { println!("{}", "-------------------------------"); let a = [2, 4, 6, 8, 10]; for element in a.iter() { println!("the value of loop1 is: {}", element); } // a[1..4] is a slice for element in a[1..4].iter() { println!("the value of loop2 is: {}", element); } // (a[1],a[1]+1,a[1]+2,...a[4]-1,a[4]) // . has a highest priority , so we should add `()` for number in (a[1]..=a[4]).rev() { println!("the value of loop3 is: {}!", number); } // 1,2,3,4 for number in (1..4).rev() { println!("the value of loop4 is: {}!", number); } for number in a[1]..=a[4] { println!("the value of loop5 is: {}!", number); } for number in 1..4 { println!("the value of loop6 is: {}!", number); } println!("{}", "-------------------------------"); }
//! Responses for DNS Commands use atat::atat_derive::AtatResp; use heapless::{consts, String}; /// 24.1 Resolve name / IP number through DNS +UDNSRN #[derive(Clone, PartialEq, AtatResp)] pub struct ResolveNameIpResponse { #[at_arg(position = 0)] pub ip_domain_string: String<consts::U128>, }
use core; #[panic_handler] pub fn panic_handler(info: &core::panic::PanicInfo) -> ! { log!("PANIC PANIC PANIC PANIC PANIC"); ::input_barrier(); ::gfx::log_clear(); log!("PANIC PANIC PANIC PANIC PANIC"); log!("{}", info); log!("Press SELECT to power off."); ::gfx::draw_commit(); ::input::wait_for_all_of(&[::io::hid::Button::Select]); ::power::power_off() } #[no_mangle] pub extern fn abort() -> ! { ::gfx::clear_screen(0xFF, 0x00, 0x00); ::gfx::reset_log_cursor(); ::gfx::draw_string((2, 2), b"ABORTED"); loop { unsafe { ::interrupts::wait_for_interrupt() }; } } #[no_mangle] pub extern fn __clzsi2(mut val: i32) -> i32 { let mut i = 32; let mut j = 16; let mut temp; while j != 0 { temp = val >> j; if temp != 0 { if j == 1 { return i - 2; } else { i -= j; val = temp; } } j >>= 1; } i - val }
extern crate clap; extern crate pgen; extern crate serde_json; #[cfg(not(test))] fn main() { use clap::{App, Arg}; let matches = App::new("Mongo DB Aggregation Pipeline Generator") .version("0.3") .author("Patrick Meredith <pmeredit@gmail.com>") .about("Compiles an easy-to-use ML-like langauge to Mongo DB Aggregation Pipeline Json") .arg( Arg::with_name("pretty") .long("pretty") .short("p") .help("Sets pretty print on, off by default"), ) .arg( Arg::with_name("gobson") .long("gobson") .short("gb") .help("Output pipeline in go bson") .conflicts_with("pretty"), ) .arg( Arg::with_name("FILE") .help("Sets the input file to use") .required(true) .index(1), ) .get_matches(); let file = matches.value_of("FILE").unwrap(); let pretty = matches.is_present("pretty"); let gobson = matches.is_present("gobson"); match pgen::run_all(file) { Ok(json) => { if gobson { println!("{}", pgen::codegen::to_go_bson(json)); } else if pretty { println!("{}", serde_json::to_string_pretty(&json).unwrap()); } else { println!("{}", serde_json::to_string(&json).unwrap()); } } Err(e) => println!("{}", e), } }
use std::io; use std::fs; use std::collections::VecDeque; #[derive(Debug, PartialEq)] enum ParamMode { Position, Immediate, } fn param_mode(digit: isize) -> ParamMode { match digit { 0 => ParamMode::Position, 1 => ParamMode::Immediate, _ => panic!("invalid parameter mode: {}", digit), } } fn param_to_value(program: &Vec<isize>, pos: usize, mode: ParamMode) -> isize { match mode { ParamMode::Position => {let inpos = program[pos] as usize; program[inpos]}, ParamMode::Immediate => program[pos], } } #[derive(Debug)] enum ProgramState { Run, Exit, NeedInput, } fn run_program(part: &mut PipelinePart) -> ProgramState { let program = &mut part.program; let ip = &mut part.ip; loop { let mut digits = Vec::new(); let mut remain = program[*ip]; for i in (2..5).rev() { digits.push(remain / 10_isize.pow(i)); remain = remain % 10_isize.pow(i); } let opcode = remain; let param_3_mode = param_mode(digits[0]); let param_2_mode = param_mode(digits[1]); let param_1_mode = param_mode(digits[2]); match opcode { // in in out 1 | 2 | 7 | 8 => { let inval1 = param_to_value(&program, *ip + 1, param_1_mode); let inval2 = param_to_value(&program, *ip + 2, param_2_mode); assert_eq!(param_3_mode, ParamMode::Position); let outpos = program[*ip + 3] as usize; match opcode { // add 1 => program[outpos] = inval1 + inval2, // multiply 2 => program[outpos] = inval1 * inval2, // less than 7 => program[outpos] = match inval1 < inval2 { true => 1, false => 0, }, // equals 8 => program[outpos] = match inval1 == inval2 { true => 1, false => 0, }, _ => panic!("program error"), } *ip += 4; }, 3 => { // in // read from input if part.input_queue.len() <= 0 { return ProgramState::NeedInput; } assert_eq!(param_1_mode, ParamMode::Position); let outpos = program[*ip + 1] as usize; program[outpos] = part.input_queue.pop_front().unwrap(); *ip += 2; } 4 => { // out // write to output let inval = param_to_value(&program, *ip + 1, param_1_mode); part.output_queue.push_back(inval); *ip += 2; } 5 | 6 => { // in in let inval1 = param_to_value(&program, *ip + 1, param_1_mode); let inval2 = param_to_value(&program, *ip + 2, param_2_mode); match opcode { 5 => { // jump if true if inval1 != 0 { *ip = inval2 as usize; } else { *ip += 3; } }, 6 => { // jump if false if inval1 == 0 { *ip = inval2 as usize; } else { *ip += 3; } }, _ => panic!("program error"), } }, 99 => break, _ => panic!("invalid opcode: {}", opcode), } } ProgramState::Exit } #[derive(Debug)] struct PipelinePart { program: Vec<isize>, state: ProgramState, input_queue: VecDeque<isize>, output_queue: VecDeque<isize>, ip: usize, previous: usize, } fn run_pipe(program: &Vec<isize>, a: isize, b: isize, c: isize, d: isize, e: isize) -> isize { let mut pipeline: [PipelinePart; 5] = [ PipelinePart{ program: program.to_vec(), state: ProgramState::Run, input_queue: VecDeque::from(vec![a, 0]), output_queue: VecDeque::new(), ip: 0, previous: 4}, PipelinePart{ program: program.to_vec(), state: ProgramState::Run, input_queue: VecDeque::from(vec![b]), output_queue: VecDeque::new(), ip: 0, previous: 0}, PipelinePart{ program: program.to_vec(), state: ProgramState::Run, input_queue: VecDeque::from(vec![c]), output_queue: VecDeque::new(), ip: 0, previous: 1}, PipelinePart{ program: program.to_vec(), state: ProgramState::Run, input_queue: VecDeque::from(vec![d]), output_queue: VecDeque::new(), ip: 0, previous: 2}, PipelinePart{ program: program.to_vec(), state: ProgramState::Run, input_queue: VecDeque::from(vec![e]), output_queue: VecDeque::new(), ip: 0, previous: 3}, ]; let mut exited = 0; while exited < 5 { exited = 0; for index in 0..5 { loop { match pipeline[index].state { ProgramState::Exit => { exited += 1; break; // go to the next part }, ProgramState::Run => { pipeline[index].state = run_program(&mut pipeline[index]); }, ProgramState::NeedInput => { let previdx = pipeline[index].previous; if pipeline[previdx].output_queue.len() > 0 { let temp = pipeline[previdx].output_queue.pop_front().unwrap(); pipeline[index].input_queue.push_back(temp); pipeline[index].state = ProgramState::Run; } else { match pipeline[previdx].state { ProgramState::Exit => panic!("pipeline fucked: {:?}", pipeline), _ => break, // go to the next part } } } } } } } pipeline[4].output_queue.pop_front().unwrap() } fn main() -> io::Result<()> { let program = fs::read_to_string("input.txt")? .trim() .split(',') .map(|x| x.parse().expect("not a number")) .collect::<Vec<isize>>(); let values = vec![5, 6, 7, 8, 9]; let mut highest_output = 0; for a in 0..5 { for b in 0..4 { for c in 0..3 { for d in 0..2 { let mut values = values.clone(); let output = run_pipe(&program, values.remove(a), values.remove(b), values.remove(c), values.remove(d), values[0]); if output > highest_output { highest_output = output; } } } } } println!("highest_output: {}", highest_output); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_1() { let program = vec![3,26,1001,26,-4,26,3,27,1002,27,2,27,1,27,26,27,4,27,1001,28,-1,28,1005,28,6,99,0,0,5]; let output = run_pipe(&program, 9, 8, 7, 6, 5); assert_eq!(output, 139629729); } #[test] fn test_2() { let program = vec![3,52,1001,52,-5,52,3,53,1,52,56,54,1007,54,5,55,1005,55,26,1001,54,-5,54,1105,1,12,1,53,54,53,1008,54,0,55,1001,55,1,55,2,53,55,53,4,53,1001,56,-1,56,1005,56,6,99,0,0,0,0,10]; let output = run_pipe(&program, 9, 7, 8, 5, 6); assert_eq!(output, 18216); } }
use std::path::PathBuf; use anyhow::{ensure, Result}; use eth2_network_libp2p::NetworkConfig; use serde::Deserialize; use thiserror::Error; #[derive(Debug, Error)] enum Error { #[error("missing executable path")] MissingExecutablePath, #[error("missing configuration")] MissingConfiguration, #[error("trailing arguments")] TrailingArguments, } #[derive(Deserialize)] pub enum Preset { Mainnet, Minimal, } #[derive(Deserialize)] #[serde(default, deny_unknown_fields)] pub struct RuntimeConfig { pub preset: Preset, pub genesis_state_path: PathBuf, #[serde(flatten)] pub network: NetworkConfig, } impl Default for RuntimeConfig { fn default() -> Self { Self { preset: Preset::Mainnet, genesis_state_path: "genesis-state.yaml".into(), network: NetworkConfig::default(), } } } impl RuntimeConfig { pub fn parse(mut strings: impl ExactSizeIterator<Item = String>) -> Result<Self> { ensure!(strings.next().is_some(), Error::MissingExecutablePath); let first_argument = strings.next().ok_or(Error::MissingConfiguration)?; ensure!(strings.len() == 0, Error::TrailingArguments); let runtime_config = serde_yaml::from_str(first_argument.as_str())?; Ok(runtime_config) } } // There used to be tests here but we were forced to omit them to save time.
extern crate diesel; extern crate r2d2; extern crate r2d2_diesel; use diesel::PgConnection; use r2d2_diesel::ConnectionManager; pub type Pool = r2d2::Pool<ConnectionManager<PgConnection>>; pub fn get_db_pool() -> Pool { let db_url = std::env::var("DATABASE_URL").expect("DATABASE_URL must be set"); let manager = ConnectionManager::<PgConnection>::new(db_url); r2d2::Pool::builder() .build(manager) .expect("Failed to create pool") }
#[derive(Clone, Copy)] pub struct Color { pub r: f32, pub g: f32, pub b: f32, pub a: f32, } #[macro_export] macro_rules! color { ($r:expr, $g:expr, $b:expr) => { Color { r: $r as f32, g: $g as f32, b: $b as f32, a: 1.0 } }; ($r:expr, $g:expr, $b:expr, $a:expr) => { Color { r: $r as f32, g: $g as f32, b: $b as f32, a: $a as f32 } }; } impl Color { pub fn argb(&self) -> u32 { (((255.0*self.a) as u32) << 3*8) | (((255.0*self.r) as u32) << 2*8) | (((255.0*self.g) as u32) << 1*8) | (((255.0*self.b) as u32) << 0*8) } }
use alga::general::{Real, SubsetOf, SupersetOf}; use alga::linear::Rotation; use core::{SquareMatrix, OwnedSquareMatrix}; use core::dimension::{DimName, DimNameAdd, DimNameSum, U1}; use core::storage::OwnedStorage; use core::allocator::{Allocator, OwnedAllocator}; use geometry::{PointBase, TranslationBase, IsometryBase, SimilarityBase, TransformBase, SuperTCategoryOf, TAffine}; /* * This file provides the following conversions: * ============================================= * * SimilarityBase -> SimilarityBase * SimilarityBase -> TransformBase * SimilarityBase -> Matrix (homogeneous) */ impl<N1, N2, D: DimName, SA, SB, R1, R2> SubsetOf<SimilarityBase<N2, D, SB, R2>> for SimilarityBase<N1, D, SA, R1> where N1: Real + SubsetOf<N2>, N2: Real + SupersetOf<N1>, R1: Rotation<PointBase<N1, D, SA>> + SubsetOf<R2>, R2: Rotation<PointBase<N2, D, SB>>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, D, U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA>, SB::Alloc: OwnedAllocator<N2, D, U1, SB> { #[inline] fn to_superset(&self) -> SimilarityBase<N2, D, SB, R2> { SimilarityBase::from_isometry( self.isometry.to_superset(), self.scaling().to_superset() ) } #[inline] fn is_in_subset(sim: &SimilarityBase<N2, D, SB, R2>) -> bool { ::is_convertible::<_, IsometryBase<N1, D, SA, R1>>(&sim.isometry) && ::is_convertible::<_, N1>(&sim.scaling()) } #[inline] unsafe fn from_superset_unchecked(sim: &SimilarityBase<N2, D, SB, R2>) -> Self { SimilarityBase::from_isometry( sim.isometry.to_subset_unchecked(), sim.scaling().to_subset_unchecked() ) } } impl<N1, N2, D, SA, SB, R, C> SubsetOf<TransformBase<N2, D, SB, C>> for SimilarityBase<N1, D, SA, R> where N1: Real, N2: Real + SupersetOf<N1>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, C: SuperTCategoryOf<TAffine>, R: Rotation<PointBase<N1, D, SA>> + SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous() SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm) D: DimNameAdd<U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA> + Allocator<N1, D, D> + // needed by R Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous() Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> + Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut Allocator<N2, D, U1> + // needed by: m.fixed_slice Allocator<N2, U1, D> { // needed by: m.fixed_slice #[inline] fn to_superset(&self) -> TransformBase<N2, D, SB, C> { TransformBase::from_matrix_unchecked(self.to_homogeneous().to_superset()) } #[inline] fn is_in_subset(t: &TransformBase<N2, D, SB, C>) -> bool { <Self as SubsetOf<_>>::is_in_subset(t.matrix()) } #[inline] unsafe fn from_superset_unchecked(t: &TransformBase<N2, D, SB, C>) -> Self { Self::from_superset_unchecked(t.matrix()) } } impl<N1, N2, D, SA, SB, R> SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>> for SimilarityBase<N1, D, SA, R> where N1: Real, N2: Real + SupersetOf<N1>, SA: OwnedStorage<N1, D, U1>, SB: OwnedStorage<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, R: Rotation<PointBase<N1, D, SA>> + SubsetOf<OwnedSquareMatrix<N1, DimNameSum<D, U1>, SA::Alloc>> + // needed by: .to_homogeneous() SubsetOf<SquareMatrix<N2, DimNameSum<D, U1>, SB>>, // needed by: ::convert_unchecked(mm) D: DimNameAdd<U1>, SA::Alloc: OwnedAllocator<N1, D, U1, SA> + Allocator<N1, D, D> + // needed by R Allocator<N1, DimNameSum<D, U1>, DimNameSum<D, U1>> + // needed by: .to_homogeneous() Allocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>>, // needed by R SB::Alloc: OwnedAllocator<N2, DimNameSum<D, U1>, DimNameSum<D, U1>, SB> + Allocator<N2, D, D> + // needed by: mm.fixed_slice_mut Allocator<N2, D, U1> + // needed by: m.fixed_slice Allocator<N2, U1, D> { // needed by: m.fixed_slice #[inline] fn to_superset(&self) -> SquareMatrix<N2, DimNameSum<D, U1>, SB> { self.to_homogeneous().to_superset() } #[inline] fn is_in_subset(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> bool { let mut rot = m.fixed_slice::<D, D>(0, 0).clone_owned(); if rot.fixed_columns_mut::<U1>(0).try_normalize_mut(N2::zero()).is_some() && rot.fixed_columns_mut::<U1>(1).try_normalize_mut(N2::zero()).is_some() && rot.fixed_columns_mut::<U1>(2).try_normalize_mut(N2::zero()).is_some() { // FIXME: could we avoid explicit the computation of the determinant? // (its sign is needed to see if the scaling factor is negative). if rot.determinant() < N2::zero() { rot.fixed_columns_mut::<U1>(0).neg_mut(); rot.fixed_columns_mut::<U1>(1).neg_mut(); rot.fixed_columns_mut::<U1>(2).neg_mut(); } let bottom = m.fixed_slice::<U1, D>(D::dim(), 0); // Scalar types agree. m.iter().all(|e| SupersetOf::<N1>::is_in_subset(e)) && // The normalized block part is a rotation. // rot.is_special_orthogonal(N2::default_epsilon().sqrt()) && // The bottom row is (0, 0, ..., 1) bottom.iter().all(|e| e.is_zero()) && m[(D::dim(), D::dim())] == N2::one() } else { false } } #[inline] unsafe fn from_superset_unchecked(m: &SquareMatrix<N2, DimNameSum<D, U1>, SB>) -> Self { let mut mm = m.clone_owned(); let na = mm.fixed_slice_mut::<D, U1>(0, 0).normalize_mut(); let nb = mm.fixed_slice_mut::<D, U1>(0, 1).normalize_mut(); let nc = mm.fixed_slice_mut::<D, U1>(0, 2).normalize_mut(); let mut scale = (na + nb + nc) / ::convert(3.0); // We take the mean, for robustness. // FIXME: could we avoid the explicit computation of the determinant? // (its sign is needed to see if the scaling factor is negative). if mm.fixed_slice::<D, D>(0, 0).determinant() < N2::zero() { mm.fixed_slice_mut::<D, U1>(0, 0).neg_mut(); mm.fixed_slice_mut::<D, U1>(0, 1).neg_mut(); mm.fixed_slice_mut::<D, U1>(0, 2).neg_mut(); scale = -scale; } let t = m.fixed_slice::<D, U1>(0, D::dim()).into_owned(); let t = TranslationBase::from_vector(::convert_unchecked(t)); Self::from_parts(t, ::convert_unchecked(mm), ::convert_unchecked(scale)) } }
use std::fmt::{self, Display, Formatter}; use std::result; use crate::compiler::lexer::Line; /// Wrapped for parsing time errors pub type Result<T> = result::Result<T, Error>; /// Some Errors produced by parser and lexer which be dealt by parser for reporting syntax errors #[derive(Debug, Clone, Eq, PartialEq)] pub enum Error { /// Need more bytes EOF { line: Line }, /// Illegal Identifier IllegalIdentifier { line: Line }, /// Illegal Number Literal IllegalNumLiteral { line: Line }, /// Illegal String IllegalString { line: Line }, /// Illegal Token IllegalToken { line: Line }, /// Cannot be Escaped IllegalEscape { line: Line }, /// Need more Tokens NoMoreTokens { line: Line }, /// Illegal Expression IllegalExpression { line: Line }, /// Illegal Expression IllegalStat { line: Line }, /// Not a Identifier NotIdentifier { line: Line }, /// Not a var expression NotVarExpression { line: Line }, /// Not a operator NotOperator { line: Line }, /// Illegal function params IllegalFunction { line: Line }, /// Brackets do not match NotMatchBrackets { line: Line }, /// Missing assignment MissingAssignment { line: Line }, /// Illegal Function call IllegalFnCall { line: Line }, /// Illegal Function definition IllegalFnDef { line: Line }, /// No more Registers NoMoreRegisters, /// Illegal Register IllegalRegister, /// No more Scopes NoMoreScopes, /// Not in a loop NoLoop { line: Line }, /// Not a UpValue NotUpValue { line: Line }, /// Not a vararg function NotVararg { line: Line }, NoReturnValue, } impl Display for Error { fn fmt(&self, f: &mut Formatter) -> fmt::Result { use Error::*; match self { EOF { line } => write!(f, "line: {}, error: EOF", *line), IllegalIdentifier { line } => write!(f, "line: {}, error: IllegalIdentifier", *line), IllegalNumLiteral { line } => write!(f, "line: {}, error: IllegalNumLiteral", *line), IllegalString { line } => write!(f, "line: {}, error: IllegalString", *line), IllegalToken { line } => write!(f, "line: {}, error: IllegalToken", *line), IllegalEscape { line } => write!(f, "line: {}, error: IllegalEscape", *line), NoMoreTokens { line } => write!(f, "line: {}, error: NoMoreTokens", *line), IllegalExpression { line } => write!(f, "line: {}, error: IllegalExpression", *line), IllegalStat { line } => write!(f, "line: {}, error: IllegalStat", *line), NotIdentifier { line } => write!(f, "line: {}, error: NotIdentifier", *line), NotVarExpression { line } => write!(f, "line: {}, error: NotVarExpression", *line), NotOperator { line } => write!(f, "line: {}, error: NotOperator", *line), IllegalFunction { line } => write!(f, "line: {}, error: IllegalFunction", *line), NotMatchBrackets { line } => write!(f, "line: {}, error: NotMatchBrackets", *line), MissingAssignment { line } => write!(f, "line: {}, error: MissingAssignment", *line), IllegalFnCall { line } => write!(f, "line: {}, error: IllegalFnCall", *line), IllegalFnDef { line } => write!(f, "line: {}, error: IllegalFnDef", *line), NoMoreRegisters => write!(f, "codegen error: NoMoreRegisters"), IllegalRegister => write!(f, "codegen error: IllegalRegister"), NoMoreScopes => write!(f, "codegen error: NoMoreScopes"), NoLoop { line } => write!(f, "line: {}, codegen error: NoLoop", *line), NotUpValue { line } => write!(f, "line: {}, codegen error: NotUpValue", *line), NotVararg { line } => write!(f, "line: {}, codegen error: NotVararg", *line), _ => unreachable!(), } } }
#[macro_use] extern crate bitflags; use byteorder::BigEndian; use byteorder::ReadBytesExt; use bytes::Buf; use std::env; use std::io::{self, BufRead, Cursor, Read, Write}; use std::net::{Shutdown, SocketAddr}; use std::sync::{Arc, Mutex}; use tokio; use tokio::io::{copy, shutdown}; use tokio::net::{TcpListener, TcpStream}; use tokio::prelude::*; fn main() -> Result<(), Box<dyn std::error::Error>> { let listen_addr = env::args().nth(1).unwrap_or("127.0.0.1:8081".to_string()); let listen_addr = listen_addr.parse::<SocketAddr>()?; let server_addr = env::args().nth(2).unwrap_or("127.0.0.1:8080".to_string()); let server_addr = server_addr.parse::<SocketAddr>()?; // Create a TCP listener which will listen for incoming connections. let socket = TcpListener::bind(&listen_addr)?; println!("Listening on: {}", listen_addr); println!("Proxying to: {}", server_addr); let done = socket .incoming() .map_err(|e| println!("error accepting socket; error = {:?}", e)) .for_each(move |client| { let server = TcpStream::connect(&server_addr); let amounts = server.and_then(move |server| { let client_reader = MyTdsStream::from(client); let client_writer = client_reader.clone(); let server_reader = MyTcpStream(Arc::new(Mutex::new(server))); let server_writer = server_reader.clone(); let client_to_server = copy(client_reader, server_writer) .and_then(|(n, _, server_writer)| shutdown(server_writer).map(move |_| n)); let server_to_client = copy(server_reader, client_writer) .and_then(|(n, _, client_writer)| shutdown(client_writer).map(move |_| n)); client_to_server.join(server_to_client) }); let msg = amounts .map(move |(from_client, from_server)| { println!( "client wrote {} bytes and received {} bytes", from_client, from_server ); }) .map_err(|e| { // Don't panic. Maybe the client just disconnected too soon. println!("error: {}", e); }); tokio::spawn(msg); Ok(()) }); tokio::run(done); Ok(()) } // This is a custom type used to have a custom implementation of the // `AsyncWrite::shutdown` method which actually calls `TcpStream::shutdown` to // notify the remote end that we're done writing. #[derive(Clone)] struct MyTcpStream(Arc<Mutex<TcpStream>>); #[derive(Clone)] struct PacketAnalyzer { bytes_left: usize, header: Option<PacketHeader>, buf: Vec<u8>, } impl PacketAnalyzer { fn new() -> Self { Self { bytes_left: 0, header: None, buf: Vec::default(), } } fn append(&mut self, buf: &[u8]) { self.buf.extend_from_slice(buf); } fn parse(&mut self) -> io::Result<Vec<TdsPacket>> { let mut packets = Vec::new(); // println!( // "wd size: {}, bytes_left: {}", // self.buf.len(), // self.bytes_left // ); if self.header.is_some() && self.bytes_left <= self.buf.len() { let _data = self.buf.drain(..self.bytes_left).collect::<Vec<u8>>(); packets.push(TdsPacket { header: self.header.take().unwrap(), data: _data, }); self.bytes_left = 0; } while self.bytes_left == 0 && self.buf.len() >= 8 { let header_bytes = self.buf.drain(..8).collect::<Vec<u8>>(); let mut cursor = Cursor::new(&header_bytes); let pt = cursor.read_u8()?; //dbg!(&pt); let ps = cursor.read_u8()?; let packet_type = PacketType::from_u8(pt); let header = match packet_type { Some(ty) => PacketHeader { ty, status: PacketStatus::from_u8(ps).unwrap(), length: cursor.read_u16::<BigEndian>()?, spid: cursor.read_u16::<BigEndian>()?, id: cursor.read_u8()?, window: cursor.read_u8()?, }, None => PacketHeader { ty: PacketType::AttentionSignal, status: PacketStatus::IgnoreEvent, length: cursor.read_u16::<BigEndian>()?, spid: cursor.read_u16::<BigEndian>()?, id: cursor.read_u8()?, window: cursor.read_u8()?, }, }; //println!("{:?}", header); if header.length >= 8 { self.bytes_left = header.length as usize - 8; } self.header = Some(header); if self.buf.len() >= self.bytes_left { packets.push(TdsPacket { header: self.header.take().unwrap(), data: self.buf.drain(..self.bytes_left).collect::<Vec<u8>>(), }); self.bytes_left = 0; } } Ok(packets) } } #[derive(Clone)] struct MyTdsStream { stream: Arc<Mutex<TcpStream>>, reader: PacketAnalyzer, writer: PacketAnalyzer, } struct TdsPacket { header: PacketHeader, data: Vec<u8>, } impl MyTdsStream { fn from(stream: TcpStream) -> Self { Self { stream: Arc::new(Mutex::new(stream)), reader: PacketAnalyzer::new(), writer: PacketAnalyzer::new(), } } } impl Read for MyTdsStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { let r = self.stream.lock().unwrap().read(buf); if let Ok(n) = r { // self.reader.append(&buf[0..n]); // let packets = self.reader.parse().expect("failed to parse"); // for packet in packets { // println!("read: {:?}", packet.header); // } } r } } impl Write for MyTdsStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { let ret = self.stream.lock().unwrap().write(buf); if let Ok(n) = ret { self.writer.append(&buf[0..n]); let packets = self.writer.parse().expect(" failed to parse"); for packet in packets { println!("writ: {:?}", packet.header); } } ret } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl Read for MyTcpStream { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.lock().unwrap().read(buf) } } impl Write for MyTcpStream { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.lock().unwrap().write(buf) } fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl AsyncRead for MyTcpStream {} impl AsyncRead for MyTdsStream {} impl AsyncWrite for MyTcpStream { fn shutdown(&mut self) -> Poll<(), io::Error> { self.0.lock().unwrap().shutdown(Shutdown::Write)?; Ok(().into()) } } impl AsyncWrite for MyTdsStream { fn shutdown(&mut self) -> Poll<(), io::Error> { self.stream.lock().unwrap().shutdown(Shutdown::Write)?; Ok(().into()) } } trait FromUint where Self: Sized, { fn from_u8(n: u8) -> Option<Self>; fn from_u32(n: u32) -> Option<Self>; } macro_rules! uint_enum { ($( #[$gattr:meta] )* pub enum $ty:ident { $( $( #[$attr:meta] )* $variant:ident = $val:expr,)* }) => { uint_enum!($( #[$gattr ])* (pub) enum $ty { $( $( #[$attr] )* $variant = $val, )* }); }; ($( #[$gattr:meta] )* enum $ty:ident { $( $( #[$attr:meta] )* $variant:ident = $val:expr,)* }) => { uint_enum!($( #[$gattr ])* () enum $ty { $( $( #[$attr] )* $variant = $val, )* }); }; ($( #[$gattr:meta] )* ( $($vis:tt)* ) enum $ty:ident { $( $( #[$attr:meta] )* $variant:ident = $val:expr,)* }) => { #[derive(Debug, Copy, Clone)] $( #[$gattr] )* $( $vis )* enum $ty { $( $( #[$attr ])* $variant = $val, )* } impl FromUint for $ty { fn from_u8(n: u8) -> Option<$ty> { match n { $( x if x == $ty::$variant as u8 => Some($ty::$variant), )* _ => None } } fn from_u32(n: u32) -> Option<$ty> { match n { $( x if x == $ty::$variant as u32 => Some($ty::$variant), )* _ => None } } } } } uint_enum! { /// the type of the packet [2.2.3.1.1]#[repr(u32)] #[derive(PartialEq)] #[repr(u8)] pub enum PacketType { SQLBatch = 1, /// unused PreTDSv7Login = 2, RPC = 3, TabularResult = 4, AttentionSignal = 6, BulkLoad = 7, /// Federated Authentication Token Fat = 8, TransactionManagerReq = 14, TDSv7Login = 16, SSPI = 17, PreLogin = 18, } } uint_enum! { /// the message state [2.2.3.1.2] #[derive(PartialEq)] #[repr(u8)] pub enum PacketStatus { NormalMessage = 0, EndOfMessage = 1, /// [client to server ONLY] (EndOfMessage also required) IgnoreEvent = 3, /// [client to server ONLY] [>= TDSv7.1] ResetConnection = 0x08, /// [client to server ONLY] [>= TDSv7.3] ResetConnectionSkipTran = 0x10, } } #[derive(Debug, Clone)] pub struct PacketHeader { pub ty: PacketType, pub status: PacketStatus, /// [BE] the length of the packet (including the 8 header bytes) /// must match the negotiated size sending from client to server [since TDSv7.3] after login /// (only if not EndOfMessage) pub length: u16, /// [BE] the process ID on the server, for debugging purposes only pub spid: u16, /// packet id pub id: u8, /// currently unused pub window: u8, }
use azure_core::AddAsHeader; use http::request::Builder; use http::HeaderMap; use std::borrow::Cow; use std::collections::HashMap; use std::convert::TryFrom; #[derive(Debug, Clone, PartialEq, Eq)] pub struct Properties<'a, 'b>(HashMap<Cow<'a, str>, Cow<'b, str>>); const HEADER: &str = "x-ms-properties"; impl<'a, 'b> Default for Properties<'a, 'b> { fn default() -> Self { Self::new() } } impl<'a, 'b> Properties<'a, 'b> { pub fn new() -> Self { Self(HashMap::new()) } pub fn insert<K: Into<Cow<'a, str>>, V: Into<Cow<'b, str>>>( &mut self, k: K, v: V, ) -> Option<Cow<'b, str>> { self.0.insert(k.into(), v.into()) } pub fn hash_map(&self) -> &HashMap<Cow<'a, str>, Cow<'b, str>> { &self.0 } } impl<'a, 'b> AddAsHeader for Properties<'a, 'b> { fn add_as_header(&self, builder: Builder) -> Builder { // the header is a comma separated list of key=base64(value) see // [https://docs.microsoft.com/rest/api/storageservices/datalakestoragegen2/filesystem/create#request-headers](https://docs.microsoft.com/rest/api/storageservices/datalakestoragegen2/filesystem/create#request-headers) let mut s = String::new(); self.0.iter().for_each(|(k, v)| { s.push_str(&format!("{}={},", k.as_ref(), base64::encode(v.as_ref()))); }); // since we added a comma to the last entry, we will strip it to the exported header (this // is safe since we know that comma is 1 byte in UTF8): builder.header(HEADER, &s[..s.len() - 1]) } fn add_as_header2( &self, request: &mut azure_core::Request, ) -> Result<(), azure_core::HTTPHeaderError> { // the header is a comma separated list of key=base64(value) see // [https://docs.microsoft.com/rest/api/storageservices/datalakestoragegen2/filesystem/create#request-headers](https://docs.microsoft.com/rest/api/storageservices/datalakestoragegen2/filesystem/create#request-headers) let s = self .0 .iter() .map(|(k, v)| format!("{}={}", k.as_ref(), base64::encode(v.as_ref()))) .collect::<Vec<_>>() .join(","); request .headers_mut() .append(HEADER, http::header::HeaderValue::from_str(&s)?); Ok(()) } } impl TryFrom<&HeaderMap> for Properties<'static, 'static> { type Error = crate::Error; fn try_from(headers: &HeaderMap) -> Result<Self, Self::Error> { let mut properties = Self::new(); // this is probably too complicated. Should we split // it in more maneageable code blocks? // The logic is this: // 1. Look for the header. If not found return error // 2. Split the header value by comma // 3. For each comma separated value: // 4. Split by equals. If we do not have at least 2 entries, return error. // 5. For each pair: // 6. Base64 decode the second entry (value). If error, return error. // 7. Insert the key value pair in the returned struct. headers .get(HEADER) .ok_or_else(|| crate::Error::HeaderNotFound(HEADER.to_owned()))? // HEADER must exists or we return Err .to_str()? .split(',') // The list is a CSV so we split by comma .map(|key_value_pair| { let mut key_and_value = key_value_pair.split('='); // Each entry is key and value separated by = // we must have a key and a value (so two entries) let key = key_and_value .next() .ok_or_else(|| crate::Error::GenericErrorWithText("missing key".to_owned()))?; let value = key_and_value.next().ok_or_else(|| { crate::Error::GenericErrorWithText("missing value".to_owned()) })?; // we do not check if there are more entries. We just ignore them. Ok((key, value)) }) .collect::<crate::Result<Vec<(&str, &str)>>>()? // if we have an error, return error .into_iter() .map(|(key, value)| { let value = std::str::from_utf8(&base64::decode(value)?)?.to_owned(); // the value is base64 encoded se we decode it Ok((key, value)) }) .collect::<crate::Result<Vec<(&str, String)>>>()? // if we have an error, return error .into_iter() .for_each(|(key, value)| { properties.insert(key.to_owned(), value); // finally store the key and value into the properties }); Ok(properties) } }