From 149809d406ad612647074c1070abe26176d4a817 Mon Sep 17 00:00:00 2001 From: Georges Chouchani Date: Mon, 27 Jun 2022 17:11:52 +0300 Subject: [PATCH 1/6] adding escrow contract --- cw20/escrow/.cargo/config | 6 + cw20/escrow/.editorconfig | 11 + cw20/escrow/.genignore | 1 + cw20/escrow/.gitignore | 16 + cw20/escrow/Cargo.toml | 33 ++ cw20/escrow/LICENSE | 202 ++++++++ cw20/escrow/NOTICE | 16 + cw20/escrow/README.md | 46 ++ cw20/escrow/cargo-generate.toml | 5 + cw20/escrow/examples/schema.rs | 22 + cw20/escrow/rustfmt.toml | 15 + cw20/escrow/src/contract.rs | 753 ++++++++++++++++++++++++++++ cw20/escrow/src/error.rs | 26 + cw20/escrow/src/integration_test.rs | 157 ++++++ cw20/escrow/src/lib.rs | 7 + cw20/escrow/src/msg.rs | 136 +++++ cw20/escrow/src/state.rs | 149 ++++++ 17 files changed, 1601 insertions(+) create mode 100644 cw20/escrow/.cargo/config create mode 100644 cw20/escrow/.editorconfig create mode 100644 cw20/escrow/.genignore create mode 100644 cw20/escrow/.gitignore create mode 100644 cw20/escrow/Cargo.toml create mode 100644 cw20/escrow/LICENSE create mode 100644 cw20/escrow/NOTICE create mode 100644 cw20/escrow/README.md create mode 100644 cw20/escrow/cargo-generate.toml create mode 100644 cw20/escrow/examples/schema.rs create mode 100644 cw20/escrow/rustfmt.toml create mode 100644 cw20/escrow/src/contract.rs create mode 100644 cw20/escrow/src/error.rs create mode 100644 cw20/escrow/src/integration_test.rs create mode 100644 cw20/escrow/src/lib.rs create mode 100644 cw20/escrow/src/msg.rs create mode 100644 cw20/escrow/src/state.rs diff --git a/cw20/escrow/.cargo/config b/cw20/escrow/.cargo/config new file mode 100644 index 0000000..8d4bc73 --- /dev/null +++ b/cw20/escrow/.cargo/config @@ -0,0 +1,6 @@ +[alias] +wasm = "build --release --target wasm32-unknown-unknown" +wasm-debug = "build --target wasm32-unknown-unknown" +unit-test = "test --lib" +integration-test = "test --test integration" +schema = "run --example schema" diff --git a/cw20/escrow/.editorconfig b/cw20/escrow/.editorconfig new file mode 100644 index 0000000..3d36f20 --- /dev/null +++ b/cw20/escrow/.editorconfig @@ -0,0 +1,11 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true + +[*.rs] +indent_size = 4 diff --git a/cw20/escrow/.genignore b/cw20/escrow/.genignore new file mode 100644 index 0000000..4fe5fd0 --- /dev/null +++ b/cw20/escrow/.genignore @@ -0,0 +1 @@ +meta/ diff --git a/cw20/escrow/.gitignore b/cw20/escrow/.gitignore new file mode 100644 index 0000000..f9b9a83 --- /dev/null +++ b/cw20/escrow/.gitignore @@ -0,0 +1,16 @@ +# Build results +/target +/artifacts + +# Cargo+Git helper file (https://github.com/rust-lang/cargo/blob/0.44.1/src/cargo/sources/git/utils.rs#L320-L327) +.cargo-ok + +# Text file backups +**/*.rs.bk + +# macOS +.DS_Store + +# IDEs +*.iml +.idea diff --git a/cw20/escrow/Cargo.toml b/cw20/escrow/Cargo.toml new file mode 100644 index 0000000..f542dda --- /dev/null +++ b/cw20/escrow/Cargo.toml @@ -0,0 +1,33 @@ +[package] +name = "{{project-name}}" +version = "0.12.1" +authors = [{{authors}}] +edition = "2018" +description = "Implementation of an escrow that accepts CosmWasm-20 tokens as well as native tokens" +license = "Apache-2.0" +repository = "https://github.com/CosmWasm/cw-tokens" +homepage = "https://cosmwasm.com" +documentation = "https://docs.cosmwasm.com" + +[lib] +crate-type = ["cdylib", "rlib"] + +[features] +backtraces = ["cosmwasm-std/backtraces"] +# use library feature to disable all instantiate/execute/query exports +library = [] + +[dependencies] +cw-utils = "0.13.2" +cw2 = "0.13.2" +cw20 = "0.13.2" +cosmwasm-std = "1.0.0-beta8" +cw-storage-plus = "0.13.2" +schemars = "0.8.8" +serde = { version = "1.0.137", default-features = false, features = ["derive"] } +thiserror = "1.0.31" + +[dev-dependencies] +cosmwasm-schema = "1.0.0-beta8" +cw-multi-test = "0.13.2" +cw20-base = { version = "0.13.2", features = ["library"] } diff --git a/cw20/escrow/LICENSE b/cw20/escrow/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/cw20/escrow/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/cw20/escrow/NOTICE b/cw20/escrow/NOTICE new file mode 100644 index 0000000..934808e --- /dev/null +++ b/cw20/escrow/NOTICE @@ -0,0 +1,16 @@ +CW20-Escrow: A CosmWasm escrow contract that handles native and cw20 tokens +Copyright (C) 2020-21 Confio OÜ +Copyright (C) 2021-22 Confio GmbH + + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/cw20/escrow/README.md b/cw20/escrow/README.md new file mode 100644 index 0000000..3b04148 --- /dev/null +++ b/cw20/escrow/README.md @@ -0,0 +1,46 @@ +# CW20 Escrow + +This is an escrow meta-contract that allows multiple users to +create independent escrows. Each escrow has a sender, recipient, +and arbiter. It also has a unique id (for future calls to reference it) +and an optional timeout. + +The basic function is the sender creates an escrow with funds. +The arbiter may at any time decide to release the funds to either +the intended recipient or the original sender (but no one else), +and if it passes with optional timeout, anyone can refund the locked +tokens to the original sender. + +We also add a function called "top_up", which allows anyone to add more +funds to the contract at any time. + +## Token types + +This contract is meant not just to be functional, but also to work as a simple +example of an CW20 "Receiver". And demonstrate how the same calls can be fed +native tokens (via typical `ExecuteMsg` route), or cw20 tokens (via `Receiver` interface). + +Both `create` and `top_up` can be called directly (with a payload of native tokens), +or from a cw20 contract using the [Receiver Interface](../../packages/cw20/README.md#receiver). +This means we can load the escrow with any number of native or cw20 tokens (or a mix), +allow of which get released when the arbiter decides. + +## Running this contract + +You will need Rust 1.44.1+ with `wasm32-unknown-unknown` target installed. + +You can run unit tests on this via: + +`cargo test` + +Once you are happy with the content, you can compile it to wasm via: + +``` +RUSTFLAGS='-C link-arg=-s' cargo wasm +cp ../../target/wasm32-unknown-unknown/release/cw20_escrow.wasm . +ls -l cw20_escrow.wasm +sha256sum cw20_escrow.wasm +``` + +Or for a production-ready (optimized) build, run a build command in the +the repository root: https://github.com/CosmWasm/cw-plus#compiling. diff --git a/cw20/escrow/cargo-generate.toml b/cw20/escrow/cargo-generate.toml new file mode 100644 index 0000000..b5c5e3c --- /dev/null +++ b/cw20/escrow/cargo-generate.toml @@ -0,0 +1,5 @@ +[template] +# Files listed here will not be processed by the template engine when a project is generated. +# This is needed when files contains curly brackets as in `v4-cargo-cache-{{ arch }}-{{ checksum "Cargo.lock" }}`. +# The files will be copied 1:1 to the target project. To avoid shipping them completely add them to `.genignore`. +exclude = [".circleci/config.yml"] diff --git a/cw20/escrow/examples/schema.rs b/cw20/escrow/examples/schema.rs new file mode 100644 index 0000000..e290178 --- /dev/null +++ b/cw20/escrow/examples/schema.rs @@ -0,0 +1,22 @@ +use std::env::current_dir; +use std::fs::create_dir_all; + +use cosmwasm_schema::{export_schema, remove_schemas, schema_for}; + +use cw20_escrow::msg::{ + DetailsResponse, ExecuteMsg, InstantiateMsg, ListResponse, QueryMsg, ReceiveMsg, +}; + +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + create_dir_all(&out_dir).unwrap(); + remove_schemas(&out_dir).unwrap(); + + export_schema(&schema_for!(InstantiateMsg), &out_dir); + export_schema(&schema_for!(ExecuteMsg), &out_dir); + export_schema(&schema_for!(QueryMsg), &out_dir); + export_schema(&schema_for!(ReceiveMsg), &out_dir); + export_schema(&schema_for!(DetailsResponse), &out_dir); + export_schema(&schema_for!(ListResponse), &out_dir); +} diff --git a/cw20/escrow/rustfmt.toml b/cw20/escrow/rustfmt.toml new file mode 100644 index 0000000..11a85e6 --- /dev/null +++ b/cw20/escrow/rustfmt.toml @@ -0,0 +1,15 @@ +# stable +newline_style = "unix" +hard_tabs = false +tab_spaces = 4 + +# unstable... should we require `rustup run nightly cargo fmt` ? +# or just update the style guide when they are stable? +#fn_single_line = true +#format_code_in_doc_comments = true +#overflow_delimited_expr = true +#reorder_impl_items = true +#struct_field_align_threshold = 20 +#struct_lit_single_line = true +#report_todo = "Always" + diff --git a/cw20/escrow/src/contract.rs b/cw20/escrow/src/contract.rs new file mode 100644 index 0000000..56276c2 --- /dev/null +++ b/cw20/escrow/src/contract.rs @@ -0,0 +1,753 @@ +#[cfg(not(feature = "library"))] +use cosmwasm_std::entry_point; +use cosmwasm_std::{ + from_binary, to_binary, Addr, BankMsg, Binary, Deps, DepsMut, Env, MessageInfo, Response, + StdResult, SubMsg, WasmMsg, +}; + +use cw2::set_contract_version; +use cw20::{Balance, Cw20Coin, Cw20CoinVerified, Cw20ExecuteMsg, Cw20ReceiveMsg}; + +use crate::error::ContractError; +use crate::msg::{ + CreateMsg, DetailsResponse, ExecuteMsg, InstantiateMsg, ListResponse, QueryMsg, ReceiveMsg, +}; +use crate::state::{all_escrow_ids, Escrow, GenericBalance, ESCROWS}; + +// version info for migration info +const CONTRACT_NAME: &str = "crates.io:cw20-escrow"; +const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn instantiate( + deps: DepsMut, + _env: Env, + _info: MessageInfo, + _msg: InstantiateMsg, +) -> StdResult { + set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + // no setup + Ok(Response::default()) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn execute( + deps: DepsMut, + env: Env, + info: MessageInfo, + msg: ExecuteMsg, +) -> Result { + match msg { + ExecuteMsg::Create(msg) => { + execute_create(deps, msg, Balance::from(info.funds), &info.sender) + } + ExecuteMsg::SetRecipient { id, recipient } => { + execute_set_recipient(deps, env, info, id, recipient) + } + ExecuteMsg::Approve { id } => execute_approve(deps, env, info, id), + ExecuteMsg::TopUp { id } => execute_top_up(deps, id, Balance::from(info.funds)), + ExecuteMsg::Refund { id } => execute_refund(deps, env, info, id), + ExecuteMsg::Receive(msg) => execute_receive(deps, info, msg), + } +} + +pub fn execute_receive( + deps: DepsMut, + info: MessageInfo, + wrapper: Cw20ReceiveMsg, +) -> Result { + let msg: ReceiveMsg = from_binary(&wrapper.msg)?; + let balance = Balance::Cw20(Cw20CoinVerified { + address: info.sender, + amount: wrapper.amount, + }); + let api = deps.api; + match msg { + ReceiveMsg::Create(msg) => { + execute_create(deps, msg, balance, &api.addr_validate(&wrapper.sender)?) + } + ReceiveMsg::TopUp { id } => execute_top_up(deps, id, balance), + } +} + +pub fn execute_create( + deps: DepsMut, + msg: CreateMsg, + balance: Balance, + sender: &Addr, +) -> Result { + if balance.is_empty() { + return Err(ContractError::EmptyBalance {}); + } + + let mut cw20_whitelist = msg.addr_whitelist(deps.api)?; + + let escrow_balance = match balance { + Balance::Native(balance) => GenericBalance { + native: balance.0, + cw20: vec![], + }, + Balance::Cw20(token) => { + // make sure the token sent is on the whitelist by default + if !cw20_whitelist.iter().any(|t| t == &token.address) { + cw20_whitelist.push(token.address.clone()) + } + GenericBalance { + native: vec![], + cw20: vec![token], + } + } + }; + + let recipient: Option = msg + .recipient + .and_then(|addr| deps.api.addr_validate(&addr).ok()); + + let escrow = Escrow { + arbiter: deps.api.addr_validate(&msg.arbiter)?, + recipient, + source: sender.clone(), + title: msg.title, + description: msg.description, + end_height: msg.end_height, + end_time: msg.end_time, + balance: escrow_balance, + cw20_whitelist, + }; + + // try to store it, fail if the id was already in use + ESCROWS.update(deps.storage, &msg.id, |existing| match existing { + None => Ok(escrow), + Some(_) => Err(ContractError::AlreadyInUse {}), + })?; + + let res = Response::new().add_attributes(vec![("action", "create"), ("id", msg.id.as_str())]); + Ok(res) +} + +pub fn execute_set_recipient( + deps: DepsMut, + _env: Env, + info: MessageInfo, + id: String, + recipient: String, +) -> Result { + let mut escrow = ESCROWS.load(deps.storage, &id)?; + if info.sender != escrow.arbiter { + return Err(ContractError::Unauthorized {}); + } + + let recipient = deps.api.addr_validate(recipient.as_str())?; + escrow.recipient = Some(recipient.clone()); + ESCROWS.save(deps.storage, &id, &escrow)?; + + Ok(Response::new().add_attributes(vec![ + ("action", "set_recipient"), + ("id", id.as_str()), + ("recipient", recipient.as_str()), + ])) +} + +pub fn execute_top_up( + deps: DepsMut, + id: String, + balance: Balance, +) -> Result { + if balance.is_empty() { + return Err(ContractError::EmptyBalance {}); + } + // this fails is no escrow there + let mut escrow = ESCROWS.load(deps.storage, &id)?; + + if let Balance::Cw20(token) = &balance { + // ensure the token is on the whitelist + if !escrow.cw20_whitelist.iter().any(|t| t == &token.address) { + return Err(ContractError::NotInWhitelist {}); + } + }; + + escrow.balance.add_tokens(balance); + + // and save + ESCROWS.save(deps.storage, &id, &escrow)?; + + let res = Response::new().add_attributes(vec![("action", "top_up"), ("id", id.as_str())]); + Ok(res) +} + +pub fn execute_approve( + deps: DepsMut, + env: Env, + info: MessageInfo, + id: String, +) -> Result { + // this fails is no escrow there + let escrow = ESCROWS.load(deps.storage, &id)?; + + if info.sender != escrow.arbiter { + return Err(ContractError::Unauthorized {}); + } + if escrow.is_expired(&env) { + return Err(ContractError::Expired {}); + } + + let recipient = escrow.recipient.ok_or(ContractError::RecipientNotSet {})?; + + // we delete the escrow + ESCROWS.remove(deps.storage, &id); + + // send all tokens out + let messages: Vec = send_tokens(&recipient, &escrow.balance)?; + + Ok(Response::new() + .add_attribute("action", "approve") + .add_attribute("id", id) + .add_attribute("to", recipient) + .add_submessages(messages)) +} + +pub fn execute_refund( + deps: DepsMut, + env: Env, + info: MessageInfo, + id: String, +) -> Result { + // this fails is no escrow there + let escrow = ESCROWS.load(deps.storage, &id)?; + + // the arbiter can send anytime OR anyone can send after expiration + if !escrow.is_expired(&env) && info.sender != escrow.arbiter { + Err(ContractError::Unauthorized {}) + } else { + // we delete the escrow + ESCROWS.remove(deps.storage, &id); + + // send all tokens out + let messages = send_tokens(&escrow.source, &escrow.balance)?; + + Ok(Response::new() + .add_attribute("action", "refund") + .add_attribute("id", id) + .add_attribute("to", escrow.source) + .add_submessages(messages)) + } +} + +fn send_tokens(to: &Addr, balance: &GenericBalance) -> StdResult> { + let native_balance = &balance.native; + let mut msgs: Vec = if native_balance.is_empty() { + vec![] + } else { + vec![SubMsg::new(BankMsg::Send { + to_address: to.into(), + amount: native_balance.to_vec(), + })] + }; + + let cw20_balance = &balance.cw20; + let cw20_msgs: StdResult> = cw20_balance + .iter() + .map(|c| { + let msg = Cw20ExecuteMsg::Transfer { + recipient: to.into(), + amount: c.amount, + }; + let exec = SubMsg::new(WasmMsg::Execute { + contract_addr: c.address.to_string(), + msg: to_binary(&msg)?, + funds: vec![], + }); + Ok(exec) + }) + .collect(); + msgs.append(&mut cw20_msgs?); + Ok(msgs) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult { + match msg { + QueryMsg::List {} => to_binary(&query_list(deps)?), + QueryMsg::Details { id } => to_binary(&query_details(deps, id)?), + } +} + +fn query_details(deps: Deps, id: String) -> StdResult { + let escrow = ESCROWS.load(deps.storage, &id)?; + + let cw20_whitelist = escrow.human_whitelist(); + + // transform tokens + let native_balance = escrow.balance.native; + + let cw20_balance: StdResult> = escrow + .balance + .cw20 + .into_iter() + .map(|token| { + Ok(Cw20Coin { + address: token.address.into(), + amount: token.amount, + }) + }) + .collect(); + + let recipient = escrow.recipient.map(|addr| addr.into_string()); + + let details = DetailsResponse { + id, + arbiter: escrow.arbiter.into(), + recipient, + source: escrow.source.into(), + title: escrow.title, + description: escrow.description, + end_height: escrow.end_height, + end_time: escrow.end_time, + native_balance, + cw20_balance: cw20_balance?, + cw20_whitelist, + }; + Ok(details) +} + +fn query_list(deps: Deps) -> StdResult { + Ok(ListResponse { + escrows: all_escrow_ids(deps.storage)?, + }) +} + +#[cfg(test)] +mod tests { + use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; + use cosmwasm_std::{attr, coin, coins, CosmosMsg, StdError, Uint128}; + + use crate::msg::ExecuteMsg::TopUp; + + use super::*; + + #[test] + fn happy_path_native() { + let mut deps = mock_dependencies(); + + // instantiate an empty contract + let instantiate_msg = InstantiateMsg {}; + let info = mock_info(&String::from("anyone"), &[]); + let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); + assert_eq!(0, res.messages.len()); + + // create an escrow + let create = CreateMsg { + id: "foobar".to_string(), + arbiter: String::from("arbitrate"), + recipient: Some(String::from("recd")), + title: "some_title".to_string(), + end_time: None, + end_height: Some(123456), + cw20_whitelist: None, + description: "some_description".to_string(), + }; + let sender = String::from("source"); + let balance = coins(100, "tokens"); + let info = mock_info(&sender, &balance); + let msg = ExecuteMsg::Create(create.clone()); + let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); + assert_eq!(0, res.messages.len()); + assert_eq!(("action", "create"), res.attributes[0]); + + // ensure the details is what we expect + let details = query_details(deps.as_ref(), "foobar".to_string()).unwrap(); + assert_eq!( + details, + DetailsResponse { + id: "foobar".to_string(), + arbiter: String::from("arbitrate"), + recipient: Some(String::from("recd")), + source: String::from("source"), + title: "some_title".to_string(), + description: "some_description".to_string(), + end_height: Some(123456), + end_time: None, + native_balance: balance.clone(), + cw20_balance: vec![], + cw20_whitelist: vec![], + } + ); + + // approve it + let id = create.id.clone(); + let info = mock_info(&create.arbiter, &[]); + let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); + assert_eq!(1, res.messages.len()); + assert_eq!(("action", "approve"), res.attributes[0]); + assert_eq!( + res.messages[0], + SubMsg::new(CosmosMsg::Bank(BankMsg::Send { + to_address: create.recipient.unwrap(), + amount: balance, + })) + ); + + // second attempt fails (not found) + let id = create.id.clone(); + let info = mock_info(&create.arbiter, &[]); + let err = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap_err(); + assert!(matches!(err, ContractError::Std(StdError::NotFound { .. }))); + } + + #[test] + fn happy_path_cw20() { + let mut deps = mock_dependencies(); + + // instantiate an empty contract + let instantiate_msg = InstantiateMsg {}; + let info = mock_info(&String::from("anyone"), &[]); + let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); + assert_eq!(0, res.messages.len()); + + // create an escrow + let create = CreateMsg { + id: "foobar".to_string(), + arbiter: String::from("arbitrate"), + recipient: Some(String::from("recd")), + title: "some_title".to_string(), + end_time: None, + end_height: None, + cw20_whitelist: Some(vec![String::from("other-token")]), + description: "some_description".to_string(), + }; + let receive = Cw20ReceiveMsg { + sender: String::from("source"), + amount: Uint128::new(100), + msg: to_binary(&ExecuteMsg::Create(create.clone())).unwrap(), + }; + let token_contract = String::from("my-cw20-token"); + let info = mock_info(&token_contract, &[]); + let msg = ExecuteMsg::Receive(receive.clone()); + let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); + assert_eq!(0, res.messages.len()); + assert_eq!(("action", "create"), res.attributes[0]); + + // ensure the whitelist is what we expect + let details = query_details(deps.as_ref(), "foobar".to_string()).unwrap(); + assert_eq!( + details, + DetailsResponse { + id: "foobar".to_string(), + arbiter: String::from("arbitrate"), + recipient: Some(String::from("recd")), + source: String::from("source"), + title: "some_title".to_string(), + description: "some_description".to_string(), + end_height: None, + end_time: None, + native_balance: vec![], + cw20_balance: vec![Cw20Coin { + address: String::from("my-cw20-token"), + amount: Uint128::new(100), + }], + cw20_whitelist: vec![String::from("other-token"), String::from("my-cw20-token")], + } + ); + + // approve it + let id = create.id.clone(); + let info = mock_info(&create.arbiter, &[]); + let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); + assert_eq!(1, res.messages.len()); + assert_eq!(("action", "approve"), res.attributes[0]); + let send_msg = Cw20ExecuteMsg::Transfer { + recipient: create.recipient.unwrap(), + amount: receive.amount, + }; + assert_eq!( + res.messages[0], + SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: token_contract, + msg: to_binary(&send_msg).unwrap(), + funds: vec![] + })) + ); + + // second attempt fails (not found) + let id = create.id.clone(); + let info = mock_info(&create.arbiter, &[]); + let err = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap_err(); + assert!(matches!(err, ContractError::Std(StdError::NotFound { .. }))); + } + + #[test] + fn set_recipient_after_creation() { + let mut deps = mock_dependencies(); + + // instantiate an empty contract + let instantiate_msg = InstantiateMsg {}; + let info = mock_info(&String::from("anyone"), &[]); + let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); + assert_eq!(0, res.messages.len()); + + // create an escrow + let create = CreateMsg { + id: "foobar".to_string(), + arbiter: String::from("arbitrate"), + recipient: None, + title: "some_title".to_string(), + end_time: None, + end_height: Some(123456), + cw20_whitelist: None, + description: "some_description".to_string(), + }; + let sender = String::from("source"); + let balance = coins(100, "tokens"); + let info = mock_info(&sender, &balance); + let msg = ExecuteMsg::Create(create.clone()); + let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); + assert_eq!(0, res.messages.len()); + assert_eq!(("action", "create"), res.attributes[0]); + + // ensure the details is what we expect + let details = query_details(deps.as_ref(), "foobar".to_string()).unwrap(); + assert_eq!( + details, + DetailsResponse { + id: "foobar".to_string(), + arbiter: String::from("arbitrate"), + recipient: None, + source: String::from("source"), + title: "some_title".to_string(), + description: "some_description".to_string(), + end_height: Some(123456), + end_time: None, + native_balance: balance.clone(), + cw20_balance: vec![], + cw20_whitelist: vec![], + } + ); + + // approve it, should fail as we have not set recipient + let id = create.id.clone(); + let info = mock_info(&create.arbiter, &[]); + let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }); + match res { + Err(ContractError::RecipientNotSet {}) => {} + _ => panic!("Expect recipient not set error"), + } + + // test setting recipient not arbiter + let msg = ExecuteMsg::SetRecipient { + id: create.id.clone(), + recipient: "recp".to_string(), + }; + let info = mock_info("someoneelse", &[]); + let res = execute(deps.as_mut(), mock_env(), info, msg); + match res { + Err(ContractError::Unauthorized {}) => {} + _ => panic!("Expect unauthorized error"), + } + + // test setting recipient valid + let msg = ExecuteMsg::SetRecipient { + id: create.id.clone(), + recipient: "recp".to_string(), + }; + let info = mock_info(&create.arbiter, &[]); + let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); + assert_eq!(res.messages.len(), 0); + assert_eq!( + res.attributes, + vec![ + attr("action", "set_recipient"), + attr("id", create.id.as_str()), + attr("recipient", "recp") + ] + ); + + // approve it, should now work with recp + let id = create.id.clone(); + let info = mock_info(&create.arbiter, &[]); + let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); + assert_eq!(1, res.messages.len()); + assert_eq!(("action", "approve"), res.attributes[0]); + assert_eq!( + res.messages[0], + SubMsg::new(CosmosMsg::Bank(BankMsg::Send { + to_address: "recp".to_string(), + amount: balance, + })) + ); + } + + #[test] + fn add_tokens_proper() { + let mut tokens = GenericBalance::default(); + tokens.add_tokens(Balance::from(vec![coin(123, "atom"), coin(789, "eth")])); + tokens.add_tokens(Balance::from(vec![coin(456, "atom"), coin(12, "btc")])); + assert_eq!( + tokens.native, + vec![coin(579, "atom"), coin(789, "eth"), coin(12, "btc")] + ); + } + + #[test] + fn add_cw_tokens_proper() { + let mut tokens = GenericBalance::default(); + let bar_token = Addr::unchecked("bar_token"); + let foo_token = Addr::unchecked("foo_token"); + tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { + address: foo_token.clone(), + amount: Uint128::new(12345), + })); + tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { + address: bar_token.clone(), + amount: Uint128::new(777), + })); + tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { + address: foo_token.clone(), + amount: Uint128::new(23400), + })); + assert_eq!( + tokens.cw20, + vec![ + Cw20CoinVerified { + address: foo_token, + amount: Uint128::new(35745), + }, + Cw20CoinVerified { + address: bar_token, + amount: Uint128::new(777), + } + ] + ); + } + + #[test] + fn top_up_mixed_tokens() { + let mut deps = mock_dependencies(); + + // instantiate an empty contract + let instantiate_msg = InstantiateMsg {}; + let info = mock_info(&String::from("anyone"), &[]); + let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); + assert_eq!(0, res.messages.len()); + + // only accept these tokens + let whitelist = vec![String::from("bar_token"), String::from("foo_token")]; + + // create an escrow with 2 native tokens + let create = CreateMsg { + id: "foobar".to_string(), + arbiter: String::from("arbitrate"), + recipient: Some(String::from("recd")), + title: "some_title".to_string(), + end_time: None, + end_height: None, + cw20_whitelist: Some(whitelist), + description: "some_description".to_string(), + }; + let sender = String::from("source"); + let balance = vec![coin(100, "fee"), coin(200, "stake")]; + let info = mock_info(&sender, &balance); + let msg = ExecuteMsg::Create(create.clone()); + let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); + assert_eq!(0, res.messages.len()); + assert_eq!(("action", "create"), res.attributes[0]); + + // top it up with 2 more native tokens + let extra_native = vec![coin(250, "random"), coin(300, "stake")]; + let info = mock_info(&sender, &extra_native); + let top_up = ExecuteMsg::TopUp { + id: create.id.clone(), + }; + let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); + assert_eq!(0, res.messages.len()); + assert_eq!(("action", "top_up"), res.attributes[0]); + + // top up with one foreign token + let bar_token = String::from("bar_token"); + let base = TopUp { + id: create.id.clone(), + }; + let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { + sender: String::from("random"), + amount: Uint128::new(7890), + msg: to_binary(&base).unwrap(), + }); + let info = mock_info(&bar_token, &[]); + let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); + assert_eq!(0, res.messages.len()); + assert_eq!(("action", "top_up"), res.attributes[0]); + + // top with a foreign token not on the whitelist + // top up with one foreign token + let baz_token = String::from("baz_token"); + let base = TopUp { + id: create.id.clone(), + }; + let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { + sender: String::from("random"), + amount: Uint128::new(7890), + msg: to_binary(&base).unwrap(), + }); + let info = mock_info(&baz_token, &[]); + let err = execute(deps.as_mut(), mock_env(), info, top_up).unwrap_err(); + assert_eq!(err, ContractError::NotInWhitelist {}); + + // top up with second foreign token + let foo_token = String::from("foo_token"); + let base = TopUp { + id: create.id.clone(), + }; + let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { + sender: String::from("random"), + amount: Uint128::new(888), + msg: to_binary(&base).unwrap(), + }); + let info = mock_info(&foo_token, &[]); + let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); + assert_eq!(0, res.messages.len()); + assert_eq!(("action", "top_up"), res.attributes[0]); + + // approve it + let id = create.id.clone(); + let info = mock_info(&create.arbiter, &[]); + let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); + assert_eq!(("action", "approve"), res.attributes[0]); + assert_eq!(3, res.messages.len()); + + // first message releases all native coins + assert_eq!( + res.messages[0], + SubMsg::new(CosmosMsg::Bank(BankMsg::Send { + to_address: create.recipient.clone().unwrap(), + amount: vec![coin(100, "fee"), coin(500, "stake"), coin(250, "random")], + })) + ); + + // second one release bar cw20 token + let send_msg = Cw20ExecuteMsg::Transfer { + recipient: create.recipient.clone().unwrap(), + amount: Uint128::new(7890), + }; + assert_eq!( + res.messages[1], + SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: bar_token, + msg: to_binary(&send_msg).unwrap(), + funds: vec![] + })) + ); + + // third one release foo cw20 token + let send_msg = Cw20ExecuteMsg::Transfer { + recipient: create.recipient.unwrap(), + amount: Uint128::new(888), + }; + assert_eq!( + res.messages[2], + SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: foo_token, + msg: to_binary(&send_msg).unwrap(), + funds: vec![] + })) + ); + } +} diff --git a/cw20/escrow/src/error.rs b/cw20/escrow/src/error.rs new file mode 100644 index 0000000..da4302b --- /dev/null +++ b/cw20/escrow/src/error.rs @@ -0,0 +1,26 @@ +use cosmwasm_std::StdError; +use thiserror::Error; + +#[derive(Error, Debug, PartialEq)] +pub enum ContractError { + #[error("{0}")] + Std(#[from] StdError), + + #[error("Unauthorized")] + Unauthorized {}, + + #[error("Only accepts tokens in the cw20_whitelist")] + NotInWhitelist {}, + + #[error("Escrow is expired")] + Expired {}, + + #[error("Send some coins to create an escrow")] + EmptyBalance {}, + + #[error("Escrow id already in use")] + AlreadyInUse {}, + + #[error("Recipient is not set")] + RecipientNotSet {}, +} diff --git a/cw20/escrow/src/integration_test.rs b/cw20/escrow/src/integration_test.rs new file mode 100644 index 0000000..7120bfe --- /dev/null +++ b/cw20/escrow/src/integration_test.rs @@ -0,0 +1,157 @@ +#![cfg(test)] + +use cosmwasm_std::{coins, to_binary, Addr, Empty, Uint128}; +use cw20::{Cw20Coin, Cw20Contract, Cw20ExecuteMsg}; +use cw_multi_test::{App, Contract, ContractWrapper, Executor}; + +use crate::msg::{CreateMsg, DetailsResponse, ExecuteMsg, InstantiateMsg, QueryMsg, ReceiveMsg}; + +pub fn contract_escrow() -> Box> { + let contract = ContractWrapper::new( + crate::contract::execute, + crate::contract::instantiate, + crate::contract::query, + ); + Box::new(contract) +} + +pub fn contract_cw20() -> Box> { + let contract = ContractWrapper::new( + cw20_base::contract::execute, + cw20_base::contract::instantiate, + cw20_base::contract::query, + ); + Box::new(contract) +} + +#[test] +// receive cw20 tokens and release upon approval +fn escrow_happy_path_cw20_tokens() { + // set personal balance + let owner = Addr::unchecked("owner"); + let init_funds = coins(2000, "btc"); + + let mut router = App::new(|router, _, storage| { + router + .bank + .init_balance(storage, &owner, init_funds) + .unwrap(); + }); + + // set up cw20 contract with some tokens + let cw20_id = router.store_code(contract_cw20()); + let msg = cw20_base::msg::InstantiateMsg { + name: "Cash Money".to_string(), + symbol: "CASH".to_string(), + decimals: 2, + initial_balances: vec![Cw20Coin { + address: owner.to_string(), + amount: Uint128::new(5000), + }], + mint: None, + marketing: None, + }; + let cash_addr = router + .instantiate_contract(cw20_id, owner.clone(), &msg, &[], "CASH", None) + .unwrap(); + + // set up reflect contract + let escrow_id = router.store_code(contract_escrow()); + let escrow_addr = router + .instantiate_contract( + escrow_id, + owner.clone(), + &InstantiateMsg {}, + &[], + "Escrow", + None, + ) + .unwrap(); + + // they are different + assert_ne!(cash_addr, escrow_addr); + + // set up cw20 helpers + let cash = Cw20Contract(cash_addr.clone()); + + // ensure our balances + let owner_balance = cash.balance::<_, _, Empty>(&router, owner.clone()).unwrap(); + assert_eq!(owner_balance, Uint128::new(5000)); + let escrow_balance = cash + .balance::<_, _, Empty>(&router, escrow_addr.clone()) + .unwrap(); + assert_eq!(escrow_balance, Uint128::zero()); + + // send some tokens to create an escrow + let arb = Addr::unchecked("arbiter"); + let ben = String::from("beneficiary"); + let id = "demo".to_string(); + let create_msg = ReceiveMsg::Create(CreateMsg { + id: id.clone(), + arbiter: arb.to_string(), + recipient: Some(ben.clone()), + title: "some_title".to_string(), + description: "some_description".to_string(), + end_height: None, + end_time: None, + cw20_whitelist: None, + }); + let send_msg = Cw20ExecuteMsg::Send { + contract: escrow_addr.to_string(), + amount: Uint128::new(1200), + msg: to_binary(&create_msg).unwrap(), + }; + let res = router + .execute_contract(owner.clone(), cash_addr.clone(), &send_msg, &[]) + .unwrap(); + assert_eq!(4, res.events.len()); + println!("{:?}", res.events); + + assert_eq!(res.events[0].ty.as_str(), "execute"); + let cw20_attr = res.custom_attrs(1); + println!("{:?}", cw20_attr); + assert_eq!(4, cw20_attr.len()); + + assert_eq!(res.events[2].ty.as_str(), "execute"); + let escrow_attr = res.custom_attrs(3); + println!("{:?}", escrow_attr); + assert_eq!(2, escrow_attr.len()); + + // ensure balances updated + let owner_balance = cash.balance::<_, _, Empty>(&router, owner.clone()).unwrap(); + assert_eq!(owner_balance, Uint128::new(3800)); + let escrow_balance = cash + .balance::<_, _, Empty>(&router, escrow_addr.clone()) + .unwrap(); + assert_eq!(escrow_balance, Uint128::new(1200)); + + // ensure escrow properly created + let details: DetailsResponse = router + .wrap() + .query_wasm_smart(&escrow_addr, &QueryMsg::Details { id: id.clone() }) + .unwrap(); + assert_eq!(id, details.id); + assert_eq!(arb, details.arbiter); + assert_eq!(Some(ben.clone()), details.recipient); + assert_eq!( + vec![Cw20Coin { + address: cash_addr.to_string(), + amount: Uint128::new(1200) + }], + details.cw20_balance + ); + + // release escrow + let approve_msg = ExecuteMsg::Approve { id }; + let _ = router + .execute_contract(arb, escrow_addr.clone(), &approve_msg, &[]) + .unwrap(); + + // ensure balances updated - release to ben + let owner_balance = cash.balance::<_, _, Empty>(&router, owner).unwrap(); + assert_eq!(owner_balance, Uint128::new(3800)); + let escrow_balance = cash.balance::<_, _, Empty>(&router, escrow_addr).unwrap(); + assert_eq!(escrow_balance, Uint128::zero()); + let ben_balance = cash.balance::<_, _, Empty>(&router, ben).unwrap(); + assert_eq!(ben_balance, Uint128::new(1200)); +} diff --git a/cw20/escrow/src/lib.rs b/cw20/escrow/src/lib.rs new file mode 100644 index 0000000..32ed6c3 --- /dev/null +++ b/cw20/escrow/src/lib.rs @@ -0,0 +1,7 @@ +pub mod contract; +mod error; +mod integration_test; +pub mod msg; +pub mod state; + +pub use crate::error::ContractError; diff --git a/cw20/escrow/src/msg.rs b/cw20/escrow/src/msg.rs new file mode 100644 index 0000000..6c328fc --- /dev/null +++ b/cw20/escrow/src/msg.rs @@ -0,0 +1,136 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use cosmwasm_std::{Addr, Api, Coin, StdResult}; + +use cw20::{Cw20Coin, Cw20ReceiveMsg}; + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct InstantiateMsg {} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ExecuteMsg { + Create(CreateMsg), + /// Adds all sent native tokens to the contract + TopUp { + id: String, + }, + /// Set the recipient of the given escrow + SetRecipient { + id: String, + recipient: String, + }, + /// Approve sends all tokens to the recipient. + /// Only the arbiter can do this + Approve { + /// id is a human-readable name for the escrow from create + id: String, + }, + /// Refund returns all remaining tokens to the original sender, + /// The arbiter can do this any time, or anyone can do this after a timeout + Refund { + /// id is a human-readable name for the escrow from create + id: String, + }, + /// This accepts a properly-encoded ReceiveMsg from a cw20 contract + Receive(Cw20ReceiveMsg), +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum ReceiveMsg { + Create(CreateMsg), + /// Adds all sent native tokens to the contract + TopUp { + id: String, + }, +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +pub struct CreateMsg { + /// id is a human-readable name for the escrow to use later + /// 3-20 bytes of utf-8 text + pub id: String, + /// arbiter can decide to approve or refund the escrow + pub arbiter: String, + /// if approved, funds go to the recipient + pub recipient: Option, + /// Title of the escrow + pub title: String, + /// Longer description of the escrow, e.g. what conditions should be met + pub description: String, + /// When end height set and block height exceeds this value, the escrow is expired. + /// Once an escrow is expired, it can be returned to the original funder (via "refund"). + pub end_height: Option, + /// When end time (in seconds since epoch 00:00:00 UTC on 1 January 1970) is set and + /// block time exceeds this value, the escrow is expired. + /// Once an escrow is expired, it can be returned to the original funder (via "refund"). + pub end_time: Option, + /// Besides any possible tokens sent with the CreateMsg, this is a list of all cw20 token addresses + /// that are accepted by the escrow during a top-up. This is required to avoid a DoS attack by topping-up + /// with an invalid cw20 contract. See https://github.com/CosmWasm/cosmwasm-plus/issues/19 + pub cw20_whitelist: Option>, +} + +impl CreateMsg { + pub fn addr_whitelist(&self, api: &dyn Api) -> StdResult> { + match self.cw20_whitelist.as_ref() { + Some(v) => v.iter().map(|h| api.addr_validate(h)).collect(), + None => Ok(vec![]), + } + } +} + +pub fn is_valid_name(name: &str) -> bool { + let bytes = name.as_bytes(); + if bytes.len() < 3 || bytes.len() > 20 { + return false; + } + true +} + +#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)] +#[serde(rename_all = "snake_case")] +pub enum QueryMsg { + /// Show all open escrows. Return type is ListResponse. + List {}, + /// Returns the details of the named escrow, error if not created + /// Return type: DetailsResponse. + Details { id: String }, +} + +#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +pub struct ListResponse { + /// list all registered ids + pub escrows: Vec, +} + +#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +pub struct DetailsResponse { + /// id of this escrow + pub id: String, + /// arbiter can decide to approve or refund the escrow + pub arbiter: String, + /// if approved, funds go to the recipient + pub recipient: Option, + /// if refunded, funds go to the source + pub source: String, + /// Title of the escrow + pub title: String, + /// Longer description of the escrow, e.g. what conditions should be met + pub description: String, + /// When end height set and block height exceeds this value, the escrow is expired. + /// Once an escrow is expired, it can be returned to the original funder (via "refund"). + pub end_height: Option, + /// When end time (in seconds since epoch 00:00:00 UTC on 1 January 1970) is set and + /// block time exceeds this value, the escrow is expired. + /// Once an escrow is expired, it can be returned to the original funder (via "refund"). + pub end_time: Option, + /// Balance in native tokens + pub native_balance: Vec, + /// Balance in cw20 tokens + pub cw20_balance: Vec, + /// Whitelisted cw20 tokens + pub cw20_whitelist: Vec, +} diff --git a/cw20/escrow/src/state.rs b/cw20/escrow/src/state.rs new file mode 100644 index 0000000..28d56e9 --- /dev/null +++ b/cw20/escrow/src/state.rs @@ -0,0 +1,149 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; + +use cosmwasm_std::{Addr, Coin, Env, Order, StdResult, Storage, Timestamp}; +use cw_storage_plus::Map; + +use cw20::{Balance, Cw20CoinVerified}; + +#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug, Default)] +pub struct GenericBalance { + pub native: Vec, + pub cw20: Vec, +} + +impl GenericBalance { + pub fn add_tokens(&mut self, add: Balance) { + match add { + Balance::Native(balance) => { + for token in balance.0 { + let index = self.native.iter().enumerate().find_map(|(i, exist)| { + if exist.denom == token.denom { + Some(i) + } else { + None + } + }); + match index { + Some(idx) => self.native[idx].amount += token.amount, + None => self.native.push(token), + } + } + } + Balance::Cw20(token) => { + let index = self.cw20.iter().enumerate().find_map(|(i, exist)| { + if exist.address == token.address { + Some(i) + } else { + None + } + }); + match index { + Some(idx) => self.cw20[idx].amount += token.amount, + None => self.cw20.push(token), + } + } + }; + } +} + +#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)] +pub struct Escrow { + /// arbiter can decide to approve or refund the escrow + pub arbiter: Addr, + /// if approved, funds go to the recipient, cannot approve if recipient is none + pub recipient: Option, + /// if refunded, funds go to the source + pub source: Addr, + /// Title of the escrow, for example for a bug bounty "Fix issue in contract.rs" + pub title: String, + /// Description of the escrow, a more in depth description of how to meet the escrow condition + pub description: String, + /// When end height set and block height exceeds this value, the escrow is expired. + /// Once an escrow is expired, it can be returned to the original funder (via "refund"). + pub end_height: Option, + /// When end time (in seconds since epoch 00:00:00 UTC on 1 January 1970) is set and + /// block time exceeds this value, the escrow is expired. + /// Once an escrow is expired, it can be returned to the original funder (via "refund"). + pub end_time: Option, + /// Balance in Native and Cw20 tokens + pub balance: GenericBalance, + /// All possible contracts that we accept tokens from + pub cw20_whitelist: Vec, +} + +impl Escrow { + pub fn is_expired(&self, env: &Env) -> bool { + if let Some(end_height) = self.end_height { + if env.block.height > end_height { + return true; + } + } + + if let Some(end_time) = self.end_time { + if env.block.time > Timestamp::from_seconds(end_time) { + return true; + } + } + + false + } + + pub fn human_whitelist(&self) -> Vec { + self.cw20_whitelist.iter().map(|a| a.to_string()).collect() + } +} + +pub const ESCROWS: Map<&str, Escrow> = Map::new("escrow"); + +/// This returns the list of ids for all registered escrows +pub fn all_escrow_ids(storage: &dyn Storage) -> StdResult> { + ESCROWS + .keys(storage, None, None, Order::Ascending) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + use cosmwasm_std::testing::MockStorage; + + #[test] + fn no_escrow_ids() { + let storage = MockStorage::new(); + let ids = all_escrow_ids(&storage).unwrap(); + assert_eq!(0, ids.len()); + } + + fn dummy_escrow() -> Escrow { + Escrow { + arbiter: Addr::unchecked("arb"), + recipient: Some(Addr::unchecked("recip")), + source: Addr::unchecked("source"), + title: "some_escrow".to_string(), + description: "some escrow desc".to_string(), + end_height: None, + end_time: None, + balance: Default::default(), + cw20_whitelist: vec![], + } + } + + #[test] + fn all_escrow_ids_in_order() { + let mut storage = MockStorage::new(); + ESCROWS.save(&mut storage, "lazy", &dummy_escrow()).unwrap(); + ESCROWS + .save(&mut storage, "assign", &dummy_escrow()) + .unwrap(); + ESCROWS.save(&mut storage, "zen", &dummy_escrow()).unwrap(); + + let ids = all_escrow_ids(&storage).unwrap(); + assert_eq!(3, ids.len()); + assert_eq!( + vec!["assign".to_string(), "lazy".to_string(), "zen".to_string()], + ids + ) + } +} From 7c232bf06cea9903aa01ad398bce78d5735b0e2e Mon Sep 17 00:00:00 2001 From: Georges Chouchani Date: Mon, 27 Jun 2022 17:16:46 +0300 Subject: [PATCH 2/6] added .github file --- cw20/escrow/.github/workflows/Basic.yml | 83 +++++++++++++++++++++++++ 1 file changed, 83 insertions(+) create mode 100644 cw20/escrow/.github/workflows/Basic.yml diff --git a/cw20/escrow/.github/workflows/Basic.yml b/cw20/escrow/.github/workflows/Basic.yml new file mode 100644 index 0000000..6170933 --- /dev/null +++ b/cw20/escrow/.github/workflows/Basic.yml @@ -0,0 +1,83 @@ +# Based on https://github.com/actions-rs/example/blob/master/.github/workflows/quickstart.yml + +on: [push, pull_request] + +name: Basic + +jobs: + + test: + name: Test Suite + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v2 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + target: wasm32-unknown-unknown + override: true + profile: minimal + + - name: Run unit tests + uses: actions-rs/cargo@v1 + with: + command: unit-test + args: --locked + env: + RUST_BACKTRACE: 1 + + - name: Compile WASM contract + uses: actions-rs/cargo@v1 + with: + command: wasm + args: --locked + env: + RUSTFLAGS: "-C link-arg=-s" + + lints: + name: Lints + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v2 + + - name: Install stable toolchain + uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + profile: minimal + components: rustfmt, clippy + + - name: Run cargo fmt + uses: actions-rs/cargo@v1 + with: + command: fmt + args: --all -- --check + + - name: Run cargo clippy + uses: actions-rs/cargo@v1 + with: + command: clippy + args: -- -D warnings + + - name: Generate schema + uses: actions-rs/cargo@v1 + with: + command: schema + args: --locked + + - name: Verify schema + uses: tj-actions/verify-changed-files@v8 + id: verify-schema + with: + files: schema/.*\.json + + - name: Display changed schemas + if: steps.verify-schema.outputs.files_changed == 'true' + run: | + echo "The schema files are not in sync with the repository. Please, run 'cargo schema' to generate them again and commit the changes." + exit 1 From 974fb52e7083db653e34049472218fc694059595 Mon Sep 17 00:00:00 2001 From: Georges Chouchani Date: Tue, 28 Jun 2022 14:33:03 +0300 Subject: [PATCH 3/6] cargo.toml fix --- cw20/escrow/Cargo.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cw20/escrow/Cargo.toml b/cw20/escrow/Cargo.toml index f542dda..64823f5 100644 --- a/cw20/escrow/Cargo.toml +++ b/cw20/escrow/Cargo.toml @@ -1,7 +1,7 @@ [package] name = "{{project-name}}" version = "0.12.1" -authors = [{{authors}}] +authors = ["{{authors}}"] edition = "2018" description = "Implementation of an escrow that accepts CosmWasm-20 tokens as well as native tokens" license = "Apache-2.0" From 0faf824a0b522f5d1758569d000374acfca1f006 Mon Sep 17 00:00:00 2001 From: Georges Chouchani <73434909+gachouchani1999@users.noreply.github.com> Date: Tue, 28 Jun 2022 17:03:44 +0300 Subject: [PATCH 4/6] Update cw20/escrow/src/contract.rs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Augusto Elesbão --- cw20/escrow/src/contract.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cw20/escrow/src/contract.rs b/cw20/escrow/src/contract.rs index 56276c2..251f09b 100644 --- a/cw20/escrow/src/contract.rs +++ b/cw20/escrow/src/contract.rs @@ -15,7 +15,7 @@ use crate::msg::{ use crate::state::{all_escrow_ids, Escrow, GenericBalance, ESCROWS}; // version info for migration info -const CONTRACT_NAME: &str = "crates.io:cw20-escrow"; +const CONTRACT_NAME: &str = "crates.io:{{project-name}}"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg_attr(not(feature = "library"), entry_point)] From e17231d82e2c8753173d1634660444f171fe4338 Mon Sep 17 00:00:00 2001 From: Georges Chouchani Date: Wed, 27 Jul 2022 14:57:15 +0300 Subject: [PATCH 5/6] fixed cw721-off-chain test --- cw721/off-chain-metadata/src/tests.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/cw721/off-chain-metadata/src/tests.rs b/cw721/off-chain-metadata/src/tests.rs index 2b84024..c578921 100644 --- a/cw721/off-chain-metadata/src/tests.rs +++ b/cw721/off-chain-metadata/src/tests.rs @@ -681,9 +681,9 @@ fn query_tokens_by_owner() { // Mint a couple tokens (from the same owner) let token_id1 = "grow1".to_string(); - let demeter = String::from("Demeter"); + let demeter = String::from("demeter"); let token_id2 = "grow2".to_string(); - let ceres = String::from("Ceres"); + let ceres = String::from("ceres"); let token_id3 = "sing".to_string(); let mint_msg = ExecuteMsg::Mint(MintMsg:: { From 9011ccd62e1124dec69d69dbf4d5ad8f06eb9f1c Mon Sep 17 00:00:00 2001 From: Georges Chouchani Date: Wed, 27 Jul 2022 15:15:04 +0300 Subject: [PATCH 6/6] removed pull request test --- .github/workflows/check.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/check.yml b/.github/workflows/check.yml index 3918dc9..31453a5 100644 --- a/.github/workflows/check.yml +++ b/.github/workflows/check.yml @@ -1,4 +1,4 @@ -on: [push, pull_request] +on: [push] name: Check Templates