Skip to content

Commit

Permalink
Merge pull request #211 from CronCats/refactoring
Browse files Browse the repository at this point in the history
[FEATURE]: User friendly TaskRequestBuilder for creating TaskRequests mentioned by whalelephantK
  • Loading branch information
d3v3us authored Dec 15, 2022
2 parents b987f38 + 00a093f commit 0687460
Show file tree
Hide file tree
Showing 11 changed files with 214 additions and 40 deletions.
7 changes: 1 addition & 6 deletions Cargo.lock

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

19 changes: 7 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,18 +23,17 @@ to the world, once you are ready to deploy it on a running blockchain.

## Commands
```bash
cd contracts/cw-croncat/scripts
```
# Install just
cargo install just

```bash
# For building + fmt
./build.sh
just build

# For testing everything
./test.sh
just test

# For schemas
./schema.sh
just schema

# Production compilation, run before deploying to live network
docker run --rm -v "$(pwd)":/code \
Expand All @@ -46,13 +45,9 @@ docker run --rm -v "$(pwd)":/code \
## Testnet examples

There are some scripts for testnet, mainnet and local node
```bash
cd scripts/uni-testnet
```

To build and deploy to testnet:
```bash
./start.sh -w -c
just deploy
```

Save the address of the created contract:
Expand Down Expand Up @@ -114,7 +109,7 @@ cargo run -- help

Schema Update
```bash
./build.sh
just build
```
Install yarn packages
```bash
Expand Down
4 changes: 2 additions & 2 deletions checksum
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
efc374eee9ede4a11ec6c344db13de10afdfd10510cb70f39611e2c67c20a58b cw_croncat.wasm
5863a5417a530690c765c9ca4f3943c96071b1ee7faecfc408fce01da08aec56 cw_rules.wasm
de7f6716cf0380e7eaff2440d24dada99fe054aaf51e190b80c5a8ebf35c97d5 cw_croncat.wasm
de2d1a0c648e41760020dd261f818da085c358240059acf85128f60eb0e05db2 cw_rules.wasm
3 changes: 1 addition & 2 deletions contracts/cw-croncat/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,9 @@ optimize = """docker run --rm -v "$(pwd)":/code \
"""

[dependencies]
cw-croncat-core = { version = "0.1.4", path = "../../packages/cw-croncat-core" }
cw-croncat-core = { version = "0.1.5", path = "../../packages/cw-croncat-core" }
cw-rules-core = { version = "0.1.2", path = "../../packages/cw-rules-core" }
cosmwasm-std = { version = "1.0.0", features = ["staking", "stargate"] }
cosmwasm-storage = { version = "1.0.0" }
cw-storage-plus = "0.16.0"
cw-utils = "0.13"
cw2 = "0.16.0"
Expand Down
7 changes: 1 addition & 6 deletions contracts/cw-rules/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,24 +31,18 @@ optimize = """docker run --rm -v "$(pwd)":/code \
"""

[dependencies]
cw-croncat-core = { version = "0.1.4", path = "../../packages/cw-croncat-core" }
generic-query = { version = "0.1.1", path = "../../packages/generic-query" }
smart-query = { version = "0.1.0", path = "../../packages/smart-query" }
cw-rules-core = { version = "0.1.2", path = "../../packages/cw-rules-core" }
cosmwasm-std = "1.0.0"
cosmwasm-storage = "1.0.0"
cw-storage-plus = "0.16.0"
cw-utils = "0.13.4"
cw2 = "0.16.0"
cw721 = "0.15.0"
cw721-base = "0.15.0"
cw20 = "0.13.4"
schemars = "0.8.8"
serde = { version = "1.0.137", default-features = false, features = ["derive"] }
thiserror = { version = "1.0.31" }
cw4 = "0.16.0"
cw4-group = "0.16.0"
voting-v1 = { package = "voting", version = "0.1.0", git = "https://github.com/DA0-DA0/dao-contracts.git", tag = "v1.0.0" }

# This thing saved our lives thanks @hashedone for implementing it
serde-cw-value = "0.7.0"
Expand All @@ -57,6 +51,7 @@ serde-cw-value = "0.7.0"
serde-json-wasm = { version = "0.4.1", git = "https://github.com/CyberHoward/serde-json-wasm", rev = "cdc78130b25d65981b74a5e4a10a9f8667292d36" }

