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

Contract builders #334

Merged
merged 4 commits into from
Jul 20, 2021
Merged
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
2 changes: 1 addition & 1 deletion packages/multi-test/NOTICE
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
CW Multi Test: Test helpers for multi-contract interactions
Copyright (C) 2020 Confio OÜ
Copyright (C) 2020-2021 Confio OÜ

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
Expand Down
6 changes: 5 additions & 1 deletion packages/multi-test/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
# Multi Test: Test helpers for multi-contract interactions

Let us run unit tests with contracts calling contracts, and calling
in and out of bank.
in and out of bank.

This only works with contracts and bank currently. We are working
on refactoring to make it more extensible for more handlers,
including custom messages/queries as well as IBC.
3 changes: 2 additions & 1 deletion packages/multi-test/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ use cosmwasm_std::{
};

use crate::bank::{Bank, BankCache, BankCommittable, BankOps, BankRouter};
use crate::wasm::{Contract, StorageFactory, WasmCache, WasmCommittable, WasmOps, WasmRouter};
use crate::contracts::Contract;
use crate::wasm::{StorageFactory, WasmCache, WasmCommittable, WasmOps, WasmRouter};
use schemars::JsonSchema;
use std::fmt;

Expand Down
267 changes: 267 additions & 0 deletions packages/multi-test/src/contracts.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
use schemars::JsonSchema;
use serde::de::DeserializeOwned;
use std::fmt;

use cosmwasm_std::{
from_slice, Binary, CosmosMsg, Deps, DepsMut, Empty, Env, MessageInfo, Reply, Response, SubMsg,
};

/// Interface to call into a Contract
pub trait Contract<T>
where
T: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn execute(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<T>, String>;

fn instantiate(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<T>, String>;

fn sudo(&self, deps: DepsMut, env: Env, msg: Vec<u8>) -> Result<Response<T>, String>;

fn reply(&self, deps: DepsMut, env: Env, msg: Reply) -> Result<Response<T>, String>;

fn query(&self, deps: Deps, env: Env, msg: Vec<u8>) -> Result<Binary, String>;
}

type ContractFn<T, C, E> =
fn(deps: DepsMut, env: Env, info: MessageInfo, msg: T) -> Result<Response<C>, E>;
type SudoFn<T, C, E> = fn(deps: DepsMut, env: Env, msg: T) -> Result<Response<C>, E>;
type ReplyFn<C, E> = fn(deps: DepsMut, env: Env, msg: Reply) -> Result<Response<C>, E>;
type QueryFn<T, E> = fn(deps: Deps, env: Env, msg: T) -> Result<Binary, E>;

type ContractClosure<T, C, E> = Box<dyn Fn(DepsMut, Env, MessageInfo, T) -> Result<Response<C>, E>>;
type SudoClosure<T, C, E> = Box<dyn Fn(DepsMut, Env, T) -> Result<Response<C>, E>>;
type ReplyClosure<C, E> = Box<dyn Fn(DepsMut, Env, Reply) -> Result<Response<C>, E>>;
type QueryClosure<T, E> = Box<dyn Fn(Deps, Env, T) -> Result<Binary, E>>;

/// Wraps the exported functions from a contract and provides the normalized format
/// Place T4 and E4 at the end, as we just want default placeholders for most contracts that don't have sudo
pub struct ContractWrapper<T1, T2, T3, E1, E2, E3, C = Empty, T4 = Empty, E4 = String, E5 = String>
where
T1: DeserializeOwned,
T2: DeserializeOwned,
T3: DeserializeOwned,
T4: DeserializeOwned,
E1: ToString,
E2: ToString,
E3: ToString,
E4: ToString,
E5: ToString,
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
execute_fn: ContractClosure<T1, C, E1>,
instantiate_fn: ContractClosure<T2, C, E2>,
query_fn: QueryClosure<T3, E3>,
sudo_fn: Option<SudoClosure<T4, C, E4>>,
reply_fn: Option<ReplyClosure<C, E5>>,
}

