Skip to content

Commit

Permalink
feat: kernel environment variables (#738)
Browse files Browse the repository at this point in the history
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
  • Loading branch information
crnbarr93 and coderabbitai[bot] authored Jan 2, 2025
1 parent afccffc commit f3ec59d
Show file tree
Hide file tree
Showing 17 changed files with 336 additions and 58 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Rates: Handle cross-chain recipients [(#671)](https://github.com/andromedaprotocol/andromeda-core/pull/671)
- Permissions: Permissioned Actors in AndromedaQuery [(#717)](https://github.com/andromedaprotocol/andromeda-core/pull/717)
- Added Schema and Form ADOs [(#591)](https://github.com/andromedaprotocol/andromeda-core/pull/591)
- feat: kernel environment variables [#738](https://github.com/andromedaprotocol/andromeda-core/pull/738)
- Flat Rate denom can be a VFS path [(#727)](https://github.com/andromedaprotocol/andromeda-core/pull/727)
- Auction ADO: Added buy_now_price option in Update Auction [(#730)](https://github.com/andromedaprotocol/andromeda-core/pull/730)

Expand Down
3 changes: 2 additions & 1 deletion Cargo.lock

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

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,6 @@ cw-multi-test = { version = "1.0.0", features = ["cosmwasm_1_2"] }
serde = { version = "1.0.217" }
test-case = { version = "3.3.1" }
cw-orch = "=0.24.1"
jsonschema-valid = { version = "0.5.2"}
jsonschema-valid = { version = "0.5.2" }
serde_json = { version = "1.0.134" }
rstest = "0.23.0"
10 changes: 8 additions & 2 deletions contracts/finance/andromeda-validator-staking/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -325,9 +325,15 @@ fn execute_claim(
);

let kernel_addr = ADOContract::default().get_kernel_address(deps.storage)?;
let curr_chain = AOSQuerier::get_current_chain(&deps.querier, &kernel_addr)?;

let withdraw_msg: CosmosMsg = if curr_chain == "andromeda" {
let is_andromeda_distribution = AOSQuerier::get_env_variable::<bool>(
&deps.querier,
&kernel_addr,
"andromeda_distribution",
)?
.unwrap_or(false);

let withdraw_msg: CosmosMsg = if is_andromeda_distribution {
MsgWithdrawDelegatorReward {
delegator_address: delegator.to_string(),
validator_address: validator.to_string(),
Expand Down
3 changes: 2 additions & 1 deletion contracts/os/andromeda-kernel/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "andromeda-kernel"
version = "1.2.0-b.1"
version = "1.2.0-b.2"
authors = ["Connor Barr <[email protected]>"]
edition = "2021"
rust-version = "1.65.0"
Expand Down Expand Up @@ -47,3 +47,4 @@ cw-orch = { workspace = true }

[dev-dependencies]
# andromeda-testing = { workspace = true, optional = true }
rstest = { workspace = true }
4 changes: 3 additions & 1 deletion contracts/os/andromeda-kernel/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -127,8 +127,9 @@ pub fn execute(
ExecuteMsg::UpdateChainName { chain_name } => {
execute::update_chain_name(execute_env, chain_name)
}
ExecuteMsg::SetEnv { variable, value } => execute::set_env(execute_env, variable, value),
ExecuteMsg::UnsetEnv { variable } => execute::unset_env(execute_env, variable),
ExecuteMsg::Internal(msg) => execute::internal(execute_env, msg),
// Base message
ExecuteMsg::Ownership(ownership_message) => ADOContract::default().execute_ownership(
execute_env.deps,
execute_env.env,
Expand Down Expand Up @@ -175,5 +176,6 @@ pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> Result<Binary, ContractErr
QueryMsg::ChainNameByChannel { channel } => {
encode_binary(&query::chain_name_by_channel(deps, channel)?)
}
QueryMsg::GetEnv { variable } => encode_binary(&query::get_env(deps, variable)?),
}
}
173 changes: 130 additions & 43 deletions contracts/os/andromeda-kernel/src/execute.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use cosmwasm_std::{
use crate::query;
use crate::state::{
ADO_OWNER, CHAIN_TO_CHANNEL, CHANNEL_TO_CHAIN, CHANNEL_TO_EXECUTE_MSG, CURR_CHAIN,
IBC_FUND_RECOVERY, KERNEL_ADDRESSES, PENDING_MSG_AND_FUNDS, TRIGGER_KEY,
ENV_VARIABLES, IBC_FUND_RECOVERY, KERNEL_ADDRESSES, PENDING_MSG_AND_FUNDS, TRIGGER_KEY,
};

pub fn send(ctx: ExecuteContext, message: AMPMsg) -> Result<Response, ContractError> {
Expand Down Expand Up @@ -256,42 +256,49 @@ pub fn create(
chain.is_none() || owner.is_some(),
ContractError::Unauthorized {}
);
if let Some(_chain) = chain {
Err(ContractError::CrossChainComponentsCurrentlyDisabled {})
// let channel_info = if let Some(channel_info) =
// CHAIN_TO_CHANNEL.may_load(execute_ctx.deps.storage, &chain)?
// {
// Ok::<ChannelInfo, ContractError>(channel_info)
// } else {
// return Err(ContractError::InvalidPacket {
// error: Some(format!("Channel not found for chain {chain}")),
// });
// }?;
// let kernel_msg = IbcExecuteMsg::CreateADO {
// instantiation_msg: msg.clone(),
// owner: owner.clone().unwrap(),
// ado_type: ado_type.clone(),
// };
// let ibc_msg = IbcMsg::SendPacket {
// channel_id: channel_info.direct_channel_id.clone().unwrap(),
// data: to_json_binary(&kernel_msg)?,
// timeout: execute_ctx
// .env
// .block
// .time
// .plus_seconds(PACKET_LIFETIME)
// .into(),
// };
// Ok(Response::default()
// .add_message(ibc_msg)
// .add_attributes(vec![
// attr("action", "execute_create"),
// attr("ado_type", ado_type),
// attr("owner", owner.unwrap().to_string()),
// attr("chain", chain),
// attr("receiving_kernel_address", channel_info.kernel_address),
// attr("msg", msg.to_string()),
// ]))
if let Some(chain) = chain {
let cross_chain_components_enabled = ENV_VARIABLES
.may_load(execute_ctx.deps.storage, "cross_chain_components_enabled")?
.unwrap_or("false".to_string());
ensure!(
cross_chain_components_enabled == "true",
ContractError::CrossChainComponentsCurrentlyDisabled {}
);

let channel_info = if let Some(channel_info) =
CHAIN_TO_CHANNEL.may_load(execute_ctx.deps.storage, &chain)?
{
Ok::<ChannelInfo, ContractError>(channel_info)
} else {
return Err(ContractError::InvalidPacket {
error: Some(format!("Channel not found for chain {chain}")),
});
}?;
let kernel_msg = IbcExecuteMsg::CreateADO {
instantiation_msg: msg.clone(),
owner: owner.clone().unwrap(),
ado_type: ado_type.clone(),
};
let ibc_msg = IbcMsg::SendPacket {
channel_id: channel_info.direct_channel_id.clone().unwrap(),
data: to_json_binary(&kernel_msg)?,
timeout: execute_ctx
.env
.block
.time
.plus_seconds(PACKET_LIFETIME)
.into(),
};
Ok(Response::default()
.add_message(ibc_msg)
.add_attributes(vec![
attr("action", "execute_create"),
attr("ado_type", ado_type),
attr("owner", owner.unwrap().to_string()),
attr("chain", chain),
attr("receiving_kernel_address", channel_info.kernel_address),
attr("msg", msg.to_string()),
]))
} else {
let vfs_addr = KERNEL_ADDRESSES.load(execute_ctx.deps.storage, VFS_KEY)?;
let adodb_addr = KERNEL_ADDRESSES.load(execute_ctx.deps.storage, ADO_DB_KEY)?;
Expand Down Expand Up @@ -473,6 +480,86 @@ pub fn update_chain_name(
.add_attribute("chain_name", chain_name))
}

pub fn set_env(
execute_ctx: ExecuteContext,
variable: String,
value: String,
) -> Result<Response, ContractError> {
let contract = ADOContract::default();
ensure!(
contract.is_contract_owner(execute_ctx.deps.storage, execute_ctx.info.sender.as_str())?,
ContractError::Unauthorized {}
);

ensure!(
!variable.is_empty(),
ContractError::InvalidEnvironmentVariable {
msg: "Environment variable name cannot be empty".to_string()
}
);

ensure!(
variable
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_'),
ContractError::InvalidEnvironmentVariable {
msg:
"Environment variable name can only contain alphanumeric characters and underscores"
.to_string()
}
);

ensure!(
variable.len() <= 100,
ContractError::InvalidEnvironmentVariable {
msg: "Environment variable name length exceeds the maximum allowed length of 100 characters".to_string()
}
);

ensure!(
!value.is_empty(),
ContractError::InvalidEnvironmentVariable {
msg: "Environment variable value cannot be empty".to_string()
}
);

ensure!(
value.len() <= 100,
ContractError::InvalidEnvironmentVariable {
msg: "Environment variable value length exceeds the maximum allowed length of 100 characters".to_string()
}
);

ENV_VARIABLES.save(
execute_ctx.deps.storage,
&variable.to_ascii_uppercase(),
&value,
)?;
Ok(Response::default()
.add_attribute("action", "set_env")
.add_attribute("variable", variable)
.add_attribute("value", value))
}

pub fn unset_env(execute_ctx: ExecuteContext, variable: String) -> Result<Response, ContractError> {
let contract = ADOContract::default();
ensure!(
contract.is_contract_owner(execute_ctx.deps.storage, execute_ctx.info.sender.as_str())?,
ContractError::Unauthorized {}
);

ensure!(
ENV_VARIABLES
.may_load(execute_ctx.deps.storage, &variable.to_ascii_uppercase())?
.is_some(),
ContractError::EnvironmentVariableNotFound { variable }
);
ENV_VARIABLES.remove(execute_ctx.deps.storage, &variable.to_ascii_uppercase());
Ok(Response::default()
.add_attribute("action", "unset_env")
.add_attribute("variable", variable))
}

/// Handles a given AMP message and returns a response
///
/// Separated due to common functionality across multiple messages
Expand Down Expand Up @@ -547,28 +634,28 @@ impl MsgHandler {
} = original_msg;

let recipient_addr = recipient.get_raw_address(&deps.as_ref())?;

let adodb_addr = KERNEL_ADDRESSES.load(deps.storage, ADO_DB_KEY)?;

if Binary::default() == message.clone() {
ensure!(
!funds.is_empty(),
ContractError::InvalidPacket {
error: Some("No message or funds supplied".to_string())
}
);

let sub_msg = BankMsg::Send {
to_address: recipient_addr.to_string(),
amount: funds.clone(),
};

let mut attrs = vec![];
for (idx, fund) in funds.iter().enumerate() {
attrs.push(attr(format!("funds:{sequence}:{idx}"), fund.to_string()));
}
attrs.push(attr(format!("recipient:{sequence}"), recipient_addr));

res = res
.add_submessage(SubMsg::reply_on_error(
CosmosMsg::Bank(sub_msg),
Expand Down Expand Up @@ -613,7 +700,7 @@ impl MsgHandler {
ReplyId::AMPMsg.repr(),
)?
};

res = res
.add_submessage(sub_msg)
.add_attributes(vec![attr(format!("recipient:{sequence}"), recipient_addr)]);
Expand Down
11 changes: 9 additions & 2 deletions contracts/os/andromeda-kernel/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,14 @@ use andromeda_std::{
error::ContractError,
os::{
aos_querier::AOSQuerier,
kernel::{ChainNameResponse, ChannelInfoResponse, VerifyAddressResponse},
kernel::{ChainNameResponse, ChannelInfoResponse, EnvResponse, VerifyAddressResponse},
},
};
use cosmwasm_std::{Addr, Coin, Deps};

use crate::state::{
CHAIN_TO_CHANNEL, CHANNEL_TO_CHAIN, CURR_CHAIN, IBC_FUND_RECOVERY, KERNEL_ADDRESSES,
CHAIN_TO_CHANNEL, CHANNEL_TO_CHAIN, CURR_CHAIN, ENV_VARIABLES, IBC_FUND_RECOVERY,
KERNEL_ADDRESSES,
};

pub fn key_address(deps: Deps, key: String) -> Result<Addr, ContractError> {
Expand Down Expand Up @@ -68,3 +69,9 @@ pub fn chain_name(deps: Deps) -> Result<ChainNameResponse, ContractError> {
chain_name: CURR_CHAIN.may_load(deps.storage)?.unwrap_or_default(),
})
}

pub fn get_env(deps: Deps, variable: String) -> Result<EnvResponse, ContractError> {
Ok(EnvResponse {
value: ENV_VARIABLES.may_load(deps.storage, &variable.to_ascii_uppercase())?,
})
}
2 changes: 1 addition & 1 deletion contracts/os/andromeda-kernel/src/state.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ pub struct OutgoingPacket {
}

pub const KERNEL_ADDRESSES: Map<&str, Addr> = Map::new("kernel_addresses");
pub const _ENV_VARIABLES: Map<&str, String> = Map::new("kernel_env_variables");
pub const ENV_VARIABLES: Map<&str, String> = Map::new("kernel_env_variables");
pub const CURR_CHAIN: Item<String> = Item::new("kernel_curr_chain");

//Temporary storage for creating a new ADO to assign a new owner
Expand Down
Loading

0 comments on commit f3ec59d

Please sign in to comment.