diff --git a/.gitignore b/.gitignore index 2775c45baa..d64b48786c 100644 --- a/.gitignore +++ b/.gitignore @@ -10,8 +10,8 @@ ### Editors ### .idea /target/* - */launch.json +.vscode ## Rococo genesis-state* diff --git a/.rustfmt.toml b/.rustfmt.toml new file mode 100644 index 0000000000..a77308f508 --- /dev/null +++ b/.rustfmt.toml @@ -0,0 +1,11 @@ +# https://rust-lang.github.io/rustfmt/ + +hard_tabs = false +max_width = 120 +edition = "2018" +wrap_comments = true +comment_width = 120 +imports_granularity = "Crate" + +# TODO: https://github.com/rust-lang/rustfmt/issues/3382#issuecomment-536034758 +blank_lines_lower_bound = 0 \ No newline at end of file diff --git a/.vscode/launch.json b/.vscode/launch.json deleted file mode 100644 index 0f406d2f0b..0000000000 --- a/.vscode/launch.json +++ /dev/null @@ -1,18 +0,0 @@ -{ - // Use IntelliSense to learn about possible attributes. - // Hover to view descriptions of existing attributes. - // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 - "version": "0.2.0", - "configurations": [ - { - "type": "lldb", - "request": "launch", - "name": "Debug", - "program": "${workspaceRoot}/target/debug/${workspaceRootFolderName}", - "args": [], - "cwd": "${workspaceRoot}", - "sourceLanguages": ["rust"] - } - - ] -} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 61fb092315..0000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "editor.formatOnSave": true, - "[rust]": { - "editor.defaultFormatter": "matklad.rust-analyzer" - } -} diff --git a/crates/bitcoin/src/address.rs b/crates/bitcoin/src/address.rs index f9468063b7..ac7b889a2b 100644 --- a/crates/bitcoin/src/address.rs +++ b/crates/bitcoin/src/address.rs @@ -1,24 +1,16 @@ -use crate::types::*; -use crate::Error; -use crate::Script; -use bitcoin_hashes::hash160::Hash as Hash160; -use bitcoin_hashes::Hash; +use crate::{types::*, Error, Script}; +use bitcoin_hashes::{hash160::Hash as Hash160, Hash}; use codec::{Decode, Encode}; use sha2::{Digest, Sha256}; use sp_core::H160; -use secp256k1::{ - constants::PUBLIC_KEY_SIZE, Error as Secp256k1Error, PublicKey as Secp256k1PublicKey, -}; +use secp256k1::{constants::PUBLIC_KEY_SIZE, Error as Secp256k1Error, PublicKey as Secp256k1PublicKey}; /// A Bitcoin address is a serialized identifier that represents the destination for a payment. /// Address prefixes are used to indicate the network as well as the format. Since the Parachain /// follows SPV assumptions we do not need to know which network a payment is included in. #[derive(Encode, Decode, Clone, Ord, PartialOrd, PartialEq, Eq, Debug, Copy)] -#[cfg_attr( - feature = "std", - derive(serde::Serialize, serde::Deserialize, std::hash::Hash) -)] +#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize, std::hash::Hash))] pub enum Address { P2PKH(H160), P2SH(H160), @@ -40,7 +32,8 @@ impl std::fmt::Display for Address { impl Address { pub fn from_script(script: &Script) -> Result { if script.is_p2pkh() { - // 0x76 (OP_DUP) - 0xa9 (OP_HASH160) - 0x14 (20 bytes len) - <20 bytes pubkey hash> - 0x88 (OP_EQUALVERIFY) - 0xac (OP_CHECKSIG) + // 0x76 (OP_DUP) - 0xa9 (OP_HASH160) - 0x14 (20 bytes len) - <20 bytes pubkey hash> - 0x88 (OP_EQUALVERIFY) + // - 0xac (OP_CHECKSIG) Ok(Self::P2PKH(H160::from_slice(&script.as_bytes()[3..23]))) } else if script.is_p2sh() { // 0xa9 (OP_HASH160) - 0x14 (20 bytes hash) - <20 bytes script hash> - 0x87 (OP_EQUAL) @@ -153,8 +146,7 @@ impl<'de> serde::Deserialize<'de> for PublicKey { pub mod global { use secp256k1::{ffi::types::AlignedType, AllPreallocated, Secp256k1}; - use sp_std::ops::Deref; - use sp_std::{vec, vec::Vec}; + use sp_std::{ops::Deref, vec, vec::Vec}; // this is what lazy_static uses internally use spin::Once; @@ -224,10 +216,7 @@ impl PublicKey { self.new_deposit_public_key_with_secret(&self.new_secret_key(secure_id)) } - fn new_deposit_public_key_with_secret( - &self, - secret_key: &[u8; 32], - ) -> Result { + fn new_deposit_public_key_with_secret(&self, secret_key: &[u8; 32]) -> Result { let mut public_key = Secp256k1PublicKey::from_slice(&self.0)?; // D = V * c public_key.mul_assign(global::SECP256K1, secret_key)?; @@ -245,8 +234,7 @@ impl PublicKey { mod tests { use super::*; use frame_support::assert_err; - use secp256k1::rand::rngs::OsRng; - use secp256k1::{Secp256k1, SecretKey as Secp256k1SecretKey}; + use secp256k1::{rand::rngs::OsRng, Secp256k1, SecretKey as Secp256k1SecretKey}; #[test] fn test_public_key_to_hash() { @@ -254,8 +242,8 @@ mod tests { // "02ff01b82f2f166c719937d5bd856bd919d9d6d495826cde3733cdb0d1084c8d12" let public_key = PublicKey([ - 2, 255, 1, 184, 47, 47, 22, 108, 113, 153, 55, 213, 189, 133, 107, 217, 25, 217, 214, - 212, 149, 130, 108, 222, 55, 51, 205, 176, 209, 8, 76, 141, 18, + 2, 255, 1, 184, 47, 47, 22, 108, 113, 153, 55, 213, 189, 133, 107, 217, 25, 217, 214, 212, 149, 130, 108, + 222, 55, 51, 205, 176, 209, 8, 76, 141, 18, ]); assert_eq!( @@ -274,8 +262,7 @@ mod tests { // https://en.bitcoin.it/wiki/Private_key assert_err!( Secp256k1SecretKey::from_slice( - &hex::decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141") - .unwrap() + &hex::decode("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141").unwrap() ), Secp256k1Error::InvalidSecretKey ); @@ -296,9 +283,7 @@ mod tests { let vault_public_key = PublicKey(vault_public_key.serialize()); // D = V * c - let deposit_public_key = vault_public_key - .new_deposit_public_key(secure_id.clone()) - .unwrap(); + let deposit_public_key = vault_public_key.new_deposit_public_key(secure_id.clone()).unwrap(); // d = v * c vault_secret_key @@ -315,25 +300,23 @@ mod tests { fn test_new_deposit_public_key_static() { // bcrt1qzrkyemjkaxq48zwlnhxvear8fh6lvkwszxy7dm let old_public_key = PublicKey([ - 2, 123, 236, 243, 192, 100, 34, 40, 51, 111, 129, 130, 160, 64, 129, 135, 11, 184, 68, - 84, 83, 198, 234, 196, 150, 13, 208, 86, 34, 150, 10, 59, 247, + 2, 123, 236, 243, 192, 100, 34, 40, 51, 111, 129, 130, 160, 64, 129, 135, 11, 184, 68, 84, 83, 198, 234, + 196, 150, 13, 208, 86, 34, 150, 10, 59, 247, ]); let secret_key = &[ - 137, 16, 46, 159, 212, 158, 232, 178, 197, 253, 105, 137, 102, 159, 70, 217, 110, 211, - 254, 82, 216, 4, 105, 171, 102, 252, 54, 190, 114, 91, 11, 69, + 137, 16, 46, 159, 212, 158, 232, 178, 197, 253, 105, 137, 102, 159, 70, 217, 110, 211, 254, 82, 216, 4, + 105, 171, 102, 252, 54, 190, 114, 91, 11, 69, ]; // bcrt1qn9mgwncjtnavx23utveqqcrxh3zjtll58pc744 - let new_public_key = old_public_key - .new_deposit_public_key_with_secret(secret_key) - .unwrap(); + let new_public_key = old_public_key.new_deposit_public_key_with_secret(secret_key).unwrap(); assert_eq!( new_public_key, PublicKey([ - 2, 151, 202, 113, 10, 9, 43, 125, 187, 101, 157, 152, 191, 94, 12, 236, 133, 229, - 16, 233, 221, 52, 150, 183, 243, 61, 110, 8, 152, 132, 99, 49, 189, + 2, 151, 202, 113, 10, 9, 43, 125, 187, 101, 157, 152, 191, 94, 12, 236, 133, 229, 16, 233, 221, 52, + 150, 183, 243, 61, 110, 8, 152, 132, 99, 49, 189, ]) ); } diff --git a/crates/bitcoin/src/formatter.rs b/crates/bitcoin/src/formatter.rs index 805fe58ad3..35ef1fbd38 100644 --- a/crates/bitcoin/src/formatter.rs +++ b/crates/bitcoin/src/formatter.rs @@ -1,11 +1,7 @@ use primitive_types::U256; -use sp_std::vec::Vec; -use sp_std::{prelude::*, vec}; +use sp_std::{prelude::*, vec, vec::Vec}; -use crate::merkle::MerkleProof; -use crate::script::*; -use crate::types::*; -use crate::Error; +use crate::{merkle::MerkleProof, script::*, types::*, Error}; const WITNESS_FLAG: u8 = 0x01; const WITNESS_MARKER: u8 = 0x00; @@ -290,8 +286,7 @@ impl TryFormattable for MerkleProof { .ok_or(Error::ArithmeticUnderflow)?; let mut bytes: Vec = vec![0; len]; for p in 0..self.flag_bits.len() { - bytes[p.checked_div(8).ok_or(Error::ArithmeticUnderflow)?] |= - (self.flag_bits[p] as u8) << (p % 8) as u8; + bytes[p.checked_div(8).ok_or(Error::ArithmeticUnderflow)?] |= (self.flag_bits[p] as u8) << (p % 8) as u8; } formatter.format(bytes.len() as u8); formatter.output(&bytes); @@ -343,8 +338,7 @@ impl Formatter { #[cfg(test)] mod tests { use super::*; - use crate::parser; - use crate::utils::sha256d_le; + use crate::{parser, utils::sha256d_le}; #[test] fn test_format_int_types() { @@ -403,10 +397,8 @@ mod tests { #[test] fn test_format_extended_transaction() { - let expected_hash = - H256Le::from_hex_be("b759d39a8596b70b3a46700b83e1edb247e17ba58df305421864fe7a9ac142ea"); - let expected_txid = - H256Le::from_hex_be("c586389e5e4b3acb9d6c8be1c19ae8ab2795397633176f5a6442a261bbdefc3a"); + let expected_hash = H256Le::from_hex_be("b759d39a8596b70b3a46700b83e1edb247e17ba58df305421864fe7a9ac142ea"); + let expected_txid = H256Le::from_hex_be("c586389e5e4b3acb9d6c8be1c19ae8ab2795397633176f5a6442a261bbdefc3a"); let raw_tx = parser::tests::sample_extended_transaction(); let tx_bytes = hex::decode(&raw_tx).unwrap(); let transaction = parser::parse_transaction(&tx_bytes).unwrap(); @@ -436,13 +428,8 @@ mod tests { assert_eq!( parsed_header, BlockHeader { - merkle_root: H256Le::from_hex_be( - "0c58e162a2d0a6cb5a9ed132f0fdad56eee3a3a03b3ef84aa2ec4a6825a7a029" - ), - target: U256::from_dec_str( - "1260618571951953247774709397757627131971305851995253681160192" - ) - .unwrap(), + merkle_root: H256Le::from_hex_be("0c58e162a2d0a6cb5a9ed132f0fdad56eee3a3a03b3ef84aa2ec4a6825a7a029"), + target: U256::from_dec_str("1260618571951953247774709397757627131971305851995253681160192").unwrap(), timestamp: 1603359907, version: 536870912, hash_prev_block: H256Le::from_hex_be( @@ -458,8 +445,7 @@ mod tests { // taken from https://bitcoin.org/en/developer-reference#block-headers #[test] fn test_format_u256() { - let value = U256::from_dec_str("680733321990486529407107157001552378184394215934016880640") - .unwrap(); + let value = U256::from_dec_str("680733321990486529407107157001552378184394215934016880640").unwrap(); let result = value.try_format().unwrap(); let expected = hex::decode("30c31b18").unwrap(); assert_eq!(result, expected); @@ -468,9 +454,7 @@ mod tests { #[test] fn test_format_u256_testnet() { // 0xb8e4a3e93640d7a4623e92589e40960b4b20420478d7ed60662176c323cf4caa - let value = - U256::from_dec_str("1260618571951953247774709397757627131971305851995253681160192") - .unwrap(); + let value = U256::from_dec_str("1260618571951953247774709397757627131971305851995253681160192").unwrap(); let result = value.try_format().unwrap(); let expected = hex::decode("d4c8001a").unwrap(); assert_eq!(result, expected); diff --git a/crates/bitcoin/src/merkle.rs b/crates/bitcoin/src/merkle.rs index 4c9d9ecf87..0ff161e133 100644 --- a/crates/bitcoin/src/merkle.rs +++ b/crates/bitcoin/src/merkle.rs @@ -4,10 +4,12 @@ extern crate mocktopus; #[cfg(test)] use mocktopus::macros::mockable; -use crate::parser::BytesParser; -use crate::types::{BlockHeader, CompactUint, H256Le}; -use crate::utils::hash256_merkle_step; -use crate::Error; +use crate::{ + parser::BytesParser, + types::{BlockHeader, CompactUint, H256Le}, + utils::hash256_merkle_step, + Error, +}; use sp_std::prelude::*; // Values taken from https://github.com/bitcoin/bitcoin/blob/78dae8caccd82cfbfd76557f1fb7d7557c7b5edb/src/consensus/consensus.h @@ -88,10 +90,7 @@ impl MerkleTree { } else { left }; - Ok(hash256_merkle_step( - &left.to_bytes_le(), - &right.to_bytes_le(), - )) + Ok(hash256_merkle_step(&left.to_bytes_le(), &right.to_bytes_le())) } } } @@ -108,12 +107,7 @@ impl MerkleProof { MerkleTree::compute_height(self.transactions_count) } - pub fn compute_merkle_root( - &self, - index: u32, - height: u32, - tx_ids: &[H256Le], - ) -> Result { + pub fn compute_merkle_root(&self, index: u32, height: u32, tx_ids: &[H256Le]) -> Result { MerkleTree::compute_root(index, height, self.transactions_count, &tx_ids.to_vec()) } @@ -128,10 +122,7 @@ impl MerkleProof { // this code is ported from the official Bitcoin client: // https://github.com/bitcoin/bitcoin/blob/99813a9745fe10a58bedd7a4cb721faf14f907a4/src/merkleblock.cpp let parent_of_hash = *self.flag_bits.get(traversal.bits_used).ok_or(Error::EOS)?; - traversal.bits_used = traversal - .bits_used - .checked_add(1) - .ok_or(Error::ArithmeticOverflow)?; + traversal.bits_used = traversal.bits_used.checked_add(1).ok_or(Error::ArithmeticOverflow)?; if height == 0 || !parent_of_hash { if traversal.hashes_used >= self.hashes.len() { @@ -142,10 +133,7 @@ impl MerkleProof { traversal.merkle_position = Some(pos); traversal.hash_position = Some(traversal.hashes_used); } - traversal.hashes_used = traversal - .hashes_used - .checked_add(1) - .ok_or(Error::ArithmeticOverflow)?; + traversal.hashes_used = traversal.hashes_used.checked_add(1).ok_or(Error::ArithmeticOverflow)?; return Ok(hash); } @@ -188,8 +176,7 @@ impl MerkleProof { return Err(Error::MalformedMerkleProof); } - let root = - self.traverse_and_extract(self.compute_partial_tree_height(), 0, &mut traversal)?; + let root = self.traverse_and_extract(self.compute_partial_tree_height(), 0, &mut traversal)?; let merkle_position = traversal.merkle_position.ok_or(Error::InvalidMerkleProof)?; let hash_position = traversal.hash_position.ok_or(Error::InvalidMerkleProof)?; @@ -317,16 +304,10 @@ mod tests { fn sample_valid_proof_result() -> ProofResult { let tx_id = H256Le::from_bytes_le( - &hex::decode( - "c8589f304d3b9df1d4d8b3d15eb6edaaa2af9d796e9d9ace12b31f293705c5e9".to_owned(), - ) - .unwrap(), + &hex::decode("c8589f304d3b9df1d4d8b3d15eb6edaaa2af9d796e9d9ace12b31f293705c5e9".to_owned()).unwrap(), ); let merkle_root = H256Le::from_bytes_le( - &hex::decode( - "90d079ef103a8b7d3d9315126468f78b456690ba6628d1dcd5a16c9990fbe11e".to_owned(), - ) - .unwrap(), + &hex::decode("90d079ef103a8b7d3d9315126468f78b456690ba6628d1dcd5a16c9990fbe11e".to_owned()).unwrap(), ); ProofResult { extracted_root: merkle_root, @@ -351,14 +332,12 @@ mod tests { let raw_proof = hex::decode(&PROOF_HEX[..]).unwrap(); let proof = MerkleProof::parse(&raw_proof).unwrap(); let expected_merkle_root = - H256::from_str("a0e8ab249b25ef31da538262ab8b2885ce63ca82a22fd0efdce76ea6920d1f90") - .unwrap(); + H256::from_str("a0e8ab249b25ef31da538262ab8b2885ce63ca82a22fd0efdce76ea6920d1f90").unwrap(); assert_eq!(proof.block_header.merkle_root, expected_merkle_root); assert_eq!(proof.transactions_count, 2729); assert_eq!(proof.hashes.len(), 13); // NOTE: following hash is in big endian - let expected_hash = - H256Le::from_hex_be("02bcec80995d37160bba1cfc4ef5a230321e6234e2c6f5f7cee3b61fdabada0b"); + let expected_hash = H256Le::from_hex_be("02bcec80995d37160bba1cfc4ef5a230321e6234e2c6f5f7cee3b61fdabada0b"); assert_eq!(proof.hashes[0], expected_hash); assert_eq!(proof.flag_bits.len(), 4 * 8); } @@ -376,14 +355,8 @@ mod tests { #[test] fn test_compute_tree_width() { let proof = MerkleProof::parse(&hex::decode(&PROOF_HEX[..]).unwrap()).unwrap(); - assert_eq!( - proof.compute_partial_tree_width(0), - proof.transactions_count - ); - assert_eq!( - proof.compute_partial_tree_width(1), - proof.transactions_count / 2 + 1 - ); + assert_eq!(proof.compute_partial_tree_width(0), proof.transactions_count); + assert_eq!(proof.compute_partial_tree_width(1), proof.transactions_count / 2 + 1); assert_eq!(proof.compute_partial_tree_width(12), 1); } @@ -400,8 +373,7 @@ mod tests { let result = proof.verify_proof().unwrap(); assert_eq!(result.extracted_root, merkle_root); assert_eq!(result.transaction_position, 48); - let expected_tx_hash = - H256Le::from_hex_be("61a05151711e4716f31f7a3bb956d1b030c4d92093b843fa2e771b95564f0704"); + let expected_tx_hash = H256Le::from_hex_be("61a05151711e4716f31f7a3bb956d1b030c4d92093b843fa2e771b95564f0704"); assert_eq!(result.transaction_hash, expected_tx_hash); } diff --git a/crates/bitcoin/src/parser.rs b/crates/bitcoin/src/parser.rs index 3031a42c18..24e1143c57 100644 --- a/crates/bitcoin/src/parser.rs +++ b/crates/bitcoin/src/parser.rs @@ -3,8 +3,7 @@ extern crate mocktopus; extern crate bitcoin_hashes; -use bitcoin_hashes::hash160::Hash as Hash160; -use bitcoin_hashes::Hash; +use bitcoin_hashes::{hash160::Hash as Hash160, Hash}; #[cfg(test)] use mocktopus::macros::mockable; @@ -13,8 +12,7 @@ use crate::Error; use primitive_types::U256; use sp_std::prelude::*; -use crate::address::Address; -use crate::types::*; +use crate::{address::Address, types::*}; /// Type to be parsed from a bytes array pub(crate) trait Parsable: Sized { @@ -23,11 +21,7 @@ pub(crate) trait Parsable: Sized { /// Type to be parsed from a bytes array using extra metadata pub(crate) trait ParsableMeta: Sized { - fn parse_with( - raw_bytes: &[u8], - position: usize, - extra: Metadata, - ) -> Result<(Self, usize), Error>; + fn parse_with(raw_bytes: &[u8], position: usize, extra: Metadata) -> Result<(Self, usize), Error>; } /// Macro to generate `Parsable` implementation of uint types @@ -59,8 +53,7 @@ make_parsable_int!(i64, 8); impl Parsable for CompactUint { fn parse(raw_bytes: &[u8], position: usize) -> Result<(CompactUint, usize), Error> { let last_byte = sp_std::cmp::min(position + 3, raw_bytes.len()); - let (value, bytes_consumed) = - parse_compact_uint(raw_bytes.get(position..last_byte).ok_or(Error::EOS)?)?; + let (value, bytes_consumed) = parse_compact_uint(raw_bytes.get(position..last_byte).ok_or(Error::EOS)?)?; Ok((CompactUint { value }, bytes_consumed)) } } @@ -124,11 +117,7 @@ impl Parsable for Vec { } impl ParsableMeta for TransactionInput { - fn parse_with( - raw_bytes: &[u8], - position: usize, - version: i32, - ) -> Result<(TransactionInput, usize), Error> { + fn parse_with(raw_bytes: &[u8], position: usize, version: i32) -> Result<(TransactionInput, usize), Error> { let slice = raw_bytes.get(position..).ok_or(Error::EOS)?; parse_transaction_input(slice, version) } @@ -156,12 +145,7 @@ impl Parsable for U256 { let offset = U256::from(256) .checked_pow(U256::from(exponent)) .ok_or(Error::ArithmeticOverflow)?; - Ok(( - mantissa - .checked_mul(offset) - .ok_or(Error::ArithmeticOverflow)?, - 4, - )) + Ok((mantissa.checked_mul(offset).ok_or(Error::ArithmeticOverflow)?, 4)) } } @@ -196,10 +180,7 @@ impl BytesParser { /// Peeks at the next byte without updating the parser head. pub(crate) fn next(&self) -> Result { - self.raw_bytes - .get(self.position) - .ok_or(Error::EOS) - .map(|i| i.clone()) + self.raw_bytes.get(self.position).ok_or(Error::EOS).map(|i| i.clone()) } /// This is the same as `parse` but allows to pass extra data to the parser @@ -351,10 +332,7 @@ pub fn parse_transaction(raw_transaction: &[u8]) -> Result { } /// Parses a transaction input -fn parse_transaction_input( - raw_input: &[u8], - version: i32, -) -> Result<(TransactionInput, usize), Error> { +fn parse_transaction_input(raw_input: &[u8], version: i32) -> Result<(TransactionInput, usize), Error> { let mut parser = BytesParser::new(raw_input); let previous_hash: H256Le = parser.parse()?; let previous_index: u32 = parser.parse()?; @@ -441,9 +419,7 @@ pub(crate) fn extract_address_hash_scriptsig(input_script: &[u8]) -> Result &mut Self { // TODO: compute witness commitment - self.block.transactions.insert( - 0, - generate_coinbase_transaction(address, reward, height, None, None), - ); + self.block + .transactions + .insert(0, generate_coinbase_transaction(address, reward, height, None, None)); self } @@ -649,9 +646,7 @@ pub(crate) struct CompactUint { impl CompactUint { pub(crate) fn from_usize(value: usize) -> CompactUint { - CompactUint { - value: value as u64, - } + CompactUint { value: value as u64 } } } @@ -785,8 +780,7 @@ mod tests { use super::*; use sp_std::str::FromStr; - use crate::parser::parse_transaction; - use crate::Address; + use crate::{parser::parse_transaction, Address}; fn sample_example_real_rawtx() -> String { "0200000000010140d43a99926d43eb0e619bf0b3d83b4a31f60c176beecfb9d35bf45e54d0f7420100000017160014a4b4ca48de0b3fffc15404a1acdc8dbaae226955ffffffff0100e1f5050000000017a9144a1154d50b03292b3024370901711946cb7cccc387024830450221008604ef8f6d8afa892dee0f31259b6ce02dd70c545cfcfed8148179971876c54a022076d771d6e91bed212783c9b06e0de600fab2d518fad6f15a2b191d7fbd262a3e0121039d25ab79f41f75ceaf882411fd41fa670a4c672c23ffaf0e361a969cde0692e800000000".to_owned() @@ -861,8 +855,7 @@ mod tests { #[test] fn test_transaction_builder() { - let address = - Address::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let address = Address::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); let return_data = hex::decode("01a0").unwrap(); let transaction = TransactionBuilder::new() .with_version(2) @@ -877,10 +870,7 @@ mod tests { assert_eq!(transaction.outputs[0].extract_address().unwrap(), address); assert_eq!(transaction.outputs[1].value, 0); assert_eq!( - transaction.outputs[1] - .script - .extract_op_return_data() - .unwrap(), + transaction.outputs[1].script.extract_op_return_data().unwrap(), return_data ); } @@ -896,18 +886,10 @@ mod tests { ]; Transaction::tx_id.mock_safe(|tx| { let txid = match tx.version { - 1 => H256Le::from_hex_be( - "8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87", - ), - 2 => H256Le::from_hex_be( - "fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4", - ), - 3 => H256Le::from_hex_be( - "6359f0868171b1d194cbee1af2f16ea598ae8fad666d9b012c8ed2b79a236ec4", - ), - 4 => H256Le::from_hex_be( - "e9a66845e05d5abc0ad04ec80f774a7e585c6e8db975962d069a522137b80c1d", - ), + 1 => H256Le::from_hex_be("8c14f0db3df150123e6f3dbbf30f8b955a8249b62ac1d1ff16284aefa3d06d87"), + 2 => H256Le::from_hex_be("fff2525b8931402dd09222c50775608f75787bd2b87e56995a7bdd30f79702c4"), + 3 => H256Le::from_hex_be("6359f0868171b1d194cbee1af2f16ea598ae8fad666d9b012c8ed2b79a236ec4"), + 4 => H256Le::from_hex_be("e9a66845e05d5abc0ad04ec80f774a7e585c6e8db975962d069a522137b80c1d"), _ => panic!("should not happen"), }; MockResult::Return(txid) @@ -917,8 +899,7 @@ mod tests { builder.add_transaction(tx); } let merkle_root = builder.compute_merkle_root().unwrap(); - let expected = - H256Le::from_hex_be("f3e94742aca4b5ef85488dc37c06c3282295ffec960994b2c0d5ac2a25a95766"); + let expected = H256Le::from_hex_be("f3e94742aca4b5ef85488dc37c06c3282295ffec960994b2c0d5ac2a25a95766"); assert_eq!(merkle_root, expected); } @@ -934,21 +915,11 @@ mod tests { ]; Transaction::tx_id.mock_safe(|tx| { let txid = match tx.version { - 1 => H256Le::from_hex_be( - "a335b243f5e343049fccac2cf4d70578ad705831940d3eef48360b0ea3829ed4", - ), - 2 => H256Le::from_hex_be( - "d5fd11cb1fabd91c75733f4cf8ff2f91e4c0d7afa4fd132f792eacb3ef56a46c", - ), - 3 => H256Le::from_hex_be( - "0441cb66ef0cbf78c9ecb3d5a7d0acf878bfdefae8a77541b3519a54df51e7fd", - ), - 4 => H256Le::from_hex_be( - "1a8a27d690889b28d6cb4dacec41e354c62f40d85a7f4b2d7a54ffc736c6ff35", - ), - 5 => H256Le::from_hex_be( - "1d543d550676f82bf8bf5b0cc410b16fc6fc353b2a4fd9a0d6a2312ed7338701", - ), + 1 => H256Le::from_hex_be("a335b243f5e343049fccac2cf4d70578ad705831940d3eef48360b0ea3829ed4"), + 2 => H256Le::from_hex_be("d5fd11cb1fabd91c75733f4cf8ff2f91e4c0d7afa4fd132f792eacb3ef56a46c"), + 3 => H256Le::from_hex_be("0441cb66ef0cbf78c9ecb3d5a7d0acf878bfdefae8a77541b3519a54df51e7fd"), + 4 => H256Le::from_hex_be("1a8a27d690889b28d6cb4dacec41e354c62f40d85a7f4b2d7a54ffc736c6ff35"), + 5 => H256Le::from_hex_be("1d543d550676f82bf8bf5b0cc410b16fc6fc353b2a4fd9a0d6a2312ed7338701"), _ => panic!("should not happen"), }; MockResult::Return(txid) @@ -958,16 +929,14 @@ mod tests { builder.add_transaction(tx); } let merkle_root = builder.compute_merkle_root().unwrap(); - let expected = - H256Le::from_hex_be("5766798857e436d6243b46b5c1e0af5b6806aa9c2320b3ffd4ecff7b31fd4647"); + let expected = H256Le::from_hex_be("5766798857e436d6243b46b5c1e0af5b6806aa9c2320b3ffd4ecff7b31fd4647"); assert_eq!(merkle_root, expected); } #[test] fn test_mine_block() { clear_mocks(); - let address = - Address::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let address = Address::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); let block = BlockBuilder::new() .with_version(2) .with_coinbase(&address, 50, 3) @@ -984,8 +953,7 @@ mod tests { #[test] fn test_merkle_proof() { clear_mocks(); - let address = - Address::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let address = Address::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); let transaction = TransactionBuilder::new() .with_version(2) @@ -1014,8 +982,7 @@ mod tests { let transaction = parse_transaction(&tx_bytes).unwrap(); let address = Address::P2WPKHv0(H160([ - 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, 141, 186, 174, 34, 105, - 85, + 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, 141, 186, 174, 34, 105, 85, ])); let extr_address = transaction.inputs[0].extract_address().unwrap(); @@ -1030,8 +997,7 @@ mod tests { let transaction = parse_transaction(&tx_bytes).unwrap(); let address = Address::P2WPKHv0(H160([ - 214, 173, 103, 17, 218, 48, 244, 52, 154, 13, 140, 56, 122, 81, 91, 255, 16, 236, 213, - 7, + 214, 173, 103, 17, 218, 48, 244, 52, 154, 13, 140, 56, 122, 81, 91, 255, 16, 236, 213, 7, ])); let extr_address = transaction.inputs[0].extract_address().unwrap(); @@ -1047,17 +1013,14 @@ mod tests { let expected = parse_transaction(&tx_bytes).unwrap(); // tb1qp0we5epypgj4acd2c4au58045ruud2pd6heuee - let address = - Address::P2WPKHv0(H160::from_str("0bdd9a64240a255ee1aac57bca1df5a0f9c6a82d").unwrap()); + let address = Address::P2WPKHv0(H160::from_str("0bdd9a64240a255ee1aac57bca1df5a0f9c6a82d").unwrap()); - let input_script = hex::decode( - "20706f6f6c2e656e6a6f79626f646965732e636f6d2031343262393163303337f72631e9f5cd76000001", - ) - .unwrap(); + let input_script = + hex::decode("20706f6f6c2e656e6a6f79626f646965732e636f6d2031343262393163303337f72631e9f5cd76000001") + .unwrap(); let witness_commitment = - hex::decode("aa21a9ed173684441d99dd383ca57e6a073f62694c4f7c12a158964f050b84f69ba10ec3") - .unwrap(); + hex::decode("aa21a9ed173684441d99dd383ca57e6a073f62694c4f7c12a158964f050b84f69ba10ec3").unwrap(); let actual = generate_coinbase_transaction( &address, diff --git a/crates/bitcoin/src/utils.rs b/crates/bitcoin/src/utils.rs index cf108a8978..b5cb6a5ce1 100644 --- a/crates/bitcoin/src/utils.rs +++ b/crates/bitcoin/src/utils.rs @@ -99,8 +99,7 @@ mod tests { #[test] fn test_log256() { - let value = U256::from_dec_str("680733321990486529407107157001552378184394215934016880640") - .unwrap(); + let value = U256::from_dec_str("680733321990486529407107157001552378184394215934016880640").unwrap(); let result = log256(&value); assert_eq!(result, 24); } @@ -109,8 +108,8 @@ mod tests { fn test_sha256d() { assert_eq!( [ - 97, 244, 23, 55, 79, 68, 0, 180, 125, 202, 225, 168, 244, 2, 212, 244, 218, 207, - 69, 90, 4, 66, 160, 106, 164, 85, 164, 71, 176, 212, 225, 112 + 97, 244, 23, 55, 79, 68, 0, 180, 125, 202, 225, 168, 244, 2, 212, 244, 218, 207, 69, 90, 4, 66, 160, + 106, 164, 85, 164, 71, 176, 212, 225, 112 ], sha256d(b"Hello World!") ); diff --git a/crates/btc-relay/src/benchmarking.rs b/crates/btc-relay/src/benchmarking.rs index 3af08ad086..630e434eb6 100644 --- a/crates/btc-relay/src/benchmarking.rs +++ b/crates/btc-relay/src/benchmarking.rs @@ -1,13 +1,14 @@ use super::*; use crate::Module as BtcRelay; -use bitcoin::formatter::{Formattable, TryFormattable}; -use bitcoin::types::{ - Block, BlockBuilder, RawBlockHeader, Transaction, TransactionBuilder, TransactionInputBuilder, - TransactionOutput, +use bitcoin::{ + formatter::{Formattable, TryFormattable}, + types::{ + Block, BlockBuilder, RawBlockHeader, Transaction, TransactionBuilder, TransactionInputBuilder, + TransactionOutput, + }, }; use frame_benchmarking::{account, benchmarks}; -use frame_system::Module as System; -use frame_system::RawOrigin; +use frame_system::{Module as System, RawOrigin}; use sp_core::{H256, U256}; use sp_std::prelude::*; @@ -41,15 +42,13 @@ fn mine_block_with_one_tx( .with_coinbase(false) .with_previous_hash(prev.transactions[0].hash()) .with_script(&[ - 0, 71, 48, 68, 2, 32, 91, 128, 41, 150, 96, 53, 187, 63, 230, 129, 53, 234, - 210, 186, 21, 187, 98, 38, 255, 112, 30, 27, 228, 29, 132, 140, 155, 62, 123, - 216, 232, 168, 2, 32, 72, 126, 179, 207, 142, 8, 99, 8, 32, 78, 244, 166, 106, - 160, 207, 227, 61, 210, 172, 234, 234, 93, 59, 159, 79, 12, 194, 240, 212, 3, - 120, 50, 1, 71, 81, 33, 3, 113, 209, 131, 177, 9, 29, 242, 229, 15, 217, 247, - 165, 78, 111, 80, 79, 50, 200, 117, 80, 30, 233, 210, 167, 133, 175, 62, 253, - 134, 127, 212, 51, 33, 2, 128, 200, 184, 235, 148, 25, 43, 34, 28, 173, 55, 54, - 189, 164, 187, 243, 243, 152, 7, 84, 210, 85, 156, 238, 77, 97, 188, 240, 162, - 197, 105, 62, 82, 174, + 0, 71, 48, 68, 2, 32, 91, 128, 41, 150, 96, 53, 187, 63, 230, 129, 53, 234, 210, 186, 21, 187, 98, + 38, 255, 112, 30, 27, 228, 29, 132, 140, 155, 62, 123, 216, 232, 168, 2, 32, 72, 126, 179, 207, + 142, 8, 99, 8, 32, 78, 244, 166, 106, 160, 207, 227, 61, 210, 172, 234, 234, 93, 59, 159, 79, 12, + 194, 240, 212, 3, 120, 50, 1, 71, 81, 33, 3, 113, 209, 131, 177, 9, 29, 242, 229, 15, 217, 247, + 165, 78, 111, 80, 79, 50, 200, 117, 80, 30, 233, 210, 167, 133, 175, 62, 253, 134, 127, 212, 51, + 33, 2, 128, 200, 184, 235, 148, 25, 43, 34, 28, 173, 55, 54, 189, 164, 187, 243, 243, 152, 7, 84, + 210, 85, 156, 238, 77, 97, 188, 240, 162, 197, 105, 62, 82, 174, ]) .build(), ) diff --git a/crates/btc-relay/src/lib.rs b/crates/btc-relay/src/lib.rs index c681e42b4a..8b87e4144f 100644 --- a/crates/btc-relay/src/lib.rs +++ b/crates/btc-relay/src/lib.rs @@ -26,27 +26,24 @@ extern crate mocktopus; #[cfg(test)] use mocktopus::macros::mockable; -use frame_support::runtime_print; -use frame_support::transactional; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, - ensure, IterableStorageMap, + ensure, runtime_print, transactional, IterableStorageMap, }; use frame_system::{ensure_root, ensure_signed}; use primitive_types::U256; use sp_core::H160; -use sp_std::collections::btree_set::BTreeSet; -use sp_std::prelude::*; +use sp_std::{collections::btree_set::BTreeSet, prelude::*}; // Crates -pub use bitcoin; -use bitcoin::merkle::{MerkleProof, ProofResult}; -use bitcoin::parser::{parse_block_header, parse_transaction}; -use bitcoin::types::{BlockChain, BlockHeader, H256Le, RawBlockHeader, Transaction}; -pub use bitcoin::Address as BtcAddress; -use bitcoin::Error as BitcoinError; -pub use bitcoin::PublicKey as BtcPublicKey; +pub use bitcoin::{self, Address as BtcAddress, PublicKey as BtcPublicKey}; +use bitcoin::{ + merkle::{MerkleProof, ProofResult}, + parser::{parse_block_header, parse_transaction}, + types::{BlockChain, BlockHeader, H256Le, RawBlockHeader, Transaction}, + Error as BitcoinError, +}; use security::types::ErrorCode; pub use types::RichBlockHeader; pub use weights::WeightInfo; @@ -432,11 +429,7 @@ impl Module { >::remove(relayer); } - pub fn _initialize( - relayer: T::AccountId, - raw_block_header: RawBlockHeader, - block_height: u32, - ) -> DispatchResult { + pub fn _initialize(relayer: T::AccountId, raw_block_header: RawBlockHeader, block_height: u32) -> DispatchResult { // Check if BTC-Relay was already initialized ensure!(!Self::best_block_exists(), Error::::AlreadyInitialized); @@ -444,8 +437,7 @@ impl Module { Self::ensure_relayer_authorized(relayer.clone())?; // Parse the block header bytes to extract the required info - let basic_block_header = - parse_block_header(&raw_block_header).map_err(|err| Error::::from(err))?; + let basic_block_header = parse_block_header(&raw_block_header).map_err(|err| Error::::from(err))?; let block_header_hash = raw_block_header.hash(); // construct the BlockChain struct @@ -473,33 +465,20 @@ impl Module { Self::set_best_block_height(block_height); // Emit a Initialized Event - Self::deposit_event(>::Initialized( - block_height, - block_header_hash, - relayer, - )); + Self::deposit_event(>::Initialized(block_height, block_header_hash, relayer)); Ok(()) } // TODO: wrap sla update via staked-relayers pallet - fn _store_block_header_and_update_sla( - relayer: T::AccountId, - raw_block_header: RawBlockHeader, - ) -> DispatchResult { + fn _store_block_header_and_update_sla(relayer: T::AccountId, raw_block_header: RawBlockHeader) -> DispatchResult { if let Err(err) = Self::_store_block_header(relayer.clone(), raw_block_header) { if err == DispatchError::from(Error::::DuplicateBlock) { // only accept duplicate if it is the chain head let this_header_hash = raw_block_header.hash(); let best_header_hash = Self::get_best_block(); - ensure!( - this_header_hash == best_header_hash, - Error::::OutdatedBlock - ); - ext::sla::event_update_relayer_sla::( - &relayer, - ext::sla::RelayerEvent::DuplicateBlockSubmission, - )?; + ensure!(this_header_hash == best_header_hash, Error::::OutdatedBlock); + ext::sla::event_update_relayer_sla::(&relayer, ext::sla::RelayerEvent::DuplicateBlockSubmission)?; return Ok(()); } return Err(err); @@ -510,10 +489,7 @@ impl Module { } #[transactional] - pub fn _store_block_header( - relayer: T::AccountId, - raw_block_header: RawBlockHeader, - ) -> DispatchResult { + pub fn _store_block_header(relayer: T::AccountId, raw_block_header: RawBlockHeader) -> DispatchResult { // Make sure Parachain is not shutdown ext::security::ensure_parachain_status_not_shutdown::()?; @@ -623,17 +599,10 @@ impl Module { let merkle_proof = Self::parse_merkle_proof(&raw_merkle_proof)?; - let rich_header = Self::get_block_header_from_hash( - merkle_proof - .block_header - .hash() - .map_err(|err| Error::::from(err))?, - )?; + let rich_header = + Self::get_block_header_from_hash(merkle_proof.block_header.hash().map_err(|err| Error::::from(err))?)?; - ensure!( - rich_header.chain_ref == MAIN_CHAIN_ID, - Error::::InvalidChainID - ); + ensure!(rich_header.chain_ref == MAIN_CHAIN_ID, Error::::InvalidChainID); let block_height = rich_header.block_height; @@ -648,10 +617,7 @@ impl Module { let proof_result = Self::verify_merkle_proof(&merkle_proof)?; // fail if the transaction hash is invalid - ensure!( - proof_result.transaction_hash == tx_id, - Error::::InvalidTxid - ); + ensure!(proof_result.transaction_hash == tx_id, Error::::InvalidTxid); // fail if the merkle root is invalid ensure!( @@ -707,11 +673,7 @@ impl Module { ); // Check if payment is first output - match transaction - .outputs - .get(0) - .map(|output| output.extract_address()) - { + match transaction.outputs.get(0).map(|output| output.extract_address()) { Some(Ok(extr_recipient_btc_address)) => { if recipient_btc_address == extr_recipient_btc_address { return Ok(transaction.outputs[0].value); @@ -721,11 +683,7 @@ impl Module { }; // Check if payment is second output - match transaction - .outputs - .get(1) - .map(|output| output.extract_address()) - { + match transaction.outputs.get(1).map(|output| output.extract_address()) { Some(Ok(extr_recipient_btc_address)) => { if recipient_btc_address == extr_recipient_btc_address { return Ok(transaction.outputs[1].value); @@ -735,11 +693,7 @@ impl Module { }; // Check if payment is third output - match transaction - .outputs - .get(1) - .map(|output| output.extract_address()) - { + match transaction.outputs.get(1).map(|output| output.extract_address()) { Some(Ok(extr_recipient_btc_address)) => { if recipient_btc_address == extr_recipient_btc_address { return Ok(transaction.outputs[2].value); @@ -797,11 +751,7 @@ impl Module { }; // Check if payment is third output - match transaction - .outputs - .get(2) - .map(|output| output.extract_address()) - { + match transaction.outputs.get(2).map(|output| output.extract_address()) { Some(Ok(extr_recipient_btc_address)) => { if recipient_btc_address == extr_recipient_btc_address { return Ok(( @@ -924,9 +874,7 @@ impl Module { } /// Get a block header from its hash - fn get_block_header_from_hash( - block_hash: H256Le, - ) -> Result, DispatchError> { + fn get_block_header_from_hash(block_hash: H256Le) -> Result, DispatchError> { if >::contains_key(block_hash) { return Ok(>::get(block_hash)); } @@ -1118,9 +1066,7 @@ impl Module { } fn verify_merkle_proof(merkle_proof: &MerkleProof) -> Result { - merkle_proof - .verify_proof() - .map_err(|err| Error::::from(err).into()) + merkle_proof.verify_proof().map_err(|err| Error::::from(err).into()) } /// Parses and verifies a raw Bitcoin block header. @@ -1132,11 +1078,8 @@ impl Module { /// # Returns /// /// * `pure_block_header` - PureBlockHeader representation of the 80-byte block header - fn verify_block_header( - raw_block_header: &RawBlockHeader, - ) -> Result { - let basic_block_header = - parse_block_header(&raw_block_header).map_err(|err| Error::::from(err))?; + fn verify_block_header(raw_block_header: &RawBlockHeader) -> Result { + let basic_block_header = parse_block_header(&raw_block_header).map_err(|err| Error::::from(err))?; let block_header_hash = raw_block_header.hash(); @@ -1147,8 +1090,7 @@ impl Module { ); // Check that the referenced previous block header exists in BTC-Relay - let prev_block_header = - Self::get_block_header_from_hash(basic_block_header.hash_prev_block)?; + let prev_block_header = Self::get_block_header_from_hash(basic_block_header.hash_prev_block)?; // Check that the PoW hash satisfies the target set in the block header ensure!( block_header_hash.as_u256() < basic_block_header.target, @@ -1162,12 +1104,11 @@ impl Module { return Ok(basic_block_header); } - let expected_target = - if block_height >= 2016 && block_height % DIFFICULTY_ADJUSTMENT_INTERVAL == 0 { - Self::compute_new_target(&prev_block_header, block_height)? - } else { - prev_block_header.block_header.target - }; + let expected_target = if block_height >= 2016 && block_height % DIFFICULTY_ADJUSTMENT_INTERVAL == 0 { + Self::compute_new_target(&prev_block_header, block_height)? + } else { + prev_block_header.block_header.target + }; ensure!( basic_block_header.target == expected_target, @@ -1188,11 +1129,9 @@ impl Module { block_height: u32, ) -> Result { // get time of last retarget - let last_retarget_time = - Self::get_last_retarget_time(prev_block_header.chain_ref, block_height)?; + let last_retarget_time = Self::get_last_retarget_time(prev_block_header.chain_ref, block_height)?; // Compute new target - let actual_timespan = if ((prev_block_header.block_header.timestamp as u64 - - last_retarget_time) as u32) + let actual_timespan = if ((prev_block_header.block_header.timestamp as u64 - last_retarget_time) as u32) < (TARGET_TIMESPAN / TARGET_TIMESPAN_DIVISOR) { TARGET_TIMESPAN / TARGET_TIMESPAN_DIVISOR @@ -1214,7 +1153,8 @@ impl Module { }) } - /// Returns the timestamp of the last difficulty retarget on the specified BlockChain, given the current block height + /// Returns the timestamp of the last difficulty retarget on the specified BlockChain, given the current block + /// height /// /// # Arguments /// @@ -1222,10 +1162,8 @@ impl Module { /// * `block_height` - current block height fn get_last_retarget_time(chain_ref: u32, block_height: u32) -> Result { let block_chain = Self::get_block_chain_from_id(chain_ref)?; - let last_retarget_header = Self::get_block_header_from_height( - &block_chain, - block_height - DIFFICULTY_ADJUSTMENT_INTERVAL, - )?; + let last_retarget_header = + Self::get_block_header_from_height(&block_chain, block_height - DIFFICULTY_ADJUSTMENT_INTERVAL)?; Ok(last_retarget_header.block_header.timestamp as u64) } @@ -1365,14 +1303,13 @@ impl Module { // get the previous position let prev_position = current_position - 1; // get the blockchain id - let prev_blockchain_id = - if let Ok(chain_id) = Self::get_chain_id_from_position(prev_position) { - chain_id - } else { - // swap chain positions if previous doesn't exist and retry - Self::swap_chain(prev_position, current_position); - continue; - }; + let prev_blockchain_id = if let Ok(chain_id) = Self::get_chain_id_from_position(prev_position) { + chain_id + } else { + // swap chain positions if previous doesn't exist and retry + Self::swap_chain(prev_position, current_position); + continue; + }; // get the previous blockchain height let prev_height = Self::get_block_chain_from_id(prev_blockchain_id)?.max_height; @@ -1391,11 +1328,7 @@ impl Module { let new_chain_tip = ::get(); let block_height = ::get(); let fork_depth = fork.max_height - fork.start_height; - Self::deposit_event(>::ChainReorg( - new_chain_tip, - block_height, - fork_depth, - )); + Self::deposit_event(>::ChainReorg(new_chain_tip, block_height, fork_depth)); } else { Self::deposit_event(>::ForkAheadOfMainChain( prev_height, // main chain height @@ -1553,8 +1486,7 @@ impl Module { req_confs: Option, tx_block_height: u32, ) -> Result<(), DispatchError> { - let required_confirmations = - req_confs.unwrap_or_else(|| Self::get_stable_transaction_confirmations()); + let required_confirmations = req_confs.unwrap_or_else(|| Self::get_stable_transaction_confirmations()); let required_mainchain_height = tx_block_height .checked_add(required_confirmations) @@ -1624,8 +1556,7 @@ impl Module { runtime_print!("Next best fork height: {}", next_best_fork_height); // fail if there is an ongoing fork ensure!( - best_block_height - >= next_best_fork_height + Self::get_stable_transaction_confirmations(), + best_block_height >= next_best_fork_height + Self::get_stable_transaction_confirmations(), Error::::OngoingFork ); } diff --git a/crates/btc-relay/src/mock.rs b/crates/btc-relay/src/mock.rs index 3616c60c2e..f8fee364f9 100644 --- a/crates/btc-relay/src/mock.rs +++ b/crates/btc-relay/src/mock.rs @@ -168,9 +168,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); btc_relay::GenesisConfig:: { bitcoin_confirmations: BITCOIN_CONFIRMATIONS, diff --git a/crates/btc-relay/src/tests.rs b/crates/btc-relay/src/tests.rs index c247cc8526..26d971d50a 100644 --- a/crates/btc-relay/src/tests.rs +++ b/crates/btc-relay/src/tests.rs @@ -1,23 +1,15 @@ /// Tests for BTC-Relay use primitive_types::U256; -use crate::ext; -use crate::mock::*; -use crate::types::*; -use crate::BtcAddress; +use crate::{ext, mock::*, types::*, BtcAddress}; type Event = crate::Event; -use bitcoin::formatter::TryFormattable; -use bitcoin::merkle::*; -use bitcoin::parser::*; -use bitcoin::types::*; +use bitcoin::{formatter::TryFormattable, merkle::*, parser::*, types::*}; use frame_support::{assert_err, assert_ok}; use mocktopus::mocking::*; use security::{ErrorCode, StatusCode}; -use sp_std::collections::btree_set::BTreeSet; -use sp_std::convert::TryInto; -use sp_std::str::FromStr; +use sp_std::{collections::btree_set::BTreeSet, convert::TryInto, str::FromStr}; /// # Getters and setters /// @@ -86,8 +78,7 @@ fn next_best_fork_chain_succeeds() { let start_height: u32 = 10; let block_height: u32 = 100; - let blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + let blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); BTCRelay::set_block_chain_from_id(chain_ref, &blockchain); @@ -100,10 +91,7 @@ fn next_best_fork_chain_succeeds() { #[test] fn test_get_block_chain_from_id_empty_chain_fails() { run_test(|| { - assert_err!( - BTCRelay::get_block_chain_from_id(1), - TestError::InvalidChainID - ); + assert_err!(BTCRelay::get_block_chain_from_id(1), TestError::InvalidChainID); }) } @@ -118,14 +106,9 @@ fn initialize_once_succeeds() { let block_header_hash = block_header.hash(); BTCRelay::best_block_exists.mock_safe(|| MockResult::Return(false)); - assert_ok!(BTCRelay::initialize( - Origin::signed(3), - block_header, - block_height - )); + assert_ok!(BTCRelay::initialize(Origin::signed(3), block_header, block_height)); - let init_event = - TestEvent::btc_relay(Event::Initialized(block_height, block_header_hash, 3)); + let init_event = TestEvent::btc_relay(Event::Initialized(block_height, block_header_hash, 3)); assert!(System::events().iter().any(|a| a.event == init_event)); }) } @@ -149,9 +132,8 @@ fn initialize_best_block_already_set_fails() { #[test] fn store_block_header_on_mainchain_succeeds() { run_test(|| { - BTCRelay::verify_block_header.mock_safe(|h| { - MockResult::Return(Ok(BlockHeader::from_le_bytes(h.as_bytes()).unwrap())) - }); + BTCRelay::verify_block_header + .mock_safe(|h| MockResult::Return(Ok(BlockHeader::from_le_bytes(h.as_bytes()).unwrap()))); BTCRelay::block_header_exists.mock_safe(|_| MockResult::Return(true)); let chain_ref: u32 = 0; @@ -166,25 +148,16 @@ fn store_block_header_on_mainchain_succeeds() { chain_ref: chain_ref, account_id: Default::default(), }; - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(rich_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(rich_header))); - let prev_blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); - BTCRelay::get_block_chain_from_id - .mock_safe(move |_: u32| MockResult::Return(Ok(prev_blockchain.clone()))); + let prev_blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + BTCRelay::get_block_chain_from_id.mock_safe(move |_: u32| MockResult::Return(Ok(prev_blockchain.clone()))); let block_header_hash = block_header.hash(); - assert_ok!(BTCRelay::store_block_header( - Origin::signed(3), - block_header - )); + assert_ok!(BTCRelay::store_block_header(Origin::signed(3), block_header)); - let store_main_event = TestEvent::btc_relay(Event::StoreMainChainHeader( - block_height + 1, - block_header_hash, - 3, - )); + let store_main_event = + TestEvent::btc_relay(Event::StoreMainChainHeader(block_height + 1, block_header_hash, 3)); assert!(System::events().iter().any(|a| a.event == store_main_event)); }) } @@ -212,26 +185,16 @@ fn store_block_header_on_fork_succeeds() { chain_ref: chain_ref, account_id: Default::default(), }; - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(rich_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(rich_header))); - let prev_blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); - BTCRelay::get_block_chain_from_id - .mock_safe(move |_: u32| MockResult::Return(Ok(prev_blockchain.clone()))); + let prev_blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + BTCRelay::get_block_chain_from_id.mock_safe(move |_: u32| MockResult::Return(Ok(prev_blockchain.clone()))); let block_header_hash = block_header.hash(); - assert_ok!(BTCRelay::store_block_header( - Origin::signed(3), - block_header - )); + assert_ok!(BTCRelay::store_block_header(Origin::signed(3), block_header)); - let store_fork_event = TestEvent::btc_relay(Event::StoreForkHeader( - chain_ref, - block_height, - block_header_hash, - 3, - )); + let store_fork_event = + TestEvent::btc_relay(Event::StoreForkHeader(chain_ref, block_height, block_header_hash, 3)); assert!(System::events().iter().any(|a| a.event == store_fork_event)); }) } @@ -258,8 +221,7 @@ fn check_and_do_reorg_is_main_chain_succeeds() { let start_height: u32 = 3; let block_height: u32 = 10; - let blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + let blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); assert_ok!(BTCRelay::check_and_do_reorg(&blockchain)); }) @@ -272,13 +234,9 @@ fn check_and_do_reorg_fork_id_not_found() { let start_height: u32 = 3; let block_height: u32 = 10; - let blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + let blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); - assert_err!( - BTCRelay::check_and_do_reorg(&blockchain), - TestError::ForkIdNotFound - ); + assert_err!(BTCRelay::check_and_do_reorg(&blockchain), TestError::ForkIdNotFound); }) } @@ -290,11 +248,7 @@ fn check_and_do_reorg_swap_fork_position() { let main_start_height: u32 = 3; let main_block_height: u32 = 110; let main_position: u32 = 0; - let main = get_empty_block_chain_from_chain_id_and_height( - main_chain_ref, - main_start_height, - main_block_height, - ); + let main = get_empty_block_chain_from_chain_id_and_height(main_chain_ref, main_start_height, main_block_height); BTCRelay::set_chain_from_position_and_id(main_position, main_chain_ref); BTCRelay::set_block_chain_from_id(main_chain_ref, &main); @@ -303,11 +257,7 @@ fn check_and_do_reorg_swap_fork_position() { let fork_start_height: u32 = 20; let fork_block_height: u32 = 100; let fork_position: u32 = 2; - let fork = get_empty_block_chain_from_chain_id_and_height( - fork_chain_ref, - fork_start_height, - fork_block_height, - ); + let fork = get_empty_block_chain_from_chain_id_and_height(fork_chain_ref, fork_start_height, fork_block_height); BTCRelay::set_chain_from_position_and_id(fork_position, fork_chain_ref); BTCRelay::set_block_chain_from_id(fork_chain_ref, &fork); @@ -316,11 +266,7 @@ fn check_and_do_reorg_swap_fork_position() { let swap_start_height: u32 = 43; let swap_block_height: u32 = 99; let swap_position: u32 = 1; - let swap = get_empty_block_chain_from_chain_id_and_height( - swap_chain_ref, - swap_start_height, - swap_block_height, - ); + let swap = get_empty_block_chain_from_chain_id_and_height(swap_chain_ref, swap_start_height, swap_block_height); BTCRelay::set_chain_from_position_and_id(swap_position, swap_chain_ref); BTCRelay::set_block_chain_from_id(swap_chain_ref, &swap); @@ -348,11 +294,7 @@ fn check_and_do_reorg_new_fork_is_main_chain() { let main_start_height: u32 = 4; let main_block_height: u32 = 110; let main_position: u32 = 0; - let main = get_empty_block_chain_from_chain_id_and_height( - main_chain_ref, - main_start_height, - main_block_height, - ); + let main = get_empty_block_chain_from_chain_id_and_height(main_chain_ref, main_start_height, main_block_height); BTCRelay::set_chain_from_position_and_id(main_position, main_chain_ref); BTCRelay::set_block_chain_from_id(main_chain_ref, &main); @@ -360,11 +302,7 @@ fn check_and_do_reorg_new_fork_is_main_chain() { let fork_chain_ref: u32 = 4; let fork_block_height: u32 = 117; let fork_position: u32 = 1; - let fork = get_empty_block_chain_from_chain_id_and_height( - fork_chain_ref, - main_start_height, - fork_block_height, - ); + let fork = get_empty_block_chain_from_chain_id_and_height(fork_chain_ref, main_start_height, fork_block_height); BTCRelay::set_chain_from_position_and_id(fork_position, fork_chain_ref); BTCRelay::set_block_chain_from_id(fork_chain_ref, &fork); @@ -398,11 +336,7 @@ fn check_and_do_reorg_new_fork_below_stable_transaction_confirmations() { let main_start_height: u32 = 4; let main_block_height: u32 = 110; let main_position: u32 = 0; - let main = get_empty_block_chain_from_chain_id_and_height( - main_chain_ref, - main_start_height, - main_block_height, - ); + let main = get_empty_block_chain_from_chain_id_and_height(main_chain_ref, main_start_height, main_block_height); BTCRelay::set_chain_from_position_and_id(main_position, main_chain_ref); BTCRelay::set_block_chain_from_id(main_chain_ref, &main); @@ -410,11 +344,7 @@ fn check_and_do_reorg_new_fork_below_stable_transaction_confirmations() { let fork_chain_ref: u32 = 4; let fork_block_height: u32 = 113; let fork_position: u32 = 1; - let fork = get_empty_block_chain_from_chain_id_and_height( - fork_chain_ref, - main_start_height, - fork_block_height, - ); + let fork = get_empty_block_chain_from_chain_id_and_height(fork_chain_ref, main_start_height, fork_block_height); BTCRelay::set_chain_from_position_and_id(fork_position, fork_chain_ref); BTCRelay::set_block_chain_from_id(fork_chain_ref, &fork); @@ -450,11 +380,7 @@ fn insert_sorted_succeeds() { let main_start_height: u32 = 60; let main_block_height: u32 = 110; let main_position: u32 = 0; - let main = get_empty_block_chain_from_chain_id_and_height( - main_chain_ref, - main_start_height, - main_block_height, - ); + let main = get_empty_block_chain_from_chain_id_and_height(main_chain_ref, main_start_height, main_block_height); BTCRelay::set_block_chain_from_id(main_chain_ref, &main); assert_eq!(Ok(()), BTCRelay::insert_sorted(&main)); @@ -465,11 +391,7 @@ fn insert_sorted_succeeds() { let swap_start_height: u32 = 70; let swap_block_height: u32 = 99; let swap_position: u32 = 1; - let swap = get_empty_block_chain_from_chain_id_and_height( - swap_chain_ref, - swap_start_height, - swap_block_height, - ); + let swap = get_empty_block_chain_from_chain_id_and_height(swap_chain_ref, swap_start_height, swap_block_height); BTCRelay::set_block_chain_from_id(swap_chain_ref, &swap); assert_eq!(Ok(()), BTCRelay::insert_sorted(&swap)); @@ -482,11 +404,7 @@ fn insert_sorted_succeeds() { let fork_block_height: u32 = 100; let fork_position: u32 = 1; let new_swap_pos: u32 = 2; - let fork = get_empty_block_chain_from_chain_id_and_height( - fork_chain_ref, - fork_start_height, - fork_block_height, - ); + let fork = get_empty_block_chain_from_chain_id_and_height(fork_chain_ref, fork_start_height, fork_block_height); BTCRelay::set_block_chain_from_id(fork_chain_ref, &fork); assert_eq!(Ok(()), BTCRelay::insert_sorted(&fork)); @@ -506,12 +424,7 @@ fn swap_main_blockchain_succeeds() { let main_start: u32 = 0; let main_height: u32 = 10; let main_position: u32 = 0; - let main = store_blockchain_and_random_headers( - main_chain_ref, - main_start, - main_height, - main_position, - ); + let main = store_blockchain_and_random_headers(main_chain_ref, main_start, main_height, main_position); // simulate error let header = BTCRelay::get_block_header_from_height(&main, 2).unwrap(); @@ -524,12 +437,7 @@ fn swap_main_blockchain_succeeds() { let fork_height: u32 = 17; let fork_position: u32 = 1; - let fork = store_blockchain_and_random_headers( - fork_chain_ref, - fork_start, - fork_height, - fork_position, - ); + let fork = store_blockchain_and_random_headers(fork_chain_ref, fork_start, fork_height, fork_position); let old_main_ref = fork_chain_ref + 1; // mock the chain counter @@ -543,10 +451,7 @@ fn swap_main_blockchain_succeeds() { assert_eq!(fork_height, new_main.max_height); assert_eq!(main_start, new_main.start_height); assert_eq!(main_chain_ref, new_main.chain_id); - assert_eq!( - fork_height + 1, - BTCRelay::_blocks_count(main_chain_ref) as u32 - ); + assert_eq!(fork_height + 1, BTCRelay::_blocks_count(main_chain_ref) as u32); assert_eq!(main.no_data, BTreeSet::new()); assert_eq!(main.invalid, new_main.invalid); @@ -609,8 +514,7 @@ fn test_verify_block_header_no_retarget_succeeds() { let rich_first_header = sample_parsed_first_block(chain_ref, block_height + 1); // Prev block is genesis - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(genesis_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(genesis_header))); // Not duplicate block BTCRelay::block_header_exists.mock_safe(move |_| MockResult::Return(false)); @@ -628,23 +532,17 @@ fn test_verify_block_header_correct_retarget_increase_succeeds() { // Sample interval with INCREASING target let retarget_headers = sample_retarget_interval_increase(); - let prev_block_header_rich = RichBlockHeader::::new( - retarget_headers[1], - chain_ref, - block_height, - Default::default(), - ) - .unwrap(); + let prev_block_header_rich = + RichBlockHeader::::new(retarget_headers[1], chain_ref, block_height, Default::default()) + .unwrap(); let curr_block_header = parse_block_header(&retarget_headers[2]).unwrap(); // Prev block exists - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(prev_block_header_rich))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(prev_block_header_rich))); // Not duplicate block BTCRelay::block_header_exists.mock_safe(move |_| MockResult::Return(false)); // Compute new target returns target of submitted header (i.e., correct) - BTCRelay::compute_new_target - .mock_safe(move |_, _| MockResult::Return(Ok(curr_block_header.target))); + BTCRelay::compute_new_target.mock_safe(move |_, _| MockResult::Return(Ok(curr_block_header.target))); let verified_header = BTCRelay::verify_block_header(&retarget_headers[2]).unwrap(); assert_eq!(verified_header, curr_block_header) @@ -660,23 +558,17 @@ fn test_verify_block_header_correct_retarget_decrease_succeeds() { // Sample interval with DECREASING target let retarget_headers = sample_retarget_interval_decrease(); - let prev_block_header_rich = RichBlockHeader::::new( - retarget_headers[1], - chain_ref, - block_height, - Default::default(), - ) - .unwrap(); + let prev_block_header_rich = + RichBlockHeader::::new(retarget_headers[1], chain_ref, block_height, Default::default()) + .unwrap(); let curr_block_header = parse_block_header(&retarget_headers[2]).unwrap(); // Prev block exists - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(prev_block_header_rich))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(prev_block_header_rich))); // Not duplicate block BTCRelay::block_header_exists.mock_safe(move |_| MockResult::Return(false)); // Compute new target returns target of submitted header (i.e., correct) - BTCRelay::compute_new_target - .mock_safe(move |_, _| MockResult::Return(Ok(curr_block_header.target))); + BTCRelay::compute_new_target.mock_safe(move |_, _| MockResult::Return(Ok(curr_block_header.target))); let verified_header = BTCRelay::verify_block_header(&retarget_headers[2]).unwrap(); assert_eq!(verified_header, curr_block_header) @@ -691,23 +583,17 @@ fn test_verify_block_header_missing_retarget_succeeds() { let block_height: u32 = 2015; let retarget_headers = sample_retarget_interval_increase(); - let prev_block_header_rich = RichBlockHeader::::new( - retarget_headers[1], - chain_ref, - block_height, - Default::default(), - ) - .unwrap(); + let prev_block_header_rich = + RichBlockHeader::::new(retarget_headers[1], chain_ref, block_height, Default::default()) + .unwrap(); let curr_block_header = parse_block_header(&retarget_headers[2]).unwrap(); // Prev block exists - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(prev_block_header_rich))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(prev_block_header_rich))); // Not duplicate block BTCRelay::block_header_exists.mock_safe(move |_| MockResult::Return(false)); // Compute new target returns HIGHER target - BTCRelay::compute_new_target - .mock_safe(move |_, _| MockResult::Return(Ok(curr_block_header.target + 1))); + BTCRelay::compute_new_target.mock_safe(move |_, _| MockResult::Return(Ok(curr_block_header.target + 1))); assert_err!( BTCRelay::verify_block_header(&retarget_headers[2]), @@ -724,18 +610,12 @@ fn test_compute_new_target() { let retarget_headers = sample_retarget_interval_increase(); let last_retarget_time = parse_block_header(&retarget_headers[0]).unwrap().timestamp as u64; - let prev_block_header = RichBlockHeader::::new( - retarget_headers[1], - chain_ref, - block_height, - Default::default(), - ) - .unwrap(); + let prev_block_header = + RichBlockHeader::::new(retarget_headers[1], chain_ref, block_height, Default::default()).unwrap(); let curr_block_header = parse_block_header(&retarget_headers[2]).unwrap(); - BTCRelay::get_last_retarget_time - .mock_safe(move |_, _| MockResult::Return(Ok(last_retarget_time))); + BTCRelay::get_last_retarget_time.mock_safe(move |_, _| MockResult::Return(Ok(last_retarget_time))); let new_target = BTCRelay::compute_new_target(&prev_block_header, block_height).unwrap(); @@ -753,8 +633,7 @@ fn test_verify_block_header_duplicate_fails() { let rich_first_header = sample_parsed_first_block(chain_ref, 101); // Prev block is genesis - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(genesis_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(genesis_header))); // submitted block ALREADY EXISTS BTCRelay::block_header_exists.mock_safe(move |block_hash| { assert_eq!(&block_hash, &rich_first_header.block_hash); @@ -773,16 +652,12 @@ fn test_verify_block_header_duplicate_fails() { fn test_verify_block_header_no_prev_block_fails() { run_test(|| { // Prev block is MISSING - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Err(TestError::PrevBlock.into()))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Err(TestError::PrevBlock.into()))); // submitted block does not yet exist BTCRelay::block_header_exists.mock_safe(move |_| MockResult::Return(false)); let raw_first_header = RawBlockHeader::from_hex(sample_raw_first_header()).unwrap(); - assert_err!( - BTCRelay::verify_block_header(&raw_first_header), - TestError::PrevBlock - ); + assert_err!(BTCRelay::verify_block_header(&raw_first_header), TestError::PrevBlock); }) } @@ -795,12 +670,10 @@ fn test_verify_block_header_low_diff_fails() { let genesis_header = sample_parsed_genesis_header(chain_ref, block_height); // block header with high target but weak hash - let raw_first_header_weak = - RawBlockHeader::from_hex(sample_raw_first_header_low_diff()).unwrap(); + let raw_first_header_weak = RawBlockHeader::from_hex(sample_raw_first_header_low_diff()).unwrap(); // Prev block is genesis - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(genesis_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(genesis_header))); // submitted block does not yet exist BTCRelay::block_header_exists.mock_safe(move |_| MockResult::Return(false)); @@ -821,8 +694,7 @@ fn test_validate_transaction_succeeds_with_payment() { let outputs = vec![sample_valid_payment_output()]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); BTCRelay::is_op_return_disabled.mock_safe(move || MockResult::Return(true)); @@ -843,15 +715,12 @@ fn test_validate_transaction_succeeds_with_payment_and_op_return() { let minimum_btc: i64 = 2500200000; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned(), - ) - .unwrap(); + let op_return_id = + hex::decode("aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()).unwrap(); let outputs = vec![sample_valid_payment_output(), sample_valid_data_output()]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); assert_ok!(BTCRelay::validate_transaction( Origin::signed(3), @@ -870,15 +739,12 @@ fn test_validate_transaction_succeeds_with_op_return_and_payment() { let minimum_btc: i64 = 2500200000; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned(), - ) - .unwrap(); + let op_return_id = + hex::decode("aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()).unwrap(); let outputs = vec![sample_valid_data_output(), sample_valid_payment_output()]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); assert_ok!(BTCRelay::validate_transaction( Origin::signed(3), @@ -897,10 +763,8 @@ fn test_validate_transaction_succeeds_with_payment_and_refund_and_op_return() { let minimum_btc: i64 = 2500200000; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned(), - ) - .unwrap(); + let op_return_id = + hex::decode("aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()).unwrap(); let outputs = vec![ sample_valid_payment_output(), @@ -908,8 +772,7 @@ fn test_validate_transaction_succeeds_with_payment_and_refund_and_op_return() { sample_valid_data_output(), ]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); assert_ok!(BTCRelay::validate_transaction( Origin::signed(3), @@ -930,15 +793,12 @@ fn test_validate_transaction_invalid_no_outputs_fails() { let minimum_btc: i64 = 2500200000; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned(), - ) - .unwrap(); + let op_return_id = + hex::decode("aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()).unwrap(); // missing required data output let outputs = vec![sample_valid_payment_output()]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); assert_err!( BTCRelay::validate_transaction( @@ -962,18 +822,12 @@ fn test_validate_transaction_insufficient_payment_value_fails() { let minimum_btc: i64 = 2500200000; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned(), - ) - .unwrap(); + let op_return_id = + hex::decode("aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()).unwrap(); - let outputs = vec![ - sample_insufficient_value_payment_output(), - sample_valid_data_output(), - ]; + let outputs = vec![sample_insufficient_value_payment_output(), sample_valid_data_output()]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); assert_err!( BTCRelay::validate_transaction( @@ -997,10 +851,8 @@ fn test_validate_transaction_wrong_recipient_fails() { let minimum_btc: i64 = 2500200000; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned(), - ) - .unwrap(); + let op_return_id = + hex::decode("aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()).unwrap(); let outputs = vec![ sample_wrong_recipient_payment_output(), @@ -1008,8 +860,7 @@ fn test_validate_transaction_wrong_recipient_fails() { sample_valid_data_output(), ]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); assert_err!( BTCRelay::validate_transaction( @@ -1033,19 +884,13 @@ fn test_validate_transaction_incorrect_opreturn_fails() { let minimum_btc: i64 = 2500200000; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "6a24aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675" - .to_owned(), - ) - .unwrap(); + let op_return_id = + hex::decode("6a24aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()) + .unwrap(); - let outputs = vec![ - sample_valid_payment_output(), - sample_incorrect_data_output(), - ]; + let outputs = vec![sample_valid_payment_output(), sample_incorrect_data_output()]; - BTCRelay::parse_transaction - .mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); + BTCRelay::parse_transaction.mock_safe(move |_| MockResult::Return(Ok(sample_transaction_parsed(&outputs)))); assert_err!( BTCRelay::validate_transaction( @@ -1063,8 +908,7 @@ fn test_validate_transaction_incorrect_opreturn_fails() { #[test] fn test_verify_and_validate_transaction_succeeds() { run_test(|| { - BTCRelay::get_block_chain_from_id - .mock_safe(|_| MockResult::Return(Ok(BlockChain::default()))); + BTCRelay::get_block_chain_from_id.mock_safe(|_| MockResult::Return(Ok(BlockChain::default()))); let raw_tx = hex::decode(sample_example_real_rawtx()).unwrap(); let transaction = parse_transaction(&raw_tx).unwrap(); @@ -1083,15 +927,11 @@ fn test_verify_and_validate_transaction_succeeds() { let minimum_btc: i64 = 0; let recipient_btc_address = BtcAddress::P2SH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let op_return_id = hex::decode( - "aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned(), - ) - .unwrap(); - BTCRelay::_validate_transaction.mock_safe(move |_, _, _, _| { - MockResult::Return(Ok((recipient_btc_address.clone(), 0))) - }); - BTCRelay::_verify_transaction_inclusion - .mock_safe(move |_, _, _| MockResult::Return(Ok(()))); + let op_return_id = + hex::decode("aa21a9ede5c17d15b8b1fa2811b7e6da66ffa5e1aaa05922c69068bf90cd585b95bb4675".to_owned()).unwrap(); + BTCRelay::_validate_transaction + .mock_safe(move |_, _, _, _| MockResult::Return(Ok((recipient_btc_address.clone(), 0)))); + BTCRelay::_verify_transaction_inclusion.mock_safe(move |_, _, _| MockResult::Return(Ok(()))); assert_ok!(BTCRelay::verify_and_validate_transaction( Origin::signed(3), @@ -1125,17 +965,13 @@ fn test_flag_block_error_succeeds() { BTCRelay::set_block_header_from_hash(rich_header.block_hash, &rich_header); - let blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + let blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); BTCRelay::set_block_chain_from_id(chain_ref, &blockchain); let error_codes = vec![ErrorCode::NoDataBTCRelay, ErrorCode::InvalidBTCRelay]; for error in error_codes.iter() { - assert_ok!(BTCRelay::flag_block_error( - rich_header.block_hash, - error.clone() - )); + assert_ok!(BTCRelay::flag_block_error(rich_header.block_hash, error.clone())); let curr_chain = BTCRelay::get_block_chain_from_id(chain_ref).unwrap(); if *error == ErrorCode::NoDataBTCRelay { @@ -1143,11 +979,8 @@ fn test_flag_block_error_succeeds() { } else if *error == ErrorCode::InvalidBTCRelay { assert!(curr_chain.invalid.contains(&block_height)); }; - let error_event = TestEvent::btc_relay(Event::FlagBlockError( - rich_header.block_hash, - chain_ref, - error.clone(), - )); + let error_event = + TestEvent::btc_relay(Event::FlagBlockError(rich_header.block_hash, chain_ref, error.clone())); assert!(System::events().iter().any(|a| a.event == error_event)); } }) @@ -1171,8 +1004,7 @@ fn test_flag_block_error_fails() { BTCRelay::set_block_header_from_hash(rich_header.block_hash, &rich_header); - let blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + let blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); BTCRelay::set_block_chain_from_id(chain_ref, &blockchain); // not a valid error code @@ -1204,8 +1036,7 @@ fn test_clear_block_error_succeeds() { BTCRelay::set_block_header_from_hash(rich_header.block_hash, &rich_header); - let mut blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + let mut blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); blockchain.no_data.insert(block_height); blockchain.invalid.insert(block_height); set_parachain_nodata_error(); @@ -1214,10 +1045,7 @@ fn test_clear_block_error_succeeds() { BTCRelay::set_block_chain_from_id(chain_ref, &blockchain); let clear_error = move |error: ErrorCode| { - assert_ok!(BTCRelay::clear_block_error( - rich_header.block_hash, - error.clone() - )); + assert_ok!(BTCRelay::clear_block_error(rich_header.block_hash, error.clone())); let curr_chain = BTCRelay::get_block_chain_from_id(chain_ref).unwrap(); if error == ErrorCode::NoDataBTCRelay { @@ -1225,11 +1053,8 @@ fn test_clear_block_error_succeeds() { } else if error == ErrorCode::InvalidBTCRelay { assert!(!curr_chain.invalid.contains(&block_height)); }; - let error_event = TestEvent::btc_relay(Event::ClearBlockError( - rich_header.block_hash, - chain_ref, - error.clone(), - )); + let error_event = + TestEvent::btc_relay(Event::ClearBlockError(rich_header.block_hash, chain_ref, error.clone())); assert!(System::events().iter().any(|a| a.event == error_event)); }; @@ -1266,8 +1091,7 @@ fn test_clear_block_error_fails() { BTCRelay::set_block_header_from_hash(rich_header.block_hash, &rich_header); - let blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); + let blockchain = get_empty_block_chain_from_chain_id_and_height(chain_ref, start_height, block_height); BTCRelay::set_block_chain_from_id(chain_ref, &blockchain); // not a valid error code @@ -1368,14 +1192,11 @@ fn test_verify_transaction_inclusion_succeeds() { let proof = sample_merkle_proof(); let proof_result = sample_valid_proof_result(); - let main = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); + let main = get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); - let fork = - get_empty_block_chain_from_chain_id_and_height(fork_ref, start, fork_chain_height); + let fork = get_empty_block_chain_from_chain_id_and_height(fork_ref, start, fork_chain_height); - BTCRelay::get_chain_id_from_position - .mock_safe(move |_| MockResult::Return(Ok(fork_ref.clone()))); + BTCRelay::get_chain_id_from_position.mock_safe(move |_| MockResult::Return(Ok(fork_ref.clone()))); BTCRelay::get_block_chain_from_id.mock_safe(move |id| { if id == chain_ref.clone() { return MockResult::Return(Ok(main.clone())); @@ -1389,8 +1210,7 @@ fn test_verify_transaction_inclusion_succeeds() { BTCRelay::parse_merkle_proof.mock_safe(move |_| MockResult::Return(Ok(proof.clone()))); BTCRelay::verify_merkle_proof.mock_safe(move |_| MockResult::Return(Ok(proof_result))); - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); BTCRelay::check_bitcoin_confirmations.mock_safe(|_, _, _| MockResult::Return(Ok(()))); @@ -1419,8 +1239,7 @@ fn test_verify_transaction_inclusion_empty_fork_succeeds() { let proof = sample_merkle_proof(); let proof_result = sample_valid_proof_result(); - let main = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); + let main = get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); BTCRelay::get_block_chain_from_id.mock_safe(move |id| { if id == chain_ref.clone() { @@ -1435,8 +1254,7 @@ fn test_verify_transaction_inclusion_empty_fork_succeeds() { BTCRelay::parse_merkle_proof.mock_safe(move |_| MockResult::Return(Ok(proof.clone()))); BTCRelay::verify_merkle_proof.mock_safe(move |_| MockResult::Return(Ok(proof_result))); - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); BTCRelay::check_bitcoin_confirmations.mock_safe(|_, _, _| MockResult::Return(Ok(()))); @@ -1466,23 +1284,17 @@ fn test_verify_transaction_inclusion_invalid_tx_id_fails() { // Mismatching TXID let invalid_tx_id = H256Le::from_bytes_le( - &hex::decode( - "0000000000000000000000000000000000000000000000000000000000000000".to_owned(), - ) - .unwrap(), + &hex::decode("0000000000000000000000000000000000000000000000000000000000000000".to_owned()).unwrap(), ); let proof = sample_merkle_proof(); let proof_result = sample_valid_proof_result(); - let main = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); + let main = get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); - let fork = - get_empty_block_chain_from_chain_id_and_height(fork_ref, start, fork_chain_height); + let fork = get_empty_block_chain_from_chain_id_and_height(fork_ref, start, fork_chain_height); - BTCRelay::get_chain_id_from_position - .mock_safe(move |_| MockResult::Return(Ok(fork_ref.clone()))); + BTCRelay::get_chain_id_from_position.mock_safe(move |_| MockResult::Return(Ok(fork_ref.clone()))); BTCRelay::get_block_chain_from_id.mock_safe(move |id| { if id == chain_ref.clone() { return MockResult::Return(Ok(main.clone())); @@ -1496,20 +1308,14 @@ fn test_verify_transaction_inclusion_invalid_tx_id_fails() { BTCRelay::parse_merkle_proof.mock_safe(move |_| MockResult::Return(Ok(proof.clone()))); BTCRelay::verify_merkle_proof.mock_safe(move |_| MockResult::Return(Ok(proof_result))); - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); BTCRelay::check_bitcoin_confirmations.mock_safe(|_, _, _| MockResult::Return(Ok(()))); BTCRelay::check_parachain_confirmations.mock_safe(|_| MockResult::Return(Ok(()))); assert_err!( - BTCRelay::verify_transaction_inclusion( - Origin::signed(3), - invalid_tx_id, - raw_merkle_proof, - confirmations, - ), + BTCRelay::verify_transaction_inclusion(Origin::signed(3), invalid_tx_id, raw_merkle_proof, confirmations,), TestError::InvalidTxid ); }); @@ -1530,24 +1336,18 @@ fn test_verify_transaction_inclusion_invalid_merkle_root_fails() { // Mismatching merkle root let invalid_merkle_root = H256Le::from_bytes_le( - &hex::decode( - "0000000000000000000000000000000000000000000000000000000000000000".to_owned(), - ) - .unwrap(), + &hex::decode("0000000000000000000000000000000000000000000000000000000000000000".to_owned()).unwrap(), ); rich_block_header.block_header.merkle_root = invalid_merkle_root; let proof = sample_merkle_proof(); let proof_result = sample_valid_proof_result(); - let main = - get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); + let main = get_empty_block_chain_from_chain_id_and_height(chain_ref, start, main_chain_height); - let fork = - get_empty_block_chain_from_chain_id_and_height(fork_ref, start, fork_chain_height); + let fork = get_empty_block_chain_from_chain_id_and_height(fork_ref, start, fork_chain_height); - BTCRelay::get_chain_id_from_position - .mock_safe(move |_| MockResult::Return(Ok(fork_ref.clone()))); + BTCRelay::get_chain_id_from_position.mock_safe(move |_| MockResult::Return(Ok(fork_ref.clone()))); BTCRelay::get_block_chain_from_id.mock_safe(move |id| { if id == chain_ref.clone() { return MockResult::Return(Ok(main.clone())); @@ -1560,8 +1360,7 @@ fn test_verify_transaction_inclusion_invalid_merkle_root_fails() { BTCRelay::parse_merkle_proof.mock_safe(move |_| MockResult::Return(Ok(proof.clone()))); - BTCRelay::get_block_header_from_hash - .mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); + BTCRelay::get_block_header_from_hash.mock_safe(move |_| MockResult::Return(Ok(rich_block_header))); BTCRelay::check_bitcoin_confirmations.mock_safe(|_, _, _| MockResult::Return(Ok(()))); @@ -1583,20 +1382,14 @@ fn test_verify_transaction_inclusion_invalid_merkle_root_fails() { fn test_verify_transaction_inclusion_fails_with_ongoing_fork() { run_test(|| { BTCRelay::get_chain_id_from_position.mock_safe(|_| MockResult::Return(Ok(1))); - BTCRelay::get_block_chain_from_id - .mock_safe(|_| MockResult::Return(Ok(BlockChain::default()))); + BTCRelay::get_block_chain_from_id.mock_safe(|_| MockResult::Return(Ok(BlockChain::default()))); let tx_id = sample_valid_proof_result().transaction_hash; let raw_merkle_proof = vec![0u8; 100]; let confirmations = None; assert_err!( - BTCRelay::verify_transaction_inclusion( - Origin::signed(3), - tx_id, - raw_merkle_proof, - confirmations, - ), + BTCRelay::verify_transaction_inclusion(Origin::signed(3), tx_id, raw_merkle_proof, confirmations,), TestError::OngoingFork ); }); @@ -1642,8 +1435,7 @@ fn test_check_bitcoin_confirmations_secure_stable_confs_succeeds() { // relevant check: ok let stable_confs = 10; - BTCRelay::get_stable_transaction_confirmations - .mock_safe(move || MockResult::Return(stable_confs)); + BTCRelay::get_stable_transaction_confirmations.mock_safe(move || MockResult::Return(stable_confs)); assert_ok!(BTCRelay::check_bitcoin_confirmations( main_chain_height, req_confs, @@ -1661,8 +1453,7 @@ fn test_check_bitcoin_confirmations_secure_user_confs_succeeds() { let req_confs = None; let stable_confs = 10; - BTCRelay::get_stable_transaction_confirmations - .mock_safe(move || MockResult::Return(stable_confs)); + BTCRelay::get_stable_transaction_confirmations.mock_safe(move || MockResult::Return(stable_confs)); assert_ok!(BTCRelay::check_bitcoin_confirmations( main_chain_height, req_confs, @@ -1681,8 +1472,7 @@ fn test_check_bitcoin_confirmations_secure_insufficient_stable_confs_succeeds() // relevant check: fails let stable_confs = 10; - BTCRelay::get_stable_transaction_confirmations - .mock_safe(move || MockResult::Return(stable_confs)); + BTCRelay::get_stable_transaction_confirmations.mock_safe(move || MockResult::Return(stable_confs)); assert_err!( BTCRelay::check_bitcoin_confirmations(main_chain_height, req_confs, tx_block_height,), @@ -1722,10 +1512,7 @@ fn test_check_parachain_confirmations_insufficient_confs_fails() { #[test] fn get_chain_from_id_err() { run_test(|| { - assert_err!( - BTCRelay::get_block_chain_from_id(0), - TestError::InvalidChainID - ); + assert_err!(BTCRelay::get_block_chain_from_id(0), TestError::InvalidChainID); }); } @@ -1737,11 +1524,7 @@ fn get_chain_from_id_ok() { let main_start_height: u32 = 3; let main_block_height: u32 = 110; let main_position: u32 = 0; - let main = get_empty_block_chain_from_chain_id_and_height( - main_chain_ref, - main_start_height, - main_block_height, - ); + let main = get_empty_block_chain_from_chain_id_and_height(main_chain_ref, main_start_height, main_block_height); BTCRelay::set_chain_from_position_and_id(main_position, main_chain_ref); BTCRelay::set_block_chain_from_id(main_chain_ref, &main); @@ -1752,34 +1535,21 @@ fn get_chain_from_id_ok() { #[test] fn store_generated_block_headers() { let target = U256::from(2).pow(254.into()); - let miner = - BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let get_header = - |block: &Block| RawBlockHeader::from_bytes(&block.header.try_format().unwrap()).unwrap(); + let miner = BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let get_header = |block: &Block| RawBlockHeader::from_bytes(&block.header.try_format().unwrap()).unwrap(); run_test(|| { - let mut last_block = BlockBuilder::new() - .with_coinbase(&miner, 50, 0) - .mine(target) - .unwrap(); - assert_ok!(BTCRelay::initialize( - Origin::signed(3), - get_header(&last_block), - 0 - )); + let mut last_block = BlockBuilder::new().with_coinbase(&miner, 50, 0).mine(target).unwrap(); + assert_ok!(BTCRelay::initialize(Origin::signed(3), get_header(&last_block), 0)); for i in 1..20 { last_block = BlockBuilder::new() .with_coinbase(&miner, 50, i) .with_previous_hash(last_block.header.hash().unwrap()) .mine(target) .unwrap(); - assert_ok!(BTCRelay::store_block_header( - Origin::signed(3), - get_header(&last_block) - )); + assert_ok!(BTCRelay::store_block_header(Origin::signed(3), get_header(&last_block))); } - let main_chain: BlockChain = - BTCRelay::get_block_chain_from_id(crate::MAIN_CHAIN_ID).unwrap(); + let main_chain: BlockChain = BTCRelay::get_block_chain_from_id(crate::MAIN_CHAIN_ID).unwrap(); assert_eq!(main_chain.start_height, 0); assert_eq!(main_chain.max_height, 19); }) @@ -1811,10 +1581,7 @@ fn test_extract_value_succeeds() { let transaction = TransactionBuilder::new() .with_version(2) - .add_output(TransactionOutput::payment( - recipient_value, - &recipient_btc_address, - )) + .add_output(TransactionOutput::payment(recipient_value, &recipient_btc_address)) .build(); assert_eq!( @@ -1889,16 +1656,12 @@ fn test_extract_value_and_op_return_succeeds() { let transaction = TransactionBuilder::new() .with_version(2) - .add_output(TransactionOutput::payment( - recipient_value, - &recipient_btc_address, - )) + .add_output(TransactionOutput::payment(recipient_value, &recipient_btc_address)) .add_output(TransactionOutput::op_return(0, &op_return)) .build(); let (extr_value, extr_data) = - BTCRelay::extract_payment_value_and_op_return(transaction, recipient_btc_address) - .unwrap(); + BTCRelay::extract_payment_value_and_op_return(transaction, recipient_btc_address).unwrap(); assert_eq!(extr_value, recipient_value); assert_eq!(extr_data, op_return); @@ -1907,8 +1670,7 @@ fn test_extract_value_and_op_return_succeeds() { #[test] fn test_check_and_do_reorg() { - use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageMap; - use crate::{Chains, ChainsIndex}; + use crate::{sp_api_hidden_includes_decl_storage::hidden_include::StorageMap, Chains, ChainsIndex}; use bitcoin::types::BlockChain; use sp_std::collections::btree_set::BTreeSet; @@ -1988,9 +1750,10 @@ fn test_check_and_do_reorg() { #[test] fn test_remove_blockchain_from_chain() { - use crate::sp_api_hidden_includes_decl_storage::hidden_include::IterableStorageMap; - use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageMap; - use crate::Chains; + use crate::{ + sp_api_hidden_includes_decl_storage::hidden_include::{IterableStorageMap, StorageMap}, + Chains, + }; run_test(|| { Chains::insert(0, 0); @@ -2007,27 +1770,20 @@ fn test_remove_blockchain_from_chain() { #[test] fn test_ensure_relayer_authorized() { - use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageValue; - use crate::DisableRelayerAuth; + use crate::{sp_api_hidden_includes_decl_storage::hidden_include::StorageValue, DisableRelayerAuth}; run_test(|| { DisableRelayerAuth::set(true); assert_ok!(BTCRelay::ensure_relayer_authorized(0)); DisableRelayerAuth::set(false); - assert_err!( - BTCRelay::ensure_relayer_authorized(0), - TestError::RelayerNotAuthorized - ); + assert_err!(BTCRelay::ensure_relayer_authorized(0), TestError::RelayerNotAuthorized); BTCRelay::register_authorized_relayer(0); assert_ok!(BTCRelay::ensure_relayer_authorized(0)); BTCRelay::deregister_authorized_relayer(0); - assert_err!( - BTCRelay::ensure_relayer_authorized(0), - TestError::RelayerNotAuthorized - ); + assert_err!(BTCRelay::ensure_relayer_authorized(0), TestError::RelayerNotAuthorized); }) } @@ -2052,8 +1808,7 @@ fn test_store_block_header_and_update_sla_succeeds() { #[test] fn test_store_block_header_and_update_sla_succeeds_with_duplicate() { run_test(|| { - BTCRelay::_store_block_header - .mock_safe(|_, _| MockResult::Return(Err(TestError::DuplicateBlock.into()))); + BTCRelay::_store_block_header.mock_safe(|_, _| MockResult::Return(Err(TestError::DuplicateBlock.into()))); BTCRelay::get_best_block.mock_safe(|| MockResult::Return(RawBlockHeader::default().hash())); @@ -2073,8 +1828,7 @@ fn test_store_block_header_and_update_sla_succeeds_with_duplicate() { #[test] fn test_store_block_header_and_update_sla_fails_with_invalid() { run_test(|| { - BTCRelay::_store_block_header - .mock_safe(|_, _| MockResult::Return(Err(TestError::DiffTargetHeader.into()))); + BTCRelay::_store_block_header.mock_safe(|_, _| MockResult::Return(Err(TestError::DiffTargetHeader.into()))); ext::sla::event_update_relayer_sla::.mock_safe(|_, _| { panic!("Should not call sla update for invalid block"); @@ -2089,11 +1843,9 @@ fn test_store_block_header_and_update_sla_fails_with_invalid() { /// # Util functions -const SAMPLE_TX_ID: &'static str = - "c8589f304d3b9df1d4d8b3d15eb6edaaa2af9d796e9d9ace12b31f293705c5e9"; +const SAMPLE_TX_ID: &'static str = "c8589f304d3b9df1d4d8b3d15eb6edaaa2af9d796e9d9ace12b31f293705c5e9"; -const SAMPLE_MERKLE_ROOT: &'static str = - "1EE1FB90996CA1D5DCD12866BA9066458BF768641215933D7D8B3A10EF79D090"; +const SAMPLE_MERKLE_ROOT: &'static str = "1EE1FB90996CA1D5DCD12866BA9066458BF768641215933D7D8B3A10EF79D090"; fn sample_merkle_proof() -> MerkleProof { MerkleProof { @@ -2110,9 +1862,7 @@ fn sample_block_header() -> BlockHeader { target: 123.into(), timestamp: 1601494682, version: 2, - hash_prev_block: H256Le::from_hex_be( - "0000000000000000000e84948eaacb9b03382782f16f2d8a354de69f2e5a2a68", - ), + hash_prev_block: H256Le::from_hex_be("0000000000000000000e84948eaacb9b03382782f16f2d8a354de69f2e5a2a68"), nonce: 0, } } @@ -2128,11 +1878,7 @@ fn sample_valid_proof_result() -> ProofResult { } } -fn get_empty_block_chain_from_chain_id_and_height( - chain_id: u32, - start_height: u32, - block_height: u32, -) -> BlockChain { +fn get_empty_block_chain_from_chain_id_and_height(chain_id: u32, start_height: u32, block_height: u32) -> BlockChain { let blockchain = BlockChain { chain_id: chain_id, start_height: start_height, @@ -2149,8 +1895,7 @@ fn get_invalid_empty_block_chain_from_chain_id_and_height( start_height: u32, block_height: u32, ) -> BlockChain { - let mut blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_id, start_height, block_height); + let mut blockchain = get_empty_block_chain_from_chain_id_and_height(chain_id, start_height, block_height); blockchain.invalid.insert(block_height - 1); blockchain @@ -2161,19 +1906,13 @@ fn get_nodata_empty_block_chain_from_chain_id_and_height( start_height: u32, block_height: u32, ) -> BlockChain { - let mut blockchain = - get_empty_block_chain_from_chain_id_and_height(chain_id, start_height, block_height); + let mut blockchain = get_empty_block_chain_from_chain_id_and_height(chain_id, start_height, block_height); blockchain.no_data.insert(block_height - 1); blockchain } -fn store_blockchain_and_random_headers( - id: u32, - start_height: u32, - max_height: u32, - position: u32, -) -> BlockChain { +fn store_blockchain_and_random_headers(id: u32, start_height: u32, max_height: u32, position: u32) -> BlockChain { let mut chain = get_empty_block_chain_from_chain_id_and_height(id, start_height, max_height); // create and insert main chain headers @@ -2291,27 +2030,21 @@ fn sample_rich_tx_block_header(chain_ref: u32, block_height: u32) -> RichBlockHe fn sample_valid_payment_output() -> TransactionOutput { TransactionOutput { value: 2500200000, - script: "a91466c7060feb882664ae62ffad0051fe843e318e8587" - .try_into() - .unwrap(), + script: "a91466c7060feb882664ae62ffad0051fe843e318e8587".try_into().unwrap(), } } fn sample_insufficient_value_payment_output() -> TransactionOutput { TransactionOutput { value: 100, - script: "a91466c7060feb882664ae62ffad0051fe843e318e8587" - .try_into() - .unwrap(), + script: "a91466c7060feb882664ae62ffad0051fe843e318e8587".try_into().unwrap(), } } fn sample_wrong_recipient_payment_output() -> TransactionOutput { TransactionOutput { value: 2500200000, - script: "a914000000000000000000000000000000000000000087" - .try_into() - .unwrap(), + script: "a914000000000000000000000000000000000000000087".try_into().unwrap(), } } @@ -2337,8 +2070,7 @@ fn sample_transaction_parsed(outputs: &Vec) -> Transaction { let mut inputs: Vec = Vec::new(); let spent_output_txid = - hex::decode("b28f1e58af1d4db02d1b9f0cf8d51ece3dd5f5013fd108647821ea255ae5daff".to_owned()) - .unwrap(); + hex::decode("b28f1e58af1d4db02d1b9f0cf8d51ece3dd5f5013fd108647821ea255ae5daff".to_owned()).unwrap(); let input = TransactionInput { previous_hash: H256Le::from_bytes_le(&spent_output_txid), previous_index: 0, diff --git a/crates/btc-relay/src/types.rs b/crates/btc-relay/src/types.rs index 2214ec1c5e..238be41bc3 100644 --- a/crates/btc-relay/src/types.rs +++ b/crates/btc-relay/src/types.rs @@ -1,6 +1,8 @@ -use bitcoin::parser::FromLeBytes; -use bitcoin::types::{BlockHeader, H256Le, RawBlockHeader}; -use bitcoin::Error; +use bitcoin::{ + parser::FromLeBytes, + types::{BlockHeader, H256Le, RawBlockHeader}, + Error, +}; use codec::{Decode, Encode}; /// Bitcoin Enriched Block Headers diff --git a/crates/collateral/src/lib.rs b/crates/collateral/src/lib.rs index 7f8d6f004f..feacdb42bc 100644 --- a/crates/collateral/src/lib.rs +++ b/crates/collateral/src/lib.rs @@ -11,14 +11,15 @@ mod mock; #[cfg(test)] mod tests; -use frame_support::dispatch::{DispatchError, DispatchResult}; -use frame_support::traits::{Currency, ExistenceRequirement, ReservableCurrency}; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, ensure, sp_runtime::ModuleId, + decl_error, decl_event, decl_module, decl_storage, + dispatch::{DispatchError, DispatchResult}, + ensure, + sp_runtime::ModuleId, + traits::{Currency, ExistenceRequirement, ReservableCurrency}, }; -type BalanceOf = - <::DOT as Currency<::AccountId>>::Balance; +type BalanceOf = <::DOT as Currency<::AccountId>>::Balance; /// The collateral's module id, used for deriving its sovereign account ID. const _MODULE_ID: ModuleId = ModuleId(*b"ily/cltl"); @@ -107,17 +108,8 @@ impl Module { /// * `source` - the account to send dot /// * `destination` - the account receiving dot /// * `amount` - amount of DOT - pub fn transfer( - source: T::AccountId, - destination: T::AccountId, - amount: BalanceOf, - ) -> DispatchResult { - T::DOT::transfer( - &source, - &destination, - amount, - ExistenceRequirement::AllowDeath, - ) + pub fn transfer(source: T::AccountId, destination: T::AccountId, amount: BalanceOf) -> DispatchResult { + T::DOT::transfer(&source, &destination, amount, ExistenceRequirement::AllowDeath) } /// Lock DOT collateral @@ -164,11 +156,7 @@ impl Module { /// * `sender` - the account being slashed /// * `receiver` - the receiver of the amount /// * `amount` - the to be slashed amount - pub fn slash_collateral( - sender: T::AccountId, - receiver: T::AccountId, - amount: BalanceOf, - ) -> DispatchResult { + pub fn slash_collateral(sender: T::AccountId, receiver: T::AccountId, amount: BalanceOf) -> DispatchResult { ensure!( T::DOT::reserved_balance(&sender) >= amount, Error::::InsufficientCollateralAvailable @@ -201,11 +189,7 @@ impl Module { // subtraction should not be able to fail since remainder <= amount let slashed_amount = amount - remainder; - Self::deposit_event(RawEvent::SlashCollateral( - sender, - receiver.clone(), - slashed_amount, - )); + Self::deposit_event(RawEvent::SlashCollateral(sender, receiver.clone(), slashed_amount)); // reserve the created amount for the receiver. This should not be able to fail, since the // call above will have created enough free balance to lock. diff --git a/crates/collateral/src/mock.rs b/crates/collateral/src/mock.rs index 2ca2275002..9689cfc527 100644 --- a/crates/collateral/src/mock.rs +++ b/crates/collateral/src/mock.rs @@ -89,9 +89,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(ALICE, ALICE_BALANCE), (BOB, BOB_BALANCE)], diff --git a/crates/collateral/src/tests.rs b/crates/collateral/src/tests.rs index 5ed89f9e95..3df24b8497 100644 --- a/crates/collateral/src/tests.rs +++ b/crates/collateral/src/tests.rs @@ -142,8 +142,7 @@ fn test_release_collateral_partially_succeeds() { let init_total = Collateral::get_total_collateral(); assert_ok!(Collateral::release_collateral(&sender, release_amount)); - let release_event = - TestEvent::collateral(RawEvent::ReleaseCollateral(ALICE, release_amount)); + let release_event = TestEvent::collateral(RawEvent::ReleaseCollateral(ALICE, release_amount)); assert!(System::events().iter().any(|a| a.event == release_event)); @@ -225,8 +224,7 @@ fn test_slash_collateral_partially_succeeds() { let init_total = Collateral::get_total_collateral(); assert_ok!(Collateral::slash_collateral(sender, receiver, slash_amount)); - let slash_event = - TestEvent::collateral(RawEvent::SlashCollateral(ALICE, BOB, slash_amount)); + let slash_event = TestEvent::collateral(RawEvent::SlashCollateral(ALICE, BOB, slash_amount)); assert!(System::events().iter().any(|a| a.event == slash_event)); diff --git a/crates/exchange-rate-oracle/rpc/runtime-api/src/lib.rs b/crates/exchange-rate-oracle/rpc/runtime-api/src/lib.rs index 01917f133e..5a067f62ee 100644 --- a/crates/exchange-rate-oracle/rpc/runtime-api/src/lib.rs +++ b/crates/exchange-rate-oracle/rpc/runtime-api/src/lib.rs @@ -21,17 +21,12 @@ pub struct BalanceWrapper { } #[cfg(feature = "std")] -fn serialize_as_string( - t: &T, - serializer: S, -) -> Result { +fn serialize_as_string(t: &T, serializer: S) -> Result { serializer.serialize_str(&t.to_string()) } #[cfg(feature = "std")] -fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>( - deserializer: D, -) -> Result { +fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>(deserializer: D) -> Result { let s = String::deserialize(deserializer)?; s.parse::() .map_err(|_| serde::de::Error::custom("Parse from string failed")) diff --git a/crates/exchange-rate-oracle/rpc/src/lib.rs b/crates/exchange-rate-oracle/rpc/src/lib.rs index b53e59a344..70dc916e5e 100644 --- a/crates/exchange-rate-oracle/rpc/src/lib.rs +++ b/crates/exchange-rate-oracle/rpc/src/lib.rs @@ -9,8 +9,11 @@ pub use module_exchange_rate_oracle_rpc_runtime_api::{ }; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; -use sp_runtime::{generic::BlockId, traits::Block as BlockT, DispatchError}; +use sp_runtime::{ + generic::BlockId, + traits::{Block as BlockT, MaybeDisplay, MaybeFromStr}, + DispatchError, +}; use std::sync::Arc; #[rpc] diff --git a/crates/exchange-rate-oracle/src/benchmarking.rs b/crates/exchange-rate-oracle/src/benchmarking.rs index d4ec5902a5..9d68e817f1 100644 --- a/crates/exchange-rate-oracle/src/benchmarking.rs +++ b/crates/exchange-rate-oracle/src/benchmarking.rs @@ -1,5 +1,4 @@ -use super::Module as ExchangeRateOracle; -use super::*; +use super::{Module as ExchangeRateOracle, *}; use frame_benchmarking::{account, benchmarks}; use frame_system::RawOrigin; use sp_runtime::FixedPointNumber; diff --git a/crates/exchange-rate-oracle/src/lib.rs b/crates/exchange-rate-oracle/src/lib.rs index 3812ed780d..c6f1b1a401 100644 --- a/crates/exchange-rate-oracle/src/lib.rs +++ b/crates/exchange-rate-oracle/src/lib.rs @@ -25,25 +25,26 @@ extern crate mocktopus; use mocktopus::macros::mockable; use codec::{Decode, Encode, EncodeLike}; -use frame_support::dispatch::{DispatchError, DispatchResult}; -use frame_support::traits::Currency; -use frame_support::transactional; -use frame_support::weights::Weight; -use frame_support::{decl_error, decl_event, decl_module, decl_storage, ensure}; +use frame_support::{ + decl_error, decl_event, decl_module, decl_storage, + dispatch::{DispatchError, DispatchResult}, + ensure, + traits::Currency, + transactional, + weights::Weight, +}; use frame_system::{ensure_root, ensure_signed}; use security::{ErrorCode, StatusCode}; -use sp_arithmetic::traits::UniqueSaturatedInto; -use sp_arithmetic::traits::*; -use sp_arithmetic::FixedPointNumber; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_arithmetic::{ + traits::{UniqueSaturatedInto, *}, + FixedPointNumber, +}; +use sp_std::{convert::TryInto, vec::Vec}; -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; pub(crate) type UnsignedFixedPoint = ::UnsignedFixedPoint; @@ -71,11 +72,7 @@ const DOT_DECIMALS: u32 = 10; /// ## Configuration and Constants /// The pallet's configuration trait. pub trait Config: - frame_system::Config - + pallet_timestamp::Config - + treasury::Config - + collateral::Config - + security::Config + frame_system::Config + pallet_timestamp::Config + treasury::Config + collateral::Config + security::Config { /// The overarching event type. type Event: From> + Into<::Event>; @@ -259,11 +256,9 @@ impl Module { dot_per_btc: UnsignedFixedPoint, ) -> Result, DispatchError> { // safe to unwrap because we only use constants - let conversion_factor = UnsignedFixedPoint::::checked_from_rational( - 10_u128.pow(DOT_DECIMALS), - 10_u128.pow(BTC_DECIMALS), - ) - .unwrap(); + let conversion_factor = + UnsignedFixedPoint::::checked_from_rational(10_u128.pow(DOT_DECIMALS), 10_u128.pow(BTC_DECIMALS)) + .unwrap(); dot_per_btc .checked_mul(&conversion_factor) @@ -277,12 +272,8 @@ impl Module { pub fn btc_to_dots(amount: PolkaBTC) -> Result, DispatchError> { let rate = Self::get_exchange_rate()?; let raw_amount = Self::into_u128(amount)?; - let converted = rate - .checked_mul_int(raw_amount) - .ok_or(Error::::ArithmeticOverflow)?; - let result = converted - .try_into() - .map_err(|_e| Error::::TryIntoIntError)?; + let converted = rate.checked_mul_int(raw_amount).ok_or(Error::::ArithmeticOverflow)?; + let result = converted.try_into().map_err(|_e| Error::::TryIntoIntError)?; Ok(result) } @@ -294,9 +285,7 @@ impl Module { } // The code below performs `raw_amount/rate`, plus necessary type conversions - let dot_as_inner: Inner = raw_amount - .try_into() - .map_err(|_| Error::::TryIntoIntError)?; + let dot_as_inner: Inner = raw_amount.try_into().map_err(|_| Error::::TryIntoIntError)?; let btc_raw: u128 = T::UnsignedFixedPoint::checked_from_integer(dot_as_inner) .ok_or(Error::::TryIntoIntError)? .checked_div(&rate) @@ -305,9 +294,7 @@ impl Module { .checked_div(&UnsignedFixedPoint::::accuracy()) .ok_or(Error::::ArithmeticUnderflow)? .unique_saturated_into(); - btc_raw - .try_into() - .map_err(|_e| Error::::TryIntoIntError.into()) + btc_raw.try_into().map_err(|_e| Error::::TryIntoIntError.into()) } pub fn get_last_exchange_rate_time() -> T::Moment { diff --git a/crates/exchange-rate-oracle/src/mock.rs b/crates/exchange-rate-oracle/src/mock.rs index 1ab147cbf0..02a021f18a 100644 --- a/crates/exchange-rate-oracle/src/mock.rs +++ b/crates/exchange-rate-oracle/src/mock.rs @@ -118,9 +118,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); exchange_rate_oracle::GenesisConfig:: { authorized_oracles: vec![(0, "test".as_bytes().to_vec())], diff --git a/crates/exchange-rate-oracle/src/tests.rs b/crates/exchange-rate-oracle/src/tests.rs index 9b42309f39..434dec2ac5 100644 --- a/crates/exchange-rate-oracle/src/tests.rs +++ b/crates/exchange-rate-oracle/src/tests.rs @@ -1,5 +1,7 @@ -use crate::mock::{run_test, ExchangeRateOracle, Origin, System, Test, TestError, TestEvent}; -use crate::BtcTxFeesPerByte; +use crate::{ + mock::{run_test, ExchangeRateOracle, Origin, System, Test, TestError, TestEvent}, + BtcTxFeesPerByte, +}; use frame_support::{assert_err, assert_ok, dispatch::DispatchError}; use mocktopus::mocking::*; use sp_arithmetic::FixedU128; @@ -28,8 +30,7 @@ fn set_exchange_rate_succeeds() { let rate = FixedU128::checked_from_rational(100, 1).unwrap(); ExchangeRateOracle::is_authorized.mock_safe(|_| MockResult::Return(true)); - ExchangeRateOracle::dot_per_btc_to_planck_per_satoshi - .mock_safe(|amount| MockResult::Return(Ok(amount))); + ExchangeRateOracle::dot_per_btc_to_planck_per_satoshi.mock_safe(|amount| MockResult::Return(Ok(amount))); let result = ExchangeRateOracle::set_exchange_rate(Origin::signed(3), rate); assert_ok!(result); @@ -55,10 +56,7 @@ fn set_exchange_rate_recovers_from_oracle_offline() { MockResult::Return(()) }); - assert_ok!(ExchangeRateOracle::set_exchange_rate( - Origin::signed(3), - rate - )); + assert_ok!(ExchangeRateOracle::set_exchange_rate(Origin::signed(3), rate)); assert!(oracle_recovered, "Oracle should be recovered from offline"); } }); @@ -71,8 +69,7 @@ fn set_exchange_rate_fails_with_invalid_oracle_source() { let failed_rate = FixedU128::checked_from_rational(100, 1).unwrap(); ExchangeRateOracle::is_authorized.mock_safe(|_| MockResult::Return(true)); - ExchangeRateOracle::dot_per_btc_to_planck_per_satoshi - .mock_safe(|amount| MockResult::Return(Ok(amount))); + ExchangeRateOracle::dot_per_btc_to_planck_per_satoshi.mock_safe(|amount| MockResult::Return(Ok(amount))); assert_ok!(ExchangeRateOracle::set_exchange_rate( Origin::signed(4), successful_rate @@ -133,8 +130,7 @@ fn is_max_delay_passed() { let now = 1585776145; ExchangeRateOracle::get_current_time.mock_safe(move || MockResult::Return(now)); - ExchangeRateOracle::get_last_exchange_rate_time - .mock_safe(move || MockResult::Return(now - 3600)); + ExchangeRateOracle::get_last_exchange_rate_time.mock_safe(move || MockResult::Return(now - 3600)); // max delay is 30 minutes but 1 hour passed ExchangeRateOracle::get_max_delay.mock_safe(|| MockResult::Return(1800)); @@ -176,11 +172,7 @@ fn insert_authorized_oracle_succeeds() { TestError::InvalidOracleSource ); assert_err!( - ExchangeRateOracle::insert_authorized_oracle( - Origin::signed(oracle), - oracle, - Vec::::new() - ), + ExchangeRateOracle::insert_authorized_oracle(Origin::signed(oracle), oracle, Vec::::new()), DispatchError::BadOrigin ); assert_ok!(ExchangeRateOracle::insert_authorized_oracle( @@ -200,10 +192,7 @@ fn remove_authorized_oracle_succeeds() { ExchangeRateOracle::remove_authorized_oracle(Origin::signed(oracle), oracle), DispatchError::BadOrigin ); - assert_ok!(ExchangeRateOracle::remove_authorized_oracle( - Origin::root(), - oracle, - )); + assert_ok!(ExchangeRateOracle::remove_authorized_oracle(Origin::root(), oracle,)); }); } @@ -235,12 +224,7 @@ fn set_btc_tx_fees_per_byte_succeeds() { run_test(|| { ExchangeRateOracle::is_authorized.mock_safe(|_| MockResult::Return(true)); - assert_ok!(ExchangeRateOracle::set_btc_tx_fees_per_byte( - Origin::signed(3), - 1, - 1, - 1 - )); + assert_ok!(ExchangeRateOracle::set_btc_tx_fees_per_byte(Origin::signed(3), 1, 1, 1)); assert_eq!( ExchangeRateOracle::satoshi_per_bytes(), diff --git a/crates/fee/src/lib.rs b/crates/fee/src/lib.rs index 50a7fbd09f..3d7da85943 100644 --- a/crates/fee/src/lib.rs +++ b/crates/fee/src/lib.rs @@ -26,18 +26,15 @@ extern crate mocktopus; use mocktopus::macros::mockable; use codec::{Decode, Encode, EncodeLike}; -use frame_support::transactional; -use frame_support::{decl_error, decl_event, decl_module, decl_storage}; use frame_support::{ + decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, - ensure, + ensure, transactional, weights::Weight, }; use frame_system::ensure_signed; -use sp_arithmetic::traits::*; -use sp_arithmetic::FixedPointNumber; -use sp_std::convert::TryInto; -use sp_std::vec::*; +use sp_arithmetic::{traits::*, FixedPointNumber}; +use sp_std::{convert::TryInto, vec::*}; use types::{Inner, PolkaBTC, UnsignedFixedPoint, DOT}; pub trait WeightInfo { @@ -46,9 +43,7 @@ pub trait WeightInfo { } /// The pallet's configuration trait. -pub trait Config: - frame_system::Config + collateral::Config + treasury::Config + sla::Config -{ +pub trait Config: frame_system::Config + collateral::Config + treasury::Config + sla::Config { /// The overarching event type. type Event: From> + Into<::Event>; @@ -255,10 +250,8 @@ impl Module { /// then clears the current epoch rewards. pub fn update_rewards_for_epoch() -> DispatchResult { // calculate vault rewards - let ( - total_vault_rewards_for_issued_in_polka_btc, - total_vault_rewards_for_locked_in_polka_btc, - ) = Self::vault_rewards_for_epoch_in_polka_btc()?; + let (total_vault_rewards_for_issued_in_polka_btc, total_vault_rewards_for_locked_in_polka_btc) = + Self::vault_rewards_for_epoch_in_polka_btc()?; let (total_vault_rewards_for_issued_in_dot, total_vault_rewards_for_locked_in_dot) = Self::vault_rewards_for_epoch_in_dot()?; for (account, amount_in_polka_btc, amount_in_dot) in ext::sla::get_vault_rewards::( @@ -286,10 +279,9 @@ impl Module { // calculate staked relayer rewards let total_relayer_rewards_in_polka_btc = Self::relayer_rewards_for_epoch_in_polka_btc()?; let total_relayer_rewards_in_dot = Self::relayer_rewards_for_epoch_in_dot()?; - for (account, amount_in_polka_btc, amount_in_dot) in ext::sla::get_relayer_rewards::( - total_relayer_rewards_in_polka_btc, - total_relayer_rewards_in_dot, - )? { + for (account, amount_in_polka_btc, amount_in_dot) in + ext::sla::get_relayer_rewards::(total_relayer_rewards_in_polka_btc, total_relayer_rewards_in_dot)? + { // increase polka_btc rewards >::insert( account.clone(), @@ -309,8 +301,7 @@ impl Module { // calculate maintainer rewards let maintainer_account_id = Self::maintainer_account_id(); // increase polka_DOT rewards - let total_maintainer_rewards_in_polka_btc = - Self::maintainer_rewards_for_epoch_in_polka_btc()?; + let total_maintainer_rewards_in_polka_btc = Self::maintainer_rewards_for_epoch_in_polka_btc()?; >::insert( maintainer_account_id.clone(), >::get(maintainer_account_id.clone()) @@ -488,10 +479,7 @@ impl Module { } /// Take the `percentage` of an `amount` - fn calculate_for( - amount: Inner, - percentage: UnsignedFixedPoint, - ) -> Result, DispatchError> { + fn calculate_for(amount: Inner, percentage: UnsignedFixedPoint) -> Result, DispatchError> { // we add 0.5 before we do the final integer division to round the result we return. // note that unwrapping is safe because we use a constant let rounding_addition = UnsignedFixedPoint::::checked_from_rational(1, 2).unwrap(); @@ -507,40 +495,27 @@ impl Module { .ok_or(Error::::ArithmeticUnderflow.into()) } - fn btc_for( - amount: PolkaBTC, - percentage: UnsignedFixedPoint, - ) -> Result, DispatchError> { - Self::inner_to_btc(Self::calculate_for( - Self::btc_to_inner(amount)?, - percentage, - )?) + fn btc_for(amount: PolkaBTC, percentage: UnsignedFixedPoint) -> Result, DispatchError> { + Self::inner_to_btc(Self::calculate_for(Self::btc_to_inner(amount)?, percentage)?) } fn dot_for(amount: DOT, percentage: UnsignedFixedPoint) -> Result, DispatchError> { - Self::inner_to_dot(Self::calculate_for( - Self::dot_to_inner(amount)?, - percentage, - )?) + Self::inner_to_dot(Self::calculate_for(Self::dot_to_inner(amount)?, percentage)?) } #[allow(dead_code)] /// Helper for validating the `chain_spec` parameters fn ensure_rationals_sum_to_one(dist: Vec>) -> DispatchResult { - let sum = dist - .iter() - .fold(UnsignedFixedPoint::::default(), |a, &b| a + b); - let one = - UnsignedFixedPoint::::checked_from_integer(Module::::btc_to_inner(1u32.into())?) - .ok_or(Error::::ArithmeticOverflow)?; + let sum = dist.iter().fold(UnsignedFixedPoint::::default(), |a, &b| a + b); + let one = UnsignedFixedPoint::::checked_from_integer(Module::::btc_to_inner(1u32.into())?) + .ok_or(Error::::ArithmeticOverflow)?; ensure!(sum == one, Error::::InvalidRewardDist); Ok(()) } /// Total epoch rewards in PolkaBTC for vaults fn vault_rewards_for_epoch_in_polka_btc() -> Result<(PolkaBTC, PolkaBTC), DispatchError> { - let total_vault_rewards = - Self::btc_for(Self::epoch_rewards_polka_btc(), Self::vault_rewards())?; + let total_vault_rewards = Self::btc_for(Self::epoch_rewards_polka_btc(), Self::vault_rewards())?; Ok(( Self::btc_for(total_vault_rewards, Self::vault_rewards_issued())?, Self::btc_for(total_vault_rewards, Self::vault_rewards_locked())?, diff --git a/crates/fee/src/mock.rs b/crates/fee/src/mock.rs index 340a1df566..2d47acd3a7 100644 --- a/crates/fee/src/mock.rs +++ b/crates/fee/src/mock.rs @@ -167,9 +167,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); storage.into() } diff --git a/crates/fee/src/tests.rs b/crates/fee/src/tests.rs index 4f71097580..d196219638 100644 --- a/crates/fee/src/tests.rs +++ b/crates/fee/src/tests.rs @@ -1,5 +1,4 @@ -use crate::mock::*; -use crate::*; +use crate::{mock::*, *}; use frame_support::{assert_err, assert_ok}; use mocktopus::mocking::*; use sp_arithmetic::{FixedPointNumber, FixedU128}; @@ -77,9 +76,8 @@ fn test_rewards_accrue_per_epoch() { >::set(FixedU128::checked_from_integer(1).unwrap()); >::set(50); - ext::sla::get_relayer_rewards::.mock_safe(|total_polka_btc, total_dot| { - MockResult::Return(Ok(vec![(0, total_polka_btc, total_dot)])) - }); + ext::sla::get_relayer_rewards:: + .mock_safe(|total_polka_btc, total_dot| MockResult::Return(Ok(vec![(0, total_polka_btc, total_dot)]))); >::set(100); assert_ok!(Fee::begin_block(2000)); @@ -164,10 +162,7 @@ fn test_withdraw_polka_btc_succeeds() { #[test] fn test_withdraw_dot_fails_with_insufficient_balance() { run_test(|| { - assert_err!( - Fee::withdraw_dot(Origin::signed(0), 1000), - TestError::InsufficientFunds - ); + assert_err!(Fee::withdraw_dot(Origin::signed(0), 1000), TestError::InsufficientFunds); }) } diff --git a/crates/fee/src/types.rs b/crates/fee/src/types.rs index d43de2d509..d50df627a3 100644 --- a/crates/fee/src/types.rs +++ b/crates/fee/src/types.rs @@ -2,12 +2,10 @@ use crate::Config; use frame_support::traits::Currency; use sp_arithmetic::FixedPointNumber; -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; pub(crate) type UnsignedFixedPoint = ::UnsignedFixedPoint; diff --git a/crates/issue/rpc/src/lib.rs b/crates/issue/rpc/src/lib.rs index b7f7625895..f5b89aa414 100644 --- a/crates/issue/rpc/src/lib.rs +++ b/crates/issue/rpc/src/lib.rs @@ -14,11 +14,7 @@ pub use module_issue_rpc_runtime_api::IssueApi as IssueRuntimeApi; #[rpc] pub trait IssueApi { #[rpc(name = "issue_getIssueRequests")] - fn get_issue_requests( - &self, - account_id: AccountId, - at: Option, - ) -> Result>; + fn get_issue_requests(&self, account_id: AccountId, at: Option) -> Result>; #[rpc(name = "issue_getVaultIssueRequests")] fn get_vault_issue_requests( @@ -56,8 +52,8 @@ impl From for i64 { } } -impl - IssueApi<::Hash, AccountId, H256, IssueRequest> for Issue +impl IssueApi<::Hash, AccountId, H256, IssueRequest> + for Issue where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, @@ -74,12 +70,11 @@ where let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.get_issue_requests(&at, account_id) - .map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to fetch issue requests.".into(), - data: Some(format!("{:?}", e).into()), - }) + api.get_issue_requests(&at, account_id).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to fetch issue requests.".into(), + data: Some(format!("{:?}", e).into()), + }) } fn get_vault_issue_requests( @@ -90,11 +85,10 @@ where let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.get_vault_issue_requests(&at, account_id) - .map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to fetch issue requests.".into(), - data: Some(format!("{:?}", e).into()), - }) + api.get_vault_issue_requests(&at, account_id).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to fetch issue requests.".into(), + data: Some(format!("{:?}", e).into()), + }) } } diff --git a/crates/issue/src/benchmarking.rs b/crates/issue/src/benchmarking.rs index 5fb8f869ea..a45b04a89f 100644 --- a/crates/issue/src/benchmarking.rs +++ b/crates/issue/src/benchmarking.rs @@ -1,26 +1,26 @@ use super::*; use crate::Module as Issue; -use bitcoin::formatter::{Formattable, TryFormattable}; -use bitcoin::types::{ - BlockBuilder, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, TransactionOutput, +use bitcoin::{ + formatter::{Formattable, TryFormattable}, + types::{BlockBuilder, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, TransactionOutput}, }; -use btc_relay::Module as BtcRelay; -use btc_relay::{BtcAddress, BtcPublicKey}; +use btc_relay::{BtcAddress, BtcPublicKey, Module as BtcRelay}; use exchange_rate_oracle::Module as ExchangeRateOracle; use frame_benchmarking::{account, benchmarks}; -use frame_system::Module as System; -use frame_system::RawOrigin; +use frame_system::{Module as System, RawOrigin}; use security::Module as Security; use sp_core::{H160, H256, U256}; use sp_runtime::FixedPointNumber; use sp_std::prelude::*; -use vault_registry::types::{Vault, Wallet}; -use vault_registry::Module as VaultRegistry; +use vault_registry::{ + types::{Vault, Wallet}, + Module as VaultRegistry, +}; fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } @@ -147,14 +147,9 @@ mod tests { #[test] fn test_benchmarks() { - ExtBuilder::build_with( - pallet_balances::GenesisConfig:: { - balances: vec![ - (account("Origin", 0, 0), 1 << 32), - (account("Vault", 0, 0), 1 << 32), - ], - }, - ) + ExtBuilder::build_with(pallet_balances::GenesisConfig:: { + balances: vec![(account("Origin", 0, 0), 1 << 32), (account("Vault", 0, 0), 1 << 32)], + }) .execute_with(|| { assert_ok!(test_benchmark_request_issue::()); assert_ok!(test_benchmark_execute_issue::()); diff --git a/crates/issue/src/ext.rs b/crates/issue/src/ext.rs index 9f8415e3ce..7a2eb4d7ce 100644 --- a/crates/issue/src/ext.rs +++ b/crates/issue/src/ext.rs @@ -41,18 +41,13 @@ pub(crate) mod vault_registry { >::slash_collateral(from, to, amount) } - pub fn is_vault_liquidated( - vault_id: &T::AccountId, - ) -> Result { + pub fn is_vault_liquidated(vault_id: &T::AccountId) -> Result { >::is_vault_liquidated(vault_id) } pub fn get_active_vault_from_id( vault_id: &T::AccountId, - ) -> Result< - vault_registry::types::Vault, DOT>, - DispatchError, - > { + ) -> Result, DOT>, DispatchError> { >::get_active_vault_from_id(vault_id) } @@ -70,10 +65,7 @@ pub(crate) mod vault_registry { >::register_deposit_address(vault_id, secure_id) } - pub fn issue_tokens( - vault_id: &T::AccountId, - amount: PolkaBTC, - ) -> DispatchResult { + pub fn issue_tokens(vault_id: &T::AccountId, amount: PolkaBTC) -> DispatchResult { >::issue_tokens(vault_id, amount) } @@ -105,17 +97,11 @@ pub(crate) mod collateral { use crate::types::DOT; use frame_support::dispatch::DispatchResult; - pub fn lock_collateral( - sender: &T::AccountId, - amount: DOT, - ) -> DispatchResult { + pub fn lock_collateral(sender: &T::AccountId, amount: DOT) -> DispatchResult { >::lock_collateral(sender, amount) } - pub fn release_collateral( - sender: &T::AccountId, - amount: DOT, - ) -> DispatchResult { + pub fn release_collateral(sender: &T::AccountId, amount: DOT) -> DispatchResult { >::release_collateral(sender, amount) } } @@ -148,9 +134,7 @@ pub(crate) mod oracle { use crate::types::{PolkaBTC, DOT}; use frame_support::dispatch::DispatchError; - pub fn btc_to_dots( - amount: PolkaBTC, - ) -> Result, DispatchError> { + pub fn btc_to_dots(amount: PolkaBTC) -> Result, DispatchError> { >::btc_to_dots(amount) } } @@ -178,21 +162,15 @@ pub(crate) mod fee { >::fee_pool_account_id() } - pub fn get_issue_fee( - amount: PolkaBTC, - ) -> Result, DispatchError> { + pub fn get_issue_fee(amount: PolkaBTC) -> Result, DispatchError> { >::get_issue_fee(amount) } - pub fn get_issue_fee_from_total( - amount: PolkaBTC, - ) -> Result, DispatchError> { + pub fn get_issue_fee_from_total(amount: PolkaBTC) -> Result, DispatchError> { >::get_issue_fee_from_total(amount) } - pub fn get_issue_griefing_collateral( - amount: DOT, - ) -> Result, DispatchError> { + pub fn get_issue_griefing_collateral(amount: DOT) -> Result, DispatchError> { >::get_issue_griefing_collateral(amount) } @@ -215,12 +193,6 @@ pub(crate) mod refund { btc_address: BtcAddress, issue_id: H256, ) -> Result<(), DispatchError> { - >::request_refund( - total_amount_btc, - vault_id, - issuer, - btc_address, - issue_id, - ) + >::request_refund(total_amount_btc, vault_id, issuer, btc_address, issue_id) } } diff --git a/crates/issue/src/lib.rs b/crates/issue/src/lib.rs index 3b805bc1f3..fc589b0ef2 100644 --- a/crates/issue/src/lib.rs +++ b/crates/issue/src/lib.rs @@ -31,19 +31,16 @@ pub use crate::types::IssueRequest; use crate::types::{PolkaBTC, Version, DOT}; use bitcoin::types::H256Le; use btc_relay::{BtcAddress, BtcPublicKey}; -use frame_support::transactional; -use frame_support::weights::Weight; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, - ensure, + ensure, transactional, + weights::Weight, }; use frame_system::{ensure_root, ensure_signed}; use primitive_types::H256; -use sp_runtime::traits::*; -use sp_runtime::ModuleId; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_runtime::{traits::*, ModuleId}; +use sp_std::{convert::TryInto, vec::Vec}; use vault_registry::CurrencySource; /// The issue module id, used for deriving its sovereign account ID. @@ -222,8 +219,7 @@ impl Module { ext::vault_registry::ensure_not_banned::(&vault_id, height)?; let amount_dot = ext::oracle::btc_to_dots::(amount_polkabtc)?; - let expected_griefing_collateral = - ext::fee::get_issue_griefing_collateral::(amount_dot)?; + let expected_griefing_collateral = ext::fee::get_issue_griefing_collateral::(amount_dot)?; ensure!( griefing_collateral >= expected_griefing_collateral, @@ -340,10 +336,7 @@ impl Module { .checked_sub(&expected_total_amount) .ok_or(Error::::ArithmeticUnderflow)?; - match ext::vault_registry::try_increase_to_be_issued_tokens::( - &issue.vault, - surplus_btc, - ) { + match ext::vault_registry::try_increase_to_be_issued_tokens::(&issue.vault, surplus_btc) { Ok(_) => { // Current vault can handle the surplus; update the issue request Self::update_issue_amount(&issue_id, &mut issue, amount_transferred)?; @@ -378,20 +371,14 @@ impl Module { if !ext::vault_registry::is_vault_liquidated::(&issue.vault)? { // reward the vault for having issued PolkaBTC by increasing its sla - ext::sla::event_update_vault_sla::( - &issue.vault, - ext::sla::VaultEvent::ExecutedIssue(issue.amount), - )?; + ext::sla::event_update_vault_sla::(&issue.vault, ext::sla::VaultEvent::ExecutedIssue(issue.amount))?; } // if it was a vault that did the execution on behalf of someone else, reward it by // increasing its SLA score if &requester != &executor { if let Ok(vault) = ext::vault_registry::get_active_vault_from_id::(&executor) { - ext::sla::event_update_vault_sla::( - &vault.id, - ext::sla::VaultEvent::SubmittedIssueProof, - )?; + ext::sla::event_update_vault_sla::(&vault.id, ext::sla::VaultEvent::SubmittedIssueProof)?; } } @@ -437,11 +424,7 @@ impl Module { // Remove issue request from storage Self::remove_issue_request(issue_id, true); - Self::deposit_event(>::CancelIssue( - issue_id, - requester, - issue.griefing_collateral, - )); + Self::deposit_event(>::CancelIssue(issue_id, requester, issue.griefing_collateral)); Ok(()) } @@ -452,10 +435,7 @@ impl Module { /// * `account_id` - user account id pub fn get_issue_requests_for_account( account_id: T::AccountId, - ) -> Vec<( - H256, - IssueRequest, DOT>, - )> { + ) -> Vec<(H256, IssueRequest, DOT>)> { >::iter() .filter(|(_, request)| request.requester == account_id) .collect::>() @@ -468,10 +448,7 @@ impl Module { /// * `account_id` - vault account id pub fn get_issue_requests_for_vault( account_id: T::AccountId, - ) -> Vec<( - H256, - IssueRequest, DOT>, - )> { + ) -> Vec<(H256, IssueRequest, DOT>)> { >::iter() .filter(|(_, request)| request.vault == account_id) .collect::>() @@ -479,12 +456,8 @@ impl Module { pub fn get_issue_request_from_id( issue_id: &H256, - ) -> Result, DOT>, DispatchError> - { - ensure!( - >::contains_key(*issue_id), - Error::::IssueIdNotFound - ); + ) -> Result, DOT>, DispatchError> { + ensure!(>::contains_key(*issue_id), Error::::IssueIdNotFound); // NOTE: temporary workaround until we delete ensure!( !>::get(*issue_id).completed, @@ -518,10 +491,7 @@ impl Module { Ok(()) } - fn insert_issue_request( - key: H256, - value: IssueRequest, DOT>, - ) { + fn insert_issue_request(key: H256, value: IssueRequest, DOT>) { >::insert(key, value) } diff --git a/crates/issue/src/mock.rs b/crates/issue/src/mock.rs index 67bab6e4be..4d1b0cdaee 100644 --- a/crates/issue/src/mock.rs +++ b/crates/issue/src/mock.rs @@ -195,21 +195,19 @@ impl ExtBuilder { pub fn build_with( dot_balances: pallet_balances::GenesisConfig, ) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); dot_balances.assimilate_storage(&mut storage).unwrap(); fee::GenesisConfig:: { issue_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% issue_griefing_collateral: FixedU128::checked_from_rational(5, 100000).unwrap(), // 0.005% - refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% - replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% fee_pool_account_id: 0, maintainer_account_id: 1, epoch_period: 5, @@ -231,15 +229,9 @@ impl ExtBuilder { } pub fn build() -> sp_io::TestExternalities { - ExtBuilder::build_with( - pallet_balances::GenesisConfig:: { - balances: vec![ - (ALICE, ALICE_BALANCE), - (BOB, BOB_BALANCE), - (CAROL, CAROL_BALANCE), - ], - }, - ) + ExtBuilder::build_with(pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, ALICE_BALANCE), (BOB, BOB_BALANCE), (CAROL, CAROL_BALANCE)], + }) } } diff --git a/crates/issue/src/tests.rs b/crates/issue/src/tests.rs index 3ba2e4796e..949dfdb194 100644 --- a/crates/issue/src/tests.rs +++ b/crates/issue/src/tests.rs @@ -1,8 +1,4 @@ -use crate::mock::*; -use crate::PolkaBTC; -use crate::RawEvent; -use crate::DOT; -use crate::{ext, has_request_expired, Config}; +use crate::{ext, has_request_expired, mock::*, Config, PolkaBTC, RawEvent, DOT}; use bitcoin::types::H256Le; use btc_relay::{BtcAddress, BtcPublicKey}; use frame_support::{assert_noop, assert_ok, dispatch::DispatchError}; @@ -24,20 +20,14 @@ fn request_issue( ext::security::get_secure_id::.mock_safe(|_| MockResult::Return(get_dummy_request_id())); - ext::vault_registry::try_increase_to_be_issued_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_issued_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::vault_registry::register_deposit_address:: .mock_safe(|_, _| MockResult::Return(Ok(BtcAddress::default()))); Issue::_request_issue(origin, amount, vault, collateral) } -fn request_issue_ok( - origin: AccountId, - amount: Balance, - vault: AccountId, - collateral: Balance, -) -> H256 { +fn request_issue_ok(origin: AccountId, amount: Balance, vault: AccountId, collateral: Balance) -> H256 { ext::vault_registry::ensure_not_banned::.mock_safe(|_, _| MockResult::Return(Ok(()))); // Default: Parachain status is "RUNNING". Set manually for failure testing @@ -45,8 +35,7 @@ fn request_issue_ok( ext::security::get_secure_id::.mock_safe(|_| MockResult::Return(get_dummy_request_id())); - ext::vault_registry::try_increase_to_be_issued_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_issued_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::vault_registry::register_deposit_address:: .mock_safe(|_, _| MockResult::Return(Ok(BtcAddress::default()))); @@ -56,22 +45,14 @@ fn request_issue_ok( fn execute_issue(origin: AccountId, issue_id: &H256) -> Result<(), DispatchError> { ext::security::ensure_parachain_status_running::.mock_safe(|| MockResult::Return(Ok(()))); - Issue::_execute_issue( - origin, - *issue_id, - H256Le::zero(), - vec![0u8; 100], - vec![0u8; 100], - ) + Issue::_execute_issue(origin, *issue_id, H256Le::zero(), vec![0u8; 100], vec![0u8; 100]) } fn cancel_issue(origin: AccountId, issue_id: &H256) -> Result<(), DispatchError> { Issue::_cancel_issue(origin, *issue_id) } -fn init_zero_vault( - id: T::AccountId, -) -> Vault, DOT> { +fn init_zero_vault(id: T::AccountId) -> Vault, DOT> { let mut vault = Vault::default(); vault.id = id; vault @@ -102,10 +83,7 @@ fn test_request_issue_banned_fails() { status: VaultStatus::Active, }, ); - assert_noop!( - request_issue(ALICE, 3, BOB, 0), - VaultRegistryError::VaultBanned - ); + assert_noop!(request_issue(ALICE, 3, BOB, 0), VaultRegistryError::VaultBanned); }) } @@ -117,10 +95,7 @@ fn test_request_issue_insufficient_collateral_fails() { ext::vault_registry::ensure_not_banned::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::oracle::btc_to_dots::.mock_safe(|_| MockResult::Return(Ok(10000000))); - assert_noop!( - request_issue(ALICE, 3, BOB, 0), - TestError::InsufficientCollateral, - ); + assert_noop!(request_issue(ALICE, 3, BOB, 0), TestError::InsufficientCollateral,); }) } @@ -154,9 +129,7 @@ fn test_request_issue_succeeds() { BtcAddress::default(), BtcPublicKey::default(), )); - assert!(System::events() - .iter() - .any(|a| a.event == request_issue_event)); + assert!(System::events().iter().any(|a| a.event == request_issue_event)); }) } @@ -165,10 +138,7 @@ fn test_execute_issue_not_found_fails() { run_test(|| { ext::vault_registry::get_active_vault_from_id:: .mock_safe(|_| MockResult::Return(Ok(init_zero_vault::(BOB)))); - assert_noop!( - execute_issue(ALICE, &H256([0; 32])), - TestError::IssueIdNotFound - ); + assert_noop!(execute_issue(ALICE, &H256([0; 32])), TestError::IssueIdNotFound); }) } @@ -180,10 +150,7 @@ fn test_execute_issue_commit_period_expired_fails() { let issue_id = request_issue_ok(ALICE, 3, BOB, 20); >::set_block_number(20); - assert_noop!( - execute_issue(ALICE, &issue_id), - TestError::CommitPeriodExpired - ); + assert_noop!(execute_issue(ALICE, &issue_id), TestError::CommitPeriodExpired); }) } @@ -194,25 +161,20 @@ fn test_execute_issue_succeeds() { .mock_safe(|_| MockResult::Return(Ok(init_zero_vault::(BOB)))); ext::vault_registry::issue_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_vault_liquidated:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::is_vault_liquidated::.mock_safe(|_| MockResult::Return(Ok(false))); let issue_id = request_issue_ok(ALICE, 3, BOB, 20); >::set_block_number(5); - ext::security::ensure_parachain_status_running:: - .mock_safe(|| MockResult::Return(Ok(()))); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::security::ensure_parachain_status_running::.mock_safe(|| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::btc_relay::validate_transaction:: .mock_safe(|_, _, _, _| MockResult::Return(Ok((BtcAddress::P2SH(H160::zero()), 3)))); assert_ok!(execute_issue(ALICE, &issue_id)); let execute_issue_event = TestEvent::issue(RawEvent::ExecuteIssue(issue_id, ALICE, 3, BOB)); - assert!(System::events() - .iter() - .any(|a| a.event == execute_issue_event)); + assert!(System::events().iter().any(|a| a.event == execute_issue_event)); assert_noop!(cancel_issue(ALICE, &issue_id), TestError::IssueCompleted); }) @@ -227,18 +189,15 @@ fn test_execute_issue_overpayment_succeeds() { let issue_id = request_issue_ok(ALICE, 3, BOB, 20); >::set_block_number(5); - ext::security::ensure_parachain_status_running:: - .mock_safe(|| MockResult::Return(Ok(()))); + ext::security::ensure_parachain_status_running::.mock_safe(|| MockResult::Return(Ok(()))); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(|_, _| MockResult::Return(Ok(()))); // pay 5 instead of the expected 3 ext::btc_relay::validate_transaction:: .mock_safe(|_, _, _, _| MockResult::Return(Ok((BtcAddress::P2SH(H160::zero()), 5)))); - ext::vault_registry::is_vault_liquidated:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::is_vault_liquidated::.mock_safe(|_| MockResult::Return(Ok(false))); unsafe { let mut increase_tokens_called = false; @@ -272,11 +231,9 @@ fn test_execute_issue_refund_succeeds() { let issue_id = request_issue_ok(ALICE, 3, BOB, 20); >::set_block_number(5); - ext::security::ensure_parachain_status_running:: - .mock_safe(|| MockResult::Return(Ok(()))); + ext::security::ensure_parachain_status_running::.mock_safe(|| MockResult::Return(Ok(()))); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(|_, _| MockResult::Return(Ok(()))); // pay 103 instead of the expected 3 ext::btc_relay::validate_transaction:: @@ -290,8 +247,7 @@ fn test_execute_issue_refund_succeeds() { ext::vault_registry::register_deposit_address:: .mock_safe(|_, _| MockResult::Return(Ok(BtcAddress::default()))); - ext::vault_registry::is_vault_liquidated:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::is_vault_liquidated::.mock_safe(|_| MockResult::Return(Ok(false))); unsafe { let mut refund_called = false; @@ -310,10 +266,7 @@ fn test_execute_issue_refund_succeeds() { #[test] fn test_cancel_issue_not_found_fails() { run_test(|| { - assert_noop!( - cancel_issue(ALICE, &H256([0; 32])), - TestError::IssueIdNotFound, - ); + assert_noop!(cancel_issue(ALICE, &H256([0; 32])), TestError::IssueIdNotFound,); }) } @@ -340,14 +293,11 @@ fn test_cancel_issue_succeeds() { ext::vault_registry::get_active_vault_from_id:: .mock_safe(|_| MockResult::Return(Ok(init_zero_vault::(BOB)))); - ext::vault_registry::decrease_to_be_issued_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::decrease_to_be_issued_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_vault_liquidated:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::is_vault_liquidated::.mock_safe(|_| MockResult::Return(Ok(false))); - ext::vault_registry::slash_collateral:: - .mock_safe(|_, _, _| MockResult::Return(Ok(()))); + ext::vault_registry::slash_collateral::.mock_safe(|_, _, _| MockResult::Return(Ok(()))); let issue_id = request_issue_ok(ALICE, 3, BOB, 20); // issue period is 10, we issued at block 1, so at block 15 the cancel should succeed @@ -382,13 +332,7 @@ fn test_execute_issue_parachain_not_running_fails() { .mock_safe(|| MockResult::Return(Err(SecurityError::ParachainNotRunning.into()))); assert_noop!( - Issue::_execute_issue( - origin, - H256::zero(), - H256Le::zero(), - vec![0u8; 100], - vec![0u8; 100], - ), + Issue::_execute_issue(origin, H256::zero(), H256Le::zero(), vec![0u8; 100], vec![0u8; 100],), SecurityError::ParachainNotRunning ); }) diff --git a/crates/issue/src/types.rs b/crates/issue/src/types.rs index dad386cf11..863dd6f35a 100644 --- a/crates/issue/src/types.rs +++ b/crates/issue/src/types.rs @@ -13,12 +13,10 @@ pub enum Version { V1, } -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; // Due to a known bug in serde we need to specify how u128 is (de)serialized. // See https://github.com/paritytech/substrate/issues/4641 @@ -32,26 +30,14 @@ pub struct IssueRequest { #[cfg_attr(feature = "std", serde(bound(serialize = "DOT: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] pub griefing_collateral: DOT, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] pub amount: PolkaBTC, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] pub fee: PolkaBTC, pub requester: AccountId, @@ -62,17 +48,12 @@ pub struct IssueRequest { } #[cfg(feature = "std")] -fn serialize_as_string( - t: &T, - serializer: S, -) -> Result { +fn serialize_as_string(t: &T, serializer: S) -> Result { serializer.serialize_str(&t.to_string()) } #[cfg(feature = "std")] -fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>( - deserializer: D, -) -> Result { +fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>(deserializer: D) -> Result { let s = String::deserialize(deserializer)?; s.parse::() .map_err(|_| serde::de::Error::custom("Parse from string failed")) diff --git a/crates/parachain-tokens/src/lib.rs b/crates/parachain-tokens/src/lib.rs index b7edcc32ae..71b6e8f156 100644 --- a/crates/parachain-tokens/src/lib.rs +++ b/crates/parachain-tokens/src/lib.rs @@ -5,9 +5,12 @@ mod types; use cumulus_primitives::ParaId; -use frame_support::dispatch::{DispatchError, DispatchResult}; -use frame_support::transactional; -use frame_support::{decl_error, decl_event, decl_module, decl_storage, traits::Get}; +use frame_support::{ + decl_error, decl_event, decl_module, decl_storage, + dispatch::{DispatchError, DispatchResult}, + traits::Get, + transactional, +}; use frame_system::ensure_signed; use sp_runtime::traits::Convert; use sp_std::{convert::TryInto, prelude::*}; diff --git a/crates/parachain-tokens/src/types.rs b/crates/parachain-tokens/src/types.rs index d7c659ba2b..7b4ad35e47 100644 --- a/crates/parachain-tokens/src/types.rs +++ b/crates/parachain-tokens/src/types.rs @@ -1,7 +1,8 @@ use codec::{Decode, Encode}; -use frame_support::runtime_print; -use frame_support::traits::Currency; -use frame_support::traits::{ExistenceRequirement::AllowDeath, WithdrawReasons}; +use frame_support::{ + runtime_print, + traits::{Currency, ExistenceRequirement::AllowDeath, WithdrawReasons}, +}; use sp_runtime::traits::{CheckedConversion, SaturatedConversion}; use sp_std::{ convert::{TryFrom, TryInto}, @@ -21,12 +22,10 @@ use xcm_executor::traits::FilterAssetLocation; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; #[cfg(feature = "disable-native-filter")] pub struct NativeAsset; @@ -99,10 +98,7 @@ impl< Ok(()) } - fn withdraw_asset( - asset: &MultiAsset, - location: &MultiLocation, - ) -> Result { + fn withdraw_asset(asset: &MultiAsset, location: &MultiLocation) -> Result { runtime_print!("Withdraw asset: {:?}, location: {:?}", asset, location); let who = AccountIdConverter::from_location(location).ok_or(XcmError::BadOrigin)?; let currency_id = currency_id_from_asset(asset).ok_or(XcmError::Unimplemented)?; diff --git a/crates/redeem/rpc/src/lib.rs b/crates/redeem/rpc/src/lib.rs index d50027661d..b144a961de 100644 --- a/crates/redeem/rpc/src/lib.rs +++ b/crates/redeem/rpc/src/lib.rs @@ -14,11 +14,7 @@ pub use module_redeem_rpc_runtime_api::RedeemApi as RedeemRuntimeApi; #[rpc] pub trait RedeemApi { #[rpc(name = "redeem_getRedeemRequests")] - fn get_redeem_requests( - &self, - account_id: AccountId, - at: Option, - ) -> Result>; + fn get_redeem_requests(&self, account_id: AccountId, at: Option) -> Result>; #[rpc(name = "redeem_getVaultRedeemRequests")] fn get_vault_redeem_requests( @@ -56,8 +52,8 @@ impl From for i64 { } } -impl - RedeemApi<::Hash, AccountId, H256, RedeemRequest> for Redeem +impl RedeemApi<::Hash, AccountId, H256, RedeemRequest> + for Redeem where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, @@ -74,12 +70,11 @@ where let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.get_redeem_requests(&at, account_id) - .map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to fetch redeem requests.".into(), - data: Some(format!("{:?}", e).into()), - }) + api.get_redeem_requests(&at, account_id).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to fetch redeem requests.".into(), + data: Some(format!("{:?}", e).into()), + }) } fn get_vault_redeem_requests( @@ -90,11 +85,10 @@ where let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.get_vault_redeem_requests(&at, account_id) - .map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to fetch redeem requests.".into(), - data: Some(format!("{:?}", e).into()), - }) + api.get_vault_redeem_requests(&at, account_id).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to fetch redeem requests.".into(), + data: Some(format!("{:?}", e).into()), + }) } } diff --git a/crates/redeem/src/benchmarking.rs b/crates/redeem/src/benchmarking.rs index dedcdfffa8..e103ad6e15 100644 --- a/crates/redeem/src/benchmarking.rs +++ b/crates/redeem/src/benchmarking.rs @@ -1,23 +1,23 @@ use super::*; use crate::Module as Redeem; -use bitcoin::formatter::{Formattable, TryFormattable}; -use bitcoin::types::{ - BlockBuilder, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, TransactionOutput, +use bitcoin::{ + formatter::{Formattable, TryFormattable}, + types::{BlockBuilder, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, TransactionOutput}, }; -use btc_relay::Module as BtcRelay; -use btc_relay::{BtcAddress, BtcPublicKey}; +use btc_relay::{BtcAddress, BtcPublicKey, Module as BtcRelay}; use frame_benchmarking::{account, benchmarks}; -use frame_system::Module as System; -use frame_system::RawOrigin; +use frame_system::{Module as System, RawOrigin}; use sp_core::{H160, H256, U256}; use sp_std::prelude::*; -use vault_registry::types::{Vault, Wallet}; -use vault_registry::Module as VaultRegistry; +use vault_registry::{ + types::{Vault, Wallet}, + Module as VaultRegistry, +}; fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } @@ -151,16 +151,10 @@ mod tests { fn test_benchmarks() { ExtBuilder::build_with( pallet_balances::GenesisConfig:: { - balances: vec![ - (account("Origin", 0, 0), 1 << 32), - (account("Vault", 0, 0), 1 << 32), - ], + balances: vec![(account("Origin", 0, 0), 1 << 32), (account("Vault", 0, 0), 1 << 32)], }, pallet_balances::GenesisConfig:: { - balances: vec![ - (account("Origin", 0, 0), 1 << 32), - (account("Vault", 0, 0), 1 << 32), - ], + balances: vec![(account("Origin", 0, 0), 1 << 32), (account("Vault", 0, 0), 1 << 32)], }, ) .execute_with(|| { diff --git a/crates/redeem/src/ext.rs b/crates/redeem/src/ext.rs index 7582e36d44..19fa5fcc36 100644 --- a/crates/redeem/src/ext.rs +++ b/crates/redeem/src/ext.rs @@ -8,10 +8,7 @@ pub(crate) mod btc_relay { use frame_support::dispatch::{DispatchError, DispatchResult}; use sp_std::vec::Vec; - pub fn verify_transaction_inclusion( - tx_id: H256Le, - merkle_proof: Vec, - ) -> DispatchResult { + pub fn verify_transaction_inclusion(tx_id: H256Le, merkle_proof: Vec) -> DispatchResult { >::_verify_transaction_inclusion(tx_id, merkle_proof, None) } @@ -31,18 +28,13 @@ pub(crate) mod vault_registry { use frame_support::dispatch::{DispatchError, DispatchResult}; use vault_registry::types::CurrencySource; - pub fn get_backing_collateral( - vault_id: &T::AccountId, - ) -> Result, DispatchError> { + pub fn get_backing_collateral(vault_id: &T::AccountId) -> Result, DispatchError> { >::get_backing_collateral(vault_id) } pub fn get_active_vault_from_id( vault_id: &T::AccountId, - ) -> Result< - vault_registry::types::Vault, DOT>, - DispatchError, - > { + ) -> Result, DOT>, DispatchError> { >::get_active_vault_from_id(vault_id) } pub fn slash_collateral( @@ -63,10 +55,7 @@ pub(crate) mod vault_registry { pub fn get_vault_from_id( vault_id: &T::AccountId, - ) -> Result< - vault_registry::types::Vault, DOT>, - DispatchError, - > { + ) -> Result, DOT>, DispatchError> { >::get_vault_from_id(vault_id) } @@ -164,24 +153,15 @@ pub(crate) mod treasury { >::get_balance_from_account(account) } - pub fn lock( - redeemer: T::AccountId, - amount: PolkaBTC, - ) -> DispatchResult { + pub fn lock(redeemer: T::AccountId, amount: PolkaBTC) -> DispatchResult { >::lock(redeemer, amount) } - pub fn unlock( - account: T::AccountId, - amount: PolkaBTC, - ) -> DispatchResult { + pub fn unlock(account: T::AccountId, amount: PolkaBTC) -> DispatchResult { >::unlock(account, amount) } - pub fn burn( - redeemer: T::AccountId, - amount: PolkaBTC, - ) -> DispatchResult { + pub fn burn(redeemer: T::AccountId, amount: PolkaBTC) -> DispatchResult { >::burn(redeemer, amount) } @@ -217,9 +197,7 @@ pub(crate) mod oracle { use crate::types::{PolkaBTC, DOT}; use frame_support::dispatch::DispatchError; - pub fn btc_to_dots( - amount: PolkaBTC, - ) -> Result, DispatchError> { + pub fn btc_to_dots(amount: PolkaBTC) -> Result, DispatchError> { >::btc_to_dots(amount) } } @@ -233,9 +211,7 @@ pub(crate) mod fee { >::fee_pool_account_id() } - pub fn get_redeem_fee( - amount: PolkaBTC, - ) -> Result, DispatchError> { + pub fn get_redeem_fee(amount: PolkaBTC) -> Result, DispatchError> { >::get_redeem_fee(amount) } diff --git a/crates/redeem/src/lib.rs b/crates/redeem/src/lib.rs index 63e2acc5ea..2cb48a74d6 100644 --- a/crates/redeem/src/lib.rs +++ b/crates/redeem/src/lib.rs @@ -31,20 +31,17 @@ pub use crate::types::RedeemRequest; use crate::types::{PolkaBTC, Version, DOT}; use bitcoin::types::H256Le; use btc_relay::BtcAddress; -use frame_support::transactional; -use frame_support::weights::Weight; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, - ensure, + ensure, transactional, + weights::Weight, }; use frame_system::{ensure_root, ensure_signed}; use primitive_types::H256; use security::ErrorCode; -use sp_runtime::traits::*; -use sp_runtime::ModuleId; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_runtime::{traits::*, ModuleId}; +use sp_std::{convert::TryInto, vec::Vec}; use vault_registry::CurrencySource; /// The redeem module id, used for deriving its sovereign account ID. @@ -264,20 +261,15 @@ impl Module { Error::::AmountBelowDustAmount ); - ext::vault_registry::try_increase_to_be_redeemed_tokens::( - &vault_id, - redeem_amount_polka_btc, - )?; + ext::vault_registry::try_increase_to_be_redeemed_tokens::(&vault_id, redeem_amount_polka_btc)?; // lock full amount (inc. fee) ext::treasury::lock::(redeemer.clone(), amount_polka_btc)?; let redeem_id = ext::security::get_secure_id::(&redeemer); - let below_premium_redeem = - ext::vault_registry::is_vault_below_premium_threshold::(&vault_id)?; + let below_premium_redeem = ext::vault_registry::is_vault_below_premium_threshold::(&vault_id)?; let premium_dot = if below_premium_redeem { - let redeem_amount_polka_btc_in_dot = - ext::oracle::btc_to_dots::(redeem_amount_polka_btc)?; + let redeem_amount_polka_btc_in_dot = ext::oracle::btc_to_dots::(redeem_amount_polka_btc)?; ext::fee::get_premium_redeem_fee::(redeem_amount_polka_btc_in_dot)? } else { Self::u128_to_dot(0u128)? @@ -316,10 +308,7 @@ impl Module { Ok(redeem_id) } - fn _liquidation_redeem( - redeemer: T::AccountId, - amount_polka_btc: PolkaBTC, - ) -> Result<(), DispatchError> { + fn _liquidation_redeem(redeemer: T::AccountId, amount_polka_btc: PolkaBTC) -> Result<(), DispatchError> { Self::ensure_parachain_running_or_error_liquidated()?; let redeemer_balance = ext::treasury::get_balance::(redeemer.clone()); @@ -354,10 +343,7 @@ impl Module { Error::::CommitPeriodExpired ); - let amount: usize = redeem - .amount_btc - .try_into() - .map_err(|_e| Error::::TryIntoIntError)?; + let amount: usize = redeem.amount_btc.try_into().map_err(|_e| Error::::TryIntoIntError)?; ext::btc_relay::verify_transaction_inclusion::(tx_id, merkle_proof)?; // NOTE: vault client must register change addresses before // sending the bitcoin transaction @@ -381,12 +367,7 @@ impl Module { )?; ext::fee::increase_polka_btc_rewards_for_epoch::(fee_polka_btc); - ext::vault_registry::redeem_tokens::( - &redeem.vault, - amount_polka_btc, - redeem.premium_dot, - &redeem.redeemer, - )?; + ext::vault_registry::redeem_tokens::(&redeem.vault, amount_polka_btc, redeem.premium_dot, &redeem.redeemer)?; Self::remove_redeem_request(redeem_id, false, false); Self::deposit_event(>::ExecuteRedeem( @@ -418,11 +399,7 @@ impl Module { // first update the polkabtc tokens; this logic is the same regardless of whether or not the vault is liquidated if reimburse { // decrease to_be_redeemed & issued - ext::vault_registry::decrease_tokens::( - &vault_id, - &redeem.redeemer, - redeem.amount_polka_btc, - )?; + ext::vault_registry::decrease_tokens::(&vault_id, &redeem.redeemer, redeem.amount_polka_btc)?; // Transfer the transaction fee to the pool. Even though the redeem was not // successful, the user receives a premium in DOT, so it's to take the fee. @@ -436,10 +413,7 @@ impl Module { // burn user's PolkaBTC, excluding fee ext::treasury::burn::(redeem.redeemer.clone(), redeem.amount_btc)?; } else { - ext::vault_registry::decrease_to_be_redeemed_tokens::( - &vault_id, - redeem.amount_polka_btc, - )?; + ext::vault_registry::decrease_to_be_redeemed_tokens::(&vault_id, redeem.amount_polka_btc)?; // unlock user's PolkaBTC, including fee let total_polka_btc = redeem @@ -492,8 +466,7 @@ impl Module { slashed_punishment_fee }; // calculate additional amount to slash, a high SLA means we slash less - let slashing_amount_in_dot = - ext::sla::calculate_slashed_amount::(&vault_id, amount_polka_btc_in_dot)?; + let slashing_amount_in_dot = ext::sla::calculate_slashed_amount::(&vault_id, amount_polka_btc_in_dot)?; // slash the remaining amount from the vault to the fee pool let remaining_dot_to_be_slashed = slashing_amount_in_dot @@ -527,9 +500,7 @@ impl Module { /// Ensure that the parachain is running or the system is in liquidation fn ensure_parachain_running_or_error_liquidated() -> DispatchResult { - ext::security::ensure_parachain_is_running_or_only_has_errors::( - [ErrorCode::Liquidation].to_vec(), - ) + ext::security::ensure_parachain_is_running_or_only_has_errors::([ErrorCode::Liquidation].to_vec()) } /// Insert a new redeem request into state. @@ -538,10 +509,7 @@ impl Module { /// /// * `key` - 256-bit identifier of the redeem request /// * `value` - the redeem request - fn insert_redeem_request( - key: H256, - value: RedeemRequest, DOT>, - ) { + fn insert_redeem_request(key: H256, value: RedeemRequest, DOT>) { >::insert(key, value) } @@ -561,10 +529,7 @@ impl Module { /// * `account_id` - user account id pub fn get_redeem_requests_for_account( account_id: T::AccountId, - ) -> Vec<( - H256, - RedeemRequest, DOT>, - )> { + ) -> Vec<(H256, RedeemRequest, DOT>)> { >::iter() .filter(|(_, request)| request.redeemer == account_id) .collect::>() @@ -577,10 +542,7 @@ impl Module { /// * `account_id` - vault account id pub fn get_redeem_requests_for_vault( account_id: T::AccountId, - ) -> Vec<( - H256, - RedeemRequest, DOT>, - )> { + ) -> Vec<(H256, RedeemRequest, DOT>)> { >::iter() .filter(|(_, request)| request.vault == account_id) .collect::>() @@ -594,8 +556,7 @@ impl Module { /// * `redeem_id` - 256-bit identifier of the redeem request pub fn get_open_redeem_request_from_id( redeem_id: &H256, - ) -> Result, DOT>, DispatchError> - { + ) -> Result, DOT>, DispatchError> { ensure!( >::contains_key(*redeem_id), Error::::RedeemIdNotFound @@ -620,8 +581,7 @@ impl Module { /// * `redeem_id` - 256-bit identifier of the redeem request pub fn get_open_or_completed_redeem_request_from_id( redeem_id: &H256, - ) -> Result, DOT>, DispatchError> - { + ) -> Result, DOT>, DispatchError> { ensure!( >::contains_key(*redeem_id), Error::::RedeemIdNotFound diff --git a/crates/redeem/src/mock.rs b/crates/redeem/src/mock.rs index 24689ab51e..37b0c63290 100644 --- a/crates/redeem/src/mock.rs +++ b/crates/redeem/src/mock.rs @@ -189,9 +189,7 @@ impl ExtBuilder { dot_balances: pallet_balances::GenesisConfig, btc_balances: pallet_balances::GenesisConfig, ) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); dot_balances.assimilate_storage(&mut storage).unwrap(); btc_balances.assimilate_storage(&mut storage).unwrap(); @@ -199,12 +197,12 @@ impl ExtBuilder { fee::GenesisConfig:: { issue_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% issue_griefing_collateral: FixedU128::checked_from_rational(5, 100000).unwrap(), // 0.005% - refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% - replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% fee_pool_account_id: 0, maintainer_account_id: 1, epoch_period: 5, @@ -264,18 +262,10 @@ impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { ExtBuilder::build_with( pallet_balances::GenesisConfig:: { - balances: vec![ - (ALICE, ALICE_BALANCE), - (BOB, BOB_BALANCE), - (CAROL, CAROL_BALANCE), - ], + balances: vec![(ALICE, ALICE_BALANCE), (BOB, BOB_BALANCE), (CAROL, CAROL_BALANCE)], }, pallet_balances::GenesisConfig:: { - balances: vec![ - (ALICE, ALICE_BALANCE), - (BOB, BOB_BALANCE), - (CAROL, CAROL_BALANCE), - ], + balances: vec![(ALICE, ALICE_BALANCE), (BOB, BOB_BALANCE), (CAROL, CAROL_BALANCE)], }, ) } diff --git a/crates/redeem/src/tests.rs b/crates/redeem/src/tests.rs index c19e0ff8d8..8f77a05887 100644 --- a/crates/redeem/src/tests.rs +++ b/crates/redeem/src/tests.rs @@ -1,6 +1,4 @@ -use crate::ext; -use crate::has_request_expired; -use crate::mock::*; +use crate::{ext, has_request_expired, mock::*}; use crate::types::{PolkaBTC, RedeemRequest, DOT}; use bitcoin::types::H256Le; @@ -22,10 +20,7 @@ macro_rules! assert_emitted { ($event:expr, $times:expr) => { let test_event = TestEvent::redeem($event); assert_eq!( - System::events() - .iter() - .filter(|a| a.event == test_event) - .count(), + System::events().iter().filter(|a| a.event == test_event).count(), $times ); }; @@ -44,17 +39,14 @@ fn btcdot_parity(btc: PolkaBTC) -> Result, DispatchError> { u128_to_dot(dot) } -fn inject_redeem_request( - key: H256, - value: RedeemRequest, -) { +fn inject_redeem_request(key: H256, value: RedeemRequest) { Redeem::insert_redeem_request(key, value) } fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } @@ -105,22 +97,15 @@ fn test_request_redeem_fails_with_amount_below_minimum() { let redeemer = ALICE; let amount = 9; - ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe( - move |vault_id, amount_btc| { - assert_eq!(vault_id, &BOB); - assert_eq!(amount_btc, amount); + ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe(move |vault_id, amount_btc| { + assert_eq!(vault_id, &BOB); + assert_eq!(amount_btc, amount); - MockResult::Return(Ok(())) - }, - ); + MockResult::Return(Ok(())) + }); assert_err!( - Redeem::request_redeem( - Origin::signed(redeemer.clone()), - 1, - BtcAddress::random(), - BOB - ), + Redeem::request_redeem(Origin::signed(redeemer.clone()), 1, BtcAddress::random(), BOB), TestError::AmountBelowDustAmount ); }) @@ -238,14 +223,12 @@ fn test_request_redeem_succeeds_with_normal_redeem() { let amount = 9; let redeem_fee = 5; - ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe( - move |vault_id, amount_btc| { - assert_eq!(vault_id, &BOB); - assert_eq!(amount_btc, amount - redeem_fee); + ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe(move |vault_id, amount_btc| { + assert_eq!(vault_id, &BOB); + assert_eq!(amount_btc, amount - redeem_fee); - MockResult::Return(Ok(())) - }, - ); + MockResult::Return(Ok(())) + }); ext::treasury::lock::.mock_safe(move |account, amount_polka_btc| { assert_eq!(account, redeemer); @@ -309,19 +292,14 @@ fn test_liquidation_redeem_succeeds() { MockResult::Return(Ok(())) }); - ext::vault_registry::redeem_tokens_liquidation::.mock_safe( - move |redeemer_id, amount| { - assert_eq!(redeemer_id, &ALICE); - assert_eq!(amount, total_amount); + ext::vault_registry::redeem_tokens_liquidation::.mock_safe(move |redeemer_id, amount| { + assert_eq!(redeemer_id, &ALICE); + assert_eq!(amount, total_amount); - MockResult::Return(Ok(())) - }, - ); + MockResult::Return(Ok(())) + }); - assert_ok!(Redeem::liquidation_redeem( - Origin::signed(ALICE), - total_amount, - )); + assert_ok!(Redeem::liquidation_redeem(Origin::signed(ALICE), total_amount,)); }) } @@ -361,8 +339,7 @@ fn test_execute_redeem_succeeds_with_another_account() { status: VaultStatus::Active, }, ); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::btc_relay::validate_transaction:: .mock_safe(|_, _, _, _| MockResult::Return(Ok((BtcAddress::P2SH(H160::zero()), 0)))); @@ -391,15 +368,13 @@ fn test_execute_redeem_succeeds_with_another_account() { MockResult::Return(Ok(())) }); - ext::vault_registry::redeem_tokens::.mock_safe( - move |vault, amount_polka_btc, premium, _| { - assert_eq!(vault, &BOB); - assert_eq!(amount_polka_btc, 100); - assert_eq!(premium, 0); + ext::vault_registry::redeem_tokens::.mock_safe(move |vault, amount_polka_btc, premium, _| { + assert_eq!(vault, &BOB); + assert_eq!(amount_polka_btc, 100); + assert_eq!(premium, 0); - MockResult::Return(Ok(())) - }, - ); + MockResult::Return(Ok(())) + }); assert_ok!(Redeem::execute_redeem( Origin::signed(ALICE), @@ -470,8 +445,7 @@ fn test_execute_redeem_succeeds() { status: VaultStatus::Active, }, ); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::btc_relay::validate_transaction:: .mock_safe(|_, _, _, _| MockResult::Return(Ok((BtcAddress::P2SH(H160::zero()), 0)))); @@ -500,15 +474,13 @@ fn test_execute_redeem_succeeds() { MockResult::Return(Ok(())) }); - ext::vault_registry::redeem_tokens::.mock_safe( - move |vault, amount_polka_btc, premium, _| { - assert_eq!(vault, &BOB); - assert_eq!(amount_polka_btc, 100); - assert_eq!(premium, 0); + ext::vault_registry::redeem_tokens::.mock_safe(move |vault, amount_polka_btc, premium, _| { + assert_eq!(vault, &BOB); + assert_eq!(amount_polka_btc, 100); + assert_eq!(premium, 0); - MockResult::Return(Ok(())) - }, - ); + MockResult::Return(Ok(())) + }); assert_ok!(Redeem::execute_redeem( Origin::signed(BOB), @@ -621,21 +593,15 @@ fn test_cancel_redeem_succeeds() { MockResult::Return(Ok(())) }); ext::sla::calculate_slashed_amount::.mock_safe(move |_, _| MockResult::Return(Ok(0))); - ext::vault_registry::slash_collateral_saturated:: - .mock_safe(move |_, _, _| MockResult::Return(Ok(0))); + ext::vault_registry::slash_collateral_saturated::.mock_safe(move |_, _, _| MockResult::Return(Ok(0))); ext::vault_registry::get_vault_from_id::.mock_safe(|_| { MockResult::Return(Ok(vault_registry::types::Vault { status: VaultStatus::Active, ..Default::default() })) }); - ext::vault_registry::decrease_to_be_redeemed_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); - assert_ok!(Redeem::cancel_redeem( - Origin::signed(ALICE), - H256([0u8; 32]), - false - )); + ext::vault_registry::decrease_to_be_redeemed_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); + assert_ok!(Redeem::cancel_redeem(Origin::signed(ALICE), H256([0u8; 32]), false)); assert_err!( Redeem::get_open_redeem_request_from_id(&H256([0u8; 32])), TestError::RedeemCancelled, diff --git a/crates/redeem/src/types.rs b/crates/redeem/src/types.rs index 89b9a80ed6..481ecf9e6f 100644 --- a/crates/redeem/src/types.rs +++ b/crates/redeem/src/types.rs @@ -13,12 +13,10 @@ pub enum Version { V1, } -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; // Due to a known bug in serde we need to specify how u128 is (de)serialized. // See https://github.com/paritytech/substrate/issues/4641 @@ -27,39 +25,21 @@ pub(crate) type PolkaBTC = <::PolkaBTC as Currency< pub struct RedeemRequest { pub vault: AccountId, pub opentime: BlockNumber, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] /// Total redeem amount (`amount_btc + dotsToBtc(amount_dot)`) pub amount_polka_btc: PolkaBTC, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] /// Total redeem fees in PolkaBTC - taken from request amount pub fee: PolkaBTC, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] /// Total amount of BTC for the vault to send pub amount_btc: PolkaBTC, @@ -83,17 +63,12 @@ pub struct RedeemRequest { } #[cfg(feature = "std")] -fn serialize_as_string( - t: &T, - serializer: S, -) -> Result { +fn serialize_as_string(t: &T, serializer: S) -> Result { serializer.serialize_str(&t.to_string()) } #[cfg(feature = "std")] -fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>( - deserializer: D, -) -> Result { +fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>(deserializer: D) -> Result { let s = String::deserialize(deserializer)?; s.parse::() .map_err(|_| serde::de::Error::custom("Parse from string failed")) diff --git a/crates/refund/rpc/src/lib.rs b/crates/refund/rpc/src/lib.rs index db44e8171b..681403004b 100644 --- a/crates/refund/rpc/src/lib.rs +++ b/crates/refund/rpc/src/lib.rs @@ -61,8 +61,8 @@ impl From for i64 { } } -impl - RefundApi<::Hash, AccountId, H256, RefundRequest> for Refund +impl RefundApi<::Hash, AccountId, H256, RefundRequest> + for Refund where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, @@ -79,12 +79,11 @@ where let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.get_refund_requests(&at, account_id) - .map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to fetch refund requests.".into(), - data: Some(format!("{:?}", e).into()), - }) + api.get_refund_requests(&at, account_id).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to fetch refund requests.".into(), + data: Some(format!("{:?}", e).into()), + }) } fn get_refund_requests_by_issue_id( @@ -111,11 +110,10 @@ where let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.get_vault_refund_requests(&at, account_id) - .map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to fetch refund requests.".into(), - data: Some(format!("{:?}", e).into()), - }) + api.get_vault_refund_requests(&at, account_id).map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to fetch refund requests.".into(), + data: Some(format!("{:?}", e).into()), + }) } } diff --git a/crates/refund/src/ext.rs b/crates/refund/src/ext.rs index 65bd910a68..c2b580b87c 100644 --- a/crates/refund/src/ext.rs +++ b/crates/refund/src/ext.rs @@ -6,9 +6,7 @@ pub(crate) mod fee { use crate::types::PolkaBTC; use frame_support::dispatch::DispatchError; - pub fn get_refund_fee_from_total( - amount: PolkaBTC, - ) -> Result, DispatchError> { + pub fn get_refund_fee_from_total(amount: PolkaBTC) -> Result, DispatchError> { >::get_refund_fee_from_total(amount) } } @@ -34,10 +32,7 @@ pub(crate) mod btc_relay { use frame_support::dispatch::{DispatchError, DispatchResult}; use sp_std::vec::Vec; - pub fn verify_transaction_inclusion( - tx_id: H256Le, - merkle_proof: Vec, - ) -> DispatchResult { + pub fn verify_transaction_inclusion(tx_id: H256Le, merkle_proof: Vec) -> DispatchResult { >::_verify_transaction_inclusion(tx_id, merkle_proof, None) } pub fn validate_transaction( @@ -80,10 +75,7 @@ pub(crate) mod vault_registry { >::try_increase_to_be_issued_tokens(vault_id, amount) } - pub fn issue_tokens( - vault_id: &T::AccountId, - amount: PolkaBTC, - ) -> DispatchResult { + pub fn issue_tokens(vault_id: &T::AccountId, amount: PolkaBTC) -> DispatchResult { >::issue_tokens(vault_id, amount) } } diff --git a/crates/refund/src/lib.rs b/crates/refund/src/lib.rs index 1b56f4469a..7a0d4598b3 100644 --- a/crates/refund/src/lib.rs +++ b/crates/refund/src/lib.rs @@ -22,16 +22,13 @@ pub mod types; use bitcoin::types::H256Le; use btc_relay::BtcAddress; -use frame_support::transactional; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchError, ensure, - weights::Weight, + decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchError, ensure, transactional, weights::Weight, }; use frame_system::ensure_signed; use primitive_types::H256; use sp_runtime::traits::CheckedSub; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_std::{convert::TryInto, vec::Vec}; use types::PolkaBTC; pub use types::RefundRequest; @@ -117,8 +114,7 @@ impl Module { /// /// # Arguments /// - /// * `total_amount_btc` - the amount that the user has overpaid. This is the amount that - /// will be refunded. + /// * `total_amount_btc` - the amount that the user has overpaid. This is the amount that will be refunded. /// * `vault_id` - id of the vault the issue was made to /// * `issuer` - id of the user that made the issue request /// * `btc_address` - the btc address that should receive the refund @@ -170,8 +166,8 @@ impl Module { /// /// # Arguments /// - /// * `refund_id` - identifier of a refund request. This ID can be obtained by - /// listening to the RequestRefund event, or by querying the open refunds. + /// * `refund_id` - identifier of a refund request. This ID can be obtained by listening to the RequestRefund event, + /// or by querying the open refunds. /// * `tx_id` - transaction hash /// * `merkle_proof` - raw bytes of the proof /// * `raw_tx` - raw bytes of the transaction @@ -268,14 +264,13 @@ impl Module { .collect::>() } - /// Return the refund request corresponding to the specified issue ID, or return an error. This function is exposed as RPC. + /// Return the refund request corresponding to the specified issue ID, or return an error. This function is exposed + /// as RPC. /// /// # Arguments /// /// * `issue_id` - The ID of an issue request - pub fn get_refund_requests_by_issue_id( - issue_id: H256, - ) -> Option<(H256, RefundRequest>)> { + pub fn get_refund_requests_by_issue_id(issue_id: H256) -> Option<(H256, RefundRequest>)> { >::iter().find(|(_, request)| request.issue_id == issue_id) } diff --git a/crates/refund/src/mock.rs b/crates/refund/src/mock.rs index 6b0b036ff9..5de6200c27 100644 --- a/crates/refund/src/mock.rs +++ b/crates/refund/src/mock.rs @@ -179,9 +179,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); sp_io::TestExternalities::from(storage) } diff --git a/crates/refund/src/tests.rs b/crates/refund/src/tests.rs index 3a1bea153f..1047b6b846 100644 --- a/crates/refund/src/tests.rs +++ b/crates/refund/src/tests.rs @@ -1,6 +1,4 @@ -use crate::ext; -use crate::mock::*; -use crate::RawEvent; +use crate::{ext, mock::*, RawEvent}; use bitcoin::types::H256Le; use btc_relay::BtcAddress; use frame_support::assert_ok; @@ -12,11 +10,9 @@ use sp_core::H160; fn test_refund_succeeds() { run_test(|| { ext::fee::get_refund_fee_from_total::.mock_safe(|_| MockResult::Return(Ok(5))); - ext::vault_registry::try_increase_to_be_issued_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_issued_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::vault_registry::issue_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::btc_relay::validate_transaction:: .mock_safe(|_, _, _, _| MockResult::Return(Ok((BtcAddress::P2SH(H160::zero()), 995)))); diff --git a/crates/refund/src/types.rs b/crates/refund/src/types.rs index 605746e782..1d284b2401 100644 --- a/crates/refund/src/types.rs +++ b/crates/refund/src/types.rs @@ -5,9 +5,8 @@ use primitive_types::H256; #[cfg(feature = "std")] use serde::{Deserialize, Deserializer, Serialize, Serializer}; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; // Due to a known bug in serde we need to specify how u128 is (de)serialized. // See https://github.com/paritytech/substrate/issues/4641 @@ -16,32 +15,17 @@ pub(crate) type PolkaBTC = <::PolkaBTC as Currency< pub struct RefundRequest { pub vault: AccountId, #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] pub amount_polka_btc: PolkaBTC, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] pub fee: PolkaBTC, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] pub amount_btc: PolkaBTC, pub issuer: AccountId, @@ -51,17 +35,12 @@ pub struct RefundRequest { } #[cfg(feature = "std")] -fn serialize_as_string( - t: &T, - serializer: S, -) -> Result { +fn serialize_as_string(t: &T, serializer: S) -> Result { serializer.serialize_str(&t.to_string()) } #[cfg(feature = "std")] -fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>( - deserializer: D, -) -> Result { +fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>(deserializer: D) -> Result { let s = String::deserialize(deserializer)?; s.parse::() .map_err(|_| serde::de::Error::custom("Parse from string failed")) diff --git a/crates/replace/rpc/src/lib.rs b/crates/replace/rpc/src/lib.rs index 6232ba3451..0e84f77b47 100644 --- a/crates/replace/rpc/src/lib.rs +++ b/crates/replace/rpc/src/lib.rs @@ -56,8 +56,8 @@ impl From for i64 { } } -impl - ReplaceApi<::Hash, AccountId, H256, ReplaceRequest> for Replace +impl ReplaceApi<::Hash, AccountId, H256, ReplaceRequest> + for Replace where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, diff --git a/crates/replace/src/benchmarking.rs b/crates/replace/src/benchmarking.rs index 8568a44f3c..95f970e50f 100644 --- a/crates/replace/src/benchmarking.rs +++ b/crates/replace/src/benchmarking.rs @@ -1,26 +1,25 @@ use super::*; -use crate::types::ReplaceRequest; -use crate::Module as Replace; -use bitcoin::formatter::{Formattable, TryFormattable}; -use bitcoin::types::{ - BlockBuilder, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, TransactionOutput, +use crate::{types::ReplaceRequest, Module as Replace}; +use bitcoin::{ + formatter::{Formattable, TryFormattable}, + types::{BlockBuilder, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, TransactionOutput}, }; -use btc_relay::Module as BtcRelay; -use btc_relay::{BtcAddress, BtcPublicKey}; +use btc_relay::{BtcAddress, BtcPublicKey, Module as BtcRelay}; use exchange_rate_oracle::Module as ExchangeRateOracle; use frame_benchmarking::{account, benchmarks}; -use frame_system::Module as System; -use frame_system::RawOrigin; +use frame_system::{Module as System, RawOrigin}; use sp_core::{H160, H256, U256}; use sp_runtime::FixedPointNumber; use sp_std::prelude::*; -use vault_registry::types::{Vault, Wallet}; -use vault_registry::Module as VaultRegistry; +use vault_registry::{ + types::{Vault, Wallet}, + Module as VaultRegistry, +}; fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } @@ -233,14 +232,9 @@ mod tests { #[test] fn test_benchmarks() { - ExtBuilder::build_with( - pallet_balances::GenesisConfig:: { - balances: vec![ - (account("Origin", 0, 0), 1 << 32), - (account("Vault", 0, 0), 1 << 32), - ], - }, - ) + ExtBuilder::build_with(pallet_balances::GenesisConfig:: { + balances: vec![(account("Origin", 0, 0), 1 << 32), (account("Vault", 0, 0), 1 << 32)], + }) .execute_with(|| { assert_ok!(test_benchmark_request_replace::()); assert_ok!(test_benchmark_withdraw_replace::()); diff --git a/crates/replace/src/ext.rs b/crates/replace/src/ext.rs index b17c642935..7283601fd9 100644 --- a/crates/replace/src/ext.rs +++ b/crates/replace/src/ext.rs @@ -8,10 +8,7 @@ pub(crate) mod btc_relay { use frame_support::dispatch::{DispatchError, DispatchResult}; use sp_std::vec::Vec; - pub fn verify_transaction_inclusion( - tx_id: H256Le, - merkle_proof: Vec, - ) -> DispatchResult { + pub fn verify_transaction_inclusion(tx_id: H256Le, merkle_proof: Vec) -> DispatchResult { >::_verify_transaction_inclusion(tx_id, merkle_proof, None) } @@ -45,12 +42,7 @@ pub(crate) mod vault_registry { tokens: PolkaBTC, collateral: DOT, ) -> DispatchResult { - >::replace_tokens( - &old_vault_id, - &new_vault_id, - tokens, - collateral, - ) + >::replace_tokens(&old_vault_id, &new_vault_id, tokens, collateral) } pub fn cancel_replace_tokens( @@ -61,24 +53,17 @@ pub(crate) mod vault_registry { >::cancel_replace_tokens(old_vault_id, new_vault_id, tokens) } - pub fn is_vault_liquidated( - vault_id: &T::AccountId, - ) -> Result { + pub fn is_vault_liquidated(vault_id: &T::AccountId) -> Result { >::is_vault_liquidated(vault_id) } pub fn get_active_vault_from_id( vault_id: &T::AccountId, - ) -> Result< - vault_registry::types::Vault, DOT>, - DispatchError, - > { + ) -> Result, DOT>, DispatchError> { >::get_active_vault_from_id(vault_id) } - pub fn get_backing_collateral( - vault_id: &T::AccountId, - ) -> Result, DispatchError> { + pub fn get_backing_collateral(vault_id: &T::AccountId) -> Result, DispatchError> { >::get_backing_collateral(vault_id) } @@ -161,17 +146,11 @@ pub(crate) mod collateral { use crate::DOT; use frame_support::dispatch::DispatchResult; - pub fn release_collateral( - sender: &T::AccountId, - amount: DOT, - ) -> DispatchResult { + pub fn release_collateral(sender: &T::AccountId, amount: DOT) -> DispatchResult { >::release_collateral(sender, amount) } - pub fn lock_collateral( - sender: T::AccountId, - amount: DOT, - ) -> DispatchResult { + pub fn lock_collateral(sender: T::AccountId, amount: DOT) -> DispatchResult { >::lock_collateral(&sender, amount) } } @@ -195,9 +174,7 @@ pub(crate) mod oracle { use crate::types::{PolkaBTC, DOT}; use frame_support::dispatch::DispatchError; - pub fn btc_to_dots( - amount: PolkaBTC, - ) -> Result, DispatchError> { + pub fn btc_to_dots(amount: PolkaBTC) -> Result, DispatchError> { >::btc_to_dots(amount) } } @@ -207,9 +184,7 @@ pub(crate) mod fee { use crate::types::DOT; use frame_support::dispatch::DispatchError; - pub fn get_replace_griefing_collateral( - amount: DOT, - ) -> Result, DispatchError> { + pub fn get_replace_griefing_collateral(amount: DOT) -> Result, DispatchError> { >::get_replace_griefing_collateral(amount) } diff --git a/crates/replace/src/lib.rs b/crates/replace/src/lib.rs index 95789284f0..7ece7944ae 100644 --- a/crates/replace/src/lib.rs +++ b/crates/replace/src/lib.rs @@ -13,20 +13,18 @@ mod default_weights; #[cfg(test)] extern crate mocktopus; -use frame_support::transactional; -use frame_support::weights::Weight; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, - ensure, + ensure, transactional, + weights::Weight, }; use frame_system::{ensure_root, ensure_signed}; #[cfg(test)] use mocktopus::macros::mockable; use primitive_types::H256; use sp_runtime::ModuleId; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_std::{convert::TryInto, vec::Vec}; use bitcoin::types::H256Le; use btc_relay::BtcAddress; @@ -290,18 +288,17 @@ impl Module { let dust_value = >::get(); ensure!(amount_btc >= dust_value, Error::::AmountBelowDustAmount); - // If the request is not for the entire BTC holdings, check that the remaining DOT collateral of the Vault is higher than MinimumCollateralVault + // If the request is not for the entire BTC holdings, check that the remaining DOT collateral of the Vault is + // higher than MinimumCollateralVault let vault_collateral = ext::vault_registry::get_backing_collateral::(&vault_id)?; if amount_btc != vault.issued_tokens { - let over_threshold = - ext::vault_registry::is_over_minimum_collateral::(vault_collateral); + let over_threshold = ext::vault_registry::is_over_minimum_collateral::(vault_collateral); ensure!(over_threshold, Error::::InsufficientCollateral); } let amount_dot = ext::oracle::btc_to_dots::(amount_btc)?; - let expected_griefing_collateral = - ext::fee::get_replace_griefing_collateral::(amount_dot)?; + let expected_griefing_collateral = ext::fee::get_replace_griefing_collateral::(amount_dot)?; // Check that the griefingCollateral is greater or equal to the expected ensure!( @@ -315,10 +312,7 @@ impl Module { ext::collateral::lock_collateral::(vault_id.clone(), griefing_collateral)?; // increase to-be-replaced tokens. This will fail if the vault does not have enough tokens available - ext::vault_registry::try_increase_to_be_replaced_tokens::( - &vault_id, - amount_btc.clone(), - )?; + ext::vault_registry::try_increase_to_be_replaced_tokens::(&vault_id, amount_btc.clone())?; // Generate a replaceId by hashing a random seed, a nonce, and the address of the Requester. let replace_id = ext::security::get_secure_id::(&vault_id); @@ -348,19 +342,18 @@ impl Module { Ok(()) } - fn _withdraw_replace_request( - vault_id: T::AccountId, - request_id: H256, - ) -> Result<(), DispatchError> { + fn _withdraw_replace_request(vault_id: T::AccountId, request_id: H256) -> Result<(), DispatchError> { // check vault exists // Retrieve the ReplaceRequest as per the replaceId parameter from Vaults in the VaultRegistry let replace = Self::get_open_replace_request(&request_id)?; - // Check that caller of the function is indeed the to-be-replaced Vault as specified in the ReplaceRequest. Return ERR_UNAUTHORIZED error if this check fails. + // Check that caller of the function is indeed the to-be-replaced Vault as specified in the ReplaceRequest. + // Return ERR_UNAUTHORIZED error if this check fails. let _vault = ext::vault_registry::get_active_vault_from_id::(&vault_id)?; ensure!(vault_id == replace.old_vault, Error::::UnauthorizedVault); - // Check that the collateral rate of the vault is not under the AuctionCollateralThreshold as defined in the VaultRegistry. If it is under the AuctionCollateralThreshold return ERR_UNAUTHORIZED + // Check that the collateral rate of the vault is not under the AuctionCollateralThreshold as defined in the + // VaultRegistry. If it is under the AuctionCollateralThreshold return ERR_UNAUTHORIZED ensure!( !ext::vault_registry::is_vault_below_auction_threshold::(vault_id.clone())?, Error::::VaultOverAuctionThreshold @@ -372,16 +365,10 @@ impl Module { } // Release the oldVault’s griefing collateral associated with this ReplaceRequests - ext::collateral::release_collateral::( - &replace.old_vault, - replace.griefing_collateral.clone(), - )?; + ext::collateral::release_collateral::(&replace.old_vault, replace.griefing_collateral.clone())?; // decrease to-be-replaced tokens, so that the vault is free to use its issued tokens again - ext::vault_registry::decrease_to_be_replaced_tokens::( - &replace.old_vault, - replace.amount.clone(), - )?; + ext::vault_registry::decrease_to_be_replaced_tokens::(&replace.old_vault, replace.amount.clone())?; // Remove the ReplaceRequest from ReplaceRequests Self::remove_replace_request(request_id, true); @@ -416,14 +403,8 @@ impl Module { ext::vault_registry::try_lock_additional_collateral::(&new_vault_id, collateral)?; // decrease old-vault's to-be-replaced tokens; turn them into to-be-redeemed tokens - ext::vault_registry::decrease_to_be_replaced_tokens::( - &replace.old_vault, - replace.amount.clone(), - )?; - ext::vault_registry::try_increase_to_be_redeemed_tokens::( - &replace.old_vault, - replace.amount.clone(), - )?; + ext::vault_registry::decrease_to_be_replaced_tokens::(&replace.old_vault, replace.amount.clone())?; + ext::vault_registry::try_increase_to_be_redeemed_tokens::(&replace.old_vault, replace.amount.clone())?; // increase to-be-issued tokens - this will fail if there is insufficient collateral ext::vault_registry::try_increase_to_be_issued_tokens::(&new_vault_id, replace.amount)?; @@ -465,7 +446,8 @@ impl Module { // Retrieve the oldVault as per the oldVault parameter from Vaults in the VaultRegistry let _old_vault = ext::vault_registry::get_active_vault_from_id::(&old_vault_id)?; - // Check that the oldVault is below the AuctionCollateralThreshold by calculating his current oldVault.issuedTokens and the oldVault.collateral + // Check that the oldVault is below the AuctionCollateralThreshold by calculating his current + // oldVault.issuedTokens and the oldVault.collateral ensure!( ext::vault_registry::is_vault_below_auction_threshold::(old_vault_id.clone())?, Error::::VaultOverAuctionThreshold @@ -553,12 +535,12 @@ impl Module { Error::::ReplacePeriodExpired ); - // Call verifyTransactionInclusion in BTC-Relay, providing txid, txBlockHeight, txIndex, and merkleProof as parameters + // Call verifyTransactionInclusion in BTC-Relay, providing txid, txBlockHeight, txIndex, and merkleProof as + // parameters ext::btc_relay::verify_transaction_inclusion::(tx_id, merkle_proof)?; // Call validateTransaction in BTC-Relay - let amount = TryInto::::try_into(replace.amount) - .map_err(|_e| Error::::TryIntoIntError)? as i64; + let amount = TryInto::::try_into(replace.amount).map_err(|_e| Error::::TryIntoIntError)? as i64; let btc_address = if let Some(btc_address) = replace.btc_address { btc_address @@ -587,11 +569,7 @@ impl Module { ext::collateral::release_collateral::(&old_vault_id, replace.griefing_collateral)?; // Emit ExecuteReplace event. - Self::deposit_event(>::ExecuteReplace( - replace_id, - old_vault_id, - new_vault_id, - )); + Self::deposit_event(>::ExecuteReplace(replace_id, old_vault_id, new_vault_id)); // Remove replace request Self::remove_replace_request(replace_id.clone(), false); @@ -618,11 +596,7 @@ impl Module { // decrease old-vault's to-be-redeemed tokens, and // decrease new-vault's to-be-issued tokens - ext::vault_registry::cancel_replace_tokens::( - &replace.old_vault, - &new_vault_id, - replace.amount, - )?; + ext::vault_registry::cancel_replace_tokens::(&replace.old_vault, &new_vault_id, replace.amount)?; // slash old-vault's griefing collateral if !ext::vault_registry::is_vault_liquidated::(&new_vault_id)? { @@ -644,14 +618,8 @@ impl Module { // if the new_vault locked additional collateral especially for this replace, // release it if it does not cause him to be undercollateralized if !ext::vault_registry::is_vault_liquidated::(&new_vault_id)? { - if ext::vault_registry::is_allowed_to_withdraw_collateral::( - &new_vault_id, - replace.collateral, - )? { - ext::vault_registry::force_withdraw_collateral::( - &new_vault_id, - replace.collateral, - )?; + if ext::vault_registry::is_allowed_to_withdraw_collateral::(&new_vault_id, replace.collateral)? { + ext::vault_registry::force_withdraw_collateral::(&new_vault_id, replace.collateral)?; } } @@ -675,10 +643,7 @@ impl Module { /// * `account_id` - user account id pub fn get_replace_requests_for_old_vault( account_id: T::AccountId, - ) -> Vec<( - H256, - ReplaceRequest, DOT>, - )> { + ) -> Vec<(H256, ReplaceRequest, DOT>)> { >::iter() .filter(|(_, request)| request.old_vault == account_id) .collect::>() @@ -691,10 +656,7 @@ impl Module { /// * `account_id` - user account id pub fn get_replace_requests_for_new_vault( account_id: T::AccountId, - ) -> Vec<( - H256, - ReplaceRequest, DOT>, - )> { + ) -> Vec<(H256, ReplaceRequest, DOT>)> { >::iter() .filter(|(_, request)| { if let Some(vault_id) = &request.new_vault { @@ -709,8 +671,7 @@ impl Module { /// Get a replace request by id. Completed or cancelled requests are not returned. pub fn get_open_replace_request( id: &H256, - ) -> Result, DOT>, DispatchError> - { + ) -> Result, DOT>, DispatchError> { let request = >::get(id).ok_or(Error::::ReplaceIdNotFound)?; // NOTE: temporary workaround until we delete ensure!(!request.completed, Error::::ReplaceCompleted); @@ -721,17 +682,13 @@ impl Module { /// Get a open or completed replace request by id. Cancelled requests are not returned. pub fn get_open_or_completed_replace_request( id: &H256, - ) -> Result, DOT>, DispatchError> - { + ) -> Result, DOT>, DispatchError> { let request = >::get(id).ok_or(Error::::ReplaceIdNotFound)?; ensure!(!request.cancelled, Error::::ReplaceCancelled); Ok(request) } - fn insert_replace_request( - key: H256, - value: ReplaceRequest, DOT>, - ) { + fn insert_replace_request(key: H256, value: ReplaceRequest, DOT>) { >::insert(key, value) } diff --git a/crates/replace/src/mock.rs b/crates/replace/src/mock.rs index e71a09b875..e5d568e201 100644 --- a/crates/replace/src/mock.rs +++ b/crates/replace/src/mock.rs @@ -189,21 +189,19 @@ impl ExtBuilder { pub fn build_with( dot_balances: pallet_balances::GenesisConfig, ) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); dot_balances.assimilate_storage(&mut storage).unwrap(); fee::GenesisConfig:: { issue_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% issue_griefing_collateral: FixedU128::checked_from_rational(5, 100000).unwrap(), // 0.005% - refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% - replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% fee_pool_account_id: 0, maintainer_account_id: 1, epoch_period: 5, @@ -228,15 +226,9 @@ impl ExtBuilder { } pub fn build() -> sp_io::TestExternalities { - ExtBuilder::build_with( - pallet_balances::GenesisConfig:: { - balances: vec![ - (ALICE, ALICE_BALANCE), - (BOB, BOB_BALANCE), - (CAROL, CAROL_BALANCE), - ], - }, - ) + ExtBuilder::build_with(pallet_balances::GenesisConfig:: { + balances: vec![(ALICE, ALICE_BALANCE), (BOB, BOB_BALANCE), (CAROL, CAROL_BALANCE)], + }) } } diff --git a/crates/replace/src/tests.rs b/crates/replace/src/tests.rs index 1bdbc14823..329d547125 100644 --- a/crates/replace/src/tests.rs +++ b/crates/replace/src/tests.rs @@ -1,6 +1,4 @@ -use crate::ext; -use crate::mock::*; -use crate::{has_request_expired, PolkaBTC, ReplaceRequest, DOT}; +use crate::{ext, has_request_expired, mock::*, PolkaBTC, ReplaceRequest, DOT}; use bitcoin::types::H256Le; use btc_relay::{BtcAddress, BtcPublicKey}; use frame_support::{ @@ -23,10 +21,7 @@ macro_rules! assert_emitted { ($event:expr, $times:expr) => { let test_event = TestEvent::replace($event); assert_eq!( - System::events() - .iter() - .filter(|a| a.event == test_event) - .count(), + System::events().iter().filter(|a| a.event == test_event).count(), $times ); }; @@ -49,8 +44,8 @@ fn test_request() -> ReplaceRequest { fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } @@ -68,11 +63,7 @@ fn test_vault() -> Vault { } } -fn request_replace( - vault: AccountId, - amount: Balance, - griefing_collateral: DOT, -) -> DispatchResult { +fn request_replace(vault: AccountId, amount: Balance, griefing_collateral: DOT) -> DispatchResult { Replace::_request_replace(vault, amount, griefing_collateral) } @@ -80,11 +71,7 @@ fn withdraw_replace(vault_id: AccountId, replace_id: H256) -> Result<(), Dispatc Replace::_withdraw_replace_request(vault_id, replace_id) } -fn accept_replace( - vault_id: AccountId, - replace_id: H256, - collateral: DOT, -) -> Result<(), DispatchError> { +fn accept_replace(vault_id: AccountId, replace_id: H256, collateral: DOT) -> Result<(), DispatchError> { Replace::_accept_replace(vault_id, replace_id, collateral, BtcAddress::default()) } @@ -155,20 +142,14 @@ fn test_auction_replace_below_dust_fails() { })) }); - assert_noop!( - auction_replace(BOB, ALICE, 0, 0), - TestError::AmountBelowDustAmount - ); + assert_noop!(auction_replace(BOB, ALICE, 0, 0), TestError::AmountBelowDustAmount); }) } #[test] fn test_request_replace_vault_not_found_fails() { run_test(|| { - assert_noop!( - request_replace(10_000, 5, 0), - VaultRegistryError::VaultNotFound - ); + assert_noop!(request_replace(10_000, 5, 0), VaultRegistryError::VaultNotFound); }) } @@ -190,10 +171,7 @@ fn test_request_replace_vault_banned_fails() { status: VaultStatus::Active, })) }); - assert_noop!( - Replace::_request_replace(BOB, 5, 0), - VaultRegistryError::VaultBanned - ); + assert_noop!(Replace::_request_replace(BOB, 5, 0), VaultRegistryError::VaultBanned); }) } #[test] @@ -219,8 +197,7 @@ fn test_request_replace_amount_below_dust_value_fails() { status: VaultStatus::Active, })) }); - ext::vault_registry::is_over_minimum_collateral:: - .mock_safe(|_| MockResult::Return(true)); + ext::vault_registry::is_over_minimum_collateral::.mock_safe(|_| MockResult::Return(true)); ext::oracle::btc_to_dots::.mock_safe(|_| MockResult::Return(Ok(0))); ext::fee::get_replace_griefing_collateral:: .mock_safe(move |_| MockResult::Return(Ok(desired_griefing_collateral))); @@ -255,8 +232,7 @@ fn test_request_replace_insufficient_griefing_collateral_fails() { status: VaultStatus::Active, })) }); - ext::vault_registry::is_over_minimum_collateral:: - .mock_safe(|_| MockResult::Return(true)); + ext::vault_registry::is_over_minimum_collateral::.mock_safe(|_| MockResult::Return(true)); ext::oracle::btc_to_dots::.mock_safe(|_| MockResult::Return(Ok(0))); ext::fee::get_replace_griefing_collateral:: .mock_safe(move |_| MockResult::Return(Ok(desired_griefing_collateral))); @@ -272,8 +248,7 @@ fn test_request_replace_insufficient_griefing_collateral_fails() { #[test] fn test_withdraw_replace_request_invalid_replace_id_fails() { run_test(|| { - Replace::get_open_replace_request - .mock_safe(|_| MockResult::Return(Err(TestError::ReplaceIdNotFound.into()))); + Replace::get_open_replace_request.mock_safe(|_| MockResult::Return(Err(TestError::ReplaceIdNotFound.into()))); assert_noop!( Replace::_withdraw_replace_request(ALICE, H256([0u8; 32])), TestError::ReplaceIdNotFound @@ -298,12 +273,8 @@ fn test_withdraw_replace_request_invalid_vault_id_fails() { fn test_withdraw_replace_req_vault_id_mismatch_fails() { run_test(|| { Replace::get_open_replace_request.mock_safe(|_| MockResult::Return(Ok(test_request()))); - ext::vault_registry::get_active_vault_from_id:: - .mock_safe(|_id| MockResult::Return(Ok(test_vault()))); - assert_noop!( - withdraw_replace(BOB, H256([0u8; 32])), - TestError::UnauthorizedVault - ); + ext::vault_registry::get_active_vault_from_id::.mock_safe(|_id| MockResult::Return(Ok(test_vault()))); + assert_noop!(withdraw_replace(BOB, H256([0u8; 32])), TestError::UnauthorizedVault); }) } @@ -318,10 +289,7 @@ fn test_withdraw_replace_req_under_secure_threshold_fails() { v })) }); - assert_noop!( - withdraw_replace(BOB, H256([0u8; 32])), - TestError::UnauthorizedVault - ); + assert_noop!(withdraw_replace(BOB, H256([0u8; 32])), TestError::UnauthorizedVault); }) } @@ -341,8 +309,7 @@ fn test_withdraw_replace_req_has_new_owner_fails() { v })) }); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(false))); assert_noop!( withdraw_replace(ALICE, H256([0u8; 32])), TestError::CancelAcceptedRequest @@ -366,8 +333,7 @@ fn test_accept_replace_bad_replace_id_fails() { v })) }); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(true))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(true))); let collateral = 100_000; assert_noop!( accept_replace(ALICE, H256([0u8; 32]), collateral), @@ -387,8 +353,7 @@ fn test_accept_replace_bad_vault_id_fails() { }); ext::vault_registry::get_active_vault_from_id:: .mock_safe(|_id| MockResult::Return(Err(VaultRegistryError::VaultNotFound.into()))); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(false))); let collateral = 100_000; assert_noop!( accept_replace(ALICE, H256([0u8; 32]), collateral), @@ -413,10 +378,8 @@ fn test_accept_replace_vault_banned_fails() { vault.banned_until = Some(100); MockResult::Return(Ok(vault)) }); - ext::vault_registry::insert_vault_deposit_address:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::insert_vault_deposit_address::.mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(false))); let collateral = 100_000; assert_noop!( accept_replace(ALICE, H256([0u8; 32]), collateral), @@ -440,17 +403,12 @@ fn test_accept_replace_insufficient_collateral_fails() { vault.banned_until = None; MockResult::Return(Ok(vault)) }); - ext::vault_registry::try_lock_additional_collateral:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::insert_vault_deposit_address:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::decrease_to_be_replaced_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_increase_to_be_redeemed_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_increase_to_be_issued_tokens::.mock_safe(|_, _| { - MockResult::Return(Err(VaultRegistryError::ExceedingVaultLimit.into())) - }); + ext::vault_registry::try_lock_additional_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::insert_vault_deposit_address::.mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::decrease_to_be_replaced_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_issued_tokens:: + .mock_safe(|_, _| MockResult::Return(Err(VaultRegistryError::ExceedingVaultLimit.into()))); let collateral = 100_000; assert_err!( @@ -508,10 +466,8 @@ fn test_auction_replace_insufficient_collateral_fails() { Ok(test_vault()) }) }); - ext::vault_registry::insert_vault_deposit_address:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::insert_vault_deposit_address::.mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(false))); let collateral = 100_000; let btc_amount = 100; assert_noop!( @@ -524,8 +480,7 @@ fn test_auction_replace_insufficient_collateral_fails() { #[test] fn test_execute_replace_bad_replace_id_fails() { run_test(|| { - Replace::get_open_replace_request - .mock_safe(|_| MockResult::Return(Err(TestError::ReplaceIdNotFound.into()))); + Replace::get_open_replace_request.mock_safe(|_| MockResult::Return(Err(TestError::ReplaceIdNotFound.into()))); let replace_id = H256::zero(); let tx_id = H256Le::zero(); @@ -565,16 +520,12 @@ fn test_execute_replace_replace_period_expired_fails() { #[test] fn test_cancel_replace_invalid_replace_id_fails() { run_test(|| { - Replace::get_open_replace_request - .mock_safe(|_| MockResult::Return(Err(TestError::ReplaceIdNotFound.into()))); + Replace::get_open_replace_request.mock_safe(|_| MockResult::Return(Err(TestError::ReplaceIdNotFound.into()))); let new_vault_id = ALICE; let replace_id = H256::zero(); - assert_err!( - cancel_replace(new_vault_id, replace_id), - TestError::ReplaceIdNotFound - ); + assert_err!(cancel_replace(new_vault_id, replace_id), TestError::ReplaceIdNotFound); }) } @@ -623,22 +574,18 @@ fn test_request_replace_with_amount_exceed_vault_issued_tokens_succeeds() { ext::vault_registry::ensure_not_banned::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::get_active_vault_from_id:: - .mock_safe(move |_| MockResult::Return(Ok(vault.clone()))); + ext::vault_registry::get_active_vault_from_id::.mock_safe(move |_| MockResult::Return(Ok(vault.clone()))); - ext::vault_registry::is_over_minimum_collateral:: - .mock_safe(|_| MockResult::Return(true)); + ext::vault_registry::is_over_minimum_collateral::.mock_safe(|_| MockResult::Return(true)); ext::collateral::lock_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_increase_to_be_replaced_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_replaced_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::security::get_secure_id::.mock_safe(|_| MockResult::Return(H256::zero())); ext::vault_registry::get_backing_collateral:: .mock_safe(move |_| MockResult::Return(Ok(griefing_collateral))); assert_ok!(request_replace(vault_id, amount, griefing_collateral)); - let event = - Event::RequestReplace(replace_id, vault_id, replace_amount, griefing_collateral); + let event = Event::RequestReplace(replace_id, vault_id, replace_amount, griefing_collateral); assert_emitted!(event); }) } @@ -656,23 +603,19 @@ fn test_request_replace_with_amount_less_than_vault_issued_tokens_succeeds() { ext::vault_registry::ensure_not_banned::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::get_active_vault_from_id:: - .mock_safe(move |_| MockResult::Return(Ok(vault.clone()))); + ext::vault_registry::get_active_vault_from_id::.mock_safe(move |_| MockResult::Return(Ok(vault.clone()))); - ext::vault_registry::is_over_minimum_collateral:: - .mock_safe(|_| MockResult::Return(true)); + ext::vault_registry::is_over_minimum_collateral::.mock_safe(|_| MockResult::Return(true)); ext::collateral::lock_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_increase_to_be_replaced_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_replaced_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::security::get_secure_id::.mock_safe(|_| MockResult::Return(H256::zero())); ext::vault_registry::get_backing_collateral:: .mock_safe(move |_| MockResult::Return(Ok(griefing_collateral))); assert_ok!(request_replace(vault_id, amount, griefing_collateral)); - let event = - Event::RequestReplace(replace_id, vault_id, replace_amount, griefing_collateral); + let event = Event::RequestReplace(replace_id, vault_id, replace_amount, griefing_collateral); assert_emitted!(event); }) } @@ -688,13 +631,10 @@ fn test_withdraw_replace_succeeds() { MockResult::Return(Ok(replace)) }); - ext::vault_registry::get_active_vault_from_id:: - .mock_safe(|_| MockResult::Return(Ok(test_vault()))); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::get_active_vault_from_id::.mock_safe(|_| MockResult::Return(Ok(test_vault()))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(false))); ext::collateral::release_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::decrease_to_be_replaced_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::decrease_to_be_replaced_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); Replace::remove_replace_request.mock_safe(|_, _| MockResult::Return(())); @@ -723,20 +663,15 @@ fn test_accept_replace_succeeds() { ext::vault_registry::ensure_not_banned::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_lock_additional_collateral:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_lock_additional_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::decrease_to_be_replaced_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::decrease_to_be_replaced_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_increase_to_be_redeemed_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_increase_to_be_issued_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_issued_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::insert_vault_deposit_address:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::insert_vault_deposit_address::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::collateral::lock_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); @@ -768,25 +703,20 @@ fn test_auction_replace_succeeds() { // NOTE: we don't use the old_vault in the code - should be changed to just // check if it exists in storage - ext::vault_registry::get_active_vault_from_id:: - .mock_safe(|_| MockResult::Return(Ok(test_vault()))); + ext::vault_registry::get_active_vault_from_id::.mock_safe(|_| MockResult::Return(Ok(test_vault()))); - ext::vault_registry::insert_vault_deposit_address:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::insert_vault_deposit_address::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(true))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(true))); ext::vault_registry::slash_collateral::.mock_safe(|_, _, fee| { assert_eq!(fee, 50); // 5% of dot equivalent of the btc_amount MockResult::Return(Ok(())) }); - ext::vault_registry::try_lock_additional_collateral:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_lock_additional_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::try_increase_to_be_redeemed_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::security::get_secure_id::.mock_safe(|_| MockResult::Return(H256::zero())); @@ -795,8 +725,7 @@ fn test_auction_replace_succeeds() { ext::fee::get_replace_griefing_collateral:: .mock_safe(move |_| MockResult::Return(Ok(griefing_collateral))); - ext::vault_registry::try_increase_to_be_issued_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::try_increase_to_be_issued_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); Replace::current_height.mock_safe(move || MockResult::Return(height.clone())); @@ -840,28 +769,21 @@ fn test_execute_replace_succeeds() { Replace::current_height.mock_safe(|| MockResult::Return(10)); Replace::replace_period.mock_safe(|| MockResult::Return(20)); - ext::vault_registry::get_active_vault_from_id:: - .mock_safe(|_| MockResult::Return(Ok(test_vault()))); + ext::vault_registry::get_active_vault_from_id::.mock_safe(|_| MockResult::Return(Ok(test_vault()))); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::btc_relay::validate_transaction:: .mock_safe(|_, _, _, _| MockResult::Return(Ok((BtcAddress::P2SH(H160::zero()), 0)))); - ext::vault_registry::replace_tokens:: - .mock_safe(|_, _, _, _| MockResult::Return(Ok(()))); + ext::vault_registry::replace_tokens::.mock_safe(|_, _, _, _| MockResult::Return(Ok(()))); ext::collateral::release_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_vault_liquidated:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::is_vault_liquidated::.mock_safe(|_| MockResult::Return(Ok(false))); Replace::remove_replace_request.mock_safe(|_, _| MockResult::Return(())); - assert_eq!( - execute_replace(replace_id, tx_id, merkle_proof, raw_tx), - Ok(()) - ); + assert_eq!(execute_replace(replace_id, tx_id, merkle_proof, raw_tx), Ok(())); let event = Event::ExecuteReplace(replace_id, old_vault_id, new_vault_id); assert_emitted!(event); @@ -886,20 +808,15 @@ fn test_cancel_replace_succeeds() { }); Replace::current_height.mock_safe(|| MockResult::Return(15)); Replace::replace_period.mock_safe(|| MockResult::Return(2)); - ext::vault_registry::cancel_replace_tokens:: - .mock_safe(|_, _, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_vault_liquidated:: - .mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::cancel_replace_tokens::.mock_safe(|_, _, _| MockResult::Return(Ok(()))); + ext::vault_registry::is_vault_liquidated::.mock_safe(|_| MockResult::Return(Ok(false))); Replace::remove_replace_request.mock_safe(|_, _| MockResult::Return(())); - ext::vault_registry::slash_collateral:: - .mock_safe(|_, _, _| MockResult::Return(Ok(()))); - ext::vault_registry::is_allowed_to_withdraw_collateral:: - .mock_safe(|_, _| MockResult::Return(Ok(false))); + ext::vault_registry::slash_collateral::.mock_safe(|_, _, _| MockResult::Return(Ok(()))); + ext::vault_registry::is_allowed_to_withdraw_collateral::.mock_safe(|_, _| MockResult::Return(Ok(false))); assert_eq!(cancel_replace(new_vault_id, replace_id), Ok(())); - let event = - Event::CancelReplace(replace_id, new_vault_id, old_vault_id, griefing_collateral); + let event = Event::CancelReplace(replace_id, new_vault_id, old_vault_id, griefing_collateral); assert_emitted!(event); }) } @@ -924,10 +841,7 @@ fn test_cancel_replace_as_third_party_fails() { Replace::replace_period.mock_safe(|| MockResult::Return(2)); Replace::remove_replace_request.mock_safe(|_, _| MockResult::Return(())); - assert_noop!( - cancel_replace(canceller, replace_id), - TestError::UnauthorizedVault - ); + assert_noop!(cancel_replace(canceller, replace_id), TestError::UnauthorizedVault); }) } @@ -937,10 +851,7 @@ fn test_request_replace_parachain_not_running_fails() { run_test(|| { ext::security::ensure_parachain_status_running:: .mock_safe(|| MockResult::Return(Err(SecurityError::ParachainNotRunning.into()))); - assert_noop!( - request_replace(10_000, 1, 0), - SecurityError::ParachainNotRunning - ); + assert_noop!(request_replace(10_000, 1, 0), SecurityError::ParachainNotRunning); }) } @@ -949,10 +860,7 @@ fn test_accept_replace_parachain_not_running_fails() { run_test(|| { ext::security::ensure_parachain_status_running:: .mock_safe(|| MockResult::Return(Err(SecurityError::ParachainNotRunning.into()))); - assert_noop!( - accept_replace(BOB, H256::zero(), 1), - SecurityError::ParachainNotRunning - ); + assert_noop!(accept_replace(BOB, H256::zero(), 1), SecurityError::ParachainNotRunning); }) } @@ -961,10 +869,7 @@ fn test_auction_replace_parachain_not_running_fails() { run_test(|| { ext::security::ensure_parachain_status_running:: .mock_safe(|| MockResult::Return(Err(SecurityError::ParachainNotRunning.into()))); - assert_noop!( - auction_replace(ALICE, BOB, 1, 1), - SecurityError::ParachainNotRunning - ); + assert_noop!(auction_replace(ALICE, BOB, 1, 1), SecurityError::ParachainNotRunning); }) } @@ -985,10 +890,7 @@ fn test_cancel_replace_parachain_not_running_fails() { run_test(|| { ext::security::ensure_parachain_status_running:: .mock_safe(|| MockResult::Return(Err(SecurityError::ParachainNotRunning.into()))); - assert_noop!( - cancel_replace(ALICE, H256::zero()), - SecurityError::ParachainNotRunning - ); + assert_noop!(cancel_replace(ALICE, H256::zero()), SecurityError::ParachainNotRunning); }) } @@ -1004,15 +906,11 @@ fn test_withdraw_replace_parachain_not_running_succeeds() { MockResult::Return(Ok(replace)) }); - ext::vault_registry::get_active_vault_from_id:: - .mock_safe(|_| MockResult::Return(Ok(test_vault()))); - ext::vault_registry::is_vault_below_auction_threshold:: - .mock_safe(|_| MockResult::Return(Ok(false))); - ext::vault_registry::try_increase_to_be_redeemed_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::get_active_vault_from_id::.mock_safe(|_| MockResult::Return(Ok(test_vault()))); + ext::vault_registry::is_vault_below_auction_threshold::.mock_safe(|_| MockResult::Return(Ok(false))); + ext::vault_registry::try_increase_to_be_redeemed_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::collateral::release_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - ext::vault_registry::decrease_to_be_replaced_tokens:: - .mock_safe(|_, _| MockResult::Return(Ok(()))); + ext::vault_registry::decrease_to_be_replaced_tokens::.mock_safe(|_, _| MockResult::Return(Ok(()))); ext::security::ensure_parachain_status_running:: .mock_safe(|| MockResult::Return(Err(SecurityError::ParachainNotRunning.into()))); diff --git a/crates/replace/src/types.rs b/crates/replace/src/types.rs index 3fd946b7ba..3f005e5318 100644 --- a/crates/replace/src/types.rs +++ b/crates/replace/src/types.rs @@ -14,11 +14,9 @@ pub enum Version { V1, } -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; // Due to a known bug in serde we need to specify how u128 is (de)serialized. // See https://github.com/paritytech/substrate/issues/4641 @@ -27,15 +25,9 @@ pub(crate) type PolkaBTC = <::PolkaBTC as Currency< pub struct ReplaceRequest { pub old_vault: AccountId, pub open_time: BlockNumber, - #[cfg_attr( - feature = "std", - serde(bound(deserialize = "PolkaBTC: std::str::FromStr")) - )] + #[cfg_attr(feature = "std", serde(bound(deserialize = "PolkaBTC: std::str::FromStr")))] #[cfg_attr(feature = "std", serde(deserialize_with = "deserialize_from_string"))] - #[cfg_attr( - feature = "std", - serde(bound(serialize = "PolkaBTC: std::fmt::Display")) - )] + #[cfg_attr(feature = "std", serde(bound(serialize = "PolkaBTC: std::fmt::Display")))] #[cfg_attr(feature = "std", serde(serialize_with = "serialize_as_string"))] pub amount: PolkaBTC, #[cfg_attr(feature = "std", serde(bound(deserialize = "DOT: std::str::FromStr")))] @@ -60,17 +52,12 @@ pub struct ReplaceRequest { // be only a temporary workaround) #[cfg(feature = "std")] -fn serialize_as_string( - t: &T, - serializer: S, -) -> Result { +fn serialize_as_string(t: &T, serializer: S) -> Result { serializer.serialize_str(&t.to_string()) } #[cfg(feature = "std")] -fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>( - deserializer: D, -) -> Result { +fn deserialize_from_string<'de, D: Deserializer<'de>, T: std::str::FromStr>(deserializer: D) -> Result { let s = String::deserialize(deserializer)?; s.parse::() .map_err(|_| serde::de::Error::custom("Parse from string failed")) diff --git a/crates/security/src/lib.rs b/crates/security/src/lib.rs index 7b1bb087cf..23740844f8 100644 --- a/crates/security/src/lib.rs +++ b/crates/security/src/lib.rs @@ -23,15 +23,12 @@ use mocktopus::macros::mockable; pub use crate::types::{ErrorCode, StatusCode}; use codec::Encode; -use frame_support::transactional; -use frame_support::{decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult}; +use frame_support::{decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, transactional}; use frame_system::ensure_root; use primitive_types::H256; use sha2::{Digest, Sha256}; use sp_core::U256; -use sp_std::collections::btree_set::BTreeSet; -use sp_std::iter::FromIterator; -use sp_std::prelude::*; +use sp_std::{collections::btree_set::BTreeSet, iter::FromIterator, prelude::*}; /// ## Configuration /// The pallet's configuration trait. @@ -156,9 +153,7 @@ impl Module { /// /// Returns the first unexpected error that is encountered, /// or Ok(()) if only expected errors / no errors at all were found - pub fn ensure_parachain_is_running_or_only_has_errors( - error_codes: Vec, - ) -> DispatchResult { + pub fn ensure_parachain_is_running_or_only_has_errors(error_codes: Vec) -> DispatchResult { if ::get() == StatusCode::Running { Ok(()) } else if ::get() == StatusCode::Error { @@ -177,26 +172,22 @@ impl Module { /// Checks if the Parachain has a NoDataBTCRelay Error state pub fn is_parachain_error_no_data_btcrelay() -> bool { - ::get() == StatusCode::Error - && ::get().contains(&ErrorCode::NoDataBTCRelay) + ::get() == StatusCode::Error && ::get().contains(&ErrorCode::NoDataBTCRelay) } /// Checks if the Parachain has a InvalidBTCRelay Error state pub fn is_parachain_error_invalid_btcrelay() -> bool { - ::get() == StatusCode::Error - && ::get().contains(&ErrorCode::InvalidBTCRelay) + ::get() == StatusCode::Error && ::get().contains(&ErrorCode::InvalidBTCRelay) } /// Checks if the Parachain has a OracleOffline Error state pub fn is_parachain_error_oracle_offline() -> bool { - ::get() == StatusCode::Error - && ::get().contains(&ErrorCode::OracleOffline) + ::get() == StatusCode::Error && ::get().contains(&ErrorCode::OracleOffline) } /// Checks if the Parachain has a Liquidation Error state pub fn is_parachain_error_liquidation() -> bool { - ::get() == StatusCode::Error - && ::get().contains(&ErrorCode::Liquidation) + ::get() == StatusCode::Error && ::get().contains(&ErrorCode::Liquidation) } /// Gets the current `StatusCode`. @@ -249,10 +240,7 @@ impl Module { Self::set_status(StatusCode::Running); } - Self::deposit_event(Event::RecoverFromErrors( - Self::get_parachain_status(), - error_codes, - )); + Self::deposit_event(Event::RecoverFromErrors(Self::get_parachain_status(), error_codes)); } /// Recovers the BTC Parachain state from an `ORACLE_OFFLINE` error diff --git a/crates/security/src/mock.rs b/crates/security/src/mock.rs index b48cd2c523..ab7719cb93 100644 --- a/crates/security/src/mock.rs +++ b/crates/security/src/mock.rs @@ -68,9 +68,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); storage.into() } diff --git a/crates/security/src/tests.rs b/crates/security/src/tests.rs index 29b8bfe0a6..10a302d80f 100644 --- a/crates/security/src/tests.rs +++ b/crates/security/src/tests.rs @@ -1,6 +1,4 @@ -use crate::mock::*; -use crate::ErrorCode; -use crate::StatusCode; +use crate::{mock::*, ErrorCode, StatusCode}; use frame_support::{assert_noop, assert_ok}; use sp_core::H256; @@ -14,10 +12,7 @@ macro_rules! assert_emitted { ($event:expr, $times:expr) => { let test_event = TestEvent::security($event); assert_eq!( - System::events() - .iter() - .filter(|a| a.event == test_event) - .count(), + System::events().iter().filter(|a| a.event == test_event).count(), $times ); }; @@ -108,31 +103,28 @@ fn test_ensure_parachain_does_not_have_errors() { fn test_ensure_parachain_is_running_or_only_has_errors() { run_test(|| { Security::set_status(StatusCode::Running); - assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors( - vec![] - )); + assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors(vec![])); Security::set_status(StatusCode::Error); - assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors( - vec![ErrorCode::InvalidBTCRelay] - )); + assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors(vec![ + ErrorCode::InvalidBTCRelay + ])); Security::insert_error(ErrorCode::InvalidBTCRelay); - assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors( - vec![ErrorCode::InvalidBTCRelay] - )); + assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors(vec![ + ErrorCode::InvalidBTCRelay + ])); Security::insert_error(ErrorCode::NoDataBTCRelay); assert_noop!( - Security::ensure_parachain_is_running_or_only_has_errors(vec![ - ErrorCode::InvalidBTCRelay - ]), + Security::ensure_parachain_is_running_or_only_has_errors(vec![ErrorCode::InvalidBTCRelay]), TestError::NoDataBTCRelay ); - assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors( - vec![ErrorCode::InvalidBTCRelay, ErrorCode::NoDataBTCRelay] - )); + assert_ok!(Security::ensure_parachain_is_running_or_only_has_errors(vec![ + ErrorCode::InvalidBTCRelay, + ErrorCode::NoDataBTCRelay + ])); }) } @@ -190,10 +182,7 @@ where #[test] fn test_recover_from_oracle_offline_succeeds() { run_test(|| { - test_recover_from_( - Security::recover_from_oracle_offline, - vec![ErrorCode::OracleOffline], - ); + test_recover_from_(Security::recover_from_oracle_offline, vec![ErrorCode::OracleOffline]); }) } @@ -223,8 +212,8 @@ fn testget_secure_id() { assert_eq!( Security::get_secure_id(&1), H256::from_slice(&[ - 71, 121, 67, 63, 246, 65, 71, 242, 66, 184, 148, 234, 23, 56, 62, 52, 108, 82, 213, - 33, 160, 200, 214, 1, 13, 46, 37, 138, 95, 245, 117, 109 + 71, 121, 67, 63, 246, 65, 71, 242, 66, 184, 148, 234, 23, 56, 62, 52, 108, 82, 213, 33, 160, 200, 214, + 1, 13, 46, 37, 138, 95, 245, 117, 109 ]) ); }) diff --git a/crates/security/src/types.rs b/crates/security/src/types.rs index c677270cb9..cdf6648878 100644 --- a/crates/security/src/types.rs +++ b/crates/security/src/types.rs @@ -1,6 +1,5 @@ use codec::{Decode, Encode}; -use sp_std::cmp::Ord; -use sp_std::fmt::Debug; +use sp_std::{cmp::Ord, fmt::Debug}; /// Enum indicating the status of the BTC Parachain. #[derive(Encode, Decode, Clone, PartialEq, Eq, Debug)] diff --git a/crates/sla/rpc/src/lib.rs b/crates/sla/rpc/src/lib.rs index dd290a08bc..72942d4d28 100644 --- a/crates/sla/rpc/src/lib.rs +++ b/crates/sla/rpc/src/lib.rs @@ -8,8 +8,11 @@ use module_exchange_rate_oracle_rpc_runtime_api::BalanceWrapper; pub use module_sla_rpc_runtime_api::SlaApi as SlaRuntimeApi; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; -use sp_runtime::{generic::BlockId, traits::Block as BlockT, DispatchError}; +use sp_runtime::{ + generic::BlockId, + traits::{Block as BlockT, MaybeDisplay, MaybeFromStr}, + DispatchError, +}; use std::sync::Arc; #[rpc] diff --git a/crates/sla/src/ext.rs b/crates/sla/src/ext.rs index 47a56d1754..5dcca8e35c 100644 --- a/crates/sla/src/ext.rs +++ b/crates/sla/src/ext.rs @@ -17,15 +17,12 @@ pub(crate) mod vault_registry { pub fn get_vault_from_id( vault_id: &T::AccountId, - ) -> Result< - vault_registry::types::Vault, DOT>, - DispatchError, - > { + ) -> Result, DOT>, DispatchError> { >::get_vault_from_id(vault_id) } - pub fn get_premium_redeem_threshold( - ) -> ::UnsignedFixedPoint { + pub fn get_premium_redeem_threshold() -> ::UnsignedFixedPoint + { >::get_premium_redeem_threshold() } @@ -46,9 +43,7 @@ pub(crate) mod vault_registry { >::get_total_backing_collateral(include_liquidation_vault) } - pub fn get_backing_collateral( - vault_id: &T::AccountId, - ) -> Result, DispatchError> { + pub fn get_backing_collateral(vault_id: &T::AccountId) -> Result, DispatchError> { >::get_backing_collateral(vault_id) } } diff --git a/crates/sla/src/lib.rs b/crates/sla/src/lib.rs index 2a25b11b9d..75567a78da 100644 --- a/crates/sla/src/lib.rs +++ b/crates/sla/src/lib.rs @@ -22,27 +22,21 @@ pub mod types; use crate::types::{Inner, RelayerEvent, VaultEvent}; use codec::{Decode, Encode, EncodeLike}; -use frame_support::traits::Currency; -use frame_support::transactional; -use frame_support::{decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchError}; +use frame_support::{ + decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchError, traits::Currency, transactional, +}; use frame_system::ensure_root; -use sp_arithmetic::traits::*; -use sp_arithmetic::FixedPointNumber; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_arithmetic::{traits::*, FixedPointNumber}; +use sp_std::{convert::TryInto, vec::Vec}; -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; pub(crate) type SignedFixedPoint = ::SignedFixedPoint; /// The pallet's configuration trait. -pub trait Config: - frame_system::Config + collateral::Config + treasury::Config + vault_registry::Config -{ +pub trait Config: frame_system::Config + collateral::Config + treasury::Config + vault_registry::Config { /// The overarching event type. type Event: From> + Into<::Event>; @@ -149,9 +143,7 @@ impl Module { let score = Self::relayer_sla(&relayer_id) .checked_mul(&stake_fixed_point) .ok_or(Error::::ArithmeticOverflow)?; - total_score = total_score - .checked_add(&score) - .ok_or(Error::::ArithmeticOverflow)?; + total_score = total_score.checked_add(&score).ok_or(Error::::ArithmeticOverflow)?; } >::set(total_score); Ok(()) @@ -183,11 +175,7 @@ impl Module { let bounded_new_sla = Self::_limit(T::SignedFixedPoint::zero(), new_sla, max_sla); >::insert(vault_id, bounded_new_sla); - Self::deposit_event(>::UpdateVaultSLA( - vault_id.clone(), - bounded_new_sla, - delta_sla, - )); + Self::deposit_event(>::UpdateVaultSLA(vault_id.clone(), bounded_new_sla, delta_sla)); Ok(()) } @@ -198,10 +186,7 @@ impl Module { /// /// * `relayer_id` - account id of the relayer /// * `event` - the event that has happened - pub fn event_update_relayer_sla( - relayer_id: &T::AccountId, - event: RelayerEvent, - ) -> Result<(), DispatchError> { + pub fn event_update_relayer_sla(relayer_id: &T::AccountId, event: RelayerEvent) -> Result<(), DispatchError> { let current_sla = >::get(relayer_id); let delta_sla = Self::_get_relayer_sla(event); @@ -226,16 +211,11 @@ impl Module { let new_total_relayer_score = total_relayer_score.checked_add(&delta_score)?; Some(new_total_relayer_score) }; - let new_total = - calculate_new_total_relayer_score().ok_or(Error::::InvalidTotalRelayerScore)?; + let new_total = calculate_new_total_relayer_score().ok_or(Error::::InvalidTotalRelayerScore)?; >::set(new_total); >::insert(relayer_id, new_sla); - Self::deposit_event(>::UpdateRelayerSLA( - relayer_id.clone(), - new_sla, - delta_sla, - )); + Self::deposit_event(>::UpdateRelayerSLA(relayer_id.clone(), new_sla, delta_sla)); } Ok(()) @@ -251,16 +231,11 @@ impl Module { total_reward_for_issued_in_dot: DOT, total_reward_for_locked_in_dot: DOT, ) -> Result, DOT)>, DispatchError> { - let total_issued = - Self::polkabtc_to_u128(ext::vault_registry::get_total_issued_tokens::(false)?)?; - let total_locked = Self::dot_to_u128(ext::vault_registry::get_total_backing_collateral::< - T, - >(false)?)?; + let total_issued = Self::polkabtc_to_u128(ext::vault_registry::get_total_issued_tokens::(false)?)?; + let total_locked = Self::dot_to_u128(ext::vault_registry::get_total_backing_collateral::(false)?)?; - let total_reward_for_issued_in_polka_btc = - Self::polkabtc_to_u128(total_reward_for_issued_in_polka_btc)?; - let total_reward_for_locked_in_polka_btc = - Self::polkabtc_to_u128(total_reward_for_locked_in_polka_btc)?; + let total_reward_for_issued_in_polka_btc = Self::polkabtc_to_u128(total_reward_for_issued_in_polka_btc)?; + let total_reward_for_locked_in_polka_btc = Self::polkabtc_to_u128(total_reward_for_locked_in_polka_btc)?; let total_reward_for_issued_in_dot = Self::dot_to_u128(total_reward_for_issued_in_dot)?; let total_reward_for_locked_in_dot = Self::dot_to_u128(total_reward_for_locked_in_dot)?; @@ -365,25 +340,15 @@ impl Module { /// /// * `vault_id` - account of the vault in question /// * `stake` - the amount of collateral placed for the redeem/replace - pub fn calculate_slashed_amount( - vault_id: &T::AccountId, - stake: DOT, - ) -> Result, DispatchError> { + pub fn calculate_slashed_amount(vault_id: &T::AccountId, stake: DOT) -> Result, DispatchError> { let current_sla = >::get(vault_id); - let liquidation_threshold = - ext::vault_registry::get_liquidation_collateral_threshold::(); + let liquidation_threshold = ext::vault_registry::get_liquidation_collateral_threshold::(); let liquidation_threshold = Self::fixed_point_unsigned_to_signed(liquidation_threshold)?; let premium_redeem_threshold = ext::vault_registry::get_premium_redeem_threshold::(); - let premium_redeem_threshold = - Self::fixed_point_unsigned_to_signed(premium_redeem_threshold)?; - - Self::_calculate_slashed_amount( - current_sla, - stake, - liquidation_threshold, - premium_redeem_threshold, - ) + let premium_redeem_threshold = Self::fixed_point_unsigned_to_signed(premium_redeem_threshold)?; + + Self::_calculate_slashed_amount(current_sla, stake, liquidation_threshold, premium_redeem_threshold) } /// Explicitly set the vault's SLA score, used in tests. @@ -393,13 +358,9 @@ impl Module { /// initializes the relayer's stake. Not that this module assumes that once set, the stake /// remains unchanged forever - pub fn initialize_relayer_stake( - relayer_id: &T::AccountId, - stake: DOT, - ) -> Result<(), DispatchError> { + pub fn initialize_relayer_stake(relayer_id: &T::AccountId, stake: DOT) -> Result<(), DispatchError> { let stake = Self::dot_to_u128(stake)?; - let stake = T::SignedFixedPoint::checked_from_rational(stake, 1u128) - .ok_or(Error::::TryIntoIntError)?; + let stake = T::SignedFixedPoint::checked_from_rational(stake, 1u128).ok_or(Error::::TryIntoIntError)?; >::insert(relayer_id, stake); Ok(()) @@ -448,9 +409,7 @@ impl Module { /// /// * `amount` - the amount of polkabtc that was issued /// * `vault_id` - account of the vault - fn _executed_issue_sla_change( - amount: PolkaBTC, - ) -> Result { + fn _executed_issue_sla_change(amount: PolkaBTC) -> Result { // update the number of issues performed let mut count = ::get(); count = count.checked_add(1).ok_or(Error::::ArithmeticOverflow)?; @@ -459,8 +418,8 @@ impl Module { // TODO: fix this let total = ext::treasury::get_total_supply::(); let total_raw = Self::polkabtc_to_u128(total)?; - let average = T::SignedFixedPoint::checked_from_rational(total_raw, count) - .ok_or(Error::::TryIntoIntError)?; + let average = + T::SignedFixedPoint::checked_from_rational(total_raw, count).ok_or(Error::::TryIntoIntError)?; let max_sla_change = >::get(); @@ -472,20 +431,12 @@ impl Module { .checked_mul(&max_sla_change) .ok_or(Error::::ArithmeticOverflow)?; - let ret = Self::_limit( - T::SignedFixedPoint::zero(), - potential_sla_increase, - max_sla_change, - ); + let ret = Self::_limit(T::SignedFixedPoint::zero(), potential_sla_increase, max_sla_change); Ok(ret) } /// returns `value` if it is between `min` and `max`; otherwise it returns the bound - fn _limit( - min: T::SignedFixedPoint, - value: T::SignedFixedPoint, - max: T::SignedFixedPoint, - ) -> T::SignedFixedPoint { + fn _limit(min: T::SignedFixedPoint, value: T::SignedFixedPoint, max: T::SignedFixedPoint) -> T::SignedFixedPoint { if value < min { min } else if value > max { @@ -501,14 +452,10 @@ impl Module { RelayerEvent::BlockSubmission => >::get(), RelayerEvent::DuplicateBlockSubmission => >::get(), RelayerEvent::CorrectNoDataVoteOrReport => >::get(), - RelayerEvent::CorrectInvalidVoteOrReport => { - >::get() - } + RelayerEvent::CorrectInvalidVoteOrReport => >::get(), RelayerEvent::CorrectLiquidationReport => >::get(), RelayerEvent::CorrectTheftReport => >::get(), - RelayerEvent::CorrectOracleOfflineReport => { - >::get() - } + RelayerEvent::CorrectOracleOfflineReport => >::get(), RelayerEvent::FalseNoDataVoteOrReport => >::get(), RelayerEvent::FalseInvalidVoteOrReport => >::get(), RelayerEvent::IgnoredVote => >::get(), @@ -519,37 +466,20 @@ impl Module { fn _set_relayer_sla(event: RelayerEvent, value: T::SignedFixedPoint) { match event { RelayerEvent::BlockSubmission => >::set(value), - RelayerEvent::DuplicateBlockSubmission => { - >::set(value) - } - RelayerEvent::CorrectNoDataVoteOrReport => { - >::set(value) - } - RelayerEvent::CorrectInvalidVoteOrReport => { - >::set(value) - } - RelayerEvent::CorrectLiquidationReport => { - >::set(value) - } + RelayerEvent::DuplicateBlockSubmission => >::set(value), + RelayerEvent::CorrectNoDataVoteOrReport => >::set(value), + RelayerEvent::CorrectInvalidVoteOrReport => >::set(value), + RelayerEvent::CorrectLiquidationReport => >::set(value), RelayerEvent::CorrectTheftReport => >::set(value), - RelayerEvent::CorrectOracleOfflineReport => { - >::set(value) - } - RelayerEvent::FalseNoDataVoteOrReport => { - >::set(value) - } - RelayerEvent::FalseInvalidVoteOrReport => { - >::set(value) - } + RelayerEvent::CorrectOracleOfflineReport => >::set(value), + RelayerEvent::FalseNoDataVoteOrReport => >::set(value), + RelayerEvent::FalseInvalidVoteOrReport => >::set(value), RelayerEvent::IgnoredVote => >::set(value), } } /// Calculate the reward of a given relayer, given the total reward for the whole relayer pool - fn _calculate_relayer_reward( - relayer_id: &T::AccountId, - total_reward: u128, - ) -> Result { + fn _calculate_relayer_reward(relayer_id: &T::AccountId, total_reward: u128) -> Result { let stake = Self::get_relayer_stake(&relayer_id); let sla = >::get(&relayer_id); let total_relayer_score = >::get(); @@ -572,17 +502,14 @@ impl Module { } /// Convert a given threshold from the vault registry to a signed fixed point type - fn fixed_point_unsigned_to_signed( - value: U, - ) -> Result, DispatchError> { + fn fixed_point_unsigned_to_signed(value: U) -> Result, DispatchError> { let raw: i128 = value .into_inner() .unique_saturated_into() .try_into() .map_err(|_| Error::::TryIntoIntError)?; - let ret = T::SignedFixedPoint::checked_from_rational(raw, U::accuracy()) - .ok_or(Error::::TryIntoIntError)?; + let ret = T::SignedFixedPoint::checked_from_rational(raw, U::accuracy()).ok_or(Error::::TryIntoIntError)?; Ok(ret) } diff --git a/crates/sla/src/mock.rs b/crates/sla/src/mock.rs index 922aac1830..1bc4512601 100644 --- a/crates/sla/src/mock.rs +++ b/crates/sla/src/mock.rs @@ -160,9 +160,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); sla::GenesisConfig:: { vault_target_sla: FixedI128::from(100), diff --git a/crates/sla/src/tests.rs b/crates/sla/src/tests.rs index c685f1c5cf..7f473cdc77 100644 --- a/crates/sla/src/tests.rs +++ b/crates/sla/src/tests.rs @@ -1,8 +1,7 @@ -use crate::ext; -use crate::mock::*; -use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageMap; -use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageValue; use crate::{ + ext, + mock::*, + sp_api_hidden_includes_decl_storage::hidden_include::{StorageMap, StorageValue}, types::{RelayerEvent, VaultEvent}, RelayerSla, TotalRelayerScore, }; @@ -82,8 +81,7 @@ fn test_calculate_slashed_amount_big_stake() { fn test_event_update_vault_sla_succeeds() { run_test(|| { let amount = 100u64; - ext::vault_registry::get_backing_collateral:: - .mock_safe(|_| MockResult::Return(Ok(ALICE_STAKE as u64))); + ext::vault_registry::get_backing_collateral::.mock_safe(|_| MockResult::Return(Ok(ALICE_STAKE as u64))); ext::treasury::get_total_supply::.mock_safe(move || MockResult::Return(amount)); Sla::event_update_vault_sla(&ALICE, VaultEvent::ExecutedIssue(amount)).unwrap(); @@ -98,8 +96,7 @@ fn test_event_update_vault_sla_succeeds() { fn test_event_update_vault_sla_half_size_increase() { run_test(|| { let amount = 100u64; - ext::vault_registry::get_backing_collateral:: - .mock_safe(|_| MockResult::Return(Ok(ALICE_STAKE as u64))); + ext::vault_registry::get_backing_collateral::.mock_safe(|_| MockResult::Return(Ok(ALICE_STAKE as u64))); ext::treasury::get_total_supply::.mock_safe(move || MockResult::Return(amount * 2)); Sla::event_update_vault_sla(&ALICE, VaultEvent::ExecutedIssue(amount)).unwrap(); @@ -117,10 +114,7 @@ fn test_event_update_relayer_sla_succeeds() { for i in 0..100 { Sla::event_update_relayer_sla(&ALICE, RelayerEvent::BlockSubmission).unwrap(); - assert_eq!( - >::get(ALICE), - FixedI128::from(i + 1) - ); + assert_eq!(>::get(ALICE), FixedI128::from(i + 1)); } >::insert(ALICE, FixedI128::from(50)); @@ -245,10 +239,7 @@ fn test_event_update_relayer_total_sla_score() { // decrease in alice' score all the way to 0 -> total be equal to bob's part Sla::event_update_relayer_sla(&ALICE, RelayerEvent::FalseInvalidVoteOrReport).unwrap(); - assert_eq!( - >::get(), - FixedI128::from(BOB_STAKE as i128) - ); + assert_eq!(>::get(), FixedI128::from(BOB_STAKE as i128)); }) } @@ -272,20 +263,14 @@ fn test_calculate_reward() { } // equal sla, but alice and bob have 1:4 staked collateral ratio - assert_eq!( - Sla::_calculate_relayer_reward(&ALICE, 1_000_000), - Ok(200_000) - ); + assert_eq!(Sla::_calculate_relayer_reward(&ALICE, 1_000_000), Ok(200_000)); for _ in 0..30 { Sla::event_update_relayer_sla(&ALICE, RelayerEvent::BlockSubmission).unwrap(); } // alice and bob have 4:1 sla ratio, and 1:4 staked collateral ratio, so both get 50% - assert_eq!( - Sla::_calculate_relayer_reward(&ALICE, 1_000_000), - Ok(500_000) - ); + assert_eq!(Sla::_calculate_relayer_reward(&ALICE, 1_000_000), Ok(500_000)); }) } diff --git a/crates/staked-relayers/rpc/src/lib.rs b/crates/staked-relayers/rpc/src/lib.rs index 712369fb47..62632a78fa 100644 --- a/crates/staked-relayers/rpc/src/lib.rs +++ b/crates/staked-relayers/rpc/src/lib.rs @@ -14,12 +14,7 @@ pub use module_staked_relayers_rpc_runtime_api::StakedRelayersApi as StakedRelay #[rpc] pub trait StakedRelayersApi { #[rpc(name = "stakedRelayers_isTransactionInvalid")] - fn is_transaction_invalid( - &self, - vault_id: AccountId, - raw_tx: Vec, - at: Option, - ) -> Result<()>; + fn is_transaction_invalid(&self, vault_id: AccountId, raw_tx: Vec, at: Option) -> Result<()>; } /// A struct that implements the [`StakedRelayersApi`]. @@ -50,8 +45,7 @@ impl From for i64 { } } -impl StakedRelayersApi<::Hash, AccountId> - for StakedRelayers +impl StakedRelayersApi<::Hash, AccountId> for StakedRelayers where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, @@ -67,22 +61,21 @@ where let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.is_transaction_invalid(&at, vault_id, raw_tx) - .map_or_else( - |e| { - Err(RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to check if transaction is invalid.".into(), - data: Some(format!("{:?}", e).into()), - }) - }, - |result| { - result.map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Transaction is valid.".into(), - data: Some(format!("{:?}", e).into()), - }) - }, - ) + api.is_transaction_invalid(&at, vault_id, raw_tx).map_or_else( + |e| { + Err(RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to check if transaction is invalid.".into(), + data: Some(format!("{:?}", e).into()), + }) + }, + |result| { + result.map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Transaction is valid.".into(), + data: Some(format!("{:?}", e).into()), + }) + }, + ) } } diff --git a/crates/staked-relayers/src/benchmarking.rs b/crates/staked-relayers/src/benchmarking.rs index 831b77a27d..738b8f6a60 100644 --- a/crates/staked-relayers/src/benchmarking.rs +++ b/crates/staked-relayers/src/benchmarking.rs @@ -1,28 +1,27 @@ use super::*; use crate::Module as StakedRelayers; -use bitcoin::formatter::{Formattable, TryFormattable}; -use bitcoin::types::{ - BlockBuilder, H256Le, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, - TransactionOutput, +use bitcoin::{ + formatter::{Formattable, TryFormattable}, + types::{BlockBuilder, H256Le, RawBlockHeader, TransactionBuilder, TransactionInputBuilder, TransactionOutput}, }; -use btc_relay::Module as BtcRelay; -use btc_relay::{BtcAddress, BtcPublicKey}; +use btc_relay::{BtcAddress, BtcPublicKey, Module as BtcRelay}; use collateral::Module as Collateral; use exchange_rate_oracle::Module as ExchangeRateOracle; use frame_benchmarking::{account, benchmarks}; -use frame_system::Module as System; -use frame_system::RawOrigin; +use frame_system::{Module as System, RawOrigin}; // use pallet_timestamp::Now; use sp_core::{H160, U256}; use sp_runtime::FixedPointNumber; use sp_std::prelude::*; -use vault_registry::types::{Vault, Wallet}; -use vault_registry::Module as VaultRegistry; +use vault_registry::{ + types::{Vault, Wallet}, + Module as VaultRegistry, +}; fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } @@ -206,10 +205,7 @@ mod tests { fn test_benchmarks() { ExtBuilder::build_with(|storage| { pallet_balances::GenesisConfig:: { - balances: vec![ - (account("Origin", 0, 0), 1 << 32), - (account("Vault", 0, 0), 1 << 32), - ], + balances: vec![(account("Origin", 0, 0), 1 << 32), (account("Vault", 0, 0), 1 << 32)], } .assimilate_storage(storage) .unwrap(); @@ -250,9 +246,7 @@ mod tests { assert_ok!(test_benchmark_force_status_update::()); assert_ok!(test_benchmark_slash_staked_relayer::()); assert_ok!(test_benchmark_report_vault_theft::()); - assert_ok!(test_benchmark_report_vault_under_liquidation_threshold::< - Test, - >()); + assert_ok!(test_benchmark_report_vault_under_liquidation_threshold::()); // assert_ok!(test_benchmark_report_oracle_offline::()); assert_ok!(test_benchmark_remove_active_status_update::()); assert_ok!(test_benchmark_remove_inactive_status_update::()); diff --git a/crates/staked-relayers/src/ext.rs b/crates/staked-relayers/src/ext.rs index ac4554e864..c74250c360 100644 --- a/crates/staked-relayers/src/ext.rs +++ b/crates/staked-relayers/src/ext.rs @@ -44,10 +44,7 @@ pub(crate) mod vault_registry { pub fn get_active_vault_from_id( vault_id: &T::AccountId, - ) -> Result< - vault_registry::types::Vault, DOT>, - DispatchError, - > { + ) -> Result, DOT>, DispatchError> { >::get_active_vault_from_id(vault_id) } @@ -61,13 +58,8 @@ pub(crate) mod vault_registry { >::liquidate_vault(vault_id) } - pub fn liquidate_theft_vault( - vault_id: &T::AccountId, - ) -> DispatchResult { - >::liquidate_vault_with_status( - vault_id, - VaultStatus::CommittedTheft, - ) + pub fn liquidate_theft_vault(vault_id: &T::AccountId) -> DispatchResult { + >::liquidate_vault_with_status(vault_id, VaultStatus::CommittedTheft) } } @@ -105,17 +97,11 @@ pub(crate) mod btc_relay { use security::types::ErrorCode; use sp_std::prelude::*; - pub(crate) fn flag_block_error( - block_hash: H256Le, - error: ErrorCode, - ) -> DispatchResult { + pub(crate) fn flag_block_error(block_hash: H256Le, error: ErrorCode) -> DispatchResult { >::flag_block_error(block_hash, error) } - pub(crate) fn clear_block_error( - block_hash: H256Le, - error: ErrorCode, - ) -> DispatchResult { + pub(crate) fn clear_block_error(block_hash: H256Le, error: ErrorCode) -> DispatchResult { >::clear_block_error(block_hash, error) } @@ -154,8 +140,7 @@ pub(crate) mod redeem { pub(crate) fn get_open_or_completed_redeem_request_from_id( id: &H256, - ) -> Result, DOT>, DispatchError> - { + ) -> Result, DOT>, DispatchError> { >::get_open_or_completed_redeem_request_from_id(id) } } @@ -169,8 +154,7 @@ pub(crate) mod replace { pub(crate) fn get_open_or_completed_replace_request( id: &H256, - ) -> Result, DOT>, DispatchError> - { + ) -> Result, DOT>, DispatchError> { >::get_open_or_completed_replace_request(id) } } @@ -210,9 +194,7 @@ pub(crate) mod sla { >::initialize_relayer_stake(relayer_id, stake) } - pub fn _on_runtime_upgrade( - stakes: Vec<(T::AccountId, DOT)>, - ) -> Result<(), DispatchError> { + pub fn _on_runtime_upgrade(stakes: Vec<(T::AccountId, DOT)>) -> Result<(), DispatchError> { >::_on_runtime_upgrade(stakes) } } diff --git a/crates/staked-relayers/src/lib.rs b/crates/staked-relayers/src/lib.rs index b4bbacfc58..2815617a11 100644 --- a/crates/staked-relayers/src/lib.rs +++ b/crates/staked-relayers/src/lib.rs @@ -27,27 +27,22 @@ use mocktopus::macros::mockable; pub use security; -use crate::types::{ - PolkaBTC, ProposalStatus, StakedRelayer, StatusUpdate, StatusUpdateId, Tally, Votes, DOT, -}; -use bitcoin::parser::parse_transaction; -use bitcoin::types::*; +use crate::types::{PolkaBTC, ProposalStatus, StakedRelayer, StatusUpdate, StatusUpdateId, Tally, Votes, DOT}; +use bitcoin::{parser::parse_transaction, types::*}; use btc_relay::BtcAddress; -use frame_support::transactional; use frame_support::{ decl_error, decl_event, decl_module, decl_storage, dispatch::{DispatchError, DispatchResult}, ensure, traits::Get, + transactional, weights::Weight, IterableStorageMap, }; use frame_system::{ensure_root, ensure_signed}; use primitive_types::H256; use security::types::{ErrorCode, StatusCode}; -use sp_std::collections::btree_set::BTreeSet; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_std::{collections::btree_set::BTreeSet, convert::TryInto, vec::Vec}; use vault_registry::Wallet; pub trait WeightInfo { @@ -723,10 +718,7 @@ impl Module { /// /// * `id` - account id of the relayer pub(crate) fn ensure_relayer_is_registered(id: &T::AccountId) -> DispatchResult { - ensure!( - >::contains_key(id), - Error::::NotRegistered, - ); + ensure!(>::contains_key(id), Error::::NotRegistered,); Ok(()) } @@ -747,13 +739,8 @@ impl Module { /// # Arguments /// /// * `id` - account id of the relayer - fn get_inactive_staked_relayer( - id: &T::AccountId, - ) -> Result, T::BlockNumber>, DispatchError> { - ensure!( - >::contains_key(id), - Error::::NotRegistered, - ); + fn get_inactive_staked_relayer(id: &T::AccountId) -> Result, T::BlockNumber>, DispatchError> { + ensure!(>::contains_key(id), Error::::NotRegistered,); Ok(>::get(id)) } @@ -764,11 +751,7 @@ impl Module { /// * `id` - account id of the relayer /// * `stake` - token deposited /// * `height` - bonding height - pub(crate) fn insert_active_staked_relayer( - id: &T::AccountId, - stake: DOT, - height: T::BlockNumber, - ) { + pub(crate) fn insert_active_staked_relayer(id: &T::AccountId, stake: DOT, height: T::BlockNumber) { >::insert(id, StakedRelayer { stake, height }); } @@ -779,11 +762,7 @@ impl Module { /// * `id` - account id of the relayer /// * `stake` - token deposited /// * `height` - bonding height - pub(crate) fn insert_inactive_staked_relayer( - id: &T::AccountId, - stake: DOT, - height: T::BlockNumber, - ) { + pub(crate) fn insert_inactive_staked_relayer(id: &T::AccountId, stake: DOT, height: T::BlockNumber) { >::insert(id, StakedRelayer { stake, height }); } @@ -856,10 +835,7 @@ impl Module { /// /// * `error` - optional errorcode /// * `votes` - vote set, includes account set and total stake - fn slash_staked_relayers( - error: &Option, - votes: &Votes>, - ) -> DispatchResult { + fn slash_staked_relayers(error: &Option, votes: &Votes>) -> DispatchResult { // TODO: slash block proposer if let Some(ErrorCode::NoDataBTCRelay) = error { // we don't slash participants for this @@ -870,11 +846,7 @@ impl Module { // active participants are not allowed to deregister during // an ongoing status update, so this call should never revert let staked_relayer = Self::get_active_staked_relayer(acc)?; - ext::collateral::slash_collateral::( - acc.clone(), - >::get(), - staked_relayer.stake, - )?; + ext::collateral::slash_collateral::(acc.clone(), >::get(), staked_relayer.stake)?; Self::remove_active_staked_relayer(acc); } @@ -915,41 +887,27 @@ impl Module { // reward relayers for correct votes by increasing their sla for relayer in correct_voters { if no_data_relayer { - ext::sla::event_update_relayer_sla::( - &relayer, - ext::sla::RelayerEvent::CorrectNoDataVoteOrReport, - )?; + ext::sla::event_update_relayer_sla::(&relayer, ext::sla::RelayerEvent::CorrectNoDataVoteOrReport)?; } if invalid_relayer { - ext::sla::event_update_relayer_sla::( - &relayer, - ext::sla::RelayerEvent::CorrectInvalidVoteOrReport, - )?; + ext::sla::event_update_relayer_sla::(&relayer, ext::sla::RelayerEvent::CorrectInvalidVoteOrReport)?; } } // punish relayers for incorrect votes by decreasing their sla for relayer in incorrect_voters { if no_data_relayer { - ext::sla::event_update_relayer_sla::( - &relayer, - ext::sla::RelayerEvent::FalseNoDataVoteOrReport, - )?; + ext::sla::event_update_relayer_sla::(&relayer, ext::sla::RelayerEvent::FalseNoDataVoteOrReport)?; } if invalid_relayer { - ext::sla::event_update_relayer_sla::( - &relayer, - ext::sla::RelayerEvent::FalseInvalidVoteOrReport, - )?; + ext::sla::event_update_relayer_sla::(&relayer, ext::sla::RelayerEvent::FalseInvalidVoteOrReport)?; } } // punish relayers that didn't vote by decreasing their sla let mut voters = status_update.tally.aye.accounts.clone(); voters.append(&mut status_update.tally.nay.accounts.clone()); - let all_relayers: BTreeSet<_> = >::iter() - .map(|(relayer, _)| relayer) - .collect(); + let all_relayers: BTreeSet<_> = >::iter().map(|(relayer, _)| relayer).collect(); for abstainer in all_relayers.difference(&voters) { let staked_relayer = >::get(abstainer); if staked_relayer.height > status_update.start { @@ -957,10 +915,7 @@ impl Module { continue; } - ext::sla::event_update_relayer_sla::( - &abstainer, - ext::sla::RelayerEvent::IgnoredVote, - )?; + ext::sla::event_update_relayer_sla::(&abstainer, ext::sla::RelayerEvent::IgnoredVote)?; } Ok(()) @@ -976,10 +931,7 @@ impl Module { status_update_id: StatusUpdateId, mut status_update: &mut StatusUpdate>, ) -> DispatchResult { - ensure!( - status_update.tally.is_approved(), - Error::::InsufficientYesVotes - ); + ensure!(status_update.tally.is_approved(), Error::::InsufficientYesVotes); let status_code = status_update.new_status_code.clone(); ext::security::set_status::(status_code.clone()); @@ -990,8 +942,7 @@ impl Module { let old_status_code = status_update.old_status_code.clone(); if let Some(ref error_code) = add_error { - if error_code == &ErrorCode::NoDataBTCRelay || error_code == &ErrorCode::InvalidBTCRelay - { + if error_code == &ErrorCode::NoDataBTCRelay || error_code == &ErrorCode::InvalidBTCRelay { ext::btc_relay::flag_block_error::( btc_block_hash.ok_or(Error::::ExpectedBlockHash)?, error_code.clone(), @@ -1001,8 +952,7 @@ impl Module { } if let Some(ref error_code) = remove_error { - if error_code == &ErrorCode::NoDataBTCRelay || error_code == &ErrorCode::InvalidBTCRelay - { + if error_code == &ErrorCode::NoDataBTCRelay || error_code == &ErrorCode::InvalidBTCRelay { ext::btc_relay::clear_block_error::( btc_block_hash.ok_or(Error::::ExpectedBlockHash)?, error_code.clone(), @@ -1036,10 +986,7 @@ impl Module { status_update_id: StatusUpdateId, mut status_update: &mut StatusUpdate>, ) -> DispatchResult { - ensure!( - !status_update.tally.is_approved(), - Error::::InsufficientNoVotes - ); + ensure!(!status_update.tally.is_approved(), Error::::InsufficientNoVotes); status_update.proposal_status = ProposalStatus::Rejected; Self::slash_staked_relayers(&status_update.add_error, &status_update.tally.aye)?; @@ -1093,9 +1040,7 @@ impl Module { payments: &Vec<(i64, BtcAddress)>, wallet: &Wallet, ) -> bool { - let request_value = match TryInto::::try_into(request_value) - .map_err(|_e| Error::::TryIntoIntError) - { + let request_value = match TryInto::::try_into(request_value).map_err(|_e| Error::::TryIntoIntError) { Ok(value) => value as i64, Err(_) => return false, }; @@ -1129,8 +1074,7 @@ impl Module { let vault = ext::vault_registry::get_active_vault_from_id::(vault_id)?; // TODO: ensure this cannot fail on invalid - let tx = - parse_transaction(raw_tx.as_slice()).map_err(|_| Error::::InvalidTransaction)?; + let tx = parse_transaction(raw_tx.as_slice()).map_err(|_| Error::::InvalidTransaction)?; // collect all addresses that feature in the inputs of the transaction let input_addresses: Vec> = tx @@ -1187,12 +1131,7 @@ impl Module { match ext::redeem::get_open_or_completed_redeem_request_from_id::(&request_id) { Ok(req) => { ensure!( - !Self::is_valid_request_transaction( - req.amount_btc, - req.btc_address, - &payments, - &vault.wallet, - ), + !Self::is_valid_request_transaction(req.amount_btc, req.btc_address, &payments, &vault.wallet,), Error::::ValidRedeemTransaction ); } @@ -1205,12 +1144,7 @@ impl Module { if let Some(btc_address) = req.btc_address { // only check replace if we have a valid btc_address ensure!( - !Self::is_valid_request_transaction( - req.amount, - btc_address, - &payments, - &vault.wallet, - ), + !Self::is_valid_request_transaction(req.amount, btc_address, &payments, &vault.wallet,), Error::::ValidReplaceTransaction ); } @@ -1278,12 +1212,7 @@ decl_event!( Option, Option, ), - RejectStatusUpdate( - StatusUpdateId, - StatusCode, - Option, - Option, - ), + RejectStatusUpdate(StatusUpdateId, StatusCode, Option, Option), ForceStatusUpdate(StatusCode, Option, Option), SlashStakedRelayer(AccountId), OracleOffline(), diff --git a/crates/staked-relayers/src/mock.rs b/crates/staked-relayers/src/mock.rs index d2448cd956..c432a85080 100644 --- a/crates/staked-relayers/src/mock.rs +++ b/crates/staked-relayers/src/mock.rs @@ -222,19 +222,17 @@ impl ExtBuilder { where F: FnOnce(&mut sp_core::storage::Storage), { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); fee::GenesisConfig:: { issue_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% issue_griefing_collateral: FixedU128::checked_from_rational(5, 100000).unwrap(), // 0.005% - refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% - replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% fee_pool_account_id: 0, maintainer_account_id: 1, epoch_period: 5, diff --git a/crates/staked-relayers/src/tests.rs b/crates/staked-relayers/src/tests.rs index 40e647e9fc..9d27dcd5cf 100644 --- a/crates/staked-relayers/src/tests.rs +++ b/crates/staked-relayers/src/tests.rs @@ -1,9 +1,14 @@ extern crate hex; -use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageMap; -use crate::types::{ProposalStatus, StakedRelayer, StatusUpdate, Tally, Votes}; -use crate::{ext, mock::*}; -use bitcoin::formatter::Formattable; -use bitcoin::types::{H256Le, TransactionBuilder, TransactionInputBuilder, TransactionOutput}; +use crate::{ + ext, + mock::*, + sp_api_hidden_includes_decl_storage::hidden_include::StorageMap, + types::{ProposalStatus, StakedRelayer, StatusUpdate, Tally, Votes}, +}; +use bitcoin::{ + formatter::Formattable, + types::{H256Le, TransactionBuilder, TransactionInputBuilder, TransactionOutput}, +}; use btc_relay::{BtcAddress, BtcPublicKey}; use frame_support::{assert_err, assert_noop, assert_ok, dispatch::DispatchError}; use mocktopus::mocking::*; @@ -11,8 +16,7 @@ use redeem::types::RedeemRequest; use replace::types::ReplaceRequest; use security::types::{ErrorCode, StatusCode}; use sp_core::{H160, H256}; -use std::convert::TryInto; -use std::str::FromStr; +use std::{convert::TryInto, str::FromStr}; use vault_registry::{Vault, VaultStatus, Wallet}; type Event = crate::Event; @@ -28,10 +32,7 @@ macro_rules! assert_emitted { ($event:expr, $times:expr) => { let test_event = TestEvent::staked_relayers($event); assert_eq!( - System::events() - .iter() - .filter(|a| a.event == test_event) - .count(), + System::events().iter().filter(|a| a.event == test_event).count(), $times ); }; @@ -46,16 +47,13 @@ macro_rules! assert_not_emitted { fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } /// Mocking functions -fn init_zero_vault( - id: AccountId, - btc_address: Option, -) -> Vault { +fn init_zero_vault(id: AccountId, btc_address: Option) -> Vault { let mut vault = Vault::default(); vault.id = id; vault.wallet = Wallet::new(dummy_public_key()); @@ -82,8 +80,7 @@ fn test_register_staked_relayer_fails_with_insufficient_stake() { #[test] fn test_register_staked_relayer_succeeds() { - use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageMap; - use crate::InactiveStakedRelayers; + use crate::{sp_api_hidden_includes_decl_storage::hidden_include::StorageMap, InactiveStakedRelayers}; run_test(|| { let relayer = Origin::signed(ALICE); @@ -91,10 +88,7 @@ fn test_register_staked_relayer_succeeds() { ext::collateral::lock_collateral::.mock_safe(|_, _| MockResult::Return(Ok(()))); - assert_ok!(StakedRelayers::register_staked_relayer( - relayer.clone(), - amount - )); + assert_ok!(StakedRelayers::register_staked_relayer(relayer.clone(), amount)); assert_emitted!(Event::RegisterStakedRelayer(ALICE, 11, amount)); let maturity_height = System::block_number() + StakedRelayers::get_maturity_period(); @@ -236,8 +230,7 @@ fn test_suggest_status_update_fails_with_not_registered() { #[ignore] fn test_suggest_status_update_fails_with_governance_only() { run_test(|| { - StakedRelayers::only_governance - .mock_safe(|_| MockResult::Return(Err(TestError::GovernanceOnly.into()))); + StakedRelayers::only_governance.mock_safe(|_| MockResult::Return(Err(TestError::GovernanceOnly.into()))); assert_err!( StakedRelayers::suggest_status_update( @@ -698,16 +691,10 @@ fn test_reject_status_update_succeeds() { #[test] fn test_force_status_update_fails_with_governance_only() { run_test(|| { - StakedRelayers::only_governance - .mock_safe(|_| MockResult::Return(Err(TestError::GovernanceOnly.into()))); + StakedRelayers::only_governance.mock_safe(|_| MockResult::Return(Err(TestError::GovernanceOnly.into()))); assert_err!( - StakedRelayers::force_status_update( - Origin::signed(ALICE), - StatusCode::Shutdown, - None, - None - ), + StakedRelayers::force_status_update(Origin::signed(ALICE), StatusCode::Shutdown, None, None), TestError::GovernanceOnly, ); }) @@ -725,10 +712,7 @@ fn test_force_status_update_succeeds() { None )); - assert_eq!( - ext::security::get_parachain_status::(), - StatusCode::Shutdown - ); + assert_eq!(ext::security::get_parachain_status::(), StatusCode::Shutdown); assert_emitted!(Event::ForceStatusUpdate( StatusCode::Shutdown, @@ -744,8 +728,7 @@ fn test_force_status_update_succeeds() { #[test] fn test_slash_staked_relayer_fails_with_governance_only() { run_test(|| { - StakedRelayers::only_governance - .mock_safe(|_| MockResult::Return(Err(TestError::GovernanceOnly.into()))); + StakedRelayers::only_governance.mock_safe(|_| MockResult::Return(Err(TestError::GovernanceOnly.into()))); assert_err!( StakedRelayers::slash_staked_relayer(Origin::signed(ALICE), BOB), @@ -778,10 +761,7 @@ fn test_slash_staked_relayer_succeeds() { MockResult::Return(Ok(())) }); - assert_ok!(StakedRelayers::slash_staked_relayer( - Origin::signed(ALICE), - BOB - )); + assert_ok!(StakedRelayers::slash_staked_relayer(Origin::signed(ALICE), BOB)); assert_err!( StakedRelayers::get_active_staked_relayer(&BOB), TestError::NotRegistered @@ -816,16 +796,12 @@ fn test_report_vault_passes_with_vault_transaction() { let vault = CAROL; let btc_address = BtcAddress::P2PKH(H160::from_slice(&[ - 126, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, - 50, 170, + 126, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, 50, 170, ])); - ext::vault_registry::get_active_vault_from_id::.mock_safe(move |_| { - MockResult::Return(Ok(init_zero_vault(vault.clone(), Some(btc_address)))) - }); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(move |_, _| MockResult::Return(Ok(()))); - ext::vault_registry::liquidate_theft_vault:: - .mock_safe(|_| MockResult::Return(Ok(()))); + ext::vault_registry::get_active_vault_from_id:: + .mock_safe(move |_| MockResult::Return(Ok(init_zero_vault(vault.clone(), Some(btc_address))))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(move |_, _| MockResult::Return(Ok(()))); + ext::vault_registry::liquidate_theft_vault::.mock_safe(|_| MockResult::Return(Ok(()))); assert_ok!(StakedRelayers::report_vault_theft( Origin::signed(ALICE), @@ -847,15 +823,12 @@ fn test_report_vault_fails_with_non_vault_transaction() { let vault = CAROL; let btc_address = BtcAddress::P2PKH(H160::from_slice(&[ - 125, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, - 50, 170, + 125, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, 50, 170, ])); - ext::vault_registry::get_active_vault_from_id::.mock_safe(move |_| { - MockResult::Return(Ok(init_zero_vault(vault.clone(), Some(btc_address)))) - }); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(move |_, _| MockResult::Return(Ok(()))); + ext::vault_registry::get_active_vault_from_id:: + .mock_safe(move |_| MockResult::Return(Ok(init_zero_vault(vault.clone(), Some(btc_address))))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(move |_, _| MockResult::Return(Ok(()))); ext::vault_registry::liquidate_vault::.mock_safe(|_| MockResult::Return(Ok(()))); assert_err!( @@ -881,16 +854,12 @@ fn test_report_vault_succeeds_with_segwit_transaction() { let vault = CAROL; let btc_address = BtcAddress::P2WPKHv0(H160::from_slice(&[ - 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, 141, 186, 174, 34, 105, - 85, + 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, 141, 186, 174, 34, 105, 85, ])); - ext::vault_registry::get_active_vault_from_id::.mock_safe(move |_| { - MockResult::Return(Ok(init_zero_vault(vault.clone(), Some(btc_address)))) - }); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(move |_, _| MockResult::Return(Ok(()))); - ext::vault_registry::liquidate_theft_vault:: - .mock_safe(|_| MockResult::Return(Ok(()))); + ext::vault_registry::get_active_vault_from_id:: + .mock_safe(move |_| MockResult::Return(Ok(init_zero_vault(vault.clone(), Some(btc_address))))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(move |_, _| MockResult::Return(Ok(()))); + ext::vault_registry::liquidate_theft_vault::.mock_safe(|_| MockResult::Return(Ok(()))); assert_ok!(StakedRelayers::report_vault_theft( Origin::signed(ALICE), @@ -909,11 +878,9 @@ fn test_report_vault_theft_succeeds() { let amount: Balance = 3; inject_active_staked_relayer(&ALICE, amount); - ext::btc_relay::verify_transaction_inclusion:: - .mock_safe(move |_, _| MockResult::Return(Ok(()))); + ext::btc_relay::verify_transaction_inclusion::.mock_safe(move |_, _| MockResult::Return(Ok(()))); StakedRelayers::is_transaction_invalid.mock_safe(move |_, _| MockResult::Return(Ok(()))); - ext::vault_registry::liquidate_theft_vault:: - .mock_safe(move |_| MockResult::Return(Ok(()))); + ext::vault_registry::liquidate_theft_vault::.mock_safe(move |_| MockResult::Return(Ok(()))); assert_ok!(StakedRelayers::report_vault_theft( relayer, @@ -938,10 +905,7 @@ fn test_report_vault_under_liquidation_threshold_fails() { .mock_safe(move |_| MockResult::Return(Ok(false))); assert_err!( - StakedRelayers::report_vault_under_liquidation_threshold( - Origin::signed(relayer), - vault - ), + StakedRelayers::report_vault_under_liquidation_threshold(Origin::signed(relayer), vault), TestError::CollateralOk ); }) @@ -986,10 +950,7 @@ fn test_report_vault_under_liquidation_threshold_fails_with_not_registered() { fn test_report_oracle_offline_fails_with_not_registered() { run_test(|| { let relayer = Origin::signed(ALICE); - assert_err!( - StakedRelayers::report_oracle_offline(relayer), - TestError::NotRegistered, - ); + assert_err!(StakedRelayers::report_oracle_offline(relayer), TestError::NotRegistered,); }) } @@ -1017,10 +978,7 @@ fn test_report_oracle_offline_fails_with_oracle_online() { inject_active_staked_relayer(&ALICE, amount); ext::oracle::is_max_delay_passed::.mock_safe(|| MockResult::Return(false)); - assert_err!( - StakedRelayers::report_oracle_offline(relayer), - TestError::OracleOnline, - ); + assert_err!(StakedRelayers::report_oracle_offline(relayer), TestError::OracleOnline,); }) } @@ -1045,11 +1003,9 @@ fn test_is_valid_merge_transaction_fails() { ext::vault_registry::get_active_vault_from_id:: .mock_safe(move |_| MockResult::Return(Ok(init_zero_vault(vault.clone(), None)))); - let address1 = - BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let address1 = BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let address2 = - BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); + let address2 = BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); assert_eq!( StakedRelayers::is_valid_merge_transaction( @@ -1080,18 +1036,13 @@ fn test_is_valid_merge_transaction_succeeds() { ext::vault_registry::get_active_vault_from_id:: .mock_safe(move |_| MockResult::Return(Ok(init_zero_vault(vault.clone(), None)))); - let address = - BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let address = BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); let mut wallet = Wallet::new(dummy_public_key()); wallet.add_btc_address(address); assert_eq!( - StakedRelayers::is_valid_merge_transaction( - &vec![(100, address.clone())], - &vec![], - &wallet - ), + StakedRelayers::is_valid_merge_transaction(&vec![(100, address.clone())], &vec![], &wallet), true ); }) @@ -1104,11 +1055,9 @@ fn test_is_valid_request_transaction_fails() { ext::vault_registry::get_active_vault_from_id:: .mock_safe(move |_| MockResult::Return(Ok(init_zero_vault(vault.clone(), None)))); - let address1 = - BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let address1 = BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let address2 = - BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); + let address2 = BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); let mut wallet = Wallet::new(dummy_public_key()); wallet.add_btc_address(address2); @@ -1133,11 +1082,9 @@ fn test_is_valid_request_transaction_fails() { #[test] fn test_is_valid_request_transaction_succeeds() { run_test(|| { - let recipient_address = - BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let recipient_address = BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); - let vault_address = - BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); + let vault_address = BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); let request_value = 100; let change_value = 50; @@ -1164,8 +1111,7 @@ fn test_is_valid_request_transaction_succeeds() { fn test_is_transaction_invalid_fails_with_valid_merge_transaction() { run_test(|| { let address = BtcAddress::P2PKH(H160::from_slice(&[ - 126, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, - 50, 170, + 126, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, 50, 170, ])); let mut wallet = Wallet::new(dummy_public_key()); @@ -1193,17 +1139,16 @@ fn test_is_transaction_invalid_fails_with_valid_merge_transaction() { .with_sequence(4294967295) .with_previous_index(1) .with_previous_hash(H256Le::from_bytes_le(&[ - 193, 80, 65, 160, 109, 235, 107, 56, 24, 176, 34, 250, 197, 88, 218, 76, - 226, 9, 127, 8, 96, 200, 246, 66, 16, 91, 186, 217, 210, 155, 224, 42, + 193, 80, 65, 160, 109, 235, 107, 56, 24, 176, 34, 250, 197, 88, 218, 76, 226, 9, 127, 8, 96, + 200, 246, 66, 16, 91, 186, 217, 210, 155, 224, 42, ])) .with_script(&[ - 73, 48, 70, 2, 33, 0, 207, 210, 162, 211, 50, 178, 154, 220, 225, 25, 197, - 90, 159, 173, 211, 192, 115, 51, 32, 36, 183, 226, 114, 81, 62, 81, 98, 60, - 161, 89, 147, 72, 2, 33, 0, 155, 72, 45, 127, 123, 77, 71, 154, 255, 98, - 189, 205, 174, 165, 70, 103, 115, 125, 86, 248, 212, 214, 61, 208, 62, 195, - 239, 101, 30, 217, 162, 84, 1, 33, 3, 37, 248, 176, 57, 161, 24, 97, 101, - 156, 155, 240, 63, 67, 252, 78, 160, 85, 243, 167, 28, 214, 12, 123, 31, - 212, 116, 171, 87, 143, 153, 119, 250, + 73, 48, 70, 2, 33, 0, 207, 210, 162, 211, 50, 178, 154, 220, 225, 25, 197, 90, 159, 173, 211, + 192, 115, 51, 32, 36, 183, 226, 114, 81, 62, 81, 98, 60, 161, 89, 147, 72, 2, 33, 0, 155, 72, + 45, 127, 123, 77, 71, 154, 255, 98, 189, 205, 174, 165, 70, 103, 115, 125, 86, 248, 212, 214, + 61, 208, 62, 195, 239, 101, 30, 217, 162, 84, 1, 33, 3, 37, 248, 176, 57, 161, 24, 97, 101, + 156, 155, 240, 63, 67, 252, 78, 160, 85, 243, 167, 28, 214, 12, 123, 31, 212, 116, 171, 87, + 143, 153, 119, 250, ]) .build(), ) @@ -1221,15 +1166,13 @@ fn test_is_transaction_invalid_fails_with_valid_merge_transaction() { fn test_is_transaction_invalid_fails_with_valid_request_or_redeem() { run_test(|| { let vault_address = BtcAddress::P2WPKHv0(H160::from_slice(&[ - 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, 141, 186, 174, 34, 105, - 85, + 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, 141, 186, 174, 34, 105, 85, ])); let mut wallet = Wallet::new(dummy_public_key()); wallet.add_btc_address(vault_address); - let recipient_address = - BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); + let recipient_address = BtcAddress::P2PKH(H160::from_str(&"5f69790b72c98041330644bbd50f2ebb5d073c36").unwrap()); ext::vault_registry::get_active_vault_from_id::.mock_safe(move |_| { MockResult::Return(Ok(Vault { @@ -1273,27 +1216,23 @@ fn test_is_transaction_invalid_fails_with_valid_request_or_redeem() { )) .with_sequence(4294967295) .with_script(&[ - 22, 0, 20, 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, - 141, 186, 174, 34, 105, 85, + 22, 0, 20, 164, 180, 202, 72, 222, 11, 63, 255, 193, 84, 4, 161, 172, 220, 141, 186, 174, 34, + 105, 85, ]) .add_witness(&[ - 48, 69, 2, 33, 0, 134, 4, 239, 143, 109, 138, 250, 137, 45, 238, 15, 49, - 37, 155, 108, 224, 45, 215, 12, 84, 92, 252, 254, 216, 20, 129, 121, 151, - 24, 118, 197, 74, 2, 32, 118, 215, 113, 214, 233, 27, 237, 33, 39, 131, - 201, 176, 110, 13, 230, 0, 250, 178, 213, 24, 250, 214, 241, 90, 43, 25, - 29, 127, 189, 38, 42, 62, 1, + 48, 69, 2, 33, 0, 134, 4, 239, 143, 109, 138, 250, 137, 45, 238, 15, 49, 37, 155, 108, 224, 45, + 215, 12, 84, 92, 252, 254, 216, 20, 129, 121, 151, 24, 118, 197, 74, 2, 32, 118, 215, 113, 214, + 233, 27, 237, 33, 39, 131, 201, 176, 110, 13, 230, 0, 250, 178, 213, 24, 250, 214, 241, 90, 43, + 25, 29, 127, 189, 38, 42, 62, 1, ]) .add_witness(&[ - 3, 157, 37, 171, 121, 244, 31, 117, 206, 175, 136, 36, 17, 253, 65, 250, - 103, 10, 76, 103, 44, 35, 255, 175, 14, 54, 26, 150, 156, 222, 6, 146, 232, + 3, 157, 37, 171, 121, 244, 31, 117, 206, 175, 136, 36, 17, 253, 65, 250, 103, 10, 76, 103, 44, + 35, 255, 175, 14, 54, 26, 150, 156, 222, 6, 146, 232, ]) .build(), ) .add_output(TransactionOutput::payment(100, &recipient_address)) - .add_output(TransactionOutput::op_return( - 0, - &H256::from_slice(&[0; 32]).as_bytes(), - )) + .add_output(TransactionOutput::op_return(0, &H256::from_slice(&[0; 32]).as_bytes())) .build(); assert_err!( @@ -1330,12 +1269,10 @@ fn test_is_transaction_invalid_fails_with_valid_request_or_redeem() { fn test_is_transaction_invalid_succeeds() { run_test(|| { let vault_address = BtcAddress::P2PKH(H160::from_slice(&[ - 126, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, - 50, 170, + 126, 125, 148, 208, 221, 194, 29, 131, 191, 188, 252, 119, 152, 228, 84, 126, 223, 8, 50, 170, ])); - let recipient_address = - BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); + let recipient_address = BtcAddress::P2PKH(H160::from_str(&"66c7060feb882664ae62ffad0051fe843e318e85").unwrap()); ext::vault_registry::get_active_vault_from_id:: .mock_safe(move |_| MockResult::Return(Ok(init_zero_vault(BOB, Some(vault_address))))); @@ -1348,34 +1285,31 @@ fn test_is_transaction_invalid_succeeds() { .with_sequence(4294967295) .with_previous_index(1) .with_previous_hash(H256Le::from_bytes_le(&[ - 193, 80, 65, 160, 109, 235, 107, 56, 24, 176, 34, 250, 197, 88, 218, 76, - 226, 9, 127, 8, 96, 200, 246, 66, 16, 91, 186, 217, 210, 155, 224, 42, + 193, 80, 65, 160, 109, 235, 107, 56, 24, 176, 34, 250, 197, 88, 218, 76, 226, 9, 127, 8, 96, + 200, 246, 66, 16, 91, 186, 217, 210, 155, 224, 42, ])) .with_script(&[ - 73, 48, 70, 2, 33, 0, 207, 210, 162, 211, 50, 178, 154, 220, 225, 25, 197, - 90, 159, 173, 211, 192, 115, 51, 32, 36, 183, 226, 114, 81, 62, 81, 98, 60, - 161, 89, 147, 72, 2, 33, 0, 155, 72, 45, 127, 123, 77, 71, 154, 255, 98, - 189, 205, 174, 165, 70, 103, 115, 125, 86, 248, 212, 214, 61, 208, 62, 195, - 239, 101, 30, 217, 162, 84, 1, 33, 3, 37, 248, 176, 57, 161, 24, 97, 101, - 156, 155, 240, 63, 67, 252, 78, 160, 85, 243, 167, 28, 214, 12, 123, 31, - 212, 116, 171, 87, 143, 153, 119, 250, + 73, 48, 70, 2, 33, 0, 207, 210, 162, 211, 50, 178, 154, 220, 225, 25, 197, 90, 159, 173, 211, + 192, 115, 51, 32, 36, 183, 226, 114, 81, 62, 81, 98, 60, 161, 89, 147, 72, 2, 33, 0, 155, 72, + 45, 127, 123, 77, 71, 154, 255, 98, 189, 205, 174, 165, 70, 103, 115, 125, 86, 248, 212, 214, + 61, 208, 62, 195, 239, 101, 30, 217, 162, 84, 1, 33, 3, 37, 248, 176, 57, 161, 24, 97, 101, + 156, 155, 240, 63, 67, 252, 78, 160, 85, 243, 167, 28, 214, 12, 123, 31, 212, 116, 171, 87, + 143, 153, 119, 250, ]) .build(), ) .add_output(TransactionOutput::payment(100, &recipient_address)) .build(); - assert_ok!(StakedRelayers::is_transaction_invalid( - &BOB, - transaction.format() - )); + assert_ok!(StakedRelayers::is_transaction_invalid(&BOB, transaction.format())); }) } #[test] fn test_is_transaction_invalid_fails_with_valid_merge_testnet_transaction() { run_test(|| { - // bitcoin-cli -testnet getrawtransaction "3453e52ebab8ac96159d6b19114b492a05cce05a8fdfdaf5dea266ac10601ce4" 0 "00000000000000398849cc9d67261ec2d5fea07db87ab66a8ea47bc05acfb194" + // bitcoin-cli -testnet getrawtransaction "3453e52ebab8ac96159d6b19114b492a05cce05a8fdfdaf5dea266ac10601ce4" 0 + // "00000000000000398849cc9d67261ec2d5fea07db87ab66a8ea47bc05acfb194" let raw_tx_hex = "0200000000010108ce8e8943edbbf09d070bb893e09c0de12c0cf3704fe8a9b0f8b8d1a4a7a4760000000017160014473ca3f4d726ce9c21af7cdc3fcc13264f681b04feffffff02b377413f0000000017a914fe5183ccb89d98beaa6908c7cf1bd109029482cf87142e1a00000000001976a914d0a46d39dafa3012c2a7ed4d82d644b428e4586b88ac02473044022069484377c6627ccca566d4c4ac2cb84d1b0662f5ffbd384815c5e98b072759fc022061de3b77b4543ef43bb969d3f97fbbbdcddc008438720e7026181d99c455b2410121034172c29d3da8279f71adda48db8281d65b794e73cf04ea91fac4293030f0fe91a3ee1c00"; let raw_tx = hex::decode(&raw_tx_hex).unwrap(); @@ -1423,7 +1357,8 @@ fn test_is_transaction_invalid_fails_with_valid_merge_testnet_transaction() { #[test] fn test_is_transaction_invalid_succeeds_with_testnet_transaction() { run_test(|| { - // bitcoin-cli -testnet getrawtransaction "3453e52ebab8ac96159d6b19114b492a05cce05a8fdfdaf5dea266ac10601ce4" 0 "00000000000000398849cc9d67261ec2d5fea07db87ab66a8ea47bc05acfb194" + // bitcoin-cli -testnet getrawtransaction "3453e52ebab8ac96159d6b19114b492a05cce05a8fdfdaf5dea266ac10601ce4" 0 + // "00000000000000398849cc9d67261ec2d5fea07db87ab66a8ea47bc05acfb194" let raw_tx_hex = "0200000000010108ce8e8943edbbf09d070bb893e09c0de12c0cf3704fe8a9b0f8b8d1a4a7a4760000000017160014473ca3f4d726ce9c21af7cdc3fcc13264f681b04feffffff02b377413f0000000017a914fe5183ccb89d98beaa6908c7cf1bd109029482cf87142e1a00000000001976a914d0a46d39dafa3012c2a7ed4d82d644b428e4586b88ac02473044022069484377c6627ccca566d4c4ac2cb84d1b0662f5ffbd384815c5e98b072759fc022061de3b77b4543ef43bb969d3f97fbbbdcddc008438720e7026181d99c455b2410121034172c29d3da8279f71adda48db8281d65b794e73cf04ea91fac4293030f0fe91a3ee1c00"; let raw_tx = hex::decode(&raw_tx_hex).unwrap(); @@ -1486,13 +1421,7 @@ fn test_remove_inactive_status_update_only_root() { #[test] fn runtime_upgrade_succeeds() { run_test(|| { - >::insert( - ALICE, - StakedRelayer { - height: 0, - stake: 10, - }, - ); + >::insert(ALICE, StakedRelayer { height: 0, stake: 10 }); assert_ok!(StakedRelayers::_on_runtime_upgrade()); }) diff --git a/crates/staked-relayers/src/types.rs b/crates/staked-relayers/src/types.rs index 5531dd27e9..508ea4fcf0 100644 --- a/crates/staked-relayers/src/types.rs +++ b/crates/staked-relayers/src/types.rs @@ -3,17 +3,12 @@ use codec::{Decode, Encode}; use frame_support::traits::Currency; use security::types::{ErrorCode, StatusCode}; use sp_arithmetic::traits::Saturating; -use sp_std::cmp::Ord; -use sp_std::collections::btree_set::BTreeSet; -use sp_std::fmt::Debug; -use sp_std::prelude::Vec; +use sp_std::{cmp::Ord, collections::btree_set::BTreeSet, fmt::Debug, prelude::Vec}; -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; pub type StatusUpdateId = u64; @@ -85,9 +80,11 @@ impl Votes { /// democracy pallet in FRAME with restricted functionality. #[derive(Encode, Decode, Default, Clone, PartialEq, Debug)] pub struct Tally { - /// Set of accounts which have voted FOR this status update. This can be either Staked Relayers or the Governance Mechanism. + /// Set of accounts which have voted FOR this status update. This can be either Staked Relayers or the Governance + /// Mechanism. pub(crate) aye: Votes, - /// Set of accounts which have voted AGAINST this status update. This can be either Staked Relayers or the Governance Mechanism. + /// Set of accounts which have voted AGAINST this status update. This can be either Staked Relayers or the + /// Governance Mechanism. pub(crate) nay: Votes, } diff --git a/crates/treasury/src/lib.rs b/crates/treasury/src/lib.rs index 19167d506e..91f4dbd0af 100644 --- a/crates/treasury/src/lib.rs +++ b/crates/treasury/src/lib.rs @@ -13,14 +13,15 @@ mod tests; #[cfg(test)] extern crate mocktopus; -use frame_support::traits::{Currency, ExistenceRequirement, ReservableCurrency}; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, dispatch::DispatchResult, ensure, + decl_error, decl_event, decl_module, decl_storage, + dispatch::DispatchResult, + ensure, + traits::{Currency, ExistenceRequirement, ReservableCurrency}, }; use sp_runtime::ModuleId; -type BalanceOf = - <::PolkaBTC as Currency<::AccountId>>::Balance; +type BalanceOf = <::PolkaBTC as Currency<::AccountId>>::Balance; /// The treasury's module id, used for deriving its sovereign account ID. const _MODULE_ID: ModuleId = ModuleId(*b"ily/trsy"); @@ -189,17 +190,8 @@ impl Module { /// * `source` - the account transferring tokens /// * `destination` - the account receiving tokens /// * `amount` - amount of PolkaBTC - pub fn transfer( - source: T::AccountId, - destination: T::AccountId, - amount: BalanceOf, - ) -> DispatchResult { - T::PolkaBTC::transfer( - &source, - &destination, - amount, - ExistenceRequirement::AllowDeath, - ) + pub fn transfer(source: T::AccountId, destination: T::AccountId, amount: BalanceOf) -> DispatchResult { + T::PolkaBTC::transfer(&source, &destination, amount, ExistenceRequirement::AllowDeath) } /// Transfer locked PolkaBTC to the free balance of another account diff --git a/crates/treasury/src/mock.rs b/crates/treasury/src/mock.rs index 4a8fd08cf1..397b60ed46 100644 --- a/crates/treasury/src/mock.rs +++ b/crates/treasury/src/mock.rs @@ -90,9 +90,7 @@ pub struct ExtBuilder; impl ExtBuilder { pub fn build() -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); pallet_balances::GenesisConfig:: { balances: vec![(ALICE, ALICE_BALANCE), (BOB, BOB_BALANCE)], diff --git a/crates/treasury/src/tests.rs b/crates/treasury/src/tests.rs index 94e2adac44..73da40dfe5 100644 --- a/crates/treasury/src/tests.rs +++ b/crates/treasury/src/tests.rs @@ -75,10 +75,7 @@ fn test_lock_fails() { let init_locked_balance = Treasury::get_locked_balance_from_account(ALICE); let init_total_supply = Treasury::get_total_supply(); - assert_err!( - Treasury::lock(redeemer, amount), - TestError::InsufficientFunds - ); + assert_err!(Treasury::lock(redeemer, amount), TestError::InsufficientFunds); let balance = Treasury::get_balance_from_account(ALICE); let locked_balance = Treasury::get_locked_balance_from_account(ALICE); @@ -127,10 +124,7 @@ fn test_burn_fails() { let init_locked_balance = Treasury::get_locked_balance_from_account(ALICE); let init_total_supply = Treasury::get_total_supply(); - assert_err!( - Treasury::burn(redeemer, amount), - TestError::InsufficientLockedFunds - ); + assert_err!(Treasury::burn(redeemer, amount), TestError::InsufficientLockedFunds); let balance = Treasury::get_balance_from_account(ALICE); let locked_balance = Treasury::get_locked_balance_from_account(ALICE); diff --git a/crates/vault-registry/rpc/src/lib.rs b/crates/vault-registry/rpc/src/lib.rs index a3c9788c92..faa0c09d41 100644 --- a/crates/vault-registry/rpc/src/lib.rs +++ b/crates/vault-registry/rpc/src/lib.rs @@ -8,8 +8,11 @@ use module_exchange_rate_oracle_rpc_runtime_api::BalanceWrapper; pub use module_vault_registry_rpc_runtime_api::VaultRegistryApi as VaultRegistryRuntimeApi; use sp_api::ProvideRuntimeApi; use sp_blockchain::HeaderBackend; -use sp_runtime::traits::{MaybeDisplay, MaybeFromStr}; -use sp_runtime::{generic::BlockId, traits::Block as BlockT, DispatchError}; +use sp_runtime::{ + generic::BlockId, + traits::{Block as BlockT, MaybeDisplay, MaybeFromStr}, + DispatchError, +}; use std::sync::Arc; #[rpc] @@ -20,10 +23,7 @@ where UnsignedFixedPoint: Codec + MaybeDisplay + MaybeFromStr, { #[rpc(name = "vaultRegistry_getTotalCollateralization")] - fn get_total_collateralization( - &self, - at: Option, - ) -> JsonRpcResult; + fn get_total_collateralization(&self, at: Option) -> JsonRpcResult; #[rpc(name = "vaultRegistry_getFirstVaultWithSufficientCollateral")] fn get_first_vault_with_sufficient_collateral( @@ -90,11 +90,7 @@ where ) -> JsonRpcResult>; #[rpc(name = "vaultRegistry_isVaultBelowAuctionThreshold")] - fn is_vault_below_auction_threshold( - &self, - vault: AccountId, - at: Option, - ) -> JsonRpcResult; + fn is_vault_below_auction_threshold(&self, vault: AccountId, at: Option) -> JsonRpcResult; } /// A struct that implements the [`VaultRegistryApi`]. @@ -148,8 +144,7 @@ fn handle_response( } impl - VaultRegistryApi<::Hash, AccountId, PolkaBTC, DOT, UnsignedFixedPoint> - for VaultRegistry + VaultRegistryApi<::Hash, AccountId, PolkaBTC, DOT, UnsignedFixedPoint> for VaultRegistry where Block: BlockT, C: Send + Sync + 'static + ProvideRuntimeApi + HeaderBackend, @@ -159,10 +154,7 @@ where DOT: Codec + MaybeDisplay + MaybeFromStr, UnsignedFixedPoint: Codec + MaybeDisplay + MaybeFromStr, { - fn get_total_collateralization( - &self, - at: Option<::Hash>, - ) -> JsonRpcResult { + fn get_total_collateralization(&self, at: Option<::Hash>) -> JsonRpcResult { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); @@ -266,12 +258,7 @@ where let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); handle_response( - api.get_collateralization_from_vault_and_collateral( - &at, - vault, - collateral, - only_issued, - ), + api.get_collateralization_from_vault_and_collateral(&at, vault, collateral, only_issued), "Unable to get collateralization from vault.".into(), ) } @@ -297,23 +284,22 @@ where ) -> JsonRpcResult> { let api = self.client.runtime_api(); let at = BlockId::hash(at.unwrap_or_else(|| self.client.info().best_hash)); - api.get_required_collateral_for_vault(&at, vault_id) - .map_or_else( - |e| { - Err(RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to get required collateral for vault.".into(), - data: Some(format!("{:?}", e).into()), - }) - }, - |result| { - result.map_err(|e| RpcError { - code: ErrorCode::ServerError(Error::RuntimeError.into()), - message: "Unable to get required collateral for vault.".into(), - data: Some(format!("{:?}", e).into()), - }) - }, - ) + api.get_required_collateral_for_vault(&at, vault_id).map_or_else( + |e| { + Err(RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to get required collateral for vault.".into(), + data: Some(format!("{:?}", e).into()), + }) + }, + |result| { + result.map_err(|e| RpcError { + code: ErrorCode::ServerError(Error::RuntimeError.into()), + message: "Unable to get required collateral for vault.".into(), + data: Some(format!("{:?}", e).into()), + }) + }, + ) } fn is_vault_below_auction_threshold( diff --git a/crates/vault-registry/src/benchmarking.rs b/crates/vault-registry/src/benchmarking.rs index 561657a678..5b13537d8e 100644 --- a/crates/vault-registry/src/benchmarking.rs +++ b/crates/vault-registry/src/benchmarking.rs @@ -1,14 +1,13 @@ use super::*; -use crate::types::BtcPublicKey; -use crate::Module as VaultRegistry; +use crate::{types::BtcPublicKey, Module as VaultRegistry}; use frame_benchmarking::{account, benchmarks}; use frame_system::RawOrigin; use sp_std::prelude::*; fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } @@ -63,13 +62,9 @@ mod tests { #[test] fn test_benchmarks() { - ExtBuilder::build_with( - pallet_balances::GenesisConfig:: { - balances: (0..100) - .map(|i| (account("Origin", i, 0), 1 << 64)) - .collect(), - }, - ) + ExtBuilder::build_with(pallet_balances::GenesisConfig:: { + balances: (0..100).map(|i| (account("Origin", i, 0), 1 << 64)).collect(), + }) .execute_with(|| { assert_ok!(test_benchmark_register_vault::()); assert_ok!(test_benchmark_lock_additional_collateral::()); diff --git a/crates/vault-registry/src/ext.rs b/crates/vault-registry/src/ext.rs index be0f782d4f..9ce7167d17 100644 --- a/crates/vault-registry/src/ext.rs +++ b/crates/vault-registry/src/ext.rs @@ -18,10 +18,7 @@ pub(crate) mod collateral { >::lock_collateral(sender, amount) } - pub fn release_collateral( - sender: &T::AccountId, - amount: DOT, - ) -> DispatchResult { + pub fn release_collateral(sender: &T::AccountId, amount: DOT) -> DispatchResult { >::release_collateral(sender, amount) } @@ -48,14 +45,8 @@ pub(crate) mod oracle { use crate::types::{PolkaBTC, DOT}; use frame_support::dispatch::DispatchError; - pub trait Exchangeable: - exchange_rate_oracle::Config + ::treasury::Config + ::collateral::Config - { - } - impl Exchangeable for T where - T: exchange_rate_oracle::Config + ::treasury::Config + ::collateral::Config - { - } + pub trait Exchangeable: exchange_rate_oracle::Config + ::treasury::Config + ::collateral::Config {} + impl Exchangeable for T where T: exchange_rate_oracle::Config + ::treasury::Config + ::collateral::Config {} pub fn btc_to_dots(amount: PolkaBTC) -> Result, DispatchError> { >::btc_to_dots(amount) @@ -80,9 +71,7 @@ pub(crate) mod security { >::ensure_parachain_status_not_shutdown() } - pub fn ensure_parachain_does_not_have_errors( - error_codes: Vec, - ) -> DispatchResult { + pub fn ensure_parachain_does_not_have_errors(error_codes: Vec) -> DispatchResult { >::ensure_parachain_does_not_have_errors(error_codes) } } diff --git a/crates/vault-registry/src/lib.rs b/crates/vault-registry/src/lib.rs index 6fdeec45bb..a8e77390bc 100644 --- a/crates/vault-registry/src/lib.rs +++ b/crates/vault-registry/src/lib.rs @@ -26,25 +26,25 @@ extern crate mocktopus; use mocktopus::macros::mockable; use codec::{Decode, Encode, EncodeLike}; -use frame_support::dispatch::{DispatchError, DispatchResult}; -use frame_support::traits::Randomness; -use frame_support::transactional; -use frame_support::weights::Weight; use frame_support::{ - decl_error, decl_event, decl_module, decl_storage, ensure, IterableStorageMap, + decl_error, decl_event, decl_module, decl_storage, + dispatch::{DispatchError, DispatchResult}, + ensure, + traits::Randomness, + transactional, + weights::Weight, + IterableStorageMap, }; use frame_system::ensure_signed; use primitive_types::U256; use security::ErrorCode; -use sp_arithmetic::traits::*; -use sp_arithmetic::FixedPointNumber; +use sp_arithmetic::{traits::*, FixedPointNumber}; use sp_core::H256; -use sp_std::convert::TryInto; -use sp_std::vec::Vec; +use sp_std::{convert::TryInto, vec::Vec}; use crate::types::{ - BtcAddress, DefaultSystemVault, DefaultVault, Inner, PolkaBTC, RichSystemVault, RichVault, - UnsignedFixedPoint, UpdatableVault, Version, DOT, + BtcAddress, DefaultSystemVault, DefaultVault, Inner, PolkaBTC, RichSystemVault, RichVault, UnsignedFixedPoint, + UpdatableVault, Version, DOT, }; #[doc(inline)] pub use crate::types::{BtcPublicKey, CurrencySource, SystemVault, Vault, VaultStatus, Wallet}; @@ -68,11 +68,7 @@ pub trait WeightInfo { /// ## Configuration and Constants /// The pallet's configuration trait. pub trait Config: - frame_system::Config - + collateral::Config - + treasury::Config - + exchange_rate_oracle::Config - + security::Config + frame_system::Config + collateral::Config + treasury::Config + exchange_rate_oracle::Config + security::Config { /// The overarching event type. type Event: From> + Into<::Event>; @@ -285,9 +281,7 @@ impl Module { // initialize TotalUserVaultBackingCollateral let total = >::iter() .map(|(_, vault)| vault.backing_collateral) - .fold(Some(0u32.into()), |total: Option>, x| { - total?.checked_add(&x) - }) + .fold(Some(0u32.into()), |total: Option>, x| total?.checked_add(&x)) .unwrap_or(0u32.into()); >::set(total); @@ -295,21 +289,14 @@ impl Module { /// Public functions - pub fn _register_vault( - vault_id: &T::AccountId, - collateral: DOT, - public_key: BtcPublicKey, - ) -> DispatchResult { + pub fn _register_vault(vault_id: &T::AccountId, collateral: DOT, public_key: BtcPublicKey) -> DispatchResult { ext::security::ensure_parachain_status_running::()?; ensure!( collateral >= Self::get_minimum_collateral_vault(), Error::::InsufficientVaultCollateralAmount ); - ensure!( - !Self::vault_exists(vault_id), - Error::::VaultAlreadyRegistered - ); + ensure!(!Self::vault_exists(vault_id), Error::::VaultAlreadyRegistered); let vault = Vault::new(vault_id.clone(), public_key).into(); Self::insert_vault(vault_id, vault); @@ -333,14 +320,9 @@ impl Module { } /// Like get_vault_from_id, but additionally checks that the vault is active - pub fn get_active_vault_from_id( - vault_id: &T::AccountId, - ) -> Result, DispatchError> { + pub fn get_active_vault_from_id(vault_id: &T::AccountId) -> Result, DispatchError> { let vault = Self::get_vault_from_id(vault_id)?; - ensure!( - vault.status == VaultStatus::Active, - Error::::VaultNotFound - ); + ensure!(vault.status == VaultStatus::Active, Error::::VaultNotFound); Ok(vault) } @@ -348,10 +330,7 @@ impl Module { >::get() } - pub fn try_lock_additional_collateral( - vault_id: &T::AccountId, - amount: DOT, - ) -> DispatchResult { + pub fn try_lock_additional_collateral(vault_id: &T::AccountId, amount: DOT) -> DispatchResult { let mut vault = Self::get_active_rich_vault_from_id(vault_id)?; // will fail if free_balance is insufficient @@ -386,10 +365,7 @@ impl Module { } /// checks if the vault would be above the secure threshold after withdrawing collateral - pub fn is_allowed_to_withdraw_collateral( - vault_id: &T::AccountId, - amount: DOT, - ) -> Result { + pub fn is_allowed_to_withdraw_collateral(vault_id: &T::AccountId, amount: DOT) -> Result { let vault = Self::get_vault_from_id(vault_id)?; let new_collateral = match vault.backing_collateral.checked_sub(&amount) { @@ -402,8 +378,7 @@ impl Module { .checked_add(&vault.to_be_issued_tokens) .ok_or(Error::::ArithmeticOverflow)?; - let is_below_threshold = - Module::::is_collateral_below_secure_threshold(new_collateral, tokens)?; + let is_below_threshold = Module::::is_collateral_below_secure_threshold(new_collateral, tokens)?; Ok(!is_below_threshold) } @@ -423,11 +398,7 @@ impl Module { Ok(amount) } - pub fn slash_collateral( - from: CurrencySource, - to: CurrencySource, - amount: DOT, - ) -> DispatchResult { + pub fn slash_collateral(from: CurrencySource, to: CurrencySource, amount: DOT) -> DispatchResult { // move funds to free balance of the source match from { CurrencySource::Backing(ref account) => { @@ -465,10 +436,7 @@ impl Module { /// # Arguments /// * `vault_id` - the id of the vault from which to increase to-be-issued tokens /// * `tokens` - the amount of tokens to be reserved - pub fn try_increase_to_be_issued_tokens( - vault_id: &T::AccountId, - tokens: PolkaBTC, - ) -> Result<(), DispatchError> { + pub fn try_increase_to_be_issued_tokens(vault_id: &T::AccountId, tokens: PolkaBTC) -> Result<(), DispatchError> { ext::security::ensure_parachain_status_running::()?; let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?; @@ -484,10 +452,7 @@ impl Module { /// /// # Arguments /// * `issue_id` - secure id for generating deposit address - pub fn register_deposit_address( - vault_id: &T::AccountId, - issue_id: H256, - ) -> Result { + pub fn register_deposit_address(vault_id: &T::AccountId, issue_id: H256) -> Result { let mut vault = Self::get_active_rich_vault_from_id(&vault_id)?; let btc_address = vault.new_deposit_address(issue_id)?; Self::deposit_event(Event::::RegisterAddress(vault.id(), btc_address)); @@ -525,10 +490,7 @@ impl Module { Ok(()) } - pub fn decrease_to_be_replaced_tokens( - vault_id: &T::AccountId, - tokens: PolkaBTC, - ) -> Result<(), DispatchError> { + pub fn decrease_to_be_replaced_tokens(vault_id: &T::AccountId, tokens: PolkaBTC) -> Result<(), DispatchError> { ext::security::ensure_parachain_status_running::()?; let mut vault = Self::get_rich_vault_from_id(&vault_id)?; vault.decrease_to_be_replaced(tokens)?; @@ -542,10 +504,7 @@ impl Module { /// # Arguments /// * `vault_id` - the id of the vault from which to decrease to-be-issued tokens /// * `tokens` - the amount of tokens to be unreserved - pub fn decrease_to_be_issued_tokens( - vault_id: &T::AccountId, - tokens: PolkaBTC, - ) -> DispatchResult { + pub fn decrease_to_be_issued_tokens(vault_id: &T::AccountId, tokens: PolkaBTC) -> DispatchResult { Self::check_parachain_not_shutdown_and_not_errors( [ ErrorCode::InvalidBTCRelay, @@ -558,10 +517,7 @@ impl Module { let mut vault = Self::get_rich_vault_from_id(vault_id)?; vault.decrease_to_be_issued(tokens)?; - Self::deposit_event(Event::::DecreaseToBeIssuedTokens( - vault_id.clone(), - tokens, - )); + Self::deposit_event(Event::::DecreaseToBeIssuedTokens(vault_id.clone(), tokens)); Ok(()) } @@ -605,10 +561,7 @@ impl Module { /// # Errors /// * `VaultNotFound` - if no vault exists for the given `vault_id` /// * `InsufficientTokensCommitted` - if the amount of redeemable tokens is too low - pub fn try_increase_to_be_redeemed_tokens( - vault_id: &T::AccountId, - tokens: PolkaBTC, - ) -> DispatchResult { + pub fn try_increase_to_be_redeemed_tokens(vault_id: &T::AccountId, tokens: PolkaBTC) -> DispatchResult { Self::check_parachain_not_shutdown_and_not_errors( [ ErrorCode::InvalidBTCRelay, @@ -623,10 +576,7 @@ impl Module { .issued_tokens .checked_sub(&vault.data.to_be_redeemed_tokens) .ok_or(Error::::ArithmeticUnderflow)?; - ensure!( - redeemable >= tokens, - Error::::InsufficientTokensCommitted - ); + ensure!(redeemable >= tokens, Error::::InsufficientTokensCommitted); vault.increase_to_be_redeemed(tokens)?; @@ -643,10 +593,7 @@ impl Module { /// # Errors /// * `VaultNotFound` - if no vault exists for the given `vault_id` /// * `InsufficientTokensCommitted` - if the amount of to-be-redeemed tokens is too low - pub fn decrease_to_be_redeemed_tokens( - vault_id: &T::AccountId, - tokens: PolkaBTC, - ) -> DispatchResult { + pub fn decrease_to_be_redeemed_tokens(vault_id: &T::AccountId, tokens: PolkaBTC) -> DispatchResult { Self::check_parachain_not_shutdown_and_not_errors( [ ErrorCode::InvalidBTCRelay, @@ -672,11 +619,7 @@ impl Module { /// * `vault_id` - the id of the vault from which to decrease tokens /// * `tokens` - the amount of tokens to be decreased /// * `user_id` - the id of the user making the redeem request - pub fn decrease_tokens( - vault_id: &T::AccountId, - user_id: &T::AccountId, - tokens: PolkaBTC, - ) -> DispatchResult { + pub fn decrease_tokens(vault_id: &T::AccountId, user_id: &T::AccountId, tokens: PolkaBTC) -> DispatchResult { Self::check_parachain_not_shutdown_and_not_errors( [ ErrorCode::InvalidBTCRelay, @@ -689,11 +632,7 @@ impl Module { let mut vault = Self::get_rich_vault_from_id(&vault_id)?; vault.decrease_tokens(tokens)?; - Self::deposit_event(Event::::DecreaseTokens( - vault.id(), - user_id.clone(), - tokens, - )); + Self::deposit_event(Event::::DecreaseTokens(vault.id(), user_id.clone(), tokens)); Ok(()) } @@ -769,16 +708,12 @@ impl Module { /// /// # Arguments /// * `redeemer_id` - the account of the user redeeming PolkaBTC - /// * `tokens` - the amount of PolkaBTC to be redeemed in DOT with the - /// LiquidationVault, denominated in BTC + /// * `tokens` - the amount of PolkaBTC to be redeemed in DOT with the LiquidationVault, denominated in BTC /// /// # Errors /// * `InsufficientTokensCommitted` - if the amount of tokens issued by the liquidation vault is too low /// * `InsufficientFunds` - if the liquidation vault does not have enough collateral to transfer - pub fn redeem_tokens_liquidation( - redeemer_id: &T::AccountId, - amount_btc: PolkaBTC, - ) -> DispatchResult { + pub fn redeem_tokens_liquidation(redeemer_id: &T::AccountId, amount_btc: PolkaBTC) -> DispatchResult { Self::check_parachain_not_shutdown_and_not_errors( [ErrorCode::InvalidBTCRelay, ErrorCode::OracleOffline].to_vec(), )?; @@ -847,13 +782,9 @@ impl Module { if old_vault.data.is_liquidated() { // release old-vault's collateral - let current_backing = - CurrencySource::::Backing(old_vault_id.clone()).current_balance()?; - let to_be_released = Self::calculate_collateral( - current_backing, - tokens, - old_vault.data.to_be_redeemed_tokens, - )?; + let current_backing = CurrencySource::::Backing(old_vault_id.clone()).current_balance()?; + let to_be_released = + Self::calculate_collateral(current_backing, tokens, old_vault.data.to_be_redeemed_tokens)?; Self::force_withdraw_collateral(&old_vault_id, to_be_released)?; } @@ -955,10 +886,7 @@ impl Module { /// /// # Errors /// * `VaultNotFound` - if the vault to liquidate does not exist - pub fn liquidate_vault_with_status( - vault_id: &T::AccountId, - status: VaultStatus, - ) -> DispatchResult { + pub fn liquidate_vault_with_status(vault_id: &T::AccountId, status: VaultStatus) -> DispatchResult { // Parachain must not be shutdown ext::security::ensure_parachain_status_not_shutdown::()?; @@ -1001,9 +929,7 @@ impl Module { } /// returns the total number of issued tokens - pub fn get_total_issued_tokens( - include_liquidation_vault: bool, - ) -> Result, DispatchError> { + pub fn get_total_issued_tokens(include_liquidation_vault: bool) -> Result, DispatchError> { if include_liquidation_vault { Ok(ext::treasury::total_issued::()) } else { @@ -1014,9 +940,7 @@ impl Module { } /// returns the total locked collateral, _ - pub fn get_total_backing_collateral( - include_liquidation_vault: bool, - ) -> Result, DispatchError> { + pub fn get_total_backing_collateral(include_liquidation_vault: bool) -> Result, DispatchError> { let liquidated_collateral = CurrencySource::::LiquidationVault.current_balance()?; let total = if include_liquidation_vault { >::get() @@ -1029,10 +953,7 @@ impl Module { Ok(total) } - pub fn insert_vault( - id: &T::AccountId, - vault: Vault, DOT>, - ) { + pub fn insert_vault(id: &T::AccountId, vault: Vault, DOT>) { >::insert(id, vault) } @@ -1057,23 +978,17 @@ impl Module { Ok(Self::get_vault_from_id(&vault_id)?.is_liquidated()) } - pub fn is_vault_below_auction_threshold( - vault_id: &T::AccountId, - ) -> Result { + pub fn is_vault_below_auction_threshold(vault_id: &T::AccountId) -> Result { Self::is_vault_below_threshold(&vault_id, >::get()) } - pub fn is_vault_below_premium_threshold( - vault_id: &T::AccountId, - ) -> Result { + pub fn is_vault_below_premium_threshold(vault_id: &T::AccountId) -> Result { Self::is_vault_below_threshold(&vault_id, >::get()) } /// check if the vault is below the liquidation threshold. In contrast to other thresholds, /// this is checked as ratio of `collateral / (issued - to_be_redeemed)`. - pub fn is_vault_below_liquidation_threshold( - vault_id: &T::AccountId, - ) -> Result { + pub fn is_vault_below_liquidation_threshold(vault_id: &T::AccountId) -> Result { let vault = Self::get_rich_vault_from_id(&vault_id)?; // the current locked backing collateral by the vault @@ -1086,11 +1001,7 @@ impl Module { .checked_sub(&vault.data.to_be_redeemed_tokens) .ok_or(Error::::ArithmeticUnderflow)?; - Self::is_collateral_below_threshold( - collateral, - tokens, - >::get(), - ) + Self::is_collateral_below_threshold(collateral, tokens, >::get()) } pub fn is_collateral_below_secure_threshold( @@ -1171,9 +1082,7 @@ impl Module { /// Get the first available vault with sufficient collateral to fulfil an issue request /// with the specified amount of PolkaBTC. - pub fn get_first_vault_with_sufficient_collateral( - amount: PolkaBTC, - ) -> Result { + pub fn get_first_vault_with_sufficient_collateral(amount: PolkaBTC) -> Result { // find all vault accounts with sufficient collateral let suitable_vaults = >::iter() .filter_map(|v| { @@ -1197,9 +1106,7 @@ impl Module { } /// Get the first available vault with sufficient locked PolkaBTC to fulfil a redeem request. - pub fn get_first_vault_with_sufficient_tokens( - amount: PolkaBTC, - ) -> Result { + pub fn get_first_vault_with_sufficient_tokens(amount: PolkaBTC) -> Result { // find all vault accounts with sufficient collateral let suitable_vaults = >::iter() .filter_map(|v| { @@ -1225,8 +1132,8 @@ impl Module { /// Get all vaults below the premium redeem threshold /// Checks three conditions: /// 1. the vault must have tokens issued - /// 2. the vault must be available to redeem tokens (not all issued tokens currently bein part of redeem/replace processes) - /// 3. the vault must be below the premium redeem threshold + /// 2. the vault must be available to redeem tokens (not all issued tokens currently bein part of redeem/replace + /// processes) 3. the vault must be below the premium redeem threshold /// /// Maybe returns a tuple of (VaultId, RedeemableTokens) /// The redeemable tokens are the currently vault.issued_tokens - the vault.to_be_redeemed_tokens @@ -1243,9 +1150,7 @@ impl Module { { Some(( account_id, - vault - .issued_tokens - .saturating_sub(vault.to_be_redeemed_tokens), + vault.issued_tokens.saturating_sub(vault.to_be_redeemed_tokens), )) } else { None @@ -1262,8 +1167,7 @@ impl Module { } /// Get all vaults with non-zero issuable tokens, ordered in descending order of this amount - pub fn get_vaults_with_issuable_tokens( - ) -> Result)>, DispatchError> { + pub fn get_vaults_with_issuable_tokens() -> Result)>, DispatchError> { let mut vaults_with_issuable_tokens = >::iter() .filter_map(|(account_id, _vault)| { // iterator returns tuple of (AccountId, Vault), @@ -1289,9 +1193,7 @@ impl Module { } /// Get the amount of tokens a vault can issue - pub fn get_issuable_tokens_from_vault( - vault_id: T::AccountId, - ) -> Result, DispatchError> { + pub fn get_issuable_tokens_from_vault(vault_id: T::AccountId) -> Result, DispatchError> { let vault = Self::get_active_rich_vault_from_id(&vault_id)?; vault.issuable_tokens() } @@ -1334,22 +1236,17 @@ impl Module { /// /// # Arguments /// * `amount_btc` - the amount of polkabtc - pub fn get_required_collateral_for_polkabtc( - amount_btc: PolkaBTC, - ) -> Result, DispatchError> { + pub fn get_required_collateral_for_polkabtc(amount_btc: PolkaBTC) -> Result, DispatchError> { ext::security::ensure_parachain_status_running::()?; let threshold = >::get(); - let collateral = - Self::get_required_collateral_for_polkabtc_with_threshold(amount_btc, threshold)?; + let collateral = Self::get_required_collateral_for_polkabtc_with_threshold(amount_btc, threshold)?; Ok(collateral) } /// Get the amount of collateral required for the given vault to be at the /// current SecureCollateralThreshold with the current exchange rate - pub fn get_required_collateral_for_vault( - vault_id: T::AccountId, - ) -> Result, DispatchError> { + pub fn get_required_collateral_for_vault(vault_id: T::AccountId) -> Result, DispatchError> { ext::security::ensure_parachain_status_running::()?; let vault = Self::get_active_rich_vault_from_id(&vault_id)?; @@ -1367,9 +1264,7 @@ impl Module { } /// Like get_rich_vault_from_id, but only returns active vaults - fn get_active_rich_vault_from_id( - vault_id: &T::AccountId, - ) -> Result, DispatchError> { + fn get_active_rich_vault_from_id(vault_id: &T::AccountId) -> Result, DispatchError> { Ok(Self::get_active_vault_from_id(vault_id)?.into()) } @@ -1411,7 +1306,6 @@ impl Module { /// # Arguments /// /// * `error_codes` - list of `ErrorCode` to be checked - /// fn check_parachain_not_shutdown_and_not_errors(error_codes: Vec) -> DispatchResult { // Parachain must not be shutdown ext::security::ensure_parachain_status_not_shutdown::()?; @@ -1425,11 +1319,9 @@ impl Module { raw_collateral_in_polka_btc: u128, raw_issued_tokens: u128, ) -> Result, DispatchError> { - let collateralization = UnsignedFixedPoint::::checked_from_rational( - raw_collateral_in_polka_btc, - raw_issued_tokens, - ) - .ok_or(Error::::TryIntoIntError)?; + let collateralization = + UnsignedFixedPoint::::checked_from_rational(raw_collateral_in_polka_btc, raw_issued_tokens) + .ok_or(Error::::TryIntoIntError)?; Ok(collateralization) } @@ -1453,8 +1345,7 @@ impl Module { btc_amount: PolkaBTC, threshold: UnsignedFixedPoint, ) -> Result { - let max_tokens = - Self::calculate_max_polkabtc_from_collateral_for_threshold(collateral, threshold)?; + let max_tokens = Self::calculate_max_polkabtc_from_collateral_for_threshold(collateral, threshold)?; // check if the max_tokens are below the issued tokens Ok(max_tokens < btc_amount) } @@ -1491,8 +1382,8 @@ impl Module { let collateral_in_polka_btc = Self::polkabtc_to_u128(collateral_in_polka_btc)?; // calculate how many tokens should be maximally issued given the threshold. - let collateral_as_inner = TryInto::>::try_into(collateral_in_polka_btc) - .map_err(|_| Error::::TryIntoIntError)?; + let collateral_as_inner = + TryInto::>::try_into(collateral_in_polka_btc).map_err(|_| Error::::TryIntoIntError)?; let max_btc_as_inner = UnsignedFixedPoint::::checked_from_integer(collateral_as_inner) .ok_or(Error::::TryIntoIntError)? .checked_div(&threshold) @@ -1521,10 +1412,7 @@ impl Module { TryInto::>::try_into(x).map_err(|_| Error::::TryIntoIntError.into()) } - pub fn insert_vault_deposit_address( - vault_id: &T::AccountId, - btc_address: BtcAddress, - ) -> DispatchResult { + pub fn insert_vault_deposit_address(vault_id: &T::AccountId, btc_address: BtcAddress) -> DispatchResult { ensure!( !>::contains_key(&btc_address), Error::::ReservedDepositAddress @@ -1535,10 +1423,7 @@ impl Module { Ok(()) } - pub fn new_vault_deposit_address( - vault_id: &T::AccountId, - secure_id: H256, - ) -> Result { + pub fn new_vault_deposit_address(vault_id: &T::AccountId, secure_id: H256) -> Result { let mut vault = Self::get_active_rich_vault_from_id(vault_id)?; let btc_address = vault.new_deposit_address(secure_id)?; Ok(btc_address) @@ -1618,8 +1503,7 @@ impl CheckedMulIntRoundedUp for T { let product = self.checked_mul(&n_fixed_point)?; // convert to inner - let product_inner = - UniqueSaturatedInto::::unique_saturated_into(product.into_inner()); + let product_inner = UniqueSaturatedInto::::unique_saturated_into(product.into_inner()); // convert to u128 by dividing by a rounded up division by accuracy let accuracy = UniqueSaturatedInto::::unique_saturated_into(T::accuracy()); diff --git a/crates/vault-registry/src/mock.rs b/crates/vault-registry/src/mock.rs index fcbd52347f..80c9915c97 100644 --- a/crates/vault-registry/src/mock.rs +++ b/crates/vault-registry/src/mock.rs @@ -1,9 +1,7 @@ use crate as vault_registry; use crate::{ext, Config, Error}; -use frame_support::parameter_types; -use frame_support::traits::StorageMapShim; -use mocktopus::mocking::clear_mocks; -use mocktopus::mocking::{MockResult, Mockable}; +use frame_support::{parameter_types, traits::StorageMapShim}; +use mocktopus::mocking::{clear_mocks, MockResult, Mockable}; use sp_arithmetic::{FixedPointNumber, FixedU128}; use sp_core::H256; use sp_runtime::{ @@ -166,9 +164,7 @@ impl ExtBuilder { pub fn build_with( conf: pallet_balances::GenesisConfig, ) -> sp_io::TestExternalities { - let mut storage = frame_system::GenesisConfig::default() - .build_storage::() - .unwrap(); + let mut storage = frame_system::GenesisConfig::default().build_storage::().unwrap(); conf.assimilate_storage(&mut storage).unwrap(); @@ -192,19 +188,17 @@ impl ExtBuilder { sp_io::TestExternalities::from(storage) } pub fn build() -> sp_io::TestExternalities { - ExtBuilder::build_with( - pallet_balances::GenesisConfig:: { - balances: vec![ - (DEFAULT_ID, DEFAULT_COLLATERAL), - (OTHER_ID, DEFAULT_COLLATERAL), - (RICH_ID, RICH_COLLATERAL), - (MULTI_VAULT_TEST_IDS[0], MULTI_VAULT_TEST_COLLATERAL), - (MULTI_VAULT_TEST_IDS[1], MULTI_VAULT_TEST_COLLATERAL), - (MULTI_VAULT_TEST_IDS[2], MULTI_VAULT_TEST_COLLATERAL), - (MULTI_VAULT_TEST_IDS[3], MULTI_VAULT_TEST_COLLATERAL), - ], - }, - ) + ExtBuilder::build_with(pallet_balances::GenesisConfig:: { + balances: vec![ + (DEFAULT_ID, DEFAULT_COLLATERAL), + (OTHER_ID, DEFAULT_COLLATERAL), + (RICH_ID, RICH_COLLATERAL), + (MULTI_VAULT_TEST_IDS[0], MULTI_VAULT_TEST_COLLATERAL), + (MULTI_VAULT_TEST_IDS[1], MULTI_VAULT_TEST_COLLATERAL), + (MULTI_VAULT_TEST_IDS[2], MULTI_VAULT_TEST_COLLATERAL), + (MULTI_VAULT_TEST_IDS[3], MULTI_VAULT_TEST_COLLATERAL), + ], + }) } } diff --git a/crates/vault-registry/src/tests.rs b/crates/vault-registry/src/tests.rs index 61902c944d..3114f90c1b 100644 --- a/crates/vault-registry/src/tests.rs +++ b/crates/vault-registry/src/tests.rs @@ -1,23 +1,21 @@ -use crate::ext; -use crate::mock::{ - run_test, CollateralError, Origin, SecurityError, System, Test, TestError, TestEvent, - VaultRegistry, DEFAULT_COLLATERAL, DEFAULT_ID, MULTI_VAULT_TEST_COLLATERAL, - MULTI_VAULT_TEST_IDS, OTHER_ID, RICH_COLLATERAL, RICH_ID, +use crate::{ + ext, + mock::{ + run_test, CollateralError, Origin, SecurityError, System, Test, TestError, TestEvent, VaultRegistry, + DEFAULT_COLLATERAL, DEFAULT_ID, MULTI_VAULT_TEST_COLLATERAL, MULTI_VAULT_TEST_IDS, OTHER_ID, RICH_COLLATERAL, + RICH_ID, + }, + sp_api_hidden_includes_decl_storage::hidden_include::traits::OnInitialize, + types::{BtcAddress, PolkaBTC, DOT}, + BtcPublicKey, CurrencySource, DispatchError, Error, UpdatableVault, Vault, VaultStatus, Vaults, Wallet, H256, }; -use crate::sp_api_hidden_includes_decl_storage::hidden_include::traits::OnInitialize; -use crate::types::{BtcAddress, PolkaBTC, DOT}; -use crate::DispatchError; -use crate::Error; -use crate::H256; -use crate::{BtcPublicKey, CurrencySource, UpdatableVault, Vault, VaultStatus, Vaults, Wallet}; use frame_support::{assert_err, assert_noop, assert_ok, StorageMap}; use mocktopus::mocking::*; use primitive_types::U256; use sp_arithmetic::{FixedPointNumber, FixedU128}; use sp_runtime::traits::Header; use sp_std::convert::TryInto; -use std::collections::HashMap; -use std::rc::Rc; +use std::{collections::HashMap, rc::Rc}; type Event = crate::Event; @@ -30,10 +28,7 @@ macro_rules! assert_emitted { ($event:expr, $times:expr) => { let test_event = TestEvent::vault_registry($event); assert_eq!( - System::events() - .iter() - .filter(|a| a.event == test_event) - .count(), + System::events().iter().filter(|a| a.event == test_event).count(), $times ); }; @@ -60,15 +55,12 @@ fn set_default_thresholds() { fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } -fn create_vault_with_collateral( - id: u64, - collateral: u128, -) -> ::AccountId { +fn create_vault_with_collateral(id: u64, collateral: u128) -> ::AccountId { VaultRegistry::get_minimum_collateral_vault.mock_safe(move || MockResult::Return(collateral)); let origin = Origin::signed(id); let result = VaultRegistry::register_vault(origin, collateral, dummy_public_key()); @@ -98,10 +90,7 @@ fn create_vault_and_issue_tokens( ext::oracle::dots_to_btc::.mock_safe(move |x| MockResult::Return(Ok((x / 10).into()))); // issue PolkaBTC with 200% collateralization of DEFAULT_COLLATERAL - assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens( - &id, - issue_tokens, - )); + assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens(&id, issue_tokens,)); let res = VaultRegistry::issue_tokens(&id, issue_tokens); assert_ok!(res); @@ -111,9 +100,7 @@ fn create_vault_and_issue_tokens( id } -fn create_sample_vault_andissue_tokens( - issue_tokens: u128, -) -> ::AccountId { +fn create_sample_vault_andissue_tokens(issue_tokens: u128) -> ::AccountId { create_vault_and_issue_tokens(issue_tokens, DEFAULT_COLLATERAL, DEFAULT_ID) } @@ -131,8 +118,7 @@ fn register_vault_fails_when_given_collateral_too_low() { VaultRegistry::get_minimum_collateral_vault.mock_safe(|| MockResult::Return(200)); let id = 3; let collateral = 100; - let result = - VaultRegistry::register_vault(Origin::signed(id), collateral, dummy_public_key()); + let result = VaultRegistry::register_vault(Origin::signed(id), collateral, dummy_public_key()); assert_err!(result, TestError::InsufficientVaultCollateralAmount); assert_not_emitted!(Event::RegisterVault(id, collateral)); }); @@ -142,11 +128,7 @@ fn register_vault_fails_when_given_collateral_too_low() { fn register_vault_fails_when_account_funds_too_low() { run_test(|| { let collateral = DEFAULT_COLLATERAL + 1; - let result = VaultRegistry::register_vault( - Origin::signed(DEFAULT_ID), - collateral, - dummy_public_key(), - ); + let result = VaultRegistry::register_vault(Origin::signed(DEFAULT_ID), collateral, dummy_public_key()); assert_err!(result, CollateralError::InsufficientFunds); assert_not_emitted!(Event::RegisterVault(DEFAULT_ID, collateral)); }); @@ -156,11 +138,7 @@ fn register_vault_fails_when_account_funds_too_low() { fn register_vault_fails_when_already_registered() { run_test(|| { let id = create_sample_vault(); - let result = VaultRegistry::register_vault( - Origin::signed(id), - DEFAULT_COLLATERAL, - dummy_public_key(), - ); + let result = VaultRegistry::register_vault(Origin::signed(id), DEFAULT_COLLATERAL, dummy_public_key()); assert_err!(result, TestError::VaultAlreadyRegistered); assert_emitted!(Event::RegisterVault(id, DEFAULT_COLLATERAL), 1); }); @@ -239,10 +217,7 @@ fn try_increase_to_be_issued_tokens_fails_with_insufficient_collateral() { run_test(|| { let id = create_sample_vault(); let vault = VaultRegistry::get_active_rich_vault_from_id(&id).unwrap(); - let res = VaultRegistry::try_increase_to_be_issued_tokens( - &id, - vault.issuable_tokens().unwrap() + 1, - ); + let res = VaultRegistry::try_increase_to_be_issued_tokens(&id, vault.issuable_tokens().unwrap() + 1); // important: should not change the storage state assert_noop!(res, TestError::ExceedingVaultLimit); }); @@ -292,10 +267,7 @@ fn issue_tokens_fails_with_insufficient_tokens() { run_test(|| { let id = create_sample_vault(); - assert_err!( - VaultRegistry::issue_tokens(&id, 50), - TestError::ArithmeticUnderflow - ); + assert_err!(VaultRegistry::issue_tokens(&id, 50), TestError::ArithmeticUnderflow); }); } @@ -535,11 +507,7 @@ fn redeem_tokens_liquidation_does_not_call_recover_when_unnecessary() { assert_ok!(VaultRegistry::redeem_tokens_liquidation(&user_id, 10)); let liquidation_vault = VaultRegistry::get_rich_liquidation_vault(); assert_eq!(liquidation_vault.data.issued_tokens, 15); - assert_emitted!(Event::RedeemTokensLiquidation( - user_id, - 10, - (1000 * 10) / 50 - )); + assert_emitted!(Event::RedeemTokensLiquidation(user_id, 10, (1000 * 10) / 50)); }); } @@ -569,9 +537,7 @@ fn replace_tokens_liquidation_succeeds() { VaultRegistry::try_increase_to_be_issued_tokens(&old_id, 50).unwrap(); assert_ok!(VaultRegistry::issue_tokens(&old_id, 50)); - assert_ok!(VaultRegistry::try_increase_to_be_redeemed_tokens( - &old_id, 50 - )); + assert_ok!(VaultRegistry::try_increase_to_be_redeemed_tokens(&old_id, 50)); assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens(&new_id, 50)); assert_ok!(VaultRegistry::replace_tokens(&old_id, &new_id, 50, 20)); @@ -601,9 +567,7 @@ fn cancel_replace_tokens_succeeds() { VaultRegistry::try_increase_to_be_issued_tokens(&old_id, 50).unwrap(); assert_ok!(VaultRegistry::issue_tokens(&old_id, 50)); - assert_ok!(VaultRegistry::try_increase_to_be_redeemed_tokens( - &old_id, 50 - )); + assert_ok!(VaultRegistry::try_increase_to_be_redeemed_tokens(&old_id, 50)); assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens(&new_id, 50)); assert_ok!(VaultRegistry::cancel_replace_tokens(&old_id, &new_id, 50)); @@ -653,8 +617,7 @@ fn liquidate_succeeds() { let vault_orig = >::get(&vault_id); - ext::oracle::btc_to_dots:: - .mock_safe(|_| MockResult::Return(Ok(1000000000u32.into()))); + ext::oracle::btc_to_dots::.mock_safe(|_| MockResult::Return(Ok(1000000000u32.into()))); assert_ok!(VaultRegistry::liquidate_vault(&vault_id)); @@ -672,8 +635,7 @@ fn liquidate_succeeds() { VaultStatus::Liquidated )); - let moved_collateral = (collateral_before - * (issued_tokens + to_be_issued_tokens - to_be_redeemed_tokens)) + let moved_collateral = (collateral_before * (issued_tokens + to_be_issued_tokens - to_be_redeemed_tokens)) / (issued_tokens + to_be_issued_tokens); // check liquidation_vault tokens & collateral @@ -698,10 +660,7 @@ fn liquidate_succeeds() { let user_vault_after = VaultRegistry::get_rich_vault_from_id(&vault_id).unwrap(); assert_eq!(user_vault_after.data.issued_tokens, 0); assert_eq!(user_vault_after.data.to_be_issued_tokens, 0); - assert_eq!( - user_vault_after.data.to_be_redeemed_tokens, - to_be_redeemed_tokens - ); + assert_eq!(user_vault_after.data.to_be_redeemed_tokens, to_be_redeemed_tokens); assert_eq!( ext::collateral::for_account::(&vault_id), collateral_before - moved_collateral @@ -764,8 +723,7 @@ fn liquidate_at_most_secure_threshold() { VaultStatus::Liquidated )); - let moved_collateral = (used_collateral - * (issued_tokens + to_be_issued_tokens - to_be_redeemed_tokens)) + let moved_collateral = (used_collateral * (issued_tokens + to_be_issued_tokens - to_be_redeemed_tokens)) / (to_be_issued_tokens + issued_tokens); // check liquidation_vault tokens & collateral @@ -790,10 +748,7 @@ fn liquidate_at_most_secure_threshold() { let user_vault_after = VaultRegistry::get_rich_vault_from_id(&vault_id).unwrap(); assert_eq!(user_vault_after.data.issued_tokens, 0); assert_eq!(user_vault_after.data.to_be_issued_tokens, 0); - assert_eq!( - user_vault_after.data.to_be_redeemed_tokens, - to_be_redeemed_tokens - ); + assert_eq!(user_vault_after.data.to_be_redeemed_tokens, to_be_redeemed_tokens); assert_eq!( ext::collateral::for_account::(&vault_id), used_collateral - moved_collateral @@ -840,8 +795,7 @@ fn is_collateral_below_threshold_true_succeeds() { let btc_amount = 50; let threshold = FixedU128::checked_from_rational(201, 100).unwrap(); // 201% - ext::oracle::dots_to_btc:: - .mock_safe(move |_| MockResult::Return(Ok(collateral.clone()))); + ext::oracle::dots_to_btc::.mock_safe(move |_| MockResult::Return(Ok(collateral.clone()))); assert_eq!( VaultRegistry::is_collateral_below_threshold(collateral, btc_amount, threshold), @@ -908,8 +862,7 @@ fn is_collateral_below_threshold_false_succeeds() { let btc_amount = 50; let threshold = FixedU128::checked_from_rational(200, 100).unwrap(); // 200% - ext::oracle::dots_to_btc:: - .mock_safe(move |_| MockResult::Return(Ok(collateral.clone()))); + ext::oracle::dots_to_btc::.mock_safe(move |_| MockResult::Return(Ok(collateral.clone()))); assert_eq!( VaultRegistry::is_collateral_below_threshold(collateral, btc_amount, threshold), @@ -924,13 +877,10 @@ fn calculate_max_polkabtc_from_collateral_for_threshold_succeeds() { let collateral: u128 = u64::MAX as u128; let threshold = FixedU128::checked_from_rational(200, 100).unwrap(); // 200% - ext::oracle::dots_to_btc:: - .mock_safe(move |_| MockResult::Return(Ok(collateral.clone()))); + ext::oracle::dots_to_btc::.mock_safe(move |_| MockResult::Return(Ok(collateral.clone()))); assert_eq!( - VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold( - collateral, threshold - ), + VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold(collateral, threshold), Ok((u64::MAX / 2) as u128) ); }) @@ -957,9 +907,7 @@ fn test_threshold_equivalent_to_legacy_calculation() { .checked_div(threshold.into()) .unwrap_or(0.into()); - Ok(VaultRegistry::u128_to_polkabtc( - scaled_max_tokens.try_into()?, - )?) + Ok(VaultRegistry::u128_to_polkabtc(scaled_max_tokens.try_into()?)?) } run_test(|| { @@ -968,11 +916,8 @@ fn test_threshold_equivalent_to_legacy_calculation() { for btc in random_start..random_start + 199999 { ext::oracle::dots_to_btc::.mock_safe(move |x| MockResult::Return(Ok(x.clone()))); ext::oracle::btc_to_dots::.mock_safe(move |x| MockResult::Return(Ok(x.clone()))); - let old = - legacy_calculate_max_polkabtc_from_collateral_for_threshold(btc, 199999).unwrap(); - let new = - VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold(btc, threshold) - .unwrap(); + let old = legacy_calculate_max_polkabtc_from_collateral_for_threshold(btc, 199999).unwrap(); + let new = VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold(btc, threshold).unwrap(); assert_eq!(old, new); } }) @@ -1016,8 +961,7 @@ fn test_get_required_collateral_threshold_equivalent_to_legacy_calculation_() { ext::oracle::dots_to_btc::.mock_safe(move |x| MockResult::Return(Ok(x.clone()))); ext::oracle::btc_to_dots::.mock_safe(move |x| MockResult::Return(Ok(x.clone()))); let old = legacy_get_required_collateral_for_polkabtc_with_threshold(btc, 199999); - let new = - VaultRegistry::get_required_collateral_for_polkabtc_with_threshold(btc, threshold); + let new = VaultRegistry::get_required_collateral_for_polkabtc_with_threshold(btc, threshold); assert_eq!(old, new); } }) @@ -1033,22 +977,14 @@ fn get_required_collateral_for_polkabtc_with_threshold_succeeds() { ext::oracle::btc_to_dots::.mock_safe(move |x| MockResult::Return(Ok(x.clone()))); let min_collateral = - VaultRegistry::get_required_collateral_for_polkabtc_with_threshold(btc, threshold) - .unwrap(); + VaultRegistry::get_required_collateral_for_polkabtc_with_threshold(btc, threshold).unwrap(); let max_btc_for_min_collateral = - VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold( - min_collateral, - threshold, - ) - .unwrap(); + VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold(min_collateral, threshold).unwrap(); let max_btc_for_below_min_collateral = - VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold( - min_collateral - 1, - threshold, - ) - .unwrap(); + VaultRegistry::calculate_max_polkabtc_from_collateral_for_threshold(min_collateral - 1, threshold) + .unwrap(); // Check that the amount we found is indeed the lowest amount that is sufficient for `btc` assert!(max_btc_for_min_collateral >= btc); @@ -1072,10 +1008,7 @@ fn _is_vault_below_auction_threshold_false_succeeds() { ext::collateral::for_account::.mock_safe(|_| MockResult::Return(DEFAULT_COLLATERAL)); ext::oracle::dots_to_btc::.mock_safe(|_| MockResult::Return(Ok(DEFAULT_COLLATERAL))); - assert_eq!( - VaultRegistry::is_vault_below_auction_threshold(&id), - Ok(false) - ) + assert_eq!(VaultRegistry::is_vault_below_auction_threshold(&id), Ok(false)) }); } @@ -1087,11 +1020,7 @@ fn register_vault_parachain_not_running_fails() { .mock_safe(|| MockResult::Return(Err(SecurityError::ParachainNotRunning.into()))); assert_noop!( - VaultRegistry::register_vault( - Origin::signed(DEFAULT_ID), - DEFAULT_COLLATERAL, - dummy_public_key() - ), + VaultRegistry::register_vault(Origin::signed(DEFAULT_ID), DEFAULT_COLLATERAL, dummy_public_key()), SecurityError::ParachainNotRunning ); }); @@ -1125,13 +1054,9 @@ fn is_vault_below_liquidation_threshold_true_succeeds() { assert_ok!(res); ext::collateral::for_account::.mock_safe(|_| MockResult::Return(DEFAULT_COLLATERAL)); - ext::oracle::dots_to_btc:: - .mock_safe(|_| MockResult::Return(Ok(DEFAULT_COLLATERAL / 2))); + ext::oracle::dots_to_btc::.mock_safe(|_| MockResult::Return(Ok(DEFAULT_COLLATERAL / 2))); - assert_eq!( - VaultRegistry::is_vault_below_liquidation_threshold(&id), - Ok(true) - ); + assert_eq!(VaultRegistry::is_vault_below_liquidation_threshold(&id), Ok(true)); }) } @@ -1167,10 +1092,7 @@ fn get_unsettled_collateralization_from_vault_succeeds() { let issue_tokens: u128 = DEFAULT_COLLATERAL / 10 / 4; // = 2 let id = create_sample_vault_andissue_tokens(issue_tokens); - assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens( - &id, - issue_tokens - ),); + assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens(&id, issue_tokens),); assert_eq!( VaultRegistry::get_collateralization_from_vault(id, true), @@ -1185,10 +1107,7 @@ fn get_settled_collateralization_from_vault_succeeds() { let issue_tokens: u128 = DEFAULT_COLLATERAL / 10 / 4; // = 2 let id = create_sample_vault_andissue_tokens(issue_tokens); - assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens( - &id, - issue_tokens - ),); + assert_ok!(VaultRegistry::try_increase_to_be_issued_tokens(&id, issue_tokens),); assert_eq!( VaultRegistry::get_collateralization_from_vault(id, false), @@ -1265,14 +1184,14 @@ fn get_vaults_with_issuable_tokens_succeeds() { let id1 = 3; let collateral1 = 100; create_vault_with_collateral(id1, collateral1); - let issuable_tokens1 = VaultRegistry::get_issuable_tokens_from_vault(id1.clone()) - .expect("Sample vault is unable to issue tokens"); + let issuable_tokens1 = + VaultRegistry::get_issuable_tokens_from_vault(id1.clone()).expect("Sample vault is unable to issue tokens"); let id2 = 4; let collateral2 = 50; create_vault_with_collateral(id2, collateral2); - let issuable_tokens2 = VaultRegistry::get_issuable_tokens_from_vault(id2.clone()) - .expect("Sample vault is unable to issue tokens"); + let issuable_tokens2 = + VaultRegistry::get_issuable_tokens_from_vault(id2.clone()).expect("Sample vault is unable to issue tokens"); // Check result is ordered in descending order assert_eq!(issuable_tokens1.gt(&issuable_tokens2), true); @@ -1289,8 +1208,8 @@ fn get_vaults_with_issuable_tokens_succeeds_when_there_are_liquidated_vaults() { let id1 = 3; let collateral1 = 100; create_vault_with_collateral(id1, collateral1); - let issuable_tokens1 = VaultRegistry::get_issuable_tokens_from_vault(id1.clone()) - .expect("Sample vault is unable to issue tokens"); + let issuable_tokens1 = + VaultRegistry::get_issuable_tokens_from_vault(id1.clone()).expect("Sample vault is unable to issue tokens"); let id2 = 4; let collateral2 = 50; @@ -1315,8 +1234,8 @@ fn get_vaults_with_issuable_tokens_filters_out_banned_vaults() { let id1 = 3; let collateral1 = 100; create_vault_with_collateral(id1, collateral1); - let issuable_tokens1 = VaultRegistry::get_issuable_tokens_from_vault(id1.clone()) - .expect("Sample vault is unable to issue tokens"); + let issuable_tokens1 = + VaultRegistry::get_issuable_tokens_from_vault(id1.clone()).expect("Sample vault is unable to issue tokens"); let id2 = 4; let collateral2 = 50; @@ -1326,8 +1245,8 @@ fn get_vaults_with_issuable_tokens_filters_out_banned_vaults() { let mut vault = VaultRegistry::get_rich_vault_from_id(&id2).unwrap(); vault.ban_until(1000); - let issuable_tokens2 = VaultRegistry::get_issuable_tokens_from_vault(id2.clone()) - .expect("Sample vault is unable to issue tokens"); + let issuable_tokens2 = + VaultRegistry::get_issuable_tokens_from_vault(id2.clone()).expect("Sample vault is unable to issue tokens"); assert_eq!(issuable_tokens2, 0); @@ -1390,10 +1309,7 @@ fn get_first_vault_with_sufficient_tokens_considers_to_be_redeemed() { TestError::NoVaultWithSufficientTokens ); - assert_eq!( - VaultRegistry::get_first_vault_with_sufficient_tokens(3), - Ok(id) - ); + assert_eq!(VaultRegistry::get_first_vault_with_sufficient_tokens(3), Ok(id)); }) } @@ -1501,12 +1417,7 @@ fn wallet_has_btc_address_succeeds() { // } fn setup_block(i: u64, parent_hash: H256) -> H256 { - System::initialize( - &i, - &parent_hash, - &Default::default(), - frame_system::InitKind::Full, - ); + System::initialize(&i, &parent_hash, &Default::default(), frame_system::InitKind::Full); >::on_initialize(i); let header = System::finalize(); @@ -1545,15 +1456,9 @@ fn runtime_upgrade_succeeds() { ..Default::default() }, ); - assert_eq!( - 0, - VaultRegistry::get_total_backing_collateral(false).unwrap() - ); + assert_eq!(0, VaultRegistry::get_total_backing_collateral(false).unwrap()); VaultRegistry::_on_runtime_upgrade(); - assert_eq!( - 60, - VaultRegistry::get_total_backing_collateral(false).unwrap() - ); + assert_eq!(60, VaultRegistry::get_total_backing_collateral(false).unwrap()); }) } @@ -1564,22 +1469,14 @@ fn get_first_vault_with_sufficient_tokens_returns_different_vaults_for_different let vault_ids = MULTI_VAULT_TEST_IDS .iter() - .map(|&i| { - create_vault_and_issue_tokens( - MULTI_VAULT_TEST_COLLATERAL / 100, - MULTI_VAULT_TEST_COLLATERAL, - i, - ) - }) + .map(|&i| create_vault_and_issue_tokens(MULTI_VAULT_TEST_COLLATERAL / 100, MULTI_VAULT_TEST_COLLATERAL, i)) .collect::>(); let selected_ids = (1..50) .map(|i| VaultRegistry::get_first_vault_with_sufficient_tokens(i).unwrap()) .collect::>(); // check that all vaults have been selected at least once - assert!(vault_ids - .iter() - .all(|&x| selected_ids.iter().any(|&y| x == y))); + assert!(vault_ids.iter().all(|&x| selected_ids.iter().any(|&y| x == y))); }); } @@ -1590,13 +1487,7 @@ fn get_first_vault_with_sufficient_tokens_returns_different_vaults_for_different let vault_ids = MULTI_VAULT_TEST_IDS .iter() - .map(|&i| { - create_vault_and_issue_tokens( - MULTI_VAULT_TEST_COLLATERAL / 100, - MULTI_VAULT_TEST_COLLATERAL, - i, - ) - }) + .map(|&i| create_vault_and_issue_tokens(MULTI_VAULT_TEST_COLLATERAL / 100, MULTI_VAULT_TEST_COLLATERAL, i)) .collect::>(); let selected_ids = (101..150) .map(|i| { @@ -1606,9 +1497,7 @@ fn get_first_vault_with_sufficient_tokens_returns_different_vaults_for_different .collect::>(); // check that all vaults have been selected at least once - assert!(vault_ids - .iter() - .all(|&x| selected_ids.iter().any(|&y| x == y))); + assert!(vault_ids.iter().all(|&x| selected_ids.iter().any(|&y| x == y))); }); } #[test] @@ -1618,22 +1507,14 @@ fn get_first_vault_with_sufficient_collateral_returns_different_vaults_for_diffe let vault_ids = MULTI_VAULT_TEST_IDS .iter() - .map(|&i| { - create_vault_and_issue_tokens( - MULTI_VAULT_TEST_COLLATERAL / 100, - MULTI_VAULT_TEST_COLLATERAL, - i, - ) - }) + .map(|&i| create_vault_and_issue_tokens(MULTI_VAULT_TEST_COLLATERAL / 100, MULTI_VAULT_TEST_COLLATERAL, i)) .collect::>(); let selected_ids = (1..50) .map(|i| VaultRegistry::get_first_vault_with_sufficient_collateral(i).unwrap()) .collect::>(); // check that all vaults have been selected at least once - assert!(vault_ids - .iter() - .all(|&x| selected_ids.iter().any(|&y| x == y))); + assert!(vault_ids.iter().all(|&x| selected_ids.iter().any(|&y| x == y))); }); } @@ -1644,13 +1525,7 @@ fn get_first_vault_with_sufficient_collateral_returns_different_vaults_for_diffe let vault_ids = MULTI_VAULT_TEST_IDS .iter() - .map(|&i| { - create_vault_and_issue_tokens( - MULTI_VAULT_TEST_COLLATERAL / 100, - MULTI_VAULT_TEST_COLLATERAL, - i, - ) - }) + .map(|&i| create_vault_and_issue_tokens(MULTI_VAULT_TEST_COLLATERAL / 100, MULTI_VAULT_TEST_COLLATERAL, i)) .collect::>(); let selected_ids = (101..150) .map(|i| { @@ -1660,8 +1535,6 @@ fn get_first_vault_with_sufficient_collateral_returns_different_vaults_for_diffe .collect::>(); // check that all vaults have been selected at least once - assert!(vault_ids - .iter() - .all(|&x| selected_ids.iter().any(|&y| x == y))); + assert!(vault_ids.iter().all(|&x| selected_ids.iter().any(|&y| x == y))); }); } diff --git a/crates/vault-registry/src/types.rs b/crates/vault-registry/src/types.rs index 5dbcb8631d..f477591a07 100644 --- a/crates/vault-registry/src/types.rs +++ b/crates/vault-registry/src/types.rs @@ -1,10 +1,10 @@ -use crate::sp_api_hidden_includes_decl_storage::hidden_include::StorageValue; -use crate::{ext, Config, Error, Module}; +use crate::{ext, sp_api_hidden_includes_decl_storage::hidden_include::StorageValue, Config, Error, Module}; use codec::{Decode, Encode, HasCompact}; -use frame_support::traits::Currency; use frame_support::{ dispatch::{DispatchError, DispatchResult}, - ensure, StorageMap, + ensure, + traits::Currency, + StorageMap, }; use sp_arithmetic::FixedPointNumber; use sp_core::H256; @@ -40,17 +40,13 @@ pub enum CurrencySource { impl CurrencySource { pub fn account_id(&self) -> ::AccountId { match self { - CurrencySource::Backing(x) - | CurrencySource::Griefing(x) - | CurrencySource::FreeBalance(x) => x.clone(), + CurrencySource::Backing(x) | CurrencySource::Griefing(x) | CurrencySource::FreeBalance(x) => x.clone(), CurrencySource::LiquidationVault => Module::::get_rich_liquidation_vault().data.id, } } pub fn current_balance(&self) -> Result, DispatchError> { match self { - CurrencySource::Backing(x) => Ok(Module::::get_rich_vault_from_id(&x)? - .data - .backing_collateral), + CurrencySource::Backing(x) => Ok(Module::::get_rich_vault_from_id(&x)?.data.backing_collateral), CurrencySource::Griefing(x) => { let backing_collateral = match Module::::get_rich_vault_from_id(&x) { Ok(vault) => vault.data.backing_collateral, @@ -62,19 +58,15 @@ impl CurrencySource { .ok_or(Error::::ArithmeticUnderflow)?) } CurrencySource::FreeBalance(x) => Ok(ext::collateral::get_free_balance::(x)), - CurrencySource::LiquidationVault => { - Ok(ext::collateral::for_account::(&self.account_id())) - } + CurrencySource::LiquidationVault => Ok(ext::collateral::for_account::(&self.account_id())), } } } -pub(crate) type DOT = - <::DOT as Currency<::AccountId>>::Balance; +pub(crate) type DOT = <::DOT as Currency<::AccountId>>::Balance; -pub(crate) type PolkaBTC = <::PolkaBTC as Currency< - ::AccountId, ->>::Balance; +pub(crate) type PolkaBTC = + <::PolkaBTC as Currency<::AccountId>>::Balance; pub(crate) type UnsignedFixedPoint = ::UnsignedFixedPoint; @@ -166,10 +158,7 @@ pub struct SystemVault { impl Vault { - pub(crate) fn new( - id: AccountId, - public_key: BtcPublicKey, - ) -> Vault { + pub(crate) fn new(id: AccountId, public_key: BtcPublicKey) -> Vault { let wallet = Wallet::new(public_key); Vault { id, @@ -189,12 +178,8 @@ impl = Vault< - ::AccountId, - ::BlockNumber, - PolkaBTC, - DOT, ->; +pub type DefaultVault = + Vault<::AccountId, ::BlockNumber, PolkaBTC, DOT>; pub type DefaultSystemVault = SystemVault<::AccountId, PolkaBTC>; @@ -382,10 +367,8 @@ impl RichVault { let secure_threshold = Module::::secure_collateral_threshold(); - let issuable = Module::::calculate_max_polkabtc_from_collateral_for_threshold( - free_collateral, - secure_threshold, - )?; + let issuable = + Module::::calculate_max_polkabtc_from_collateral_for_threshold(free_collateral, secure_threshold)?; Ok(issuable) } @@ -525,10 +508,7 @@ impl RichVault { }); } - pub(crate) fn new_deposit_address( - &mut self, - secure_id: H256, - ) -> Result { + pub(crate) fn new_deposit_address(&mut self, secure_id: H256) -> Result { let public_key = self.new_deposit_public_key(secure_id)?; let btc_address = BtcAddress::P2WPKHv0(public_key.to_hash()); self.insert_deposit_address(btc_address); diff --git a/parachain/rpc/src/lib.rs b/parachain/rpc/src/lib.rs index 138b2704b1..cde9f719e3 100644 --- a/parachain/rpc/src/lib.rs +++ b/parachain/rpc/src/lib.rs @@ -6,8 +6,7 @@ #![warn(missing_docs)] use btc_parachain_runtime::{ - opaque::Block, AccountId, Balance, BlockNumber, Index, IssueRequest, RedeemRequest, - RefundRequest, ReplaceRequest, + opaque::Block, AccountId, Balance, BlockNumber, Index, IssueRequest, RedeemRequest, RefundRequest, ReplaceRequest, }; pub use sc_rpc_api::DenyUnsafe; use sp_api::ProvideRuntimeApi; @@ -40,13 +39,7 @@ where C::Api: pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi, C::Api: module_exchange_rate_oracle_rpc::ExchangeRateOracleRuntimeApi, C::Api: module_staked_relayers_rpc::StakedRelayersRuntimeApi, - C::Api: module_vault_registry_rpc::VaultRegistryRuntimeApi< - Block, - AccountId, - Balance, - Balance, - FixedU128, - >, + C::Api: module_vault_registry_rpc::VaultRegistryRuntimeApi, C::Api: module_issue_rpc::IssueRuntimeApi< Block, AccountId, @@ -59,12 +52,7 @@ where H256, RedeemRequest, >, - C::Api: module_refund_rpc::RefundRuntimeApi< - Block, - AccountId, - H256, - RefundRequest, - >, + C::Api: module_refund_rpc::RefundRuntimeApi>, C::Api: module_replace_rpc::ReplaceRuntimeApi< Block, AccountId, @@ -105,13 +93,9 @@ where client.clone(), ))); - io.extend_with(StakedRelayersApi::to_delegate(StakedRelayers::new( - client.clone(), - ))); + io.extend_with(StakedRelayersApi::to_delegate(StakedRelayers::new(client.clone()))); - io.extend_with(VaultRegistryApi::to_delegate(VaultRegistry::new( - client.clone(), - ))); + io.extend_with(VaultRegistryApi::to_delegate(VaultRegistry::new(client.clone()))); io.extend_with(IssueApi::to_delegate(Issue::new(client.clone()))); diff --git a/parachain/runtime/src/lib.rs b/parachain/runtime/src/lib.rs index f946d5253a..253fa8dc70 100644 --- a/parachain/runtime/src/lib.rs +++ b/parachain/runtime/src/lib.rs @@ -8,8 +8,10 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); -use frame_support::dispatch::{DispatchError, DispatchResult}; -use frame_support::traits::StorageMapShim; +use frame_support::{ + dispatch::{DispatchError, DispatchResult}, + traits::StorageMapShim, +}; use sp_arithmetic::{FixedI128, FixedU128}; use sp_core::H256; @@ -44,8 +46,7 @@ pub use sp_runtime::BuildStorage; pub use sp_runtime::{Perbill, Permill}; // PolkaBTC exports -pub use btc_relay::bitcoin; -pub use btc_relay::Call as RelayCall; +pub use btc_relay::{bitcoin, Call as RelayCall}; pub use module_exchange_rate_oracle_rpc_runtime_api::BalanceWrapper; // XCM imports @@ -57,9 +58,8 @@ use { sp_runtime::traits::Convert, xcm::v0::{Junction, MultiLocation, NetworkId}, xcm_builder::{ - AccountId32Aliases, LocationInverter, ParentIsDefault, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SovereignSignedViaLocation, + AccountId32Aliases, LocationInverter, ParentIsDefault, RelayChainAsNative, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SovereignSignedViaLocation, }, xcm_executor::{Config, XcmExecutor}, }; @@ -255,12 +255,9 @@ impl pallet_grandpa::Config for Runtime { type Event = Event; type Call = Call; type KeyOwnerProofSystem = (); - type KeyOwnerProof = - >::Proof; - type KeyOwnerIdentification = >::IdentificationTuple; + type KeyOwnerProof = >::Proof; + type KeyOwnerIdentification = + >::IdentificationTuple; type HandleEquivocation = (); type WeightInfo = (); } @@ -602,13 +599,8 @@ pub type UncheckedExtrinsic = generic::UncheckedExtrinsic; /// Executive: handles dispatch to the various modules. -pub type Executive = frame_executive::Executive< - Runtime, - Block, - frame_system::ChainContext, - Runtime, - AllModules, ->; +pub type Executive = + frame_executive::Executive, Runtime, AllModules>; #[cfg(not(feature = "disable-runtime-api"))] impl_runtime_apis! { diff --git a/parachain/runtime/tests/bitcoin_data.rs b/parachain/runtime/tests/bitcoin_data.rs index 4ee44e7ba4..f091823090 100644 --- a/parachain/runtime/tests/bitcoin_data.rs +++ b/parachain/runtime/tests/bitcoin_data.rs @@ -1,7 +1,6 @@ use bitcoin::types::{H256Le, RawBlockHeader}; use serde::Deserialize; -use std::fs; -use std::path::PathBuf; +use std::{fs, path::PathBuf}; const ERR_FILE_NOT_FOUND: &'static str = "Testdata not found. Please run the python script under the parachain/scripts folder to obtain bitcoin blocks and transactions."; const ERR_JSON_FORMAT: &'static str = "JSON was not well-formatted"; diff --git a/parachain/runtime/tests/mock/issue_testing_utils.rs b/parachain/runtime/tests/mock/issue_testing_utils.rs index b46b450a7d..35b6fed42a 100644 --- a/parachain/runtime/tests/mock/issue_testing_utils.rs +++ b/parachain/runtime/tests/mock/issue_testing_utils.rs @@ -42,9 +42,7 @@ impl RequestIssueBuilder { } pub fn request(&self) -> (H256, IssueRequest) { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); SystemModule::set_block_number(1); @@ -126,13 +124,8 @@ impl ExecuteIssueBuilder { } // alice executes the issuerequest by confirming the btc transaction - Call::Issue(IssueCall::execute_issue( - self.issue_id, - tx_id, - proof, - raw_tx, - )) - .dispatch(origin_of(account_of(self.submitter))) + Call::Issue(IssueCall::execute_issue(self.issue_id, tx_id, proof, raw_tx)) + .dispatch(origin_of(account_of(self.submitter))) } pub fn assert_execute(&self) { assert_ok!(self.execute()); @@ -149,9 +142,7 @@ pub fn assert_issue_request_event() -> H256 { Event::issue(IssueEvent::RequestIssue(_, _, _, _, _, _, _, _)) => true, _ => false, }); - let id = if let Event::issue(IssueEvent::RequestIssue(id, _, _, _, _, _, _, _)) = - record.unwrap().event - { + let id = if let Event::issue(IssueEvent::RequestIssue(id, _, _, _, _, _, _, _)) = record.unwrap().event { id } else { panic!("request issue event not found") @@ -170,8 +161,7 @@ pub fn assert_refund_request_event() -> H256 { } pub fn execute_refund(vault_id: [u8; 32]) -> (H256, RefundRequest) { - let refund_address_script = - bitcoin::Script::try_from("a914d7ff6d60ebf40a9b1886acce06653ba2224d8fea87").unwrap(); + let refund_address_script = bitcoin::Script::try_from("a914d7ff6d60ebf40a9b1886acce06653ba2224d8fea87").unwrap(); let refund_address = BtcAddress::from_script(&refund_address_script).unwrap(); let refund_id = assert_refund_request_event(); @@ -195,7 +185,5 @@ pub fn cancel_issue(issue_id: H256, vault: [u8; 32]) { SystemModule::set_block_number(IssueModule::issue_period() + 1 + 1); // cancel issue request - assert_ok!( - Call::Issue(IssueCall::cancel_issue(issue_id)).dispatch(origin_of(account_of(vault))) - ); + assert_ok!(Call::Issue(IssueCall::cancel_issue(issue_id)).dispatch(origin_of(account_of(vault)))); } diff --git a/parachain/runtime/tests/mock/mod.rs b/parachain/runtime/tests/mock/mod.rs index 4699f9ed28..e584264473 100644 --- a/parachain/runtime/tests/mock/mod.rs +++ b/parachain/runtime/tests/mock/mod.rs @@ -1,8 +1,10 @@ #![allow(dead_code)] extern crate hex; -pub use bitcoin::formatter::{Formattable, TryFormattable}; -pub use bitcoin::types::*; +pub use bitcoin::{ + formatter::{Formattable, TryFormattable}, + types::*, +}; pub use btc_parachain_runtime::{AccountId, Call, Event, Runtime}; pub use btc_relay::{BtcAddress, BtcPublicKey}; pub use frame_support::{assert_noop, assert_ok, dispatch::DispatchResultWithPostInfo}; @@ -105,20 +107,12 @@ impl UserData { } // set free balance: - CollateralModule::transfer(account_id.clone(), account_of(FAUCET), old.free_balance) - .unwrap(); - CollateralModule::transfer(account_of(FAUCET), account_id.clone(), new.free_balance) - .unwrap(); + CollateralModule::transfer(account_id.clone(), account_of(FAUCET), old.free_balance).unwrap(); + CollateralModule::transfer(account_of(FAUCET), account_id.clone(), new.free_balance).unwrap(); // set locked balance: - CollateralModule::slash_collateral( - account_id.clone(), - account_of(FAUCET), - old.locked_balance, - ) - .unwrap(); - CollateralModule::transfer(account_of(FAUCET), account_id.clone(), new.locked_balance) - .unwrap(); + CollateralModule::slash_collateral(account_id.clone(), account_of(FAUCET), old.locked_balance).unwrap(); + CollateralModule::transfer(account_of(FAUCET), account_id.clone(), new.locked_balance).unwrap(); CollateralModule::lock_collateral(&account_id, new.locked_balance).unwrap(); // set free_tokens @@ -172,9 +166,7 @@ impl CoreVaultData { to_be_issued: vault.to_be_issued_tokens, issued: vault.issued_tokens, to_be_redeemed: vault.to_be_redeemed_tokens, - backing_collateral: CurrencySource::::LiquidationVault - .current_balance() - .unwrap(), + backing_collateral: CurrencySource::::LiquidationVault.current_balance().unwrap(), griefing_collateral: 0, free_balance: CollateralModule::get_balance_from_account(&account_id), } @@ -308,30 +300,28 @@ pub fn set_default_thresholds() { pub fn dummy_public_key() -> BtcPublicKey { BtcPublicKey([ - 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, - 18, 45, 222, 180, 119, 54, 243, 97, 173, 150, 161, 169, 230, + 2, 205, 114, 218, 156, 16, 235, 172, 106, 37, 18, 153, 202, 140, 176, 91, 207, 51, 187, 55, 18, 45, 222, 180, + 119, 54, 243, 97, 173, 150, 161, 169, 230, ]) } #[allow(dead_code)] pub fn try_register_vault(collateral: u128, vault: [u8; 32]) { if let Err(_) = VaultRegistryModule::get_vault_from_id(&account_of(vault)) { - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); }; } #[allow(dead_code)] pub fn force_issue_tokens(user: [u8; 32], vault: [u8; 32], collateral: u128, tokens: u128) { // register the vault - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); // increase to be issued tokens assert_ok!(VaultRegistryModule::try_increase_to_be_issued_tokens( @@ -340,10 +330,7 @@ pub fn force_issue_tokens(user: [u8; 32], vault: [u8; 32], collateral: u128, tok )); // issue tokens - assert_ok!(VaultRegistryModule::issue_tokens( - &account_of(vault), - tokens - )); + assert_ok!(VaultRegistryModule::issue_tokens(&account_of(vault), tokens)); // mint tokens to the user treasury::Module::::mint(user.into(), tokens); @@ -353,8 +340,7 @@ pub fn force_issue_tokens(user: [u8; 32], vault: [u8; 32], collateral: u128, tok pub fn required_collateral_for_issue(issue_btc: u128) -> u128 { let fee_amount_btc = FeeModule::get_issue_fee(issue_btc).unwrap(); let total_amount_btc = issue_btc + fee_amount_btc; - let collateral_vault = - VaultRegistryModule::get_required_collateral_for_polkabtc(total_amount_btc).unwrap(); + let collateral_vault = VaultRegistryModule::get_required_collateral_for_polkabtc(total_amount_btc).unwrap(); collateral_vault } @@ -383,14 +369,13 @@ impl TransactionGenerator { confirmations: 7, amount: 100, script: vec![ - 0, 71, 48, 68, 2, 32, 91, 128, 41, 150, 96, 53, 187, 63, 230, 129, 53, 234, 210, - 186, 21, 187, 98, 38, 255, 112, 30, 27, 228, 29, 132, 140, 155, 62, 123, 216, 232, - 168, 2, 32, 72, 126, 179, 207, 142, 8, 99, 8, 32, 78, 244, 166, 106, 160, 207, 227, - 61, 210, 172, 234, 234, 93, 59, 159, 79, 12, 194, 240, 212, 3, 120, 50, 1, 71, 81, - 33, 3, 113, 209, 131, 177, 9, 29, 242, 229, 15, 217, 247, 165, 78, 111, 80, 79, 50, - 200, 117, 80, 30, 233, 210, 167, 133, 175, 62, 253, 134, 127, 212, 51, 33, 2, 128, - 200, 184, 235, 148, 25, 43, 34, 28, 173, 55, 54, 189, 164, 187, 243, 243, 152, 7, - 84, 210, 85, 156, 238, 77, 97, 188, 240, 162, 197, 105, 62, 82, 174, + 0, 71, 48, 68, 2, 32, 91, 128, 41, 150, 96, 53, 187, 63, 230, 129, 53, 234, 210, 186, 21, 187, 98, 38, + 255, 112, 30, 27, 228, 29, 132, 140, 155, 62, 123, 216, 232, 168, 2, 32, 72, 126, 179, 207, 142, 8, 99, + 8, 32, 78, 244, 166, 106, 160, 207, 227, 61, 210, 172, 234, 234, 93, 59, 159, 79, 12, 194, 240, 212, 3, + 120, 50, 1, 71, 81, 33, 3, 113, 209, 131, 177, 9, 29, 242, 229, 15, 217, 247, 165, 78, 111, 80, 79, 50, + 200, 117, 80, 30, 233, 210, 167, 133, 175, 62, 253, 134, 127, 212, 51, 33, 2, 128, 200, 184, 235, 148, + 25, 43, 34, 28, 173, 55, 54, 189, 164, 187, 243, 243, 152, 7, 84, 210, 85, 156, 238, 77, 97, 188, 240, + 162, 197, 105, 62, 82, 174, ], return_data: Some(H256::zero()), ..Default::default() @@ -434,9 +419,8 @@ impl TransactionGenerator { .mine(U256::from(2).pow(254.into())) .unwrap(); - let raw_init_block_header = - RawBlockHeader::from_bytes(&init_block.header.try_format().unwrap()) - .expect("could not serialize block header"); + let raw_init_block_header = RawBlockHeader::from_bytes(&init_block.header.try_format().unwrap()) + .expect("could not serialize block header"); match Call::BTCRelay(BTCRelayCall::initialize( raw_init_block_header.try_into().expect("bad block header"), @@ -464,8 +448,7 @@ impl TransactionGenerator { transaction_builder.add_output(TransactionOutput::payment(value.into(), &self.address)); if let Some(op_return_data) = self.return_data { - transaction_builder - .add_output(TransactionOutput::op_return(0, op_return_data.as_bytes())); + transaction_builder.add_output(TransactionOutput::op_return(0, op_return_data.as_bytes())); } let transaction = transaction_builder.build(); @@ -480,8 +463,8 @@ impl TransactionGenerator { .mine(U256::from(2).pow(254.into())) .unwrap(); - let raw_block_header = RawBlockHeader::from_bytes(&block.header.try_format().unwrap()) - .expect("could not serialize block header"); + let raw_block_header = + RawBlockHeader::from_bytes(&block.header.try_format().unwrap()).expect("could not serialize block header"); let tx_id = transaction.tx_id(); let tx_block_height = height; @@ -493,11 +476,7 @@ impl TransactionGenerator { raw_block_header.try_into().expect("bad block header") )) .dispatch(origin_of(account_of(self.relayer)))); - assert_store_main_chain_header_event( - height, - block.header.hash().unwrap(), - account_of(self.relayer), - ); + assert_store_main_chain_header_event(height, block.header.hash().unwrap(), account_of(self.relayer)); // Mine six new blocks to get over required confirmations let mut prev_block_hash = block.header.hash().unwrap(); @@ -513,19 +492,14 @@ impl TransactionGenerator { .mine(U256::from(2).pow(254.into())) .unwrap(); - let raw_conf_block_header = - RawBlockHeader::from_bytes(&conf_block.header.try_format().unwrap()) - .expect("could not serialize block header"); + let raw_conf_block_header = RawBlockHeader::from_bytes(&conf_block.header.try_format().unwrap()) + .expect("could not serialize block header"); assert_ok!(Call::BTCRelay(BTCRelayCall::store_block_header( raw_conf_block_header.try_into().expect("bad block header"), )) .dispatch(origin_of(account_of(self.relayer)))); - assert_store_main_chain_header_event( - height, - conf_block.header.hash().unwrap(), - account_of(self.relayer), - ); + assert_store_main_chain_header_event(height, conf_block.header.hash().unwrap(), account_of(self.relayer)); prev_block_hash = conf_block.header.hash().unwrap(); } @@ -603,10 +577,7 @@ impl ExtBuilder { (account_of(FAUCET), 1 << 60), // create accounts for vault & fee pool; this needs a minimum amount because // the parachain refuses to create accounts with a balance below `ExistentialDeposit` - ( - account_of(LIQUIDATION_VAULT), - INITIAL_LIQUIDATION_VAULT_BALANCE, - ), + (account_of(LIQUIDATION_VAULT), INITIAL_LIQUIDATION_VAULT_BALANCE), (account_of(FEE_POOL), 1000), ], } @@ -668,12 +639,12 @@ impl ExtBuilder { fee::GenesisConfig:: { issue_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% issue_griefing_collateral: FixedU128::checked_from_rational(5, 100000).unwrap(), // 0.005% - refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% - replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% fee_pool_account_id: account_of(FEE_POOL), maintainer_account_id: account_of(MAINTAINER), epoch_period: 5, diff --git a/parachain/runtime/tests/mock/redeem_testing_utils.rs b/parachain/runtime/tests/mock/redeem_testing_utils.rs index 02f56b4d21..84f02e7a31 100644 --- a/parachain/runtime/tests/mock/redeem_testing_utils.rs +++ b/parachain/runtime/tests/mock/redeem_testing_utils.rs @@ -6,12 +6,7 @@ pub const USER_BTC_ADDRESS: BtcAddress = BtcAddress::P2PKH(H160([2u8; 20])); pub const DEFAULT_USER_FREE_BALANCE: u128 = 1_000_000; pub const DEFAULT_USER_LOCKED_BALANCE: u128 = 100_000; -pub fn setup_cancelable_redeem( - user: [u8; 32], - vault: [u8; 32], - collateral: u128, - polka_btc: u128, -) -> H256 { +pub fn setup_cancelable_redeem(user: [u8; 32], vault: [u8; 32], collateral: u128, polka_btc: u128) -> H256 { let redeem_id = setup_redeem(polka_btc, user, vault, collateral); // expire request without transferring btc @@ -37,9 +32,7 @@ pub fn setup_redeem(polka_btc: u128, user: [u8; 32], vault: [u8; 32], collateral set_default_thresholds(); - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); let fee = FeeModule::get_redeem_fee(polka_btc).unwrap(); @@ -90,18 +83,12 @@ pub fn execute_redeem(polka_btc: u128, redeem_id: H256) { SystemModule::set_block_number(1 + CONFIRMATIONS); - assert_ok!(Call::Redeem(RedeemCall::execute_redeem( - redeem_id, - tx_id, - merkle_proof, - raw_tx - )) - .dispatch(origin_of(account_of(VAULT)))); + assert_ok!( + Call::Redeem(RedeemCall::execute_redeem(redeem_id, tx_id, merkle_proof, raw_tx)) + .dispatch(origin_of(account_of(VAULT))) + ); } pub fn cancel_redeem(redeem_id: H256, redeemer: [u8; 32], reimburse: bool) { - assert_ok!( - Call::Redeem(RedeemCall::cancel_redeem(redeem_id, reimburse)) - .dispatch(origin_of(account_of(redeemer))) - ); + assert_ok!(Call::Redeem(RedeemCall::cancel_redeem(redeem_id, reimburse)).dispatch(origin_of(account_of(redeemer)))); } diff --git a/parachain/runtime/tests/test_btc_relay.rs b/parachain/runtime/tests/test_btc_relay.rs index 1493aea07f..15b7c04619 100644 --- a/parachain/runtime/tests/test_btc_relay.rs +++ b/parachain/runtime/tests/test_btc_relay.rs @@ -24,16 +24,10 @@ fn integration_test_submit_block_headers_and_verify_transaction_inclusion() { )) .dispatch(origin_of(account_of(ALICE)))); for block in test_data.iter().skip(1) { - assert_ok!( - Call::BTCRelay(BTCRelayCall::store_block_header(block.get_raw_header())) - .dispatch(origin_of(account_of(ALICE))) - ); + assert_ok!(Call::BTCRelay(BTCRelayCall::store_block_header(block.get_raw_header())) + .dispatch(origin_of(account_of(ALICE)))); - assert_store_main_chain_header_event( - block.height, - block.get_block_hash(), - account_of(ALICE), - ); + assert_store_main_chain_header_event(block.height, block.get_block_hash(), account_of(ALICE)); } SystemModule::set_block_number(1 + CONFIRMATIONS); // verify all transaction @@ -52,12 +46,8 @@ fn integration_test_submit_block_headers_and_verify_transaction_inclusion() { } else { // expect to fail due to insufficient confirmations assert_noop!( - Call::BTCRelay(BTCRelayCall::verify_transaction_inclusion( - txid, - raw_merkle_proof, - None, - )) - .dispatch(origin_of(account_of(ALICE))), + Call::BTCRelay(BTCRelayCall::verify_transaction_inclusion(txid, raw_merkle_proof, None,)) + .dispatch(origin_of(account_of(ALICE))), BTCRelayError::BitcoinConfirmations ); } diff --git a/parachain/runtime/tests/test_fee_pool.rs b/parachain/runtime/tests/test_fee_pool.rs index f8252f28a0..d0c96d5ae9 100644 --- a/parachain/runtime/tests/test_fee_pool.rs +++ b/parachain/runtime/tests/test_fee_pool.rs @@ -1,6 +1,8 @@ mod mock; -use mock::issue_testing_utils::{ExecuteIssueBuilder, RequestIssueBuilder}; -use mock::*; +use mock::{ + issue_testing_utils::{ExecuteIssueBuilder, RequestIssueBuilder}, + *, +}; const PROOF_SUBMITTER: [u8; 32] = BOB; const VAULT1: [u8; 32] = CAROL; @@ -28,16 +30,10 @@ fn setup_relayer(relayer: [u8; 32], sla: u32, stake: u128) { }, ); // register as staked relayer - assert_ok!( - Call::StakedRelayers(StakedRelayersCall::register_staked_relayer(stake)) - .dispatch(origin_of(account_of(relayer))) - ); + assert_ok!(Call::StakedRelayers(StakedRelayersCall::register_staked_relayer(stake)) + .dispatch(origin_of(account_of(relayer)))); for _ in 0..sla { - SlaModule::event_update_relayer_sla( - &account_of(relayer), - sla::types::RelayerEvent::BlockSubmission, - ) - .unwrap(); + SlaModule::event_update_relayer_sla(&account_of(relayer), sla::types::RelayerEvent::BlockSubmission).unwrap(); } } @@ -82,24 +78,19 @@ fn get_rewards(currency: Currency, account: [u8; 32]) -> u128 { Currency::DOT => { let amount = FeeModule::get_dot_rewards(&account_of(account)); assert_noop!( - Call::Fee(FeeCall::withdraw_dot(amount + 1)) - .dispatch(origin_of(account_of(account))), + Call::Fee(FeeCall::withdraw_dot(amount + 1)).dispatch(origin_of(account_of(account))), FeeError::InsufficientFunds, ); - assert_ok!( - Call::Fee(FeeCall::withdraw_dot(amount)).dispatch(origin_of(account_of(account))) - ); + assert_ok!(Call::Fee(FeeCall::withdraw_dot(amount)).dispatch(origin_of(account_of(account)))); amount } Currency::PolkaBTC => { let amount = FeeModule::get_polka_btc_rewards(&account_of(account)); assert_noop!( - Call::Fee(FeeCall::withdraw_dot(amount + 1)) - .dispatch(origin_of(account_of(account))), + Call::Fee(FeeCall::withdraw_dot(amount + 1)).dispatch(origin_of(account_of(account))), FeeError::InsufficientFunds, ); - assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc(amount)) - .dispatch(origin_of(account_of(account)))); + assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc(amount)).dispatch(origin_of(account_of(account)))); amount } } @@ -121,9 +112,7 @@ fn set_issued_and_backing(vault: [u8; 32], amount_issued: u128, backing: u128) { let fee = FeeModule::get_issue_fee_from_total(amount_issued).unwrap(); let request_amount = amount_issued - fee; - let (issue_id, _) = RequestIssueBuilder::new(request_amount) - .with_vault(vault) - .request(); + let (issue_id, _) = RequestIssueBuilder::new(request_amount).with_vault(vault).request(); ExecuteIssueBuilder::new(issue_id) .with_submitter(PROOF_SUBMITTER, true) .with_relayer(ISSUE_RELAYER) @@ -214,10 +203,7 @@ fn test_vault_fee_pool_withdrawal_over_multiple_epochs() { vault_epoch_1_rewards + (vault_epoch_2_rewards * 26) / 100, ); // second vault gets the other 74% - assert_eq_modulo_rounding!( - get_rewards(currency, VAULT2), - (vault_epoch_2_rewards * 74) / 100, - ); + assert_eq_modulo_rounding!(get_rewards(currency, VAULT2), (vault_epoch_2_rewards * 74) / 100,); }) } @@ -243,15 +229,9 @@ fn test_relayer_fee_pool_withdrawal() { assert_ok!(FeeModule::update_rewards_for_epoch()); // First vault gets 20% of the vault pool - assert_eq_modulo_rounding!( - get_rewards(currency, RELAYER_1), - (relayer_rewards * 20) / 100, - ); + assert_eq_modulo_rounding!(get_rewards(currency, RELAYER_1), (relayer_rewards * 20) / 100,); // second vault gets the other 80% - assert_eq_modulo_rounding!( - get_rewards(currency, RELAYER_2), - (relayer_rewards * 80) / 100, - ); + assert_eq_modulo_rounding!(get_rewards(currency, RELAYER_2), (relayer_rewards * 80) / 100,); }) } diff --git a/parachain/runtime/tests/test_issue.rs b/parachain/runtime/tests/test_issue.rs index e9f0dc5e86..297a7bc053 100644 --- a/parachain/runtime/tests/test_issue.rs +++ b/parachain/runtime/tests/test_issue.rs @@ -1,8 +1,7 @@ mod mock; use frame_support::assert_err; -use mock::issue_testing_utils::*; -use mock::*; +use mock::{issue_testing_utils::*, *}; #[test] fn integration_test_issue_should_fail_if_not_running() { @@ -10,8 +9,7 @@ fn integration_test_issue_should_fail_if_not_running() { SecurityModule::set_status(StatusCode::Shutdown); assert_noop!( - Call::Issue(IssueCall::request_issue(0, account_of(BOB), 0)) - .dispatch(origin_of(account_of(ALICE))), + Call::Issue(IssueCall::request_issue(0, account_of(BOB), 0)).dispatch(origin_of(account_of(ALICE))), SecurityError::ParachainNotRunning, ); @@ -31,9 +29,7 @@ fn integration_test_issue_should_fail_if_not_running() { #[test] fn integration_test_issue_polka_btc_execute() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); let user = ALICE; let vault = BOB; @@ -48,16 +44,14 @@ fn integration_test_issue_polka_btc_execute() { let initial_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let initial_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault_proof_submitter)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault_proof_submitter))) + ); // alice requests polka_btc by locking btc with bob assert_ok!(Call::Issue(IssueCall::request_issue( @@ -74,16 +68,13 @@ fn integration_test_issue_polka_btc_execute() { let total_amount_btc = amount_btc + fee_amount_btc; // send the btc from the user to the vault - let (tx_id, _height, proof, raw_tx) = - generate_transaction_and_mine(vault_btc_address, total_amount_btc, None); + let (tx_id, _height, proof, raw_tx) = generate_transaction_and_mine(vault_btc_address, total_amount_btc, None); SystemModule::set_block_number(1 + CONFIRMATIONS); // alice executes the issue by confirming the btc transaction - assert_ok!( - Call::Issue(IssueCall::execute_issue(issue_id, tx_id, proof, raw_tx)) - .dispatch(origin_of(account_of(vault_proof_submitter))) - ); + assert_ok!(Call::Issue(IssueCall::execute_issue(issue_id, tx_id, proof, raw_tx)) + .dispatch(origin_of(account_of(vault_proof_submitter)))); // check that the vault who submitted the proof is rewarded with increased SLA score assert_eq!( @@ -94,10 +85,7 @@ fn integration_test_issue_polka_btc_execute() { // check the sla increase let expected_sla_increase = SlaModule::vault_executed_issue_max_sla_change() * FixedI128::checked_from_rational(amount_btc, total_amount_btc).unwrap(); - assert_eq!( - SlaModule::vault_sla(account_of(vault)), - expected_sla_increase - ); + assert_eq!(SlaModule::vault_sla(account_of(vault)), expected_sla_increase); // fee should be added to epoch rewards assert_eq!(FeeModule::epoch_rewards_polka_btc(), fee_amount_btc); @@ -121,9 +109,9 @@ fn integration_test_issue_polka_btc_execute() { // force issue rewards and withdraw assert_ok!(FeeModule::update_rewards_for_epoch()); - assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc( - FeeModule::get_polka_btc_rewards(&account_of(vault)) - )) + assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc(FeeModule::get_polka_btc_rewards( + &account_of(vault) + ))) .dispatch(origin_of(account_of(vault)))); }); } @@ -131,9 +119,7 @@ fn integration_test_issue_polka_btc_execute() { #[test] fn integration_test_withdraw_after_request_issue() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); let vault = BOB; let vault_proof_submitter = CAROL; @@ -144,16 +130,14 @@ fn integration_test_withdraw_after_request_issue() { SystemModule::set_block_number(1); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault_proof_submitter)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault_proof_submitter))) + ); // alice requests polka_btc by locking btc with bob assert_ok!(Call::Issue(IssueCall::request_issue( @@ -187,9 +171,7 @@ fn integration_test_withdraw_after_request_issue() { #[test] fn integration_test_issue_overpayment() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); let user = ALICE; let vault = BOB; @@ -205,11 +187,10 @@ fn integration_test_issue_overpayment() { let initial_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let initial_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); // alice requests polka_btc by locking btc with bob assert_ok!(Call::Issue(IssueCall::request_issue( @@ -227,24 +208,19 @@ fn integration_test_issue_overpayment() { let total_amount_btc = amount_btc + fee_amount_btc; // send the btc from the user to the vault - let (tx_id, _height, proof, raw_tx) = - generate_transaction_and_mine(vault_btc_address, total_amount_btc, None); + let (tx_id, _height, proof, raw_tx) = generate_transaction_and_mine(vault_btc_address, total_amount_btc, None); SystemModule::set_block_number(1 + CONFIRMATIONS); // alice executes the issue by confirming the btc transaction assert_ok!( - Call::Issue(IssueCall::execute_issue(issue_id, tx_id, proof, raw_tx)) - .dispatch(origin_of(account_of(user))) + Call::Issue(IssueCall::execute_issue(issue_id, tx_id, proof, raw_tx)).dispatch(origin_of(account_of(user))) ); // check the sla increase let expected_sla_increase = SlaModule::vault_executed_issue_max_sla_change() * FixedI128::checked_from_rational(amount_btc, total_amount_btc).unwrap(); - assert_eq!( - SlaModule::vault_sla(account_of(vault)), - expected_sla_increase - ); + assert_eq!(SlaModule::vault_sla(account_of(vault)), expected_sla_increase); // fee should be added to epoch rewards assert_eq!(FeeModule::epoch_rewards_polka_btc(), fee_amount_btc); @@ -260,9 +236,9 @@ fn integration_test_issue_overpayment() { // force issue rewards and withdraw assert_ok!(FeeModule::update_rewards_for_epoch()); - assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc( - FeeModule::get_polka_btc_rewards(&account_of(vault)) - )) + assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc(FeeModule::get_polka_btc_rewards( + &account_of(vault) + ))) .dispatch(origin_of(account_of(vault)))); }); } @@ -376,14 +352,11 @@ fn integration_test_issue_polka_btc_cancel() { let initial_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let initial_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); // alice requests polka_btc by locking btc with bob assert_ok!(Call::Issue(IssueCall::request_issue( @@ -411,9 +384,7 @@ fn integration_test_issue_polka_btc_cancel() { ); // bob cancels issue request - assert_ok!( - Call::Issue(IssueCall::cancel_issue(issue_id)).dispatch(origin_of(account_of(vault))) - ); + assert_ok!(Call::Issue(IssueCall::cancel_issue(issue_id)).dispatch(origin_of(account_of(vault)))); let final_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let final_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); @@ -441,14 +412,11 @@ fn integration_test_issue_polka_btc_cancel_liquidated() { let initial_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let initial_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); // alice requests polka_btc by locking btc with bob assert_ok!(Call::Issue(IssueCall::request_issue( @@ -484,14 +452,9 @@ fn integration_test_issue_polka_btc_cancel_liquidated() { ); // bob cancels issue request - assert_ok!( - Call::Issue(IssueCall::cancel_issue(issue_id)).dispatch(origin_of(account_of(vault))) - ); + assert_ok!(Call::Issue(IssueCall::cancel_issue(issue_id)).dispatch(origin_of(account_of(vault)))); - assert_eq!( - VaultRegistryModule::get_liquidation_vault().to_be_issued_tokens, - 0 - ); + assert_eq!(VaultRegistryModule::get_liquidation_vault().to_be_issued_tokens, 0); let final_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let final_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); @@ -575,15 +538,12 @@ fn integration_test_issue_polka_btc_execute_liquidated() { // force issue rewards and withdraw assert_ok!(FeeModule::update_rewards_for_epoch()); - assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc( - FeeModule::get_polka_btc_rewards(&account_of(VAULT)) - )) + assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc(FeeModule::get_polka_btc_rewards( + &account_of(VAULT) + ))) .dispatch(origin_of(account_of(VAULT)))); // should not have received fee - assert_eq!( - TreasuryModule::get_balance_from_account(account_of(VAULT)), - 0 - ); + assert_eq!(TreasuryModule::get_balance_from_account(account_of(VAULT)), 0); }); } @@ -650,9 +610,9 @@ fn integration_test_issue_polka_btc_execute_not_liquidated() { // force issue rewards and withdraw assert_ok!(FeeModule::update_rewards_for_epoch()); - assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc( - FeeModule::get_polka_btc_rewards(&account_of(VAULT)) - )) + assert_ok!(Call::Fee(FeeCall::withdraw_polka_btc(FeeModule::get_polka_btc_rewards( + &account_of(VAULT) + ))) .dispatch(origin_of(account_of(VAULT)))); // check that a fee has been withdrawn assert!(TreasuryModule::get_balance_from_account(account_of(VAULT)) > 0); diff --git a/parachain/runtime/tests/test_redeem.rs b/parachain/runtime/tests/test_redeem.rs index 9a6b925b06..cd9ed21139 100644 --- a/parachain/runtime/tests/test_redeem.rs +++ b/parachain/runtime/tests/test_redeem.rs @@ -1,7 +1,6 @@ mod mock; -use mock::redeem_testing_utils::*; -use mock::*; +use mock::{redeem_testing_utils::*, *}; #[test] fn integration_test_redeem_should_fail_if_not_running() { @@ -64,13 +63,10 @@ fn integration_test_redeem_polka_btc_execute() { SystemModule::set_block_number(1 + CONFIRMATIONS); - assert_ok!(Call::Redeem(RedeemCall::execute_redeem( - redeem_id, - tx_id, - merkle_proof, - raw_tx - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!( + Call::Redeem(RedeemCall::execute_redeem(redeem_id, tx_id, merkle_proof, raw_tx)) + .dispatch(origin_of(account_of(vault))) + ); let final_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let final_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); @@ -98,9 +94,7 @@ fn integration_test_premium_redeem_polka_btc_execute() { SystemModule::set_block_number(1); - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); @@ -117,8 +111,7 @@ fn integration_test_premium_redeem_polka_btc_execute() { let initial_dot_balance = CollateralModule::get_balance_from_account(&account_of(user)); let initial_btc_balance = TreasuryModule::get_balance_from_account(account_of(user)); - let initial_vault_collateral = - CollateralModule::get_collateral_from_account(&account_of(vault)); + let initial_vault_collateral = CollateralModule::get_collateral_from_account(&account_of(vault)); let initial_btc_issuance = TreasuryModule::get_total_supply(); assert_eq!(polka_btc, initial_btc_issuance); @@ -140,13 +133,10 @@ fn integration_test_premium_redeem_polka_btc_execute() { SystemModule::set_block_number(1 + CONFIRMATIONS); - assert_ok!(Call::Redeem(RedeemCall::execute_redeem( - redeem_id, - tx_id, - merkle_proof, - raw_tx - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!( + Call::Redeem(RedeemCall::execute_redeem(redeem_id, tx_id, merkle_proof, raw_tx)) + .dispatch(origin_of(account_of(vault))) + ); assert_eq!(FeeModule::epoch_rewards_polka_btc(), redeem.fee); @@ -177,9 +167,7 @@ fn integration_test_redeem_polka_btc_liquidation_redeem() { ExtBuilder::build().execute_with(|| { SystemModule::set_block_number(1); set_default_thresholds(); - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); let issued = 400; let to_be_issued = 100; @@ -225,9 +213,7 @@ fn integration_test_redeem_polka_btc_liquidation_redeem() { VaultRegistryError::InsufficientTokensCommitted ); - assert_ok!( - Call::Redeem(RedeemCall::liquidation_redeem(325)).dispatch(origin_of(account_of(USER))) - ); + assert_ok!(Call::Redeem(RedeemCall::liquidation_redeem(325)).dispatch(origin_of(account_of(USER)))); assert_eq!( UserData::get(USER), @@ -255,8 +241,7 @@ fn integration_test_redeem_polka_btc_cancel_reimburse() { let redeem_id = setup_cancelable_redeem(user, vault, 100000000, amount_btc); let redeem = RedeemModule::get_open_redeem_request_from_id(&redeem_id).unwrap(); - let amount_without_fee_dot = - ExchangeRateOracleModule::btc_to_dots(redeem.amount_btc).unwrap(); + let amount_without_fee_dot = ExchangeRateOracleModule::btc_to_dots(redeem.amount_btc).unwrap(); let punishment_fee = FeeModule::get_punishment_fee(amount_without_fee_dot).unwrap(); assert!(punishment_fee > 0); @@ -269,8 +254,7 @@ fn integration_test_redeem_polka_btc_cancel_reimburse() { SlaModule::set_vault_sla(&account_of(vault), sla_score_before); // alice cancels redeem request and chooses to reimburse - assert_ok!(Call::Redeem(RedeemCall::cancel_redeem(redeem_id, true)) - .dispatch(origin_of(account_of(user)))); + assert_ok!(Call::Redeem(RedeemCall::cancel_redeem(redeem_id, true)).dispatch(origin_of(account_of(user)))); let new_balance = CollateralModule::get_balance_from_account(&account_of(user)); @@ -314,10 +298,8 @@ fn integration_test_redeem_polka_btc_cancel_no_reimburse() { let redeem_id = setup_cancelable_redeem(user, vault, 100000000, amount_btc); let redeem = RedeemModule::get_open_redeem_request_from_id(&redeem_id).unwrap(); - let punishment_fee = FeeModule::get_punishment_fee( - ExchangeRateOracleModule::btc_to_dots(redeem.amount_btc).unwrap(), - ) - .unwrap(); + let punishment_fee = + FeeModule::get_punishment_fee(ExchangeRateOracleModule::btc_to_dots(redeem.amount_btc).unwrap()).unwrap(); assert!(punishment_fee > 0); // get initial balance - the setup call above will have minted and locked polkabtc @@ -328,8 +310,7 @@ fn integration_test_redeem_polka_btc_cancel_no_reimburse() { SlaModule::set_vault_sla(&account_of(vault), sla_score_before); // alice cancels redeem request, but does not reimburse - assert_ok!(Call::Redeem(RedeemCall::cancel_redeem(redeem_id, false)) - .dispatch(origin_of(account_of(user)))); + assert_ok!(Call::Redeem(RedeemCall::cancel_redeem(redeem_id, false)).dispatch(origin_of(account_of(user)))); // dot-balance should have increased by punishment_fee assert_eq!( @@ -393,10 +374,7 @@ fn test_cancel_liquidated(reimburse: bool) { drop_exchange_rate_and_liquidate(VAULT); - assert_ok!( - Call::Redeem(RedeemCall::cancel_redeem(redeem_id, reimburse)) - .dispatch(origin_of(account_of(USER))) - ); + assert_ok!(Call::Redeem(RedeemCall::cancel_redeem(redeem_id, reimburse)).dispatch(origin_of(account_of(USER)))); assert_eq!( CoreVaultData::vault(VAULT), @@ -544,8 +522,7 @@ fn integration_test_redeem_banning() { ); // can still make a replace request now - assert_ok!(Call::Replace(ReplaceCall::request_replace(100, 100)) - .dispatch(origin_of(account_of(VAULT)))); + assert_ok!(Call::Replace(ReplaceCall::request_replace(100, 100)).dispatch(origin_of(account_of(VAULT)))); let replace_id = SystemModule::events() .iter() .find_map(|r| match r.event { @@ -570,34 +547,27 @@ fn integration_test_redeem_banning() { // can not issue with vault while banned assert_noop!( - Call::Issue(IssueCall::request_issue(50, account_of(VAULT), 50)) - .dispatch(origin_of(account_of(USER))), + Call::Issue(IssueCall::request_issue(50, account_of(VAULT), 50)).dispatch(origin_of(account_of(USER))), VaultRegistryError::VaultBanned, ); // can not request replace while banned assert_noop!( - Call::Replace(ReplaceCall::request_replace(0, 0)) - .dispatch(origin_of(account_of(VAULT))), + Call::Replace(ReplaceCall::request_replace(0, 0)).dispatch(origin_of(account_of(VAULT))), VaultRegistryError::VaultBanned, ); // can not accept replace of banned vault assert_noop!( - Call::Replace(ReplaceCall::accept_replace( - replace_id, - 1000, - BtcAddress::default() - )) - .dispatch(origin_of(account_of(VAULT))), + Call::Replace(ReplaceCall::accept_replace(replace_id, 1000, BtcAddress::default())) + .dispatch(origin_of(account_of(VAULT))), VaultRegistryError::VaultBanned, ); // check that the ban is not permanent SystemModule::set_block_number(100000000); assert_ok!( - Call::Issue(IssueCall::request_issue(50, account_of(VAULT), 50)) - .dispatch(origin_of(account_of(USER))) + Call::Issue(IssueCall::request_issue(50, account_of(VAULT), 50)).dispatch(origin_of(account_of(USER))) ); }) } diff --git a/parachain/runtime/tests/test_replace.rs b/parachain/runtime/tests/test_replace.rs index 2df2852b7e..6d2960bef8 100644 --- a/parachain/runtime/tests/test_replace.rs +++ b/parachain/runtime/tests/test_replace.rs @@ -34,9 +34,7 @@ fn assert_auction_event() -> H256 { let ids = events .iter() .filter_map(|r| match r.event { - Event::replace(ReplaceEvent::AuctionReplace(id, _, _, _, _, _, _, _, _)) => { - Some(id.clone()) - } + Event::replace(ReplaceEvent::AuctionReplace(id, _, _, _, _, _, _, _, _)) => Some(id.clone()), _ => None, }) .collect::>(); @@ -59,9 +57,7 @@ fn integration_test_replace_should_fail_if_not_running() { #[test] fn integration_test_replace_request_replace() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -72,10 +68,8 @@ fn integration_test_replace_request_replace() { // bob creates a vault force_issue_tokens(ALICE, BOB, collateral, amount); // bob requests a replace - assert_ok!( - Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) - .dispatch(origin_of(account_of(BOB))) - ); + assert_ok!(Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) + .dispatch(origin_of(account_of(BOB)))); // assert request event let _request_id = assert_request_event(); }); @@ -84,9 +78,7 @@ fn integration_test_replace_request_replace() { #[test] fn integration_test_replace_withdraw_replace() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -100,8 +92,7 @@ fn integration_test_replace_withdraw_replace() { force_issue_tokens(ALICE, BOB, collateral, amount); // bob requests a replace assert_ok!( - Call::Replace(ReplaceCall::request_replace(5000, griefing_collateral)) - .dispatch(origin_of(account_of(BOB))) + Call::Replace(ReplaceCall::request_replace(5000, griefing_collateral)).dispatch(origin_of(account_of(BOB))) ); // bob withdraws his replace let replace_id = assert_request_event(); @@ -112,9 +103,7 @@ fn integration_test_replace_withdraw_replace() { #[test] fn integration_test_replace_accept_replace() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -123,18 +112,15 @@ fn integration_test_replace_accept_replace() { let collateral = amount * 2; // alice creates a vault - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - amount, - dummy_public_key(), - )) - .dispatch(origin_of(account_of(ALICE)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(amount, dummy_public_key(),)) + .dispatch(origin_of(account_of(ALICE))) + ); // bob creates a vault force_issue_tokens(ALICE, BOB, collateral, amount); // bob requests a replace - assert_ok!( - Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) - .dispatch(origin_of(account_of(BOB))) - ); + assert_ok!(Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) + .dispatch(origin_of(account_of(BOB)))); let replace_id = assert_request_event(); // alice accept bob's request assert_ok!(Call::Replace(ReplaceCall::accept_replace( @@ -149,9 +135,7 @@ fn integration_test_replace_accept_replace() { #[test] fn integration_test_replace_auction_replace() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -169,11 +153,10 @@ fn integration_test_replace_auction_replace() { force_issue_tokens(user, old_vault, collateral, polkabtc); // new vault joins - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral, - dummy_public_key() - )) - .dispatch(origin_of(account_of(new_vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key())) + .dispatch(origin_of(account_of(new_vault))) + ); // exchange rate drops and vault is not collateralized any more assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( FixedU128::checked_from_integer(2).unwrap() @@ -197,19 +180,14 @@ fn integration_test_replace_auction_replace() { // auction fee is taken from old vault collateral let replace_amount_dot = ExchangeRateOracleModule::btc_to_dots(polkabtc).unwrap(); let auction_fee = FeeModule::get_auction_redeem_fee(replace_amount_dot).unwrap(); - assert_eq!( - final_old_vault_collateral, - initial_old_vault_collateral - auction_fee - ); + assert_eq!(final_old_vault_collateral, initial_old_vault_collateral - auction_fee); }); } #[test] fn integration_test_replace_execute_replace() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -227,11 +205,10 @@ fn integration_test_replace_execute_replace() { force_issue_tokens(user, old_vault, collateral, polkabtc); // new vault joins - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral, - dummy_public_key() - )) - .dispatch(origin_of(account_of(new_vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key())) + .dispatch(origin_of(account_of(new_vault))) + ); assert_ok!( Call::Replace(ReplaceCall::request_replace(polkabtc, griefing_collateral)) @@ -253,13 +230,8 @@ fn integration_test_replace_execute_replace() { generate_transaction_and_mine(new_vault_btc_address, polkabtc, Some(replace_id)); SystemModule::set_block_number(1 + CONFIRMATIONS); - let r = Call::Replace(ReplaceCall::execute_replace( - replace_id, - tx_id, - merkle_proof, - raw_tx, - )) - .dispatch(origin_of(account_of(old_vault))); + let r = Call::Replace(ReplaceCall::execute_replace(replace_id, tx_id, merkle_proof, raw_tx)) + .dispatch(origin_of(account_of(old_vault))); assert_ok!(r); }); } @@ -267,9 +239,7 @@ fn integration_test_replace_execute_replace() { #[test] fn integration_test_replace_cancel_replace() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -279,18 +249,15 @@ fn integration_test_replace_cancel_replace() { let collateral = amount * 2; // alice creates a vault - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - amount, - dummy_public_key() - )) - .dispatch(origin_of(account_of(ALICE)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(amount, dummy_public_key())) + .dispatch(origin_of(account_of(ALICE))) + ); // bob creates a vault force_issue_tokens(ALICE, BOB, collateral, amount); // bob requests a replace - assert_ok!( - Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) - .dispatch(origin_of(account_of(BOB))) - ); + assert_ok!(Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) + .dispatch(origin_of(account_of(BOB)))); // alice accepts bob's request let replace_id = assert_request_event(); assert_ok!(Call::Replace(ReplaceCall::accept_replace( @@ -302,17 +269,14 @@ fn integration_test_replace_cancel_replace() { // set block height // alice cancels replacement SystemModule::set_block_number(30); - assert_ok!(Call::Replace(ReplaceCall::cancel_replace(replace_id)) - .dispatch(origin_of(account_of(BOB)))); + assert_ok!(Call::Replace(ReplaceCall::cancel_replace(replace_id)).dispatch(origin_of(account_of(BOB)))); }); } #[test] fn integration_test_replace_cancel_auction_replace() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); let new_vault_btc_address = BtcAddress::P2PKH(H160([2; 20])); @@ -330,11 +294,10 @@ fn integration_test_replace_cancel_auction_replace() { force_issue_tokens(user, old_vault, collateral, polkabtc); // new vault joins - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral, - dummy_public_key() - )) - .dispatch(origin_of(account_of(new_vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key())) + .dispatch(origin_of(account_of(new_vault))) + ); // exchange rate drops and vault is not collateralized any more assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( @@ -372,8 +335,7 @@ fn integration_test_replace_cancel_auction_replace() { SystemModule::set_block_number(30); - assert_ok!(Call::Replace(ReplaceCall::cancel_replace(replace_id)) - .dispatch(origin_of(account_of(BOB)))); + assert_ok!(Call::Replace(ReplaceCall::cancel_replace(replace_id)).dispatch(origin_of(account_of(BOB)))); // check old vault collateral assert_eq!( @@ -393,9 +355,7 @@ fn integration_test_replace_cancel_auction_replace() { #[test] fn integration_test_replace_cancel_repeatedly_fails() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -415,11 +375,10 @@ fn integration_test_replace_cancel_repeatedly_fails() { force_issue_tokens(user, old_vault, collateral, polkabtc); // new vault joins - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral, - dummy_public_key() - )) - .dispatch(origin_of(account_of(new_vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral, dummy_public_key())) + .dispatch(origin_of(account_of(new_vault))) + ); // exchange rate drops and vault is not collateralized any more assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( FixedU128::checked_from_integer(2).unwrap() @@ -465,9 +424,7 @@ fn integration_test_replace_cancel_repeatedly_fails() { // liquidation tests.. fn setup_replace(polkabtc: u128) -> H256 { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -500,11 +457,10 @@ fn setup_replace(polkabtc: u128) -> H256 { )) .dispatch(origin_of(account_of(NEW_VAULT)))); - assert_ok!(Call::Replace(ReplaceCall::request_replace( - polkabtc, - DEFAULT_GRIEFING_COLLATERAL - )) - .dispatch(origin_of(account_of(OLD_VAULT)))); + assert_ok!( + Call::Replace(ReplaceCall::request_replace(polkabtc, DEFAULT_GRIEFING_COLLATERAL)) + .dispatch(origin_of(account_of(OLD_VAULT))) + ); let replace_id = assert_request_event(); @@ -528,21 +484,17 @@ fn execute_replace(replace_id: H256) { generate_transaction_and_mine(btc_address, replace.amount, Some(replace_id)); SystemModule::set_block_number(1 + CONFIRMATIONS); - assert_ok!(Call::Replace(ReplaceCall::execute_replace( - replace_id, - tx_id, - merkle_proof, - raw_tx, - )) - .dispatch(origin_of(account_of(OLD_VAULT)))); + assert_ok!( + Call::Replace(ReplaceCall::execute_replace(replace_id, tx_id, merkle_proof, raw_tx,)) + .dispatch(origin_of(account_of(OLD_VAULT))) + ); } fn cancel_replace(replace_id: H256) { // set block height // alice cancels replacement SystemModule::set_block_number(30); - assert_ok!(Call::Replace(ReplaceCall::cancel_replace(replace_id)) - .dispatch(origin_of(account_of(NEW_VAULT)))); + assert_ok!(Call::Replace(ReplaceCall::cancel_replace(replace_id)).dispatch(origin_of(account_of(NEW_VAULT)))); } #[test] fn integration_test_replace_execute_replace_success() { @@ -635,8 +587,7 @@ fn integration_test_replace_execute_replace_old_vault_liquidated() { CoreVaultData { to_be_redeemed: 250, backing_collateral: (DEFAULT_COLLATERAL * 250) / 2500, - free_balance: (DEFAULT_COLLATERAL * replace_tokens) / 2500 - + DEFAULT_GRIEFING_COLLATERAL, + free_balance: (DEFAULT_COLLATERAL * replace_tokens) / 2500 + DEFAULT_GRIEFING_COLLATERAL, ..Default::default() } ); @@ -1063,9 +1014,7 @@ fn integration_test_replace_cancel_replace_both_vaults_liquidated() { #[test] fn integration_test_issue_using_griefing_collateral_fails() { ExtBuilder::build().execute_with(|| { - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); set_default_thresholds(); SystemModule::set_block_number(1); @@ -1077,28 +1026,18 @@ fn integration_test_issue_using_griefing_collateral_fails() { force_issue_tokens(ALICE, BOB, collateral, amount); assert_noop!( - Call::Issue(IssueCall::request_issue( - 1000, - account_of(OLD_VAULT), - issue_amount - )) - .dispatch(origin_of(account_of(USER))), + Call::Issue(IssueCall::request_issue(1000, account_of(OLD_VAULT), issue_amount)) + .dispatch(origin_of(account_of(USER))), VaultRegistryError::ExceedingVaultLimit, ); - assert_ok!( - Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) - .dispatch(origin_of(account_of(OLD_VAULT))) - ); + assert_ok!(Call::Replace(ReplaceCall::request_replace(amount, griefing_collateral)) + .dispatch(origin_of(account_of(OLD_VAULT)))); // still can't do the issue, even though the vault locked griefing collateral assert_noop!( - Call::Issue(IssueCall::request_issue( - 1000, - account_of(OLD_VAULT), - issue_amount - )) - .dispatch(origin_of(account_of(USER))), + Call::Issue(IssueCall::request_issue(1000, account_of(OLD_VAULT), issue_amount)) + .dispatch(origin_of(account_of(USER))), VaultRegistryError::ExceedingVaultLimit, ); }); diff --git a/parachain/runtime/tests/test_staked_relayers.rs b/parachain/runtime/tests/test_staked_relayers.rs index b6b631ebf5..567cfee3dd 100644 --- a/parachain/runtime/tests/test_staked_relayers.rs +++ b/parachain/runtime/tests/test_staked_relayers.rs @@ -17,40 +17,32 @@ fn integration_test_report_vault_theft() { let collateral_vault = 1000000; let vault_btc_address = BtcAddress::P2SH(H160([ - 215, 255, 109, 96, 235, 244, 10, 155, 24, 134, 172, 206, 6, 101, 59, 162, 34, 77, 143, - 234, + 215, 255, 109, 96, 235, 244, 10, 155, 24, 134, 172, 206, 6, 101, 59, 162, 34, 77, 143, 234, ])); let other_btc_address = BtcAddress::P2SH(H160([1; 20])); SystemModule::set_block_number(1); - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); VaultRegistryModule::insert_vault(&account_of(LIQUIDATION_VAULT), Vault::default()); // assert_ok!(CollateralModule::lock_collateral(&account_of(vault), collateral_vault)); - assert_ok!(Call::VaultRegistry(VaultRegistryCall::register_vault( - collateral_vault, - dummy_public_key() - )) - .dispatch(origin_of(account_of(vault)))); + assert_ok!( + Call::VaultRegistry(VaultRegistryCall::register_vault(collateral_vault, dummy_public_key())) + .dispatch(origin_of(account_of(vault))) + ); assert_ok!(VaultRegistryModule::insert_vault_deposit_address( &account_of(vault), vault_btc_address )); // register as staked relayer - assert_ok!( - Call::StakedRelayers(StakedRelayersCall::register_staked_relayer(100)) - .dispatch(origin_of(account_of(user))) - ); + assert_ok!(Call::StakedRelayers(StakedRelayersCall::register_staked_relayer(100)) + .dispatch(origin_of(account_of(user)))); SystemModule::set_block_number(StakedRelayersModule::get_maturity_period() + 100); // manually activate - assert_ok!(StakedRelayersModule::activate_staked_relayer(&account_of( - user - ))); + assert_ok!(StakedRelayersModule::activate_staked_relayer(&account_of(user))); let initial_sla = SlaModule::relayer_sla(account_of(ALICE)); @@ -87,22 +79,17 @@ fn integration_test_report_vault_theft() { fn setup_registered_relayer() { SystemModule::set_block_number(1); - assert_ok!(ExchangeRateOracleModule::_set_exchange_rate( - FixedU128::one() - )); + assert_ok!(ExchangeRateOracleModule::_set_exchange_rate(FixedU128::one())); // register as staked relayer assert_ok!( - Call::StakedRelayers(StakedRelayersCall::register_staked_relayer(100)) - .dispatch(origin_of(account_of(RELAYER))) + Call::StakedRelayers(StakedRelayersCall::register_staked_relayer(100)).dispatch(origin_of(account_of(RELAYER))) ); SystemModule::set_block_number(StakedRelayersModule::get_maturity_period() + 100); // manually activate - assert_ok!(StakedRelayersModule::activate_staked_relayer(&account_of( - RELAYER - ))); + assert_ok!(StakedRelayersModule::activate_staked_relayer(&account_of(RELAYER))); } #[test] fn integration_test_report_vault_under_liquidation_threshold() { @@ -121,10 +108,12 @@ fn integration_test_report_vault_under_liquidation_threshold() { let initial_sla = SlaModule::relayer_sla(account_of(RELAYER)); - assert_ok!(Call::StakedRelayers( - StakedRelayersCall::report_vault_under_liquidation_threshold(account_of(VAULT)) - ) - .dispatch(origin_of(account_of(RELAYER)))); + assert_ok!( + Call::StakedRelayers(StakedRelayersCall::report_vault_under_liquidation_threshold( + account_of(VAULT) + )) + .dispatch(origin_of(account_of(RELAYER))) + ); // check sla increase for the report let expected_sla = initial_sla + SlaModule::relayer_correct_liquidation_report(); @@ -142,8 +131,7 @@ fn integration_test_report_oracle_offline() { >::set_timestamp(3600 * 1000 + 1); assert_ok!( - Call::StakedRelayers(StakedRelayersCall::report_oracle_offline()) - .dispatch(origin_of(account_of(RELAYER))) + Call::StakedRelayers(StakedRelayersCall::report_oracle_offline()).dispatch(origin_of(account_of(RELAYER))) ); // check sla increase for the report diff --git a/parachain/runtime/tests/test_vault_sla.rs b/parachain/runtime/tests/test_vault_sla.rs index 035817cc41..289e8b6809 100644 --- a/parachain/runtime/tests/test_vault_sla.rs +++ b/parachain/runtime/tests/test_vault_sla.rs @@ -1,9 +1,9 @@ mod mock; -use mock::issue_testing_utils::{ - self, execute_issue, execute_refund, request_issue, ExecuteIssueBuilder, +use mock::{ + issue_testing_utils::{self, execute_issue, execute_refund, request_issue, ExecuteIssueBuilder}, + redeem_testing_utils::{cancel_redeem, setup_cancelable_redeem}, + *, }; -use mock::redeem_testing_utils::{cancel_redeem, setup_cancelable_redeem}; -use mock::*; const USER: [u8; 32] = issue_testing_utils::USER; const VAULT: [u8; 32] = issue_testing_utils::VAULT; @@ -70,9 +70,7 @@ fn test_sla_increase_for_submitting_proof_for_issue_against_self() { // check that the vault who submitted the proof is rewarded with both SLA rewards assert_eq!( SlaModule::vault_sla(account_of(VAULT)), - initial_sla() - + expected_sla_increase_for_issue - + expected_sla_increase_for_proof_submission + initial_sla() + expected_sla_increase_for_issue + expected_sla_increase_for_proof_submission ); }) } diff --git a/parachain/service/src/cumulus.rs b/parachain/service/src/cumulus.rs index 55bde78623..092c0f17ff 100644 --- a/parachain/service/src/cumulus.rs +++ b/parachain/service/src/cumulus.rs @@ -2,9 +2,7 @@ use btc_parachain_runtime::{opaque::Block, RuntimeApi}; use cumulus_consensus::{build_relay_chain_consensus, BuildRelayChainConsensusParams}; use cumulus_network::build_block_announce_validator; use cumulus_primitives::ParaId; -use cumulus_service::{ - prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams, -}; +use cumulus_service::{prepare_node_config, start_collator, start_full_node, StartCollatorParams, StartFullNodeParams}; use polkadot_primitives::v0::CollatorPair; // use rococo_primitives::Block; pub use sc_executor::NativeExecutor; @@ -90,13 +88,11 @@ async fn start_node_impl( let parachain_config = prepare_node_config(parachain_config); - let polkadot_full_node = - cumulus_service::build_polkadot_full_node(polkadot_config, collator_key.public()).map_err( - |e| match e { - polkadot_service::Error::Sub(x) => x, - s => format!("{}", s).into(), - }, - )?; + let polkadot_full_node = cumulus_service::build_polkadot_full_node(polkadot_config, collator_key.public()) + .map_err(|e| match e { + polkadot_service::Error::Sub(x) => x, + s => format!("{}", s).into(), + })?; let params = new_partial(¶chain_config)?; params @@ -224,12 +220,5 @@ pub async fn start_node( id: ParaId, validator: bool, ) -> sc_service::error::Result<(TaskManager, Arc)> { - start_node_impl( - parachain_config, - collator_key, - polkadot_config, - id, - validator, - ) - .await + start_node_impl(parachain_config, collator_key, polkadot_config, id, validator).await } diff --git a/parachain/service/src/grandpa.rs b/parachain/service/src/grandpa.rs index 2b87531282..8500b326be 100644 --- a/parachain/service/src/grandpa.rs +++ b/parachain/service/src/grandpa.rs @@ -5,8 +5,7 @@ use sc_finality_grandpa::SharedVoterState; use sc_service::{error::Error as ServiceError, Configuration, RpcHandlers, TaskManager}; use sp_consensus_aura::sr25519::AuthorityPair as AuraPair; use sp_inherents::InherentDataProviders; -use std::sync::Arc; -use std::time::Duration; +use std::{sync::Arc, time::Duration}; use crate::{Executor, FullBackend, FullClient}; @@ -25,12 +24,7 @@ pub fn new_partial( sc_consensus_aura::AuraBlockImport< Block, FullClient, - sc_finality_grandpa::GrandpaBlockImport< - FullBackend, - Block, - FullClient, - FullSelectChain, - >, + sc_finality_grandpa::GrandpaBlockImport, AuraPair, >, sc_finality_grandpa::LinkHalf, @@ -54,31 +48,23 @@ pub fn new_partial( client.clone(), ); - let (grandpa_block_import, grandpa_link) = sc_finality_grandpa::block_import( - client.clone(), - &(client.clone() as Arc<_>), - select_chain.clone(), - )?; + let (grandpa_block_import, grandpa_link) = + sc_finality_grandpa::block_import(client.clone(), &(client.clone() as Arc<_>), select_chain.clone())?; - let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( - grandpa_block_import.clone(), - client.clone(), - ); + let aura_block_import = + sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(grandpa_block_import.clone(), client.clone()); - let import_queue = - sc_consensus_aura::import_queue::(ImportQueueParams { - block_import: aura_block_import.clone(), - justification_import: Some(Box::new(grandpa_block_import.clone())), - client: client.clone(), - inherent_data_providers: inherent_data_providers.clone(), - spawner: &task_manager.spawn_essential_handle(), - can_author_with: sp_consensus::CanAuthorWithNativeVersion::new( - client.executor().clone(), - ), - slot_duration: sc_consensus_aura::slot_duration(&*client)?, - registry: config.prometheus_registry(), - check_for_equivocation: Default::default(), - })?; + let import_queue = sc_consensus_aura::import_queue::(ImportQueueParams { + block_import: aura_block_import.clone(), + justification_import: Some(Box::new(grandpa_block_import.clone())), + client: client.clone(), + inherent_data_providers: inherent_data_providers.clone(), + spawner: &task_manager.spawn_essential_handle(), + can_author_with: sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()), + slot_duration: sc_consensus_aura::slot_duration(&*client)?, + registry: config.prometheus_registry(), + check_for_equivocation: Default::default(), + })?; Ok(sc_service::PartialComponents { client, @@ -155,22 +141,21 @@ pub fn new_full(mut config: Configuration) -> Result<(TaskManager, RpcHandlers), }) }; - let (rpc_handlers, telemetry_connection_notifier) = - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - network: network.clone(), - client: client.clone(), - keystore: keystore_container.sync_keystore(), - task_manager: &mut task_manager, - transaction_pool: transaction_pool.clone(), - rpc_extensions_builder, - on_demand: None, - remote_blockchain: None, - backend, - network_status_sinks, - system_rpc_tx, - config, - telemetry_span: None, - })?; + let (rpc_handlers, telemetry_connection_notifier) = sc_service::spawn_tasks(sc_service::SpawnTasksParams { + network: network.clone(), + client: client.clone(), + keystore: keystore_container.sync_keystore(), + task_manager: &mut task_manager, + transaction_pool: transaction_pool.clone(), + rpc_extensions_builder, + on_demand: None, + remote_blockchain: None, + backend, + network_status_sinks, + system_rpc_tx, + config, + telemetry_span: None, + })?; if role.is_authority() { let proposer_factory = sc_basic_authorship::ProposerFactory::new( @@ -180,30 +165,25 @@ pub fn new_full(mut config: Configuration) -> Result<(TaskManager, RpcHandlers), prometheus_registry.as_ref(), ); - let can_author_with = - sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); + let can_author_with = sp_consensus::CanAuthorWithNativeVersion::new(client.executor().clone()); - let aura = sc_consensus_aura::start_aura::( - StartAuraParams { - slot_duration: sc_consensus_aura::slot_duration(&*client)?, - client: client.clone(), - select_chain, - block_import, - proposer_factory, - inherent_data_providers: inherent_data_providers.clone(), - force_authoring, - backoff_authoring_blocks, - keystore: keystore_container.sync_keystore(), - can_author_with, - sync_oracle: network.clone(), - }, - )?; + let aura = sc_consensus_aura::start_aura::(StartAuraParams { + slot_duration: sc_consensus_aura::slot_duration(&*client)?, + client: client.clone(), + select_chain, + block_import, + proposer_factory, + inherent_data_providers: inherent_data_providers.clone(), + force_authoring, + backoff_authoring_blocks, + keystore: keystore_container.sync_keystore(), + can_author_with, + sync_oracle: network.clone(), + })?; // the AURA authoring task is considered essential, i.e. if it // fails we take down the service with it. - task_manager - .spawn_essential_handle() - .spawn_blocking("aura", aura); + task_manager.spawn_essential_handle().spawn_blocking("aura", aura); } // if the node isn't actively participating in consensus then it doesn't @@ -243,10 +223,9 @@ pub fn new_full(mut config: Configuration) -> Result<(TaskManager, RpcHandlers), // the GRANDPA voter task is considered infallible, i.e. // if it fails we take down the service with it. - task_manager.spawn_essential_handle().spawn_blocking( - "grandpa-voter", - sc_finality_grandpa::run_grandpa_voter(grandpa_config)?, - ); + task_manager + .spawn_essential_handle() + .spawn_blocking("grandpa-voter", sc_finality_grandpa::run_grandpa_voter(grandpa_config)?); } network_starter.start_network(); @@ -273,29 +252,23 @@ pub fn new_light(mut config: Configuration) -> Result<(TaskManager, RpcHandlers) on_demand.clone(), )); - let (grandpa_block_import, _) = sc_finality_grandpa::block_import( - client.clone(), - &(client.clone() as Arc<_>), - select_chain.clone(), - )?; + let (grandpa_block_import, _) = + sc_finality_grandpa::block_import(client.clone(), &(client.clone() as Arc<_>), select_chain.clone())?; - let aura_block_import = sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new( - grandpa_block_import.clone(), - client.clone(), - ); + let aura_block_import = + sc_consensus_aura::AuraBlockImport::<_, _, _, AuraPair>::new(grandpa_block_import.clone(), client.clone()); - let import_queue = - sc_consensus_aura::import_queue::(ImportQueueParams { - block_import: aura_block_import.clone(), - justification_import: Some(Box::new(grandpa_block_import.clone())), - client: client.clone(), - inherent_data_providers: InherentDataProviders::new(), - spawner: &task_manager.spawn_essential_handle(), - can_author_with: sp_consensus::NeverCanAuthor, - slot_duration: sc_consensus_aura::slot_duration(&*client)?, - registry: config.prometheus_registry(), - check_for_equivocation: Default::default(), - })?; + let import_queue = sc_consensus_aura::import_queue::(ImportQueueParams { + block_import: aura_block_import.clone(), + justification_import: Some(Box::new(grandpa_block_import.clone())), + client: client.clone(), + inherent_data_providers: InherentDataProviders::new(), + spawner: &task_manager.spawn_essential_handle(), + can_author_with: sp_consensus::NeverCanAuthor, + slot_duration: sc_consensus_aura::slot_duration(&*client)?, + registry: config.prometheus_registry(), + check_for_equivocation: Default::default(), + })?; let (network, network_status_sinks, system_rpc_tx, network_starter) = sc_service::build_network(sc_service::BuildNetworkParams { @@ -318,22 +291,21 @@ pub fn new_light(mut config: Configuration) -> Result<(TaskManager, RpcHandlers) ); } - let (rpc_handlers, _telemetry_connection_notifier) = - sc_service::spawn_tasks(sc_service::SpawnTasksParams { - remote_blockchain: Some(backend.remote_blockchain()), - transaction_pool, - task_manager: &mut task_manager, - on_demand: Some(on_demand), - rpc_extensions_builder: Box::new(|_, _| ()), - config, - client, - keystore: keystore_container.sync_keystore(), - backend, - network, - network_status_sinks, - system_rpc_tx, - telemetry_span: None, - })?; + let (rpc_handlers, _telemetry_connection_notifier) = sc_service::spawn_tasks(sc_service::SpawnTasksParams { + remote_blockchain: Some(backend.remote_blockchain()), + transaction_pool, + task_manager: &mut task_manager, + on_demand: Some(on_demand), + rpc_extensions_builder: Box::new(|_, _| ()), + config, + client, + keystore: keystore_container.sync_keystore(), + backend, + network, + network_status_sinks, + system_rpc_tx, + telemetry_span: None, + })?; network_starter.start_network(); diff --git a/parachain/src/chain_spec.rs b/parachain/src/chain_spec.rs index bc8d388232..3e9628c828 100644 --- a/parachain/src/chain_spec.rs +++ b/parachain/src/chain_spec.rs @@ -1,8 +1,7 @@ use btc_parachain_runtime::{ - AccountId, BTCRelayConfig, DOTConfig, ExchangeRateOracleConfig, FeeConfig, GenesisConfig, - IssueConfig, PolkaBTCConfig, RedeemConfig, RefundConfig, ReplaceConfig, Signature, SlaConfig, - StakedRelayersConfig, SudoConfig, SystemConfig, VaultRegistryConfig, DAYS, MINUTES, - WASM_BINARY, + AccountId, BTCRelayConfig, DOTConfig, ExchangeRateOracleConfig, FeeConfig, GenesisConfig, IssueConfig, + PolkaBTCConfig, RedeemConfig, RefundConfig, ReplaceConfig, Signature, SlaConfig, StakedRelayersConfig, SudoConfig, + SystemConfig, VaultRegistryConfig, DAYS, MINUTES, WASM_BINARY, }; #[cfg(feature = "aura-grandpa")] @@ -166,15 +165,11 @@ pub fn rococo_testnet_config(id: ParaId) -> ChainSpec { ], vec![ ( - get_account_id_from_string( - "5H8zjSWfzMn86d1meeNrZJDj3QZSvRjKxpTfuVaZ46QJZ4qs", - ), + get_account_id_from_string("5H8zjSWfzMn86d1meeNrZJDj3QZSvRjKxpTfuVaZ46QJZ4qs"), "Interlay".as_bytes().to_vec(), ), ( - get_account_id_from_string( - "5FPBT2BVVaLveuvznZ9A1TUtDcbxK5yvvGcMTJxgFmhcWGwj", - ), + get_account_id_from_string("5FPBT2BVVaLveuvznZ9A1TUtDcbxK5yvvGcMTJxgFmhcWGwj"), "Band".as_bytes().to_vec(), ), ], @@ -215,24 +210,18 @@ pub fn beta_testnet_config() -> ChainSpec { vec![ ( // 5DJ3wbdicFSFFudXndYBuvZKjucTsyxtJX5WPzQM8HysSkFY - hex!["366a092a27b4b28199a588b0155a2c9f3f0513d92481de4ee2138273926fa91c"] - .unchecked_into(), - hex!["dce82040dc0a90843897aee1cc1a96c205fe7c1165b8f46635c2547ed15a3013"] - .unchecked_into(), + hex!["366a092a27b4b28199a588b0155a2c9f3f0513d92481de4ee2138273926fa91c"].unchecked_into(), + hex!["dce82040dc0a90843897aee1cc1a96c205fe7c1165b8f46635c2547ed15a3013"].unchecked_into(), ), ( // 5HW7ApFamN6ovtDkFyj67tRLRhp8B2kVNjureRUWWYhkTg9j - hex!["f08cc7cf45f88e6dbe312a63f6ce639061834b4208415b235f77a67b51435f63"] - .unchecked_into(), - hex!["5b4651cf045ddf55f0df7bfbb9bb4c45bbeb3c536c6ce4a98275781b8f0f0754"] - .unchecked_into(), + hex!["f08cc7cf45f88e6dbe312a63f6ce639061834b4208415b235f77a67b51435f63"].unchecked_into(), + hex!["5b4651cf045ddf55f0df7bfbb9bb4c45bbeb3c536c6ce4a98275781b8f0f0754"].unchecked_into(), ), ( // 5FNbq8zGPZtinsfgyD4w2G3BMh75H3r2Qg3uKudTZkJtRru6 - hex!["925ad4bdf35945bea91baeb5419a7ffa07002c6a85ba334adfa7cb5b05623c1b"] - .unchecked_into(), - hex!["8de3db7b51864804d2dd5c5905d571aa34d7161537d5a0045755b72d1ac2062e"] - .unchecked_into(), + hex!["925ad4bdf35945bea91baeb5419a7ffa07002c6a85ba334adfa7cb5b05623c1b"].unchecked_into(), + hex!["8de3db7b51864804d2dd5c5905d571aa34d7161537d5a0045755b72d1ac2062e"].unchecked_into(), ), ], vec![ @@ -254,15 +243,11 @@ pub fn beta_testnet_config() -> ChainSpec { ], vec![ ( - get_account_id_from_string( - "5H8zjSWfzMn86d1meeNrZJDj3QZSvRjKxpTfuVaZ46QJZ4qs", - ), + get_account_id_from_string("5H8zjSWfzMn86d1meeNrZJDj3QZSvRjKxpTfuVaZ46QJZ4qs"), "Interlay".as_bytes().to_vec(), ), ( - get_account_id_from_string( - "5FPBT2BVVaLveuvznZ9A1TUtDcbxK5yvvGcMTJxgFmhcWGwj", - ), + get_account_id_from_string("5FPBT2BVVaLveuvznZ9A1TUtDcbxK5yvvGcMTJxgFmhcWGwj"), "Band".as_bytes().to_vec(), ), ], @@ -369,10 +354,7 @@ fn testnet_genesis( }, #[cfg(feature = "aura-grandpa")] pallet_grandpa: GrandpaConfig { - authorities: initial_authorities - .iter() - .map(|x| (x.1.clone(), 1)) - .collect(), + authorities: initial_authorities.iter().map(|x| (x.1.clone(), 1)).collect(), }, #[cfg(feature = "cumulus-polkadot")] parachain_info: ParachainInfoConfig { parachain_id: id }, @@ -381,11 +363,7 @@ fn testnet_genesis( key: root_key.clone(), }, pallet_balances_Instance1: DOTConfig { - balances: endowed_accounts - .iter() - .cloned() - .map(|k| (k, 1 << 60)) - .collect(), + balances: endowed_accounts.iter().cloned().map(|k| (k, 1 << 60)).collect(), }, pallet_balances_Instance2: PolkaBTCConfig { balances: vec![] }, staked_relayers: StakedRelayersConfig { @@ -421,7 +399,7 @@ fn testnet_genesis( minimum_collateral_vault: 0, punishment_delay: DAYS, secure_collateral_threshold: FixedU128::checked_from_rational(150, 100).unwrap(), // 150% - premium_redeem_threshold: FixedU128::checked_from_rational(135, 100).unwrap(), // 135% + premium_redeem_threshold: FixedU128::checked_from_rational(135, 100).unwrap(), // 135% auction_collateral_threshold: FixedU128::checked_from_rational(120, 100).unwrap(), // 120% liquidation_collateral_threshold: FixedU128::checked_from_rational(110, 100).unwrap(), // 110% liquidation_vault_account_id: liquidation_vault, @@ -429,12 +407,12 @@ fn testnet_genesis( fee: FeeConfig { issue_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% issue_griefing_collateral: FixedU128::checked_from_rational(5, 100000).unwrap(), // 0.005% - refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% - premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% - punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% - replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + refund_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + redeem_fee: FixedU128::checked_from_rational(5, 1000).unwrap(), // 0.5% + premium_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + auction_redeem_fee: FixedU128::checked_from_rational(5, 100).unwrap(), // 5% + punishment_fee: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% + replace_griefing_collateral: FixedU128::checked_from_rational(1, 10).unwrap(), // 10% fee_pool_account_id: fee_pool, maintainer_account_id: maintainer, epoch_period: 5, diff --git a/parachain/src/command.rs b/parachain/src/command.rs index 857ce6703e..8daab26506 100644 --- a/parachain/src/command.rs +++ b/parachain/src/command.rs @@ -33,10 +33,7 @@ use { cumulus_service::genesis::generate_genesis_block, log::info, polkadot_parachain::primitives::AccountIdConversion, - sc_cli::{ - CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams, - SharedParams, - }, + sc_cli::{CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams, SharedParams}, sc_service::config::{BasePath, PrometheusConfig}, sp_core::hexdisplay::HexDisplay, sp_runtime::traits::Block as BlockT, @@ -60,9 +57,7 @@ fn load_spec( #[cfg(feature = "cumulus-polkadot")] para_id, ))), - path => Ok(Box::new(chain_spec::ChainSpec::from_json_file( - path.into(), - )?)), + path => Ok(Box::new(chain_spec::ChainSpec::from_json_file(path.into())?)), } } @@ -135,8 +130,7 @@ impl SubstrateCli for RelayChainCli { } fn load_spec(&self, id: &str) -> std::result::Result, String> { - polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter()) - .load_spec(id) + polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter()).load_spec(id) } fn native_runtime_version(chain_spec: &Box) -> &'static RuntimeVersion { @@ -179,9 +173,7 @@ pub fn run() -> Result<()> { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { - client, - task_manager, - .. + client, task_manager, .. } = btc_parachain_service::new_partial(&config)?; Ok((cmd.run(client, config.database), task_manager)) }) @@ -190,9 +182,7 @@ pub fn run() -> Result<()> { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { let PartialComponents { - client, - task_manager, - .. + client, task_manager, .. } = btc_parachain_service::new_partial(&config)?; Ok((cmd.run(client, config.chain_spec), task_manager)) }) @@ -267,8 +257,7 @@ pub fn run() -> Result<()> { builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); let _ = builder.init(); - let raw_wasm_blob = - extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?; + let raw_wasm_blob = extract_genesis_wasm(&cli.load_spec(¶ms.chain.clone().unwrap_or_default())?)?; let output_buf = if params.raw { raw_wasm_blob } else { @@ -320,17 +309,14 @@ async fn start_node(cli: Cli, config: Configuration) -> sc_service::error::Resul let id = ParaId::from(cli.run.parachain_id.or(para_id).unwrap_or(100)); - let parachain_account = - AccountIdConversion::::into_account(&id); + let parachain_account = AccountIdConversion::::into_account(&id); - let block: Block = - generate_genesis_block(&config.chain_spec).map_err(|e| format!("{:?}", e))?; + let block: Block = generate_genesis_block(&config.chain_spec).map_err(|e| format!("{:?}", e))?; let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode())); let task_executor = config.task_executor.clone(); - let polkadot_config = - SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, task_executor, None) - .map_err(|err| format!("Relay chain argument error: {}", err))?; + let polkadot_config = SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, task_executor, None) + .map_err(|err| format!("Relay chain argument error: {}", err))?; let collator = cli.run.base.validator || cli.collator; info!("Parachain id: {:?}", id);