[dev-dependencies]
cw721-base = "0.15.0"
cosmwasm-schema = "1.0.0"
cw-multi-test = "0.16.0"
cw-utils = "0.13.4"
Expand Down
11 changes: 10 additions & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,16 @@ test_addrs := env_var_or_default('TEST_ADDR', `jq -r '.[].address' ci/test_accou
set export
check:
cargo fmt && cargo clippy -- -D warnings

test:
./scripts/test.sh
build:
./scripts/build.sh
deploy:
./scripts/uni-testnet/start.sh -c -w
checksum:
./scripts/update-checksum.sh
schema:
./scripts/schema.sh
juno-local:
docker kill cosmwasm || true
docker volume rm -f junod_data
Expand Down
3 changes: 1 addition & 2 deletions packages/cw-croncat-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "cw-croncat-core"
description = "CronCat core logic allowing automated scheduling of transactions and IFTTT for the interchain"
license = "MIT OR Apache-2.0"
version = "0.1.4"
version = "0.1.5"
edition = "2021"

[package.metadata.scripts]
Expand All @@ -16,7 +16,6 @@ optimize = """docker run --rm -v "$(pwd)":/code \
cosmwasm-std = { version = "1.0.0", features = ["staking", "stargate"] }
cw-rules-core = { version = "0.1.2", path = "../cw-rules-core" }
generic-query = { version = "0.1.1", path = "../generic-query" }
cosmwasm-storage = { version = "1.0.0" }
cw-storage-plus = "0.16.0"
cron_schedule = "0.2.3"
cw2 = "0.16.0"
Expand Down
4 changes: 4 additions & 0 deletions packages/cw-croncat-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ pub enum CoreError {
#[error("Boundary is not in valid format")]
InvalidBoundary {},

#[error("Interval is not valid")]
InvalidInterval {},

#[error("No coin balance found")]
EmptyBalance {},

Expand All @@ -29,6 +32,7 @@ pub enum CoreError {

#[error("Task({task_hash}) became invalid after replacing placeholder")]
TaskNoLongerValid { task_hash: String },

#[error("Must provide gas limit for WASM actions")]
NoGasLimit {},
}
114 changes: 114 additions & 0 deletions packages/cw-croncat-core/src/msg.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use crate::error::CoreError;
use crate::traits::Intervals;
use crate::types::{
Action, AgentStatus, Boundary, BoundaryValidated, GasFraction, GenericBalance, Interval, Task,
Transform,
Expand Down Expand Up @@ -273,7 +275,119 @@ pub struct TaskRequest {
pub transforms: Option<Vec<Transform>>,
pub cw20_coins: Vec<Cw20Coin>,
}
pub struct TaskRequestBuilder {
interval: Interval,
boundary: Option<Boundary>,
stop_on_fail: bool,
actions: Option<Vec<Action>>,
queries: Option<Option<Vec<CroncatQuery>>>,
transforms: Option<Option<Vec<Transform>>>,
cw20_coins: Option<Vec<Cw20Coin>>,
}
#[allow(dead_code)]
impl TaskRequestBuilder {
pub fn new() -> Self {
Self {
interval: Interval::Once,
boundary: None,
stop_on_fail: false,
actions: None,
queries: None,
transforms: None,
cw20_coins: None,
}
}
pub fn with_interval(&mut self, interval: Interval) -> &mut Self {
self.interval = interval;
self
}
pub fn once(&mut self) -> &mut Self {
self.with_interval(Interval::Once)
}
pub fn block(&mut self, block_inerval: u64) -> &mut Self {
self.with_interval(Interval::Block(block_inerval))
}
pub fn cron(&mut self, crontab: String) -> &mut Self {
self.with_interval(Interval::Cron(crontab))
}
pub fn immediate(&mut self) -> &mut Self {
self.with_interval(Interval::Immediate)
}
pub fn with_boundary(&mut self, boundary: Boundary) -> &mut Self {
self.boundary = Some(boundary);
self
}
pub fn with_time_boundary(&mut self, start: Timestamp, end: Timestamp) -> &mut Self {
self.with_boundary(Boundary::Time {
start: Some(start),
end: Some(end),
})
}
pub fn with_height_boundary(&mut self, start: u64, end: u64) -> &mut Self {
self.with_boundary(Boundary::Height {
start: Some(Uint64::new(start)),
end: Some(Uint64::new(end)),
})
}
pub fn should_stop_on_fail(&mut self, stop_on_fail: bool) -> &mut Self {
self.stop_on_fail = stop_on_fail;
self
}

pub fn with_action(&mut self, action: Action) -> &mut Self {
self.actions = Some(vec![action]);
self
}
pub fn with_actions(&mut self, actions: Vec<Action>) -> &mut Self {
self.actions = Some(actions);
self
}
pub fn with_query(&mut self, query: CroncatQuery) -> &mut Self {
self.queries = Some(Some(vec![query]));
self
}
pub fn with_queries(&mut self, queries: Vec<CroncatQuery>) -> &mut Self {
self.queries = Some(Some(queries));
self
}
pub fn with_transform(&mut self, transform: Transform) -> &mut Self {
self.transforms = Some(Some(vec![transform]));
self
}
fn with_transforms(&mut self, transforms: Vec<Transform>) -> &mut Self {
self.transforms = Some(Some(transforms));
self
}
fn with_cw20(&mut self, cw20: Cw20Coin) -> &mut Self {
self.cw20_coins = Some(vec![cw20]);
self
}
pub fn with_cw20s(&mut self, cw20s: Vec<Cw20Coin>) -> &mut Self {
self.cw20_coins = Some(cw20s);
self
}
pub fn build(&self) -> Result<TaskRequest, CoreError> {
if !self.interval.is_valid() {
return Err(CoreError::InvalidInterval {});
}
BoundaryValidated::validate_boundary(self.boundary, &self.interval)?;

Ok(TaskRequest {
interval: self.interval.clone(),
boundary: self.boundary,
stop_on_fail: self.stop_on_fail,
actions: self.actions.clone().unwrap_or_default(),
queries: self.queries.clone().unwrap_or_default(),
transforms: self.transforms.clone().unwrap_or_default(),
cw20_coins: self.cw20_coins.clone().unwrap_or_default(),
})
}
}
impl Default for TaskRequestBuilder {
fn default() -> Self {
Self::new()
}
}
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
pub struct TaskResponse {
pub task_hash: String,
Expand Down
44 changes: 43 additions & 1 deletion packages/cw-croncat-core/src/tests/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@ use cosmwasm_std::{coin, coins, Addr, BankMsg, CosmosMsg, Timestamp, Uint64};
use cw20::Cw20CoinVerified;

use crate::{
error::CoreError,
msg::{
AgentResponse, AgentTaskResponse, Croncat, GetAgentIdsResponse, GetBalancesResponse,
GetConfigResponse, GetSlotHashesResponse, GetSlotIdsResponse, GetWalletBalancesResponse,
TaskRequest, TaskResponse,
TaskRequest, TaskRequestBuilder, TaskResponse,
},
types::{
Action, Agent, AgentStatus, Boundary, BoundaryValidated, GasFraction, GenericBalance,
Expand Down Expand Up @@ -189,3 +190,44 @@ fn everything_can_be_de_serialized() {
let deser: Result<Croncat, _> = serde_json_wasm::from_str(&ser.unwrap());
assert!(deser.is_ok());
}
#[test]
fn test_task_request_builder() {
const ALICE_ADDR: &str = "juno1l8hl8e0ut8jdaecxwazs9m32ak02ez4rssq4wl";
const DENOM: &str = "ujunox";

let valid_result = TaskRequestBuilder::new()
.once()
.with_height_boundary(10, 20)
.should_stop_on_fail(true)
.with_action(Action {
msg: cosmwasm_std::CosmosMsg::Bank(cosmwasm_std::BankMsg::Send {
to_address: ALICE_ADDR.to_string(),
amount: coins(1, DENOM),
}),
gas_limit: None,
})
.build()
.unwrap();

assert!(valid_result.boundary.is_some());
assert!(valid_result.stop_on_fail);
assert!(valid_result.actions.len() == 1);

assert!(matches!(valid_result.interval, Interval::Once));

let invalid_result = TaskRequestBuilder::new()
.once()
.with_height_boundary(10, 5)
.should_stop_on_fail(true)
.with_action(Action {
msg: cosmwasm_std::CosmosMsg::Bank(cosmwasm_std::BankMsg::Send {
to_address: ALICE_ADDR.to_string(),
amount: coins(1, DENOM),
}),
gas_limit: None,
})
.build()
.unwrap_err();

assert!(matches!(invalid_result, CoreError::InvalidBoundary {}));
}
Loading

0 comments on commit 0687460

Please sign in to comment.