Skip to content

Commit

Permalink
refactor: remove unused oracle addresses (#125)
Browse files Browse the repository at this point in the history
## Overview

This PR removes all references to the old oracles from the messages and
the contract config.
Additionally, to properly remove the old oracle addresses from the
config, the migration logic has been updated and
the `MsgMigrate` has been converted to an enum to support future
migration logics.

To migrate the contract from the version `v0.4.18` the following migrate
message must be sent:
```json
{
  "v0_4_18_to_v0_4_19": {}
}
```

closes: MILKTIA-32

## What changes have been made in this PR?

- [ ] Removed all the references to the old oracles
- [ ] Added a migration logic to remove the old oracles address from the
state of the contract
- [ ] Refactored the migration logic to support future migrations

## Checklist

---

- [ ] Appropriate labels applied
- [ ] Targeted PR against correct branch
- [ ] Linked to Github issue with discussion and accepted design OR link
to spec that describes this work.
- [ ] Wrote unit and integration
- [ ] Updated relevant documentation
  • Loading branch information
manu0466 authored May 10, 2024
1 parent b0cc7ba commit c3b00e4
Show file tree
Hide file tree
Showing 12 changed files with 109 additions and 90 deletions.
4 changes: 2 additions & 2 deletions Cargo.lock

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

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
members = ["contracts/*", "packages/*"]

[workspace.package]
version = "0.4.18"
version = "0.4.19"
authors = ["Decento Labs"]
edition = "2021"
rust-version = "1.68.0"
Expand Down
28 changes: 10 additions & 18 deletions contracts/staking/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
use crate::execute::{
circuit_breaker, execute_submit_batch, fee_withdraw, handle_ibc_reply, receive_rewards,
receive_unstaked_tokens, recover, resume_contract, update_config, update_config_from_migrate,
receive_unstaked_tokens, recover, resume_contract, update_config,
};
use crate::helpers::validate_addresses;
use crate::ibc::{receive_ack, receive_timeout};
use crate::migrations;
use crate::query::{
query_all_unstake_requests, query_all_unstake_requests_v2, query_batch, query_batches,
query_batches_by_ids, query_config, query_ibc_queue, query_pending_batch, query_reply_queue,
Expand Down Expand Up @@ -34,8 +35,8 @@ use osmosis_std::types::osmosis::tokenfactory::v1beta1::MsgCreateDenom;
use semver::Version;

// Version information for migration
const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const CONTRACT_NAME: &str = env!("CARGO_PKG_NAME");
pub const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
pub const IBC_TIMEOUT: Timestamp = Timestamp::from_nanos(1000000000000); // TODO: Placeholder value for IBC timeout

pub const CELESTIA_ACCOUNT_PREFIX: &str = &"celestia";
Expand Down Expand Up @@ -79,7 +80,6 @@ pub fn instantiate(
env.contract.address, msg.liquid_stake_token_denom
),
treasury_address: Addr::unchecked(""),
operators: None,
monitors: Some(vec![]),
validators,
batch_period: 0,
Expand All @@ -93,9 +93,7 @@ pub fn instantiate(
},
minimum_liquid_stake_amount: Uint128::zero(),
ibc_channel_id: "".to_string(),
stopped: true, // we start stopped
oracle_contract_address: None, // just for migration. This always needs to be set
oracle_contract_address_v2: None,
stopped: true, // we start stopped
oracle_address: None,
};

Expand All @@ -114,8 +112,6 @@ pub fn instantiate(
Some(msg.ibc_channel_id.clone()),
Some(msg.monitors),
Some(msg.treasury_address),
msg.oracle_contract_address,
msg.oracle_contract_address_v2,
msg.oracle_address,
)?;

Expand Down Expand Up @@ -207,8 +203,6 @@ pub fn execute(
channel_id,
monitors,
treasury_address,
oracle_contract_address,
oracle_contract_address_v2,
oracle_address,
} => update_config(
deps,
Expand All @@ -223,8 +217,6 @@ pub fn execute(
channel_id,
monitors,
treasury_address,
oracle_contract_address,
oracle_contract_address_v2,
oracle_address,
),
ExecuteMsg::ReceiveRewards {} => receive_rewards(deps, env, info),
Expand Down Expand Up @@ -301,7 +293,7 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
///////////////

#[cfg_attr(not(feature = "library"), entry_point)]
pub fn migrate(mut deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {
pub fn migrate(mut deps: DepsMut, env: Env, msg: MigrateMsg) -> Result<Response, ContractError> {
let current_version = cw2::get_contract_version(deps.storage)?;
if &CONTRACT_NAME != &current_version.contract.as_str() {
return Err(StdError::generic_err("Cannot upgrade to a different contract").into());
Expand All @@ -324,14 +316,14 @@ pub fn migrate(mut deps: DepsMut, _env: Env, msg: MigrateMsg) -> Result<Response
return Err(StdError::generic_err("Cannot migrate to the same version.").into());
}

// migrate data
// update v2 oracle contract address
update_config_from_migrate(deps.branch(), msg)?;
let migration_response = match msg {
MigrateMsg::V0_4_18ToV0_4_19 {} => migrations::v0_4_19::migrate(deps.branch(), env)?,
};

// set new contract version
set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;

Ok(Response::new())
Ok(migration_response)
}

/////////////
Expand Down
4 changes: 4 additions & 0 deletions contracts/staking/src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use cosmwasm_std::{StdError, Timestamp, Uint128};
use cw2::VersionError;
use cw_controllers::AdminError;
use cw_utils::PaymentError;
use milky_way::staking::BatchStatus;
Expand Down Expand Up @@ -131,4 +132,7 @@ pub enum ContractError {

#[error("If liquid staking is done from a non native Osmosis address you need to provide an address via 'mint_to'")]
MissingMintAddress {},

#[error("{0}")]
Version(#[from] VersionError),
}
63 changes: 18 additions & 45 deletions contracts/staking/src/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@ use crate::helpers::{
compute_mint_amount, compute_unbond_amount, derive_intermediate_sender, get_rates,
paginate_map, validate_address, validate_addresses,
};
use crate::oracle::{Oracle};
use crate::oracle::Oracle;
use crate::state::{
ibc::{IBCTransfer, PacketLifecycleStatus},
Config, IbcWaitingForReply, MultisigAddressConfig, ProtocolFeeConfig, State, ADMIN, BATCHES,
CONFIG, IBC_WAITING_FOR_REPLY, INFLIGHT_PACKETS, PENDING_BATCH_ID, STATE,
};
use crate::state::{new_unstake_request, remove_unstake_request, unstake_requests, UnstakeRequest};
use cosmwasm_std::{
ensure, Addr, CosmosMsg, Deps, DepsMut, Env, IbcTimeout, MessageInfo, Order, ReplyOn,
Response, SubMsg, SubMsgResponse, SubMsgResult, Timestamp, Uint128,
ensure, Addr, CosmosMsg, Deps, DepsMut, Env, IbcTimeout, MessageInfo, Order, ReplyOn, Response,
SubMsg, SubMsgResponse, SubMsgResult, Timestamp, Uint128,
};
use cw_utils::PaymentError;
use milky_way::staking::{Batch, BatchStatus};
Expand All @@ -24,7 +24,6 @@ use osmosis_std::types::ibc::applications::transfer::v1::MsgTransfer;
use osmosis_std::types::ibc::applications::transfer::v1::MsgTransferResponse;
use osmosis_std::types::osmosis::tokenfactory::v1beta1::{MsgBurn, MsgMint};
use prost::Message;
use crate::msg::MigrateMsg;

pub fn transfer_stake_msg(
deps: &Deps,
Expand Down Expand Up @@ -92,7 +91,11 @@ fn transfer_stake_sub_msg(
})
}

fn update_oracle_msgs(deps: Deps, env: Env, config: &Config) -> Result<Vec<CosmosMsg>, ContractError> {
fn update_oracle_msgs(
deps: Deps,
env: Env,
config: &Config,
) -> Result<Vec<CosmosMsg>, ContractError> {
let (redemption_rate, purchase_rate) = get_rates(&deps);
let mut messages: Vec<CosmosMsg> = Vec::new();
// Post rates to Milkyway Oracle contract
Expand All @@ -103,12 +106,15 @@ fn update_oracle_msgs(deps: Deps, env: Env, config: &Config) -> Result<Vec<Cosmo
};

let post_rate_msg_json = serde_json::to_string(&post_rates_msg).unwrap();
messages.push(MsgExecuteContract {
sender: env.contract.address.to_string(),
contract: config.oracle_address.clone().unwrap().to_string(),
msg: post_rate_msg_json.as_bytes().to_vec(),
funds: vec![]
}.into());
messages.push(
MsgExecuteContract {
sender: env.contract.address.to_string(),
contract: config.oracle_address.clone().unwrap().to_string(),
msg: post_rate_msg_json.as_bytes().to_vec(),
funds: vec![],
}
.into(),
);

Ok(messages)
}
Expand Down Expand Up @@ -450,8 +456,7 @@ pub fn execute_withdraw(
.add_attribute("action", "execute_withdraw")
.add_attribute("batch", batch.id.to_string())
.add_attribute("amount", amount.to_string())
.add_messages([messages, update_oracle_msgs].concat())
)
.add_messages([messages, update_oracle_msgs].concat()))
}

// Add a validator to the list of validators; callable by the owner
Expand Down Expand Up @@ -681,24 +686,6 @@ pub fn recover(
.add_submessage(sub_msg))
}

pub fn update_config_from_migrate(
deps: DepsMut,
msg: MigrateMsg,
) -> ContractResult<Response> {
let mut config: Config = CONFIG.load(deps.storage)?;

// update oracle contract address v3
if msg.oracle_address.is_some() {
let oracle_address = msg.oracle_address.unwrap();
let address = validate_address(&oracle_address, "osmo")?;
config.oracle_address = Some(address);
}

CONFIG.save(deps.storage, &config)?;

Ok(Response::new().add_attribute("action", "update_oracle_address"))
}

// Update the config; callable by the owner
pub fn update_config(
deps: DepsMut,
Expand All @@ -713,8 +700,6 @@ pub fn update_config(
channel_id: Option<String>,
monitors: Option<Vec<String>>,
treasury_address: Option<String>,
oracle_contract_address: Option<String>,
oracle_contract_address_v2: Option<String>,
oracle_address: Option<String>,
) -> ContractResult<Response> {
ADMIN.assert_admin(deps.as_ref(), &info.sender)?;
Expand Down Expand Up @@ -770,18 +755,6 @@ pub fn update_config(
config.native_token_denom = native_token_denom;
}

if oracle_contract_address.is_some() {
let oracle_contract_address = oracle_contract_address.unwrap();
let address = validate_address(&oracle_contract_address, "osmo")?;
config.oracle_contract_address = Some(address);
}

if oracle_contract_address_v2.is_some() {
let oracle_contract_address_v2 = oracle_contract_address_v2.unwrap();
let address = validate_address(&oracle_contract_address_v2, "osmo")?;
config.oracle_contract_address_v2 = Some(address);
}

if oracle_address.is_some() {
let oracle_address = oracle_address.unwrap();
let address = validate_address(&oracle_address, "osmo")?;
Expand Down
1 change: 1 addition & 0 deletions contracts/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ pub mod error;
pub mod execute;
pub mod helpers;
pub mod ibc;
pub mod migrations;
pub mod msg;
pub mod oracle;
pub mod query;
Expand Down
1 change: 1 addition & 0 deletions contracts/staking/src/migrations/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pub mod v0_4_19;
69 changes: 69 additions & 0 deletions contracts/staking/src/migrations/v0_4_19.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
use crate::{
contract::{CONTRACT_NAME, CONTRACT_VERSION},
error::ContractResult,
state::{Config, CONFIG},
};
use cosmwasm_std::{DepsMut, Env, Response};
use cw2::assert_contract_version;

const FROM_VERSION: &str = "0.4.18";

pub mod v0_4_18_state {
use cosmwasm_schema::cw_serde;
use cosmwasm_std::{Addr, Uint128};
use cw_storage_plus::Item;

use crate::state::{MultisigAddressConfig, ProtocolFeeConfig};

pub const CONFIG: Item<Config> = Item::new("config");

#[cw_serde]
pub struct Config {
pub native_token_denom: String,
pub liquid_stake_token_denom: String,
pub treasury_address: Addr,
pub operators: Option<Vec<Addr>>, //depr
pub monitors: Option<Vec<Addr>>,
pub validators: Vec<Addr>,
pub batch_period: u64,
pub unbonding_period: u64,
pub protocol_fee_config: ProtocolFeeConfig,
pub multisig_address_config: MultisigAddressConfig,
pub minimum_liquid_stake_amount: Uint128,
pub ibc_channel_id: String,
pub stopped: bool,
pub oracle_contract_address: Option<Addr>,
pub oracle_contract_address_v2: Option<Addr>,
pub oracle_address: Option<Addr>,
}
}

pub fn migrate(deps: DepsMut, _env: Env) -> ContractResult<Response> {
// Ensure that we are migrating from the correct version.
assert_contract_version(deps.storage, CONTRACT_NAME, FROM_VERSION)?;

let old_config = v0_4_18_state::CONFIG.load(deps.storage)?;
// Convert the old config format to the new one.
let new_config = Config {
native_token_denom: old_config.native_token_denom,
liquid_stake_token_denom: old_config.liquid_stake_token_denom,
treasury_address: old_config.treasury_address,
monitors: old_config.monitors,
validators: old_config.validators,
batch_period: old_config.batch_period,
unbonding_period: old_config.unbonding_period,
protocol_fee_config: old_config.protocol_fee_config,
multisig_address_config: old_config.multisig_address_config,
minimum_liquid_stake_amount: old_config.minimum_liquid_stake_amount,
ibc_channel_id: old_config.ibc_channel_id,
stopped: old_config.stopped,
oracle_address: old_config.oracle_address,
};
// Save the new config.
CONFIG.save(deps.storage, &new_config)?;

Ok(Response::new()
.add_attribute("action", "migrate")
.add_attribute("from_version", FROM_VERSION)
.add_attribute("to_version", CONTRACT_VERSION))
}
12 changes: 3 additions & 9 deletions contracts/staking/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,6 @@ pub struct InstantiateMsg {
// IBC channel id on Osmosis to Celestia
pub ibc_channel_id: String,
// The redemption / purchase rate oracle address
pub oracle_contract_address: Option<String>,
// The migratable redemption / purchase rate oracle address
pub oracle_contract_address_v2: Option<String>,
// The redemption / purchase rate oracle address
pub oracle_address: Option<String>,
}

Expand Down Expand Up @@ -71,8 +67,6 @@ pub enum ExecuteMsg {
channel_id: Option<String>,
monitors: Option<Vec<String>>,
treasury_address: Option<String>,
oracle_contract_address: Option<String>,
oracle_contract_address_v2: Option<String>,
oracle_address: Option<String>,
},
ReceiveRewards {},
Expand Down Expand Up @@ -198,9 +192,9 @@ pub enum QueryMsg {
},
}

#[derive(Serialize, Deserialize, JsonSchema)]
pub struct MigrateMsg {
pub oracle_address: Option<String>
#[cw_serde]
pub enum MigrateMsg {
V0_4_18ToV0_4_19 {},
}

#[cw_serde]
Expand Down
3 changes: 0 additions & 3 deletions contracts/staking/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ pub struct Config {
pub native_token_denom: String,
pub liquid_stake_token_denom: String,
pub treasury_address: Addr,
pub operators: Option<Vec<Addr>>, //depr
pub monitors: Option<Vec<Addr>>,
pub validators: Vec<Addr>,
pub batch_period: u64,
Expand All @@ -19,8 +18,6 @@ pub struct Config {
pub minimum_liquid_stake_amount: Uint128,
pub ibc_channel_id: String,
pub stopped: bool,
pub oracle_contract_address: Option<Addr>,
pub oracle_contract_address_v2: Option<Addr>,
pub oracle_address: Option<Addr>,
}
// TODO: PENDING - DOCS DEFINE THESE AS MAPS?
Expand Down
Loading

0 comments on commit c3b00e4

Please sign in to comment.