Skip to content

Commit

Permalink
Changing the event structure and adding tests for multiple markers.
Browse files Browse the repository at this point in the history
  • Loading branch information
arnabmitra committed Aug 17, 2023
1 parent 9719a26 commit 3224838
Show file tree
Hide file tree
Showing 6 changed files with 210 additions and 30 deletions.
159 changes: 148 additions & 11 deletions crates/contract/src/execute/settlement/add_loan_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,8 @@ pub fn handle(
.iter()
.any(|event| event.ty == "loan_pool_added")
{
response = response.add_attribute("added_by", info.sender);
response = response.add_attribute("loan_pool_added_by", info.sender);
response = response.add_attribute("action", "loan_pool_added");
}
// Set response data to collaterals vector
response = response.set_data(to_binary(&LoanPoolMarkers::new(collaterals))?);
Expand All @@ -102,7 +103,7 @@ fn create_marker_pool_collateral(
Err(e) => {
return Err(ContractError::InvalidMarker {
message: format!("Unable to get marker by denom: {}", e),
})
});
}
};

Expand Down Expand Up @@ -281,22 +282,37 @@ mod tests {

// Checking response attributes and events
let mut found_event = false;
let mut found_attribute = false;

assert_eq!(response.events.len(), 1);
assert_eq!(response.attributes.len(), 2);
for event in response.events.iter() {
if event.ty == "loan_pool_added" {
found_event = true;
// Check event attributes here if needed
}
}
let mut found_attributes: Vec<String> = Vec::new();

for attribute in response.attributes.iter() {
if attribute.key == "added_by" {
assert_eq!(attribute.value, info.sender.clone());
found_attribute = true;
match attribute.key.as_str() {
"loan_pool_added_by" => {
assert_eq!(attribute.value, info.sender.clone());
found_attributes.push(attribute.key.clone());
}
"action" => {
assert_eq!(attribute.value, "loan_pool_added");
found_attributes.push(attribute.key.clone());
}
// Add more keys to check here
_ => (),
}
}

assert_eq!(
found_attributes.len(),
2,
"Did not find all required attributes"
);

assert_eq!(response.messages.len(), 1);

let expected_msg1 = SubMsg {
Expand All @@ -315,7 +331,6 @@ mod tests {

assert_eq!(response.messages[0], expected_msg1);
assert!(found_event, "Failed to find loan_pool_added event");
assert!(found_attribute, "Failed to find added_by attribute");
}
Err(e) => panic!("Error: {:?}", e),
}
Expand Down Expand Up @@ -386,7 +401,7 @@ mod tests {
fn test_handle_in_whitelist_validation_fail() {
let mut deps = mock_dependencies(&[]);
instantiate_contract(deps.as_mut()).expect("should be able to instantiate contract");
let marker = MockMarker::new_owned_marker_supply_variable("contributor");
let marker = MockMarker::new_owned_marker_custom("contributor", None, false);
let marker_denom = marker.denom.clone();
deps.querier.with_markers(vec![marker.clone()]);
let env = mock_env();
Expand Down Expand Up @@ -481,11 +496,12 @@ mod tests {
fn test_handle_in_whitelist_validation_success() {
let mut deps = mock_dependencies(&[]);
instantiate_contract(deps.as_mut()).expect("should be able to instantiate contract");
let marker = MockMarker::new_owned_marker_supply_variable("contributor");
let marker = MockMarker::new_owned_marker_custom("contributor", None, false);
let marker_denom = marker.denom.clone();
deps.querier.with_markers(vec![marker.clone()]);
let env = mock_env();
let info = mock_info("contributor", &[]);
// use gp
let info_white_list = mock_info("gp", &[]);
let addr_contributor = Addr::unchecked("contributor");
let white_list_addr = vec![addr_contributor.clone()];
Expand Down Expand Up @@ -556,12 +572,133 @@ mod tests {
}

for attribute in response.attributes.iter() {
if attribute.key == "added_by" {
if attribute.key == "loan_pool_added_by" {
assert_eq!(attribute.value, info.sender.clone());
found_attribute = true;
}
}

assert!(found_event, "Failed to find loan_pool_added event");
assert!(found_attribute, "Failed to find added_by attribute");
}
Err(e) => match e {
ContractError::InvalidMarker { .. } => (), // continue
unexpected_error => panic!("Error: {:?}", unexpected_error),
},
}
}

#[test]
fn test_handle_in_whitelist_validation_success_multiple() {
let mut deps = mock_dependencies(&[]);
instantiate_contract(deps.as_mut()).expect("should be able to instantiate contract");
let marker = MockMarker::new_owned_marker_custom("contributor", None, false);
let some_other_marker =
MockMarker::new_owned_marker_custom("contributor", Some("some_other_denom"), false);
deps.querier
.with_markers(vec![marker.clone(), some_other_marker.clone()]);
let env = mock_env();
let info = mock_info("contributor", &[]);
let info_white_list = mock_info("gp", &[]);
let addr_contributor = Addr::unchecked("contributor");
let white_list_addr = vec![addr_contributor.clone()];
let whitelist_result =
whitelist_loanpool_handle(deps.as_mut(), info_white_list.sender, white_list_addr);
assert!(whitelist_result.is_ok());
match whitelist_result {
Ok(response) => {
for attribute in response.attributes.iter() {
if attribute.key == "action" {
assert_eq!(attribute.value, "whitelist_added");
} else if attribute.key == "address_whitelisted" {
// Verify if the addresses are correct
let whitelisted_addresses: Vec<&str> = attribute.value.split(",").collect();
assert_eq!(whitelisted_addresses, vec!["contributor"]);
}
}
}
Err(e) => panic!("Error: {:?}", e),
}

// Create a loan pool
let loan_pools = ContributeLoanPools {
markers: vec![marker.denom.to_owned(), some_other_marker.denom.to_owned()],
};

let expected_collaterals = vec![
LoanPoolMarkerCollateral {
marker_address: marker.address.clone(),
marker_denom: marker.denom.to_owned(),
share_count: marker.total_supply.atomics(),
original_contributor: info.sender.to_owned(),
removed_permissions: if let Some(first_permission) = marker.permissions.first() {
vec![first_permission.clone()]
} else {
vec![]
},
},
LoanPoolMarkerCollateral {
marker_address: some_other_marker.address.clone(),
marker_denom: some_other_marker.denom.to_owned(),
share_count: some_other_marker.total_supply.atomics(),
original_contributor: info.sender.to_owned(),
removed_permissions: if let Some(first_permission) =
some_other_marker.permissions.first()
{
vec![first_permission.clone()]
} else {
vec![]
},
},
];
// Call the handle function
let loan_pool_result =
add_loanpool_handle(deps.as_mut(), env.to_owned(), info.clone(), loan_pools);
// Assert that the result is an error
assert!(loan_pool_result.is_ok());
match loan_pool_result {
Ok(response) => {
// Checking response data
let loan_pool_markers: LoanPoolMarkers =
from_binary(&response.data.unwrap()).unwrap();
assert_eq!(loan_pool_markers.collaterals, expected_collaterals); //replace `collaterals` with expected vec of collaterals

// Checking response attributes and events
let mut found_event = false;
let mut found_attribute = false;

for event in response.events.iter() {
if event.ty == "loan_pool_added" {
found_event = true;
// Check event attributes here if needed
}
}

for attribute in response.attributes.iter() {
if attribute.key == "loan_pool_added_by" {
assert_eq!(attribute.value, info.sender.clone());
found_attribute = true;
}
}

assert_eq!(response.messages.len(), 2);

let expected_msg1 = SubMsg {
id: 0,
msg: Custom(ProvenanceMsg {
route: marker_route,
params: Marker(RevokeMarkerAccess {
denom: "markerdenom".parse().unwrap(),
address: Addr::unchecked("contributor".to_string()),
}),
version: "2.0.0".parse().unwrap(),
}),
gas_limit: None,
reply_on: Never,
};

assert_eq!(response.messages[0], expected_msg1);

assert!(found_event, "Failed to find loan_pool_added event");
assert!(found_attribute, "Failed to find added_by attribute");
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ pub fn remove_loan_pool_contributors(

let response = Response::new()
.add_attribute("action", "whitelist_removed")
.add_attribute("address_removed", contributors_str);
.add_attribute("whitelist_address_removed", contributors_str);

Ok(response)
}
Expand Down Expand Up @@ -63,7 +63,7 @@ mod tests {
assert_eq!(response.attributes.len(), 2);
assert_eq!(response.attributes[0].key, "action");
assert_eq!(response.attributes[0].value, "whitelist_removed");
assert_eq!(response.attributes[1].key, "address_removed");
assert_eq!(response.attributes[1].key, "whitelist_address_removed");
assert_eq!(response.attributes[1].value, "addr1,addr2");

// Test adding contributors by someone else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn loan_pool_contributors(
let contributors_str = contributors_as_str.join(",");
let response = Response::new()
.add_attribute("action", "whitelist_added")
.add_attribute("address_whitelisted", contributors_str);
.add_attribute("addresses_whitelisted", contributors_str);
Ok(response)
}

Expand All @@ -60,7 +60,7 @@ mod tests {
assert_eq!(response.attributes.len(), 2);
assert_eq!(response.attributes[0].key, "action");
assert_eq!(response.attributes[0].value, "whitelist_added");
assert_eq!(response.attributes[1].key, "address_whitelisted");
assert_eq!(response.attributes[1].key, "addresses_whitelisted");
assert_eq!(response.attributes[1].value, "addr1,addr2");

// Test adding contributors by someone else
Expand Down
32 changes: 24 additions & 8 deletions crates/contract/src/execute/settlement/withdraw_loan_pool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,8 @@ pub fn handle(
.iter()
.any(|event| event.ty == "loan_pool_withdrawn")
{
response = response.add_attribute("removed_by", info.sender);
response = response.add_attribute("action", "loan_pool_removed");
response = response.add_attribute("loan_pool_removed_by", info.sender);
}
// Set response data to collaterals vector
response = response.set_data(to_binary(&LoanPoolMarkers::new(collaterals))?);
Expand Down Expand Up @@ -208,7 +209,7 @@ mod tests {
}

for attribute in response.attributes.iter() {
if attribute.key == "added_by" {
if attribute.key == "loan_pool_added_by" {
assert_eq!(attribute.value, info.sender.clone());
found_attribute = true;
}
Expand Down Expand Up @@ -240,10 +241,10 @@ mod tests {
let withdraw_loan_pool_result: LoanPoolMarkers =
from_binary(&response.data.unwrap()).unwrap();
assert_eq!(withdraw_loan_pool_result.collaterals, expected_collaterals); //replace `collaterals` with expected vec of collaterals

assert_eq!(response.events.len(), 1);
assert_eq!(response.attributes.len(), 2);
// Checking response attributes and events
let mut found_event = false;
let mut found_attribute = false;

for event in response.events.iter() {
if event.ty == "loan_pool_withdrawn" {
Expand All @@ -252,13 +253,29 @@ mod tests {
}
}

let mut found_attributes: Vec<String> = Vec::new();

for attribute in response.attributes.iter() {
if attribute.key == "removed_by" {
assert_eq!(attribute.value, info.sender.clone());
found_attribute = true;
match attribute.key.as_str() {
"loan_pool_removed_by" => {
assert_eq!(attribute.value, info.sender.clone());
found_attributes.push(attribute.key.clone());
}
"action" => {
assert_eq!(attribute.value, "loan_pool_removed");
found_attributes.push(attribute.key.clone());
}
// Add more keys to check here
_ => (),
}
}

assert_eq!(
found_attributes.len(),
2,
"Did not find all required attributes"
);

assert_eq!(response.messages.len(), 2);

let expected_msg1 = SubMsg {
Expand Down Expand Up @@ -294,7 +311,6 @@ mod tests {
assert_eq!(response.messages[1], expected_msg2);

assert!(found_event, "Failed to find loan_pool_withdrawn event");
assert!(found_attribute, "Failed to find withdrawn_by attribute");
}
Err(e) => panic!("Error: {:?}", e),
}
Expand Down
26 changes: 19 additions & 7 deletions crates/contract/src/util/mock_marker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,10 @@ impl Default for MockMarker {
}

impl MockMarker {
pub fn new(supply_fixed: bool) -> Self {
pub fn new(supply_fixed: bool, denom_str: String) -> Self {
Self {
address: Addr::unchecked(DEFAULT_MARKER_ADDRESS),
coins: coins(DEFAULT_MARKER_HOLDINGS, DEFAULT_MARKER_DENOM),
coins: coins(DEFAULT_MARKER_HOLDINGS, denom_str.to_owned()),
account_number: 50,
sequence: 0,
manager: "".to_string(),
Expand All @@ -68,7 +68,7 @@ impl MockMarker {
],
}],
status: MarkerStatus::Active,
denom: DEFAULT_MARKER_DENOM.to_string(),
denom: denom_str.to_owned(),
total_supply: decimal(DEFAULT_MARKER_HOLDINGS),
marker_type: MarkerType::Coin,
supply_fixed, // 'supply_fixed' passed as argument
Expand Down Expand Up @@ -96,7 +96,14 @@ impl MockMarker {
}
}

pub fn new_owned_mock_marker_supply_variable<S: Into<String>>(owner_address: S) -> Self {
pub fn new_owned_mock_marker_supply_variable<S: Into<String>>(
owner_address: S,
denom: Option<S>,
supply_fixed: bool,
) -> Self {
let default_denom = DEFAULT_MARKER_DENOM;
let denom_str = denom.map_or(default_denom.into(), Into::into);

Self {
// permissions: AccessGrant array that always leads with owner permission in test code
permissions: vec![
Expand All @@ -109,16 +116,21 @@ impl MockMarker {
permissions: vec![MarkerAccess::Admin, MarkerAccess::Withdraw],
},
],
..Self::new(false)
..Self::new(supply_fixed, denom_str)
}
}

pub fn new_owned_marker<S: Into<String>>(owner_address: S) -> Marker {
Self::new_owned_mock_marker(owner_address).to_marker()
}

pub fn new_owned_marker_supply_variable<S: Into<String>>(owner_address: S) -> Marker {
Self::new_owned_mock_marker_supply_variable(owner_address).to_marker()
pub fn new_owned_marker_custom<S: Into<String>>(
owner_address: S,
denom_str: Option<S>,
supply_fixed: bool,
) -> Marker {
Self::new_owned_mock_marker_supply_variable(owner_address, denom_str, supply_fixed)
.to_marker()
}

pub fn to_marker(self) -> Marker {
Expand Down
Loading

0 comments on commit 3224838

Please sign in to comment.