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

chain/injective #78

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
582 changes: 510 additions & 72 deletions Cargo.lock

Large diffs are not rendered by default.

16 changes: 10 additions & 6 deletions contracts/warp-account-tracker/src/execute/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,9 +76,11 @@ pub fn free_job_account(deps: DepsMut, data: FreeJobAccountMsg) -> Result<Respon
FREE_JOB_ACCOUNTS.update(
deps.storage,
(account_owner_ref, account_addr_ref),
|s| match s {
None => Ok(data.last_job_id),
Some(_) => Err(ContractError::AccountAlreadyFreeError {}),
|s| -> Result<Uint64, ContractError> {
match s {
None => Ok(data.last_job_id),
Some(last_job_id) => Ok(last_job_id), // idempotent use case, if already freed, do nothing
}
},
)?;

Expand Down Expand Up @@ -180,9 +182,11 @@ pub fn free_funding_account(
FREE_FUNDING_ACCOUNTS.update(
deps.storage,
(account_owner_addr_ref, account_addr_ref),
|s| match s {
None => Ok(vec![data.job_id]),
Some(_) => Err(ContractError::AccountAlreadyFreeError {}),
|s| -> Result<Vec<Uint64>, ContractError> {
match s {
None => Ok(vec![data.job_id]),
Some(job_ids) => Ok(job_ids), // idempotent use case, if already freed, do nothing
}
},
)?;
} else {
Expand Down
23 changes: 10 additions & 13 deletions contracts/warp-account-tracker/src/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -144,19 +144,16 @@ mod tests {
&[],
);

// Cannot free account twice
assert_err(
app.execute_contract(
Addr::unchecked(USER_1),
warp_account_tracker_contract_addr.clone(),
&ExecuteMsg::FreeJobAccount(FreeJobAccountMsg {
account_owner_addr: USER_1.to_string(),
account_addr: DUMMY_WARP_ACCOUNT_1_ADDR.to_string(),
last_job_id: DUMMY_JOB_1_ID,
}),
&[],
),
ContractError::AccountAlreadyFreeError {},
// free account idempotent
let _ = app.execute_contract(
Addr::unchecked(USER_1),
warp_account_tracker_contract_addr.clone(),
&ExecuteMsg::FreeJobAccount(FreeJobAccountMsg {
account_owner_addr: USER_1.to_string(),
account_addr: DUMMY_WARP_ACCOUNT_1_ADDR.to_string(),
last_job_id: DUMMY_JOB_1_ID,
}),
&[],
);

// Mark second account as free
Expand Down
17 changes: 17 additions & 0 deletions contracts/warp-controller/src/execute/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,6 +478,8 @@ pub fn execute_job(
let mut msgs = vec![];
let mut submsgs = vec![];

let mut execution_matched = false;

for Execution { condition, msgs } in job.executions {
let resolution: StdResult<bool> = deps.querier.query_wasm_smart(
config.resolver_address.clone(),
Expand Down Expand Up @@ -509,6 +511,9 @@ pub fn execute_job(
gas_limit: None,
reply_on: ReplyOn::Always,
});

execution_matched = true;

break;
}
Ok(false) => {
Expand All @@ -519,11 +524,23 @@ pub fn execute_job(
attrs.push(Attribute::new("job_condition_status", "invalid"));
attrs.push(Attribute::new("error", e.to_string()));
JobQueue::finalize(deps.storage, env, job.id.into(), JobStatus::Failed)?;

execution_matched = true;

break;
}
}
}

if !execution_matched {
return Ok(Response::new()
.add_attribute("action", "execute_job")
.add_attribute("executor", info.sender)
.add_attribute("job_id", job.id)
.add_attribute("job_condition", "inactive")
.add_attributes(attrs));
}

// Controller sends reward to executor
msgs.push(build_transfer_native_funds_msg(
info.sender.to_string(),
Expand Down
11 changes: 10 additions & 1 deletion contracts/warp-controller/src/reply/job.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,20 @@ pub fn execute_job(
"failed_invalid_job_status",
));
} else {
let hydrated_vars: String = deps.querier.query_wasm_smart(
config.resolver_address.clone(),
&resolver::QueryMsg::QueryHydrateVars(resolver::QueryHydrateVarsMsg {
vars: finished_job.vars,
warp_account_addr: Some(finished_job.account.to_string()),
external_inputs: None,
}),
)?;

// vars are updated to next job iteration
let new_vars: String = deps.querier.query_wasm_smart(
config.resolver_address.clone(),
&resolver::QueryMsg::QueryApplyVarFn(resolver::QueryApplyVarFnMsg {
vars: finished_job.vars,
vars: hydrated_vars,
status: finished_job.status.clone(),
warp_account_addr: Some(finished_job.account.to_string()),
}),
Expand Down
2 changes: 2 additions & 0 deletions contracts/warp-resolver/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@ schemars = "0.8"
thiserror = "1"
serde-json-wasm = "0.4.1"
json-codec-wasm = "0.1.0"
injective-cosmwasm = "0.2.22"


[dev-dependencies]
cw-multi-test = "0.16.0"
137 changes: 107 additions & 30 deletions contracts/warp-resolver/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use controller::account::WarpMsg;
use controller::job::Execution;
use injective_cosmwasm::InjectiveQueryWrapper;
use resolver::condition::{NumValue, StringEnvValue, StringValue};
use schemars::_serde_json::json;

Expand All @@ -13,8 +14,9 @@ use cosmwasm_std::{
use crate::contract::query;
use cosmwasm_schema::cw_serde;
use cosmwasm_std::testing::{mock_info, MockApi, MockQuerier, MockStorage};
use cosmwasm_std::{from_slice, Empty, Querier, QueryRequest, SystemError, SystemResult};
use cosmwasm_std::{from_slice, Querier, QueryRequest, SystemError, SystemResult};

use core::panic;
use resolver::variable::{
FnValue, QueryExpr, QueryVariable, StaticVariable, Variable, VariableKind,
};
Expand Down Expand Up @@ -77,12 +79,12 @@ pub fn mock_dependencies() -> OwnedDeps<MockStorage, MockApi, WasmMockQuerier> {
}

pub struct WasmMockQuerier {
base: MockQuerier<Empty>,
base: MockQuerier<String>,
}

impl Querier for WasmMockQuerier {
fn raw_query(&self, bin_request: &[u8]) -> SystemResult<ContractResult<Binary>> {
let request: QueryRequest<Empty> = match from_slice(bin_request) {
let request: QueryRequest<String> = match from_slice(bin_request) {
Ok(v) => v,
Err(e) => {
return SystemResult::Err(SystemError::InvalidRequest {
Expand All @@ -98,39 +100,67 @@ impl Querier for WasmMockQuerier {
impl WasmMockQuerier {
pub fn handle_query(
&self,
request: &QueryRequest<Empty>,
request: &QueryRequest<String>,
) -> SystemResult<ContractResult<Binary>> {
match &request {
QueryRequest::Wasm(WasmQuery::Smart {
contract_addr,
msg: _,
}) => {
// Mock logic for the Wasm::Smart case
// Here for simplicity, we return the contract_addr and msg as is.

// Mock logic for the Wasm::Smart case
// Here we return a JSON object with "address" and "msg" fields.
let response: String = json!({
"address": contract_addr,
"msg": "Mock message"
})
.to_string();

SystemResult::Ok(ContractResult::Ok(to_binary(&response).unwrap()))
match request {
QueryRequest::Wasm(WasmQuery::Smart { contract_addr, msg }) => {
// Check if the query is for the vault contract address to get subaccount_id
if contract_addr == "mock_vault_contract_addr" {
// Simulate response with subaccount_id
let response = json!({
"config": {
"base": {
"subaccount_id": "0xecde8308ee5413d67288fae2abfc94dabeb16bd9000000000000000000000022"
}
}
});
SystemResult::Ok(ContractResult::Ok(to_binary(&response).unwrap()))
} else {
// Default mock response for other smart contract queries
let response = json!({
"address": contract_addr,
"msg": "Mock message"
})
.to_string();
SystemResult::Ok(ContractResult::Ok(to_binary(&response).unwrap()))
}
}
QueryRequest::Custom(s) if s.contains("route") && s.contains("exchange") => {
// Parse the custom query to extract the subaccount_id
let query_data: InjectiveQueryWrapper = serde_json_wasm::from_str(s).unwrap();
let _subaccount_id = match query_data.query_data {
injective_cosmwasm::InjectiveQuery::SubaccountDeposit {
subaccount_id,
denom: _,
} => subaccount_id,
_ => panic!("wtf"),
};

// let subaccount_id = query_data.query_data["subaccount_deposit"]["subaccount_id"].as_str().unwrap_or("");

// Simulate a response for available balance based on the subaccount_id
SystemResult::Ok(ContractResult::Ok(
to_binary(&json!({
"deposits": {
"available_balance": "1000", // Mock balance
}
}))
.unwrap(),
))
}
QueryRequest::Bank(BankQuery::Balance {
address: contract_addr,
denom: _,
}) => SystemResult::Ok(ContractResult::Ok(
to_binary(&contract_addr.to_string()).unwrap(),
)),
_ => self.base.handle_query(request),
_ => panic!("Unhandled query type in mock querier"),
}
}
}

impl WasmMockQuerier {
pub fn new(base: MockQuerier<Empty>) -> Self {
pub fn new(base: MockQuerier<String>) -> Self {
WasmMockQuerier { base }
}
}
Expand Down Expand Up @@ -219,10 +249,8 @@ fn test_hydrate_vars_nested_variables_binary_json() {
init_fn: QueryExpr {
selector: "$".to_string(),
query: QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: "contract_addr".to_string(),
msg: Binary::from(
r#"{"test":"eyJhZGRyZXNzIjoiY29udHJhY3RfYWRkciIsIm1zZyI6Ik1vY2sgbWVzc2FnZSJ9"}"#.as_bytes()
),
contract_addr: "$warp.variable.var4".to_string(),
msg: Binary::from(r#"{"test":"$warp.variable.var1"}"#.as_bytes()),
}),
},
value: Some(r#"{"address":"contract_addr","msg":"Mock message"}"#.to_string()),
Expand Down Expand Up @@ -277,8 +305,8 @@ fn test_hydrate_vars_nested_variables_binary() {
init_fn: QueryExpr {
selector: "$".to_string(),
query: QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: "static_value".to_string(),
msg: Binary::from(r#"{"test": "static_value"}"#.as_bytes()),
contract_addr: "$warp.variable.var1".to_string(),
msg: Binary::from(r#"{"test": "$warp.variable.var1"}"#.as_bytes()),
}),
},
value: Some(r#"{"address":"static_value","msg":"Mock message"}"#.to_string()),
Expand Down Expand Up @@ -332,7 +360,7 @@ fn test_hydrate_vars_nested_variables_non_binary() {
init_fn: QueryExpr {
selector: "$".to_string(),
query: QueryRequest::Bank(BankQuery::Balance {
address: "static_value".to_string(),
address: "$warp.variable.var1".to_string(),
denom: "denom".to_string(),
}),
},
Expand Down Expand Up @@ -588,3 +616,52 @@ fn test_hydrate_static_env_vars_and_hydrate_msgs() {
}))
)
}

#[test]
fn test_hydrate_static_and_custom_query_vars() {
let deps = mock_dependencies();
let env = mock_env();

// Assuming 'vault_contract_addr' and 'vault_strategy_denom' are known and used for the query
let vault_contract_addr = "mock_vault_contract_addr".to_string();

// Static variable initialization similar to the SDK code for 'subaccount_id'
let subaccount_id = Variable::Query(QueryVariable {
kind: VariableKind::String,
name: "subaccount_id".to_string(),
encode: false,
value: None,
init_fn: QueryExpr {
selector: "$.config.base.subaccount_id".to_string(),
query: QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: vault_contract_addr.clone(),
msg: to_binary(&json!({"base": {"config": {}}})).unwrap(),
}),
},
reinitialize: true,
update_fn: None,
});

let next_config = Variable::Query(QueryVariable {
name: "next_config".to_string(),
kind: VariableKind::Json,
init_fn: QueryExpr {
selector: "$.config".to_string(),
query: QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: vault_contract_addr.clone(),
msg: to_binary(&json!({ "base": { "config": {} } })).unwrap(),
}),
},
value: None,
reinitialize: true,
update_fn: None,
encode: false,
});

// Hydrate variables
let vars = vec![subaccount_id, next_config];
// let vars = vec![next_config];
let hydrated_vars = hydrate_vars(deps.as_ref(), env, vars, None, None).unwrap();

println!("{:?}", hydrated_vars);
}
Loading
Loading