Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a migration to push the start date to be later #156

Merged
merged 7 commits into from
Oct 22, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Cargo.lock

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

4 changes: 2 additions & 2 deletions artifacts/checksums.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
23c1286337d166572a21356b2be93df8c3a3ed28f9d8e7b40e06b06b37fe8823 hydro.wasm
9d155b9241a64f47e8829afbb022dba5d0130ba55304ddc46950511b567c9ffd tribute.wasm
0eef6df459b3aebf48f0a716bf09cadaa71ff3c8dfa8be783b6408f9451df77b hydro.wasm
640c269dfca46d4e72e21757c667ce4e62249b24c7c1dfa106df45af6fe93df3 tribute.wasm
Binary file modified artifacts/hydro.wasm
Binary file not shown.
Binary file modified artifacts/tribute.wasm
Binary file not shown.
2 changes: 1 addition & 1 deletion contracts/hydro/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "hydro"
version = "1.0.0"
version = "1.1.0"
dusan-maksimovic marked this conversation as resolved.
Show resolved Hide resolved
authors = ["Jehan Tremback", "Philip Offtermatt", "Dusan Maksimovic"]
edition = "2018"

Expand Down
31 changes: 4 additions & 27 deletions contracts/hydro/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use crate::lsm_integration::{
get_validator_power_ratio_for_round, initialize_validator_store, validate_denom,
COSMOS_VALIDATOR_PREFIX,
};
use crate::msg::{ExecuteMsg, InstantiateMsg, MigrateMsg, TrancheInfo};
use crate::msg::{ExecuteMsg, InstantiateMsg, TrancheInfo};
use crate::query::{
AllUserLockupsResponse, ConstantsResponse, CurrentRoundResponse, ExpiredUserLockupsResponse,
ICQManagersResponse, LockEntryWithPower, ProposalResponse, QueryMsg,
Expand All @@ -42,9 +42,9 @@ use crate::validators_icqs::{
};

/// Contract name that is used for migration.
const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
/// Contract version that is used for migration.
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");

pub const MAX_LOCK_ENTRIES: usize = 100;

Expand Down Expand Up @@ -1664,7 +1664,7 @@ fn compute_round_id_for_timestamp(constants: &Constants, timestamp: u64) -> StdR
Ok(round_id)
}

