Skip to content

Commit

Permalink
Add unittests
Browse files Browse the repository at this point in the history
  • Loading branch information
deniszagumennov committed Oct 3, 2024
1 parent e0fda6a commit 09d7218
Show file tree
Hide file tree
Showing 10 changed files with 277 additions and 10 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 5 additions & 5 deletions contracts/core/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -262,26 +262,26 @@ fn test_update_withdrawn_amount() {
};

unbond_batches_map()
.save(deps.as_mut().storage, 1, withdrawn_batch)
.save(deps.as_mut().storage, 0, withdrawn_batch)
.unwrap();

unbond_batches_map()
.save(deps.as_mut().storage, 0, unbonding_batch)
.save(deps.as_mut().storage, 1, unbonding_batch)
.unwrap();

let withdrawn_res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info("withdrawal_manager_contract", &[]),
ExecuteMsg::UpdateWithdrawnAmount {
batch_id: 1,
batch_id: 0,
withdrawn_amount: Uint128::from(1001u128),
},
);
assert!(withdrawn_res.is_ok());

let new_withdrawn_amount = unbond_batches_map()
.load(deps.as_mut().storage, 1)
.load(deps.as_mut().storage, 0)
.unwrap()
.withdrawn_amount;
assert_eq!(new_withdrawn_amount, Some(Uint128::from(1001u128)));
Expand All @@ -291,7 +291,7 @@ fn test_update_withdrawn_amount() {
mock_env().clone(),
mock_info("withdrawal_manager_contract", &[]),
ExecuteMsg::UpdateWithdrawnAmount {
batch_id: 0,
batch_id: 1,
withdrawn_amount: Uint128::from(2002u128),
},
)
Expand Down
1 change: 1 addition & 0 deletions contracts/withdrawal-manager/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,4 @@ drop-helpers = { workspace = true }
thiserror = { workspace = true }
semver = { workspace = true }
cw-utils = { workspace = true }
log = "0.4.22"
17 changes: 14 additions & 3 deletions contracts/withdrawal-manager/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,7 @@ fn execute_receive_withdrawal_denoms(

let withdrawn_coin = cw_utils::one_coin(&info)?;
let Coin { amount, denom } = withdrawn_coin.clone();
let batch_id = get_batch_id_by_withdrawal_denom(denom)?;
let batch_id = get_batch_id_by_withdrawal_denom(denom, &config)?;

let unbond_batch: UnbondBatch = deps.querier.query_wasm_smart(
&config.core_contract,
Expand Down Expand Up @@ -301,24 +301,35 @@ fn execute_receive_withdrawal_denoms(
}),
];

Ok(response("execute-receive_nft", CONTRACT_NAME, attrs).add_messages(messages))
Ok(response("execute-receive_withdrawal_denoms", CONTRACT_NAME, attrs).add_messages(messages))
}