impl<T1, T2, T3, E1, E2, E3, C> ContractWrapper<T1, T2, T3, E1, E2, E3, C>
where
T1: DeserializeOwned + 'static,
T2: DeserializeOwned + 'static,
T3: DeserializeOwned + 'static,
E1: ToString + 'static,
E2: ToString + 'static,
E3: ToString + 'static,
C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,
{
pub fn new(
execute_fn: ContractFn<T1, C, E1>,
instantiate_fn: ContractFn<T2, C, E2>,
query_fn: QueryFn<T3, E3>,
) -> Self {
ContractWrapper {
execute_fn: Box::new(execute_fn),
instantiate_fn: Box::new(instantiate_fn),
query_fn: Box::new(query_fn),
sudo_fn: None,
reply_fn: None,
}
}

/// this will take a contract that returns Response<Empty> and will "upgrade" it
/// to Response<C> if needed to be compatible with a chain-specific extension
pub fn new_with_empty(
execute_fn: ContractFn<T1, Empty, E1>,
instantiate_fn: ContractFn<T2, Empty, E2>,
query_fn: QueryFn<T3, E3>,
) -> Self {
ContractWrapper {
execute_fn: customize_fn(execute_fn),
instantiate_fn: customize_fn(instantiate_fn),
query_fn: Box::new(query_fn),
sudo_fn: None,
reply_fn: None,
}
}
}

impl<T1, T2, T3, E1, E2, E3, C, T4, E4, E5> ContractWrapper<T1, T2, T3, E1, E2, E3, C, T4, E4, E5>
where
T1: DeserializeOwned + 'static,
T2: DeserializeOwned + 'static,
T3: DeserializeOwned + 'static,
T4: DeserializeOwned + 'static,
E1: ToString + 'static,
E2: ToString + 'static,
E3: ToString + 'static,
E4: ToString + 'static,
E5: ToString,
C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,
{
pub fn with_sudo<T4A, E4A>(
self,
sudo_fn: SudoFn<T4A, C, E4A>,
) -> ContractWrapper<T1, T2, T3, E1, E2, E3, C, T4A, E4A, E5>
maurolacy marked this conversation as resolved.
Show resolved Hide resolved
where
T4A: DeserializeOwned + 'static,
E4A: ToString + 'static,
{
ContractWrapper {
execute_fn: self.execute_fn,
instantiate_fn: self.instantiate_fn,
query_fn: self.query_fn,
sudo_fn: Some(Box::new(sudo_fn)),
reply_fn: self.reply_fn,
}
maurolacy marked this conversation as resolved.
Show resolved Hide resolved
}

pub fn with_reply<E5A>(
self,
reply_fn: ReplyFn<C, E5A>,
) -> ContractWrapper<T1, T2, T3, E1, E2, E3, C, T4, E4, E5A>
where
E5A: ToString + 'static,
{
ContractWrapper {
execute_fn: self.execute_fn,
instantiate_fn: self.instantiate_fn,
query_fn: self.query_fn,
sudo_fn: self.sudo_fn,
reply_fn: Some(Box::new(reply_fn)),
}
}
}

fn customize_fn<T, C, E>(raw_fn: ContractFn<T, Empty, E>) -> ContractClosure<T, C, E>
where
T: DeserializeOwned + 'static,
E: ToString + 'static,
C: Clone + fmt::Debug + PartialEq + JsonSchema + 'static,
{
let customized =
move |deps: DepsMut, env: Env, info: MessageInfo, msg: T| -> Result<Response<C>, E> {
raw_fn(deps, env, info, msg).map(customize_response::<C>)
};
Box::new(customized)
}

fn customize_response<C>(resp: Response<Empty>) -> Response<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
Response::<C> {
messages: resp.messages.into_iter().map(customize_msg::<C>).collect(),
events: resp.events,
attributes: resp.attributes,
data: resp.data,
}
}

fn customize_msg<C>(msg: SubMsg<Empty>) -> SubMsg<C>
where
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
SubMsg {
msg: match msg.msg {
CosmosMsg::Wasm(wasm) => CosmosMsg::Wasm(wasm),
CosmosMsg::Bank(bank) => CosmosMsg::Bank(bank),
CosmosMsg::Staking(staking) => CosmosMsg::Staking(staking),
CosmosMsg::Custom(_) => unreachable!(),
#[cfg(feature = "stargate")]
CosmosMsg::Ibc(ibc) => CosmosMsg::Ibc(ibc),
#[cfg(feature = "stargate")]
CosmosMsg::Stargate { type_url, value } => CosmosMsg::Stargate { type_url, value },
_ => panic!("unknown message variant {:?}", msg),
},
id: msg.id,
gas_limit: msg.gas_limit,
reply_on: msg.reply_on,
}
}

