cosmwasm-zero-to-hero
cosmwasm-zero-to-hero copied to clipboard
Contract Migration?
At the end just having a chapter on contract migration would be useful, took me a bit to learn how to do it via docs. ( This may be a good part-2 to #6 's chapter )
Could be as simple as this
pub struct ConfigResponse {
pub name: String, // cw2 name
pub version: String, // cw2 version from the .toml
}
pub const CONFIG = Item<ConfigResponse>
Then a migrate entry point which changes this value on upload
#[entry_point]
pub fn migrate(deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result<Response, ContractError> {
let ver = cw2::get_contract_version(deps.storage)?;
// ensure we are migrating from an allowed contract
if ver.contract != CONTRACT_NAME {
return Err(StdError::generic_err("Can only upgrade from same type").into());
}
if ver.version >= (*CONTRACT_VERSION).to_string() {
return Err(StdError::generic_err("Cannot upgrade from a newer version").into());
}
// set the new version
cw2::set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?;
// state breaking migrations here
// update the version field in the CONFIG since we have updated the contract
let mut config = CONFIG.load(deps.storage)?;
config.version = CONTRACT_VERSION.to_string();
CONFIG.save(deps.storage, &config)?;
Ok(Response::default()
.add_attribute("action", "migration")
.add_attribute("version", CONTRACT_VERSION)