fn get_batch_id_by_withdrawal_denom(withdrawal_denom: String) -> Result<u128, ContractError> {
fn get_batch_id_by_withdrawal_denom(
withdrawal_denom: String,
config: &Config,
) -> Result<u128, ContractError> {
let tokenfactory_denom_parts: Vec<&str> = withdrawal_denom.split('/').collect();

if tokenfactory_denom_parts.len() != 3 {
return Err(ContractError::InvalidDenom {});
}

let prefix = tokenfactory_denom_parts[0];
let creator_address = tokenfactory_denom_parts[1];
let subdenom = tokenfactory_denom_parts[2];

if !prefix.eq_ignore_ascii_case("factory") {
return Err(ContractError::InvalidDenom {});
}

if !creator_address.eq_ignore_ascii_case(config.withdrawal_token_contract.as_ref()) {
return Err(ContractError::InvalidDenom {});
}

let subdenom_parts: Vec<&str> = subdenom.split(':').collect();
if subdenom_parts.get(2).is_none() {
return Err(ContractError::InvalidDenom {});
}
let batch_id = subdenom_parts[2];

match batch_id.parse::<u128>() {
Expand Down
2 changes: 2 additions & 0 deletions contracts/withdrawal-manager/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
pub mod contract;
mod error;
#[cfg(test)]
mod tests;
246 changes: 246 additions & 0 deletions contracts/withdrawal-manager/src/tests.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
use crate::contract::execute;
use crate::error::ContractError;
use cosmwasm_std::{
testing::{mock_env, mock_info},
to_json_binary, Addr, BankMsg, Coin, CosmosMsg, Event, Response, SubMsg, Uint128, WasmMsg,
};
use drop_helpers::testing::mock_dependencies;
use drop_staking_base::state::core::{UnbondBatch, UnbondBatchStatus, UnbondBatchStatusTimestamps};
use drop_staking_base::{
msg::withdrawal_manager::ExecuteMsg,
state::withdrawal_manager::{Config, CONFIG},
};

fn get_default_config() -> Config {
Config {
core_contract: Addr::unchecked("core_contract"),
withdrawal_token_contract: Addr::unchecked("withdrawal_token_contract"),
withdrawal_voucher_contract: Addr::unchecked("withdrawal_voucher_contract"),
base_denom: "base_denom".to_string(),
}
}

fn get_default_unbond_batch_status_timestamps() -> UnbondBatchStatusTimestamps {
UnbondBatchStatusTimestamps {
new: 0,
unbond_requested: None,
unbond_failed: None,
unbonding: None,
withdrawing: None,
withdrawn: None,
withdrawing_emergency: None,
withdrawn_emergency: None,
}
}

#[test]
fn test_receive_withdrawal_denoms_happy_path() {
let mut deps = mock_dependencies(&[]);

CONFIG
.save(deps.as_mut().storage, &get_default_config())
.unwrap();

deps.querier.add_wasm_query_response("core_contract", |_| {
to_json_binary(&UnbondBatch {
total_dasset_amount_to_withdraw: Uint128::from(1001u128),
expected_native_asset_amount: Uint128::from(1001u128),
total_unbond_items: 1,
status: UnbondBatchStatus::Withdrawn,
expected_release_time: 9000,
slashing_effect: None,
unbonded_amount: Option::from(Uint128::new(1000u128)),
withdrawn_amount: None,
status_timestamps: get_default_unbond_batch_status_timestamps(),
})
.unwrap()
});

let res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info(
"any sender",
&[Coin::new(
1000,
"factory/withdrawal_token_contract/dATOM:unbond:0",
)],
),
ExecuteMsg::ReceiveWithdrawalDenoms {},
)
.unwrap();

assert_eq!(
res,
Response::new()
.add_submessages([SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: "withdrawal_token_contract".to_string(),
msg: to_json_binary(
&drop_staking_base::msg::withdrawal_token::ExecuteMsg::Burn {
batch_id: Uint128::zero(),
},
).unwrap(),
funds: vec![Coin::new(1000, "factory/withdrawal_token_contract/dATOM:unbond:0")],
})),
SubMsg::new(CosmosMsg::Bank(BankMsg::Send {
to_address: "any sender".to_string(),
amount: vec![Coin {
denom: "base_denom".to_string(),
amount: Uint128::from(999u128),
}],
})),
SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute {
contract_addr: "core_contract".to_string(),
msg: to_json_binary(
&drop_staking_base::msg::core::ExecuteMsg::UpdateWithdrawnAmount {
batch_id: 0u128,
withdrawn_amount: Uint128::from(999u128),
},
).unwrap(),
funds: vec![],
}))])
.add_event(
Event::new("crates.io:drop-staking__drop-withdrawal-manager-execute-receive_withdrawal_denoms").add_attributes(
vec![
("action", "receive_withdrawal_denoms"),
("batch_id", "0"),
("payout_amount", "999"),
("to_address", "any sender")
]
)
)
);
}

#[test]
fn test_receive_withdrawal_denoms_has_few_parts() {
let mut deps = mock_dependencies(&[]);

CONFIG
.save(deps.as_mut().storage, &get_default_config())
.unwrap();

let res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info("any sender", &[Coin::new(1000, "factory/dATOM:unbond:0")]),
ExecuteMsg::ReceiveWithdrawalDenoms {},
);
assert!(res.is_err());
assert_eq!(res, Err(ContractError::InvalidDenom {}));
}