impl<T1, T2, T3, E1, E2, E3, C, T4, E4, E5> Contract<C>
for ContractWrapper<T1, T2, T3, E1, E2, E3, C, T4, E4, E5>
where
T1: DeserializeOwned,
T2: DeserializeOwned,
T3: DeserializeOwned,
T4: DeserializeOwned,
E1: ToString,
E2: ToString,
E3: ToString,
E4: ToString,
E5: ToString,
C: Clone + fmt::Debug + PartialEq + JsonSchema,
{
fn execute(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<C>, String> {
let msg: T1 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = (self.execute_fn)(deps, env, info, msg);
res.map_err(|e| e.to_string())
}

fn instantiate(
&self,
deps: DepsMut,
env: Env,
info: MessageInfo,
msg: Vec<u8>,
) -> Result<Response<C>, String> {
let msg: T2 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = (self.instantiate_fn)(deps, env, info, msg);
res.map_err(|e| e.to_string())
}

// this returns an error if the contract doesn't implement sudo
fn sudo(&self, deps: DepsMut, env: Env, msg: Vec<u8>) -> Result<Response<C>, String> {
let msg: T4 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = match &self.sudo_fn {
Some(sudo) => sudo(deps, env, msg),
None => return Err("sudo not implemented for contract".to_string()),
};
res.map_err(|e| e.to_string())
}

// this returns an error if the contract doesn't implement reply
fn reply(&self, deps: DepsMut, env: Env, reply_data: Reply) -> Result<Response<C>, String> {
let res = match &self.reply_fn {
Some(reply) => reply(deps, env, reply_data),
None => return Err("reply not implemented for contract".to_string()),
};
res.map_err(|e| e.to_string())
}

fn query(&self, deps: Deps, env: Env, msg: Vec<u8>) -> Result<Binary, String> {
let msg: T3 = from_slice(&msg).map_err(|e| e.to_string())?;
let res = (self.query_fn)(deps, env, msg);
res.map_err(|e| e.to_string())
}
}
4 changes: 3 additions & 1 deletion packages/multi-test/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
mod app;
mod bank;
mod contracts;
mod test_helpers;
mod transactions;
mod wasm;

pub use crate::app::{parse_contract_addr, App, AppCache, AppOps};
pub use crate::bank::{Bank, BankCache, BankOps, SimpleBank};
pub use crate::wasm::{next_block, Contract, ContractWrapper, WasmCache, WasmOps, WasmRouter};
pub use crate::contracts::{Contract, ContractWrapper};
pub use crate::wasm::{next_block, WasmCache, WasmOps, WasmRouter};
18 changes: 5 additions & 13 deletions packages/multi-test/src/test_helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use cosmwasm_std::{
};
use cw_storage_plus::{Item, Map, U64Key};

use crate::wasm::{Contract, ContractWrapper};
use crate::contracts::{Contract, ContractWrapper};

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct EmptyMsg {}
Expand Down Expand Up @@ -128,12 +128,8 @@ fn query_payout(deps: Deps, _env: Env, msg: PayoutQueryMsg) -> Result<Binary, St
}

pub fn contract_payout() -> Box<dyn Contract<Empty>> {
let contract = ContractWrapper::new_with_sudo(
execute_payout,
instantiate_payout,
query_payout,
sudo_payout,
);
let contract = ContractWrapper::new(execute_payout, instantiate_payout, query_payout)
.with_sudo(sudo_payout);
maurolacy marked this conversation as resolved.
Show resolved Hide resolved
Box::new(contract)
}

Expand Down Expand Up @@ -221,11 +217,7 @@ fn reply_reflect(deps: DepsMut, _env: Env, msg: Reply) -> Result<Response<Custom
}

pub fn contract_reflect() -> Box<dyn Contract<CustomMsg>> {
let contract = ContractWrapper::new_with_reply(
execute_reflect,
instantiate_reflect,
query_reflect,
reply_reflect,
);
let contract = ContractWrapper::new(execute_reflect, instantiate_reflect, query_reflect)
.with_reply(reply_reflect);
Box::new(contract)
}
Loading