fn compute_round_end(constants: &Constants, round_id: u64) -> StdResult<Timestamp> {
pub fn compute_round_end(constants: &Constants, round_id: u64) -> StdResult<Timestamp> {
let round_end = constants
.first_round_start
.plus_nanos(constants.round_length * (round_id + 1));
Expand Down Expand Up @@ -1915,29 +1915,6 @@ fn to_lockup_with_power(
}
}

/// In the first version of Hydro, we allow contract to be un-paused through the Cosmos Hub governance
/// by migrating contract to the same code ID. This will trigger the migrate() function where we set
/// the paused flag to false.
/// Keep in mind that, for the future versions, this function should check the `CONTRACT_VERSION` and
/// perform any state changes needed. It should also handle the un-pausing of the contract, depending if
/// it was previously paused or not.
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(
deps: DepsMut<NeutronQuery>,
_env: Env,
_msg: MigrateMsg,
) -> Result<Response<NeutronMsg>, ContractError> {
CONSTANTS.update(
deps.storage,
|mut constants| -> Result<Constants, ContractError> {
constants.paused = false;
Ok(constants)
},
)?;

Ok(Response::default())
}

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(
deps: DepsMut<NeutronQuery>,
Expand Down
1 change: 1 addition & 0 deletions contracts/hydro/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
pub mod contract;
mod error;
pub mod lsm_integration;
pub mod migration;
pub mod msg;
pub mod query;
pub mod score_keeper;
Expand Down
113 changes: 113 additions & 0 deletions contracts/hydro/src/migration/migrate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
use crate::contract::{
compute_current_round_id, compute_round_end, CONTRACT_NAME, CONTRACT_VERSION,
};
use crate::error::ContractError;
use crate::msg::MigrateMsg;
use crate::state::{Constants, CONSTANTS, LOCKS_MAP};
use cosmwasm_std::{entry_point, DepsMut, Env, Order, Response, StdError, StdResult};
use cw2::{get_contract_version, set_contract_version};
use neutron_sdk::bindings::msg::NeutronMsg;
use neutron_sdk::bindings::query::NeutronQuery;

/// In the first version of Hydro, we allow contract to be un-paused through the Cosmos Hub governance
/// by migrating contract to the same code ID. This will trigger the migrate() function where we set
/// the paused flag to false.
/// Additionally, any migration logic can be added here.
/// Those migrations should check the contract version and apply the necessary changes.
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(
mut deps: DepsMut<NeutronQuery>,
env: Env,
msg: MigrateMsg,
) -> Result<Response<NeutronMsg>, ContractError> {
let contract_version = get_contract_version(deps.storage)?;
CONSTANTS.update(
deps.storage,
|mut constants| -> Result<Constants, ContractError> {
constants.paused = false;
Ok(constants)
},
)?;

if contract_version.version == CONTRACT_VERSION {
return Err(ContractError::Std(StdError::generic_err(
"Contract is already migrated to the newest version.",
)));
}

if contract_version.version == "1.0.0" {
// Perform the migration from 1.0.0 to 1.1.0
migrate_v1_0_0_to_v1_1_0(&mut deps, env, msg)?;
}

set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;

Ok(Response::default())
}

// Migrating from 1.0.0 to 1.1.0 will:
// - Update the first_round_start to the value provided in the migration message
// - For each lock, update the lock_end to the end of the new first round
// Note that this migration will only work properly if the contract is currently within the first round,
// and if the contract will be before the end of the first round after the migration, too.
fn migrate_v1_0_0_to_v1_1_0(
deps: &mut DepsMut<NeutronQuery>,
env: Env,
msg: MigrateMsg,
) -> Result<(), ContractError> {
// Migrate the contract to version 1.1.0

// ensure that the contract is currently within the first round
let constants = CONSTANTS.load(deps.storage)?;
let current_round_id = compute_current_round_id(&env, &constants)?;
if current_round_id != 0 {
return Err(ContractError::Std(StdError::generic_err(
"Migration to version 1.1.0 can only be done within the first round.",
)));
}

// update the first_round_start to the value provided in the migration message
CONSTANTS.update(
deps.storage,
|mut constants| -> Result<Constants, ContractError> {
constants.first_round_start = msg.new_first_round_start;
Ok(constants)
},
)?;

// for each lock, update the lock_end to the new round_end
let constants = CONSTANTS.load(deps.storage)?;
let first_round_end = compute_round_end(&constants, 0)?;

if first_round_end < env.block.time {
return Err(ContractError::Std(StdError::generic_err(
"Migration to version 1.1.0 can only be done if the new first round end is in the future.",
)));
}

let locks = LOCKS_MAP
.range(deps.storage, None, None, Order::Ascending)
.collect::<StdResult<Vec<_>>>()?;

for ((addr, lock_id), _) in locks {
LOCKS_MAP.update(
deps.storage,
(addr.clone(), lock_id),
|lock_entry_option| -> Result<_, ContractError> {
// update the lock_end to the new round_end
match lock_entry_option {
None => Err(ContractError::Std(StdError::generic_err(format!(
"Lock entry not found for address: {} and lock_id: {}",
addr, lock_id
)))),
Some(mut lock_entry) => {
lock_entry.lock_end = first_round_end;
Ok(lock_entry)
}
}
},
)?;
}

Ok(())
}
4 changes: 4 additions & 0 deletions contracts/hydro/src/migration/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod migrate;

#[cfg(test)]
mod testing_migrate;
163 changes: 163 additions & 0 deletions contracts/hydro/src/migration/testing_migrate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
#[cfg(test)]
mod tests {
use std::collections::HashMap;

use crate::contract::{compute_round_end, execute, instantiate, CONTRACT_NAME};
use crate::migration::migrate::migrate;
use crate::msg::{ExecuteMsg, MigrateMsg};
use crate::state::{CONSTANTS, LOCKS_MAP};
use crate::testing::{
get_default_instantiate_msg, get_message_info, set_default_validator_for_rounds,
IBC_DENOM_1, ONE_DAY_IN_NANO_SECONDS, ONE_MONTH_IN_NANO_SECONDS, VALIDATOR_1_LST_DENOM_1,
};
use crate::testing_mocks::{denom_trace_grpc_query_mock, mock_dependencies};
use cosmwasm_std::testing::mock_env;
use cosmwasm_std::{Coin, Env, Order, StdResult, Timestamp};
use cw2::{get_contract_version, set_contract_version};

#[test]
fn test_migrate_v100_to_v110() {
struct TestCase {
description: String,
migrate_msg: fn(Env) -> MigrateMsg,
env_time: fn(Env) -> u64,
expected_error: Option<&'static str>,
}

fn create_migrate_msg(env: &Env, offset: i64) -> MigrateMsg {
MigrateMsg {
new_first_round_start: Timestamp::from_nanos(
(env.block.time.nanos() as i64 + offset) as u64,
),
}
}

fn compute_env_time(env: &Env, offset: u64) -> u64 {
env.block.time.plus_nanos(offset).nanos()
}

let test_cases = [
TestCase {
description: "Happy path".to_string(),
migrate_msg: |env| create_migrate_msg(&env, ONE_DAY_IN_NANO_SECONDS as i64),
env_time: |env| compute_env_time(&env, 0),
expected_error: None,
},
TestCase {
description: "Migrate with new first round end in the past".to_string(),
migrate_msg: |env| create_migrate_msg(&env, -(ONE_MONTH_IN_NANO_SECONDS as i64)),
env_time: |env| compute_env_time(&env, 0),
expected_error: Some(
"can only be done if the new first round end is in the future",
),
},
TestCase {
description: "Migrate not during the first round".to_string(),
migrate_msg: |env| create_migrate_msg(&env, ONE_DAY_IN_NANO_SECONDS as i64),
env_time: |env| compute_env_time(&env, ONE_MONTH_IN_NANO_SECONDS * 2),
expected_error: Some("can only be done within the first round"),
},
];

for (i, test_case) in test_cases.iter().enumerate() {
// log the test case description
println!("Test case {}: {}", i, test_case.description);

let grpc_query = denom_trace_grpc_query_mock(
"transfer/channel-0".to_string(),
HashMap::from([(IBC_DENOM_1.to_string(), VALIDATOR_1_LST_DENOM_1.to_string())]),
);
let user_addr = "addr0000";
let (mut deps, mut env) = (mock_dependencies(grpc_query), mock_env());
let info = get_message_info(&deps.api, user_addr, &[]);

// Instantiate the contract
let instantiate_msg = get_default_instantiate_msg(&deps.api);
let _res =
instantiate(deps.as_mut(), env.clone(), info.clone(), instantiate_msg).unwrap();

set_default_validator_for_rounds(deps.as_mut(), 0, 100);

// Set contract version to 1.0.0
set_contract_version(deps.as_mut().storage, CONTRACT_NAME, "1.0.0").unwrap();

// Create some locks
// time will be advanced by the given duration after each lock
let lock_creation_delays = [
ONE_DAY_IN_NANO_SECONDS * 4,
ONE_DAY_IN_NANO_SECONDS * 2,
ONE_DAY_IN_NANO_SECONDS * 2,
];

for (i, &delay) in lock_creation_delays.iter().enumerate() {
let lock_info = get_message_info(
&deps.api,
user_addr,
&[Coin::new(1000u64, IBC_DENOM_1.to_string())],
);
let lock_msg = ExecuteMsg::LockTokens {
lock_duration: ONE_MONTH_IN_NANO_SECONDS,
};
let res = execute(deps.as_mut(), env.clone(), lock_info.clone(), lock_msg);
assert!(
res.is_ok(),
"Lock creation failed for lock {}: {}",
i,
res.unwrap_err()
);

// Advance time after each lock
env.block.time = env.block.time.plus_nanos(delay);
}

env.block.time = Timestamp::from_nanos((test_case.env_time)(env.clone()));
let migrate_msg = (test_case.migrate_msg)(env.clone());
let res = migrate(deps.as_mut(), env.clone(), migrate_msg.clone());

match &test_case.expected_error {
Some(expected_error) => {
assert!(
res.is_err(),
"Test case {}: Migration should have failed",
i
);
let error_string = res.unwrap_err();
assert!(
error_string.to_string().contains(expected_error),
"Test case {}: Expected error: {:?}, got: {:?}",
i,
expected_error,
error_string
);
}
None => {
assert!(res.is_ok(), "Test case {}: Migration failed: {:?}", i, res);
let contract_version = get_contract_version(deps.as_ref().storage).unwrap();
assert_eq!(contract_version.version, "1.1.0");

let constants = CONSTANTS.load(deps.as_ref().storage).unwrap();
let first_round_end = compute_round_end(&constants, 0).unwrap();
assert_eq!(
constants.first_round_start,
migrate_msg.new_first_round_start
);

let locks = LOCKS_MAP
.range(deps.as_ref().storage, None, None, Order::Ascending)
.collect::<StdResult<Vec<_>>>()
.unwrap();

assert_eq!(locks.len(), 3, "Locks count mismatch");

for ((addr, lock_id), lock_entry) in locks {
assert_eq!(
lock_entry.lock_end, first_round_end,
"Lock end mismatch for address: {} and lock_id: {}",
addr, lock_id
);
}
}
}
}
}
}
4 changes: 3 additions & 1 deletion contracts/hydro/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,4 +89,6 @@ pub enum ExecuteMsg {
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct MigrateMsg {}
pub struct MigrateMsg {
pub new_first_round_start: Timestamp,
}