#[test]
fn test_receive_withdrawal_denoms_has_incorrect_prefix() {
let mut deps = mock_dependencies(&[]);
let denom = "invalid/withdrawal_token_contract/dATOM:unbond:0";

CONFIG
.save(deps.as_mut().storage, &get_default_config())
.unwrap();

let res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info("any sender", &[Coin::new(1000, denom)]),
ExecuteMsg::ReceiveWithdrawalDenoms {},
);
assert!(res.is_err());
assert_eq!(res, Err(ContractError::InvalidDenom {}));
}

#[test]
fn test_receive_withdrawal_denoms_has_incorrect_owner() {
let mut deps = mock_dependencies(&[]);
let denom = "factory/invalid/dATOM:unbond:0";

CONFIG
.save(deps.as_mut().storage, &get_default_config())
.unwrap();

let res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info("any sender", &[Coin::new(1000, denom)]),
ExecuteMsg::ReceiveWithdrawalDenoms {},
);
assert!(res.is_err());
assert_eq!(res, Err(ContractError::InvalidDenom {}));
}

#[test]
fn test_receive_withdrawal_denoms_has_incorrect_subdenom() {
let mut deps = mock_dependencies(&[]);
let denom = "factory/withdrawal_token_contract/invalid";

CONFIG
.save(deps.as_mut().storage, &get_default_config())
.unwrap();

let res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info("any sender", &[Coin::new(1000, denom)]),
ExecuteMsg::ReceiveWithdrawalDenoms {},
);
assert!(res.is_err());
assert_eq!(res, Err(ContractError::InvalidDenom {}));
}

#[test]
fn test_receive_withdrawal_denoms_has_incorrect_subdenom_batch_id() {
let mut deps = mock_dependencies(&[]);
let denom = "factory/withdrawal_token_contract/dATOM:unbond:invalid";

CONFIG
.save(deps.as_mut().storage, &get_default_config())
.unwrap();

let res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info("any sender", &[Coin::new(1000, denom)]),
ExecuteMsg::ReceiveWithdrawalDenoms {},
);
assert!(res.is_err());
assert_eq!(res, Err(ContractError::InvalidDenom {}));
}

#[test]
fn test_receive_withdrawal_denoms_batch_not_withdrawn() {
let mut deps = mock_dependencies(&[]);

CONFIG
.save(deps.as_mut().storage, &get_default_config())
.unwrap();

deps.querier.add_wasm_query_response("core_contract", |_| {
to_json_binary(&UnbondBatch {
total_dasset_amount_to_withdraw: Uint128::from(1001u128),
expected_native_asset_amount: Uint128::from(1001u128),
total_unbond_items: 1,
status: UnbondBatchStatus::Unbonding,
expected_release_time: 9000,
slashing_effect: None,
unbonded_amount: Option::from(Uint128::new(1000u128)),
withdrawn_amount: None,
status_timestamps: get_default_unbond_batch_status_timestamps(),
})
.unwrap()
});

let res = execute(
deps.as_mut(),
mock_env().clone(),
mock_info(
"any sender",
&[Coin::new(
1000,
"factory/withdrawal_token_contract/dATOM:unbond:0",
)],
),
ExecuteMsg::ReceiveWithdrawalDenoms {},
);
assert!(res.is_err());
assert_eq!(res, Err(ContractError::BatchIsNotWithdrawn {}));
}
2 changes: 1 addition & 1 deletion contracts/withdrawal-token/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use crate::error::{ContractError, ContractResult};
use cosmwasm_std::{
attr, ensure_eq, ensure_ne, entry_point, to_json_binary, Binary, Deps, DepsMut, Env,
MessageInfo, Reply, Response, SubMsg, Uint128,
};
use drop_helpers::answer::{attr_coin, response};
use drop_staking_base::{
error::withdrawal_token::{ContractError, ContractResult},
msg::withdrawal_token::{ConfigResponse, ExecuteMsg, InstantiateMsg, MigrateMsg, QueryMsg},
state::withdrawal_token::{CORE_ADDRESS, DENOM_PREFIX},
};
Expand Down
1 change: 0 additions & 1 deletion contracts/withdrawal-token/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
pub mod contract;
pub mod error;
1 change: 1 addition & 0 deletions packages/base/src/error/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ pub mod redemption_rate_adapter;
pub mod rewards_manager;
pub mod splitter;
pub mod validatorset;
pub mod withdrawal_token;
File renamed without changes.

0 comments on commit 09d7218

Please sign in to comment.