diff --git a/Cargo.lock b/Cargo.lock index 0ae97e3f..4e149470 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -68,6 +68,56 @@ version = "1.0.89" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "86fdf8605db99b54d3cd748a44c6d04df638eb5dafb219b135d0149bd0db01f6" +[[package]] +name = "astroport" +version = "5.7.0" +source = "git+https://github.com/astroport-fi/astroport-core?branch=main#54d65dcbe9cf652c024fc0110b531f190efafce6" +dependencies = [ + "astroport-circular-buffer", + "cosmos-sdk-proto 0.19.0", + "cosmwasm-schema", + "cosmwasm-std", + "cw-asset", + "cw-storage-plus", + "cw-utils", + "cw20 1.1.2", + "itertools 0.12.1", + "prost 0.11.9", + "uint", +] + +[[package]] +name = "astroport-circular-buffer" +version = "0.2.0" +source = "git+https://github.com/astroport-fi/astroport-core?branch=main#54d65dcbe9cf652c024fc0110b531f190efafce6" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cw-storage-plus", + "thiserror", +] + +[[package]] +name = "astroport-forwarding" +version = "0.2.0" +dependencies = [ + "astroport", + "cosmwasm-schema", + "cosmwasm-std", + "cw-multi-test", + "cw-orch", + "cw-storage-plus", + "cw-utils", + "cw2", + "cw20 1.1.2", + "euclid", + "forwarding", + "mock", + "schemars", + "serde", + "thiserror", +] + [[package]] name = "async-stream" version = "0.3.6" @@ -325,6 +375,17 @@ version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" +[[package]] +name = "cosmos-sdk-proto" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73c9d2043a9e617b0d602fbc0a0ecd621568edbf3a9774890a6d562389bd8e1c" +dependencies = [ + "prost 0.11.9", + "prost-types 0.11.9", + "tendermint-proto 0.32.2", +] + [[package]] name = "cosmos-sdk-proto" version = "0.20.0" @@ -498,6 +559,29 @@ dependencies = [ "zeroize", ] +[[package]] +name = "cw-address-like" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451a4691083a88a3c0630a8a88799e9d4cd6679b7ce8ff22b8da2873ff31d380" +dependencies = [ + "cosmwasm-std", +] + +[[package]] +name = "cw-asset" +version = "3.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c999a12f8cd8736f6f86e9a4ede5905530cb23cfdef946b9da1c506ad1b70799" +dependencies = [ + "cosmwasm-schema", + "cosmwasm-std", + "cw-address-like", + "cw-storage-plus", + "cw20 1.1.2", + "thiserror", +] + [[package]] name = "cw-controllers" version = "1.1.2" @@ -1151,6 +1235,21 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8cbd1169bd7b4a0a20d92b9af7a7e0422888bd38a6f5ec29c1fd8c1558a272e" +[[package]] +name = "forwarding" +version = "0.1.0" +dependencies = [ + "astroport", + "cosmwasm-schema", + "cosmwasm-std", + "cw-orch", + "cw-storage-plus", + "cw20 1.1.2", + "euclid", + "schemars", + "serde", +] + [[package]] name = "futures" version = "0.3.31" diff --git a/Cargo.toml b/Cargo.toml index 9b0a76ed..d06d94fd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,6 +4,7 @@ resolver = "2" members = [ "contracts/hub/*", "contracts/liquidity/*", + "contracts/forwarding/*", "contracts/common/*", "packages/*", "tests-integration", @@ -25,6 +26,7 @@ strip = true euclid = { path = "./packages/euclid" } euclid-ibc = { path = "./packages/euclid_ibc" } euclid-utils = { path = "./packages/euclid_utils" } +forwarding = { path = "./packages/forwarding" } cosmwasm-std = "1.5.3" cosmwasm-schema = "1.5.0" diff --git a/contracts/forwarding/astroport-forwarding/.cargo/config.toml b/contracts/forwarding/astroport-forwarding/.cargo/config.toml new file mode 100644 index 00000000..af5698e5 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/.cargo/config.toml @@ -0,0 +1,4 @@ +[alias] +wasm = "build --release --lib --target wasm32-unknown-unknown" +unit-test = "test --lib" +schema = "run --bin schema" diff --git a/contracts/forwarding/astroport-forwarding/.editorconfig b/contracts/forwarding/astroport-forwarding/.editorconfig new file mode 100644 index 00000000..3d36f20b --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/.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/contracts/forwarding/astroport-forwarding/.gitignore b/contracts/forwarding/astroport-forwarding/.gitignore new file mode 100644 index 00000000..9095deaa --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/.gitignore @@ -0,0 +1,16 @@ +# Build results +/target +/schema + +# 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/contracts/forwarding/astroport-forwarding/Cargo.toml b/contracts/forwarding/astroport-forwarding/Cargo.toml new file mode 100644 index 00000000..0b526944 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/Cargo.toml @@ -0,0 +1,58 @@ +[package] +name = "astroport-forwarding" +version = "0.2.0" +authors = ["Anshudhar Kumar Singh "] +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[lib] +crate-type = ["cdylib", "rlib"] + +[profile.release] +opt-level = 3 +debug = false +rpath = false +lto = true +debug-assertions = false +codegen-units = 1 +panic = 'abort' +incremental = false +overflow-checks = true + +[features] +# for more explicit tests, cargo test --features=backtraces +backtraces = ["cosmwasm-std/backtraces"] +# use library feature to disable all instantiate/execute/query exports +library = [] + +[package.metadata.scripts] +optimize = """docker run --rm -v "$(pwd)":/code \ + --mount type=volume,source="$(basename "$(pwd)")_cache",target=/target \ + --mount type=volume,source=registry_cache,target=/usr/local/cargo/registry \ + cosmwasm/optimizer:0.15.0 +""" + +[dependencies] +cosmwasm-schema = { workspace = true } +cosmwasm-std = { workspace = true, features = [ + "cosmwasm_1_2", + # Enable this if you only deploy to chains that have CosmWasm 1.4 or higher + # "cosmwasm_1_4", + "ibc3", +] } +cw-storage-plus = { workspace = true } +cw2 = { workspace = true } +cw20 = { workspace = true } +schemars = { workspace = true } +serde = { workspace = true, default-features = false, features = ["derive"] } +thiserror = { workspace = true } +euclid = { workspace = true } +forwarding = { workspace = true } +cw-orch = "=0.24.1" +astroport = { git = "https://github.com/astroport-fi/astroport-core", branch = "main" } +cw-utils = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +cw-multi-test = { workspace = true } +mock = { workspace = true } diff --git a/contracts/forwarding/astroport-forwarding/LICENSE b/contracts/forwarding/astroport-forwarding/LICENSE new file mode 100644 index 00000000..d6456956 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/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/contracts/forwarding/astroport-forwarding/NOTICE b/contracts/forwarding/astroport-forwarding/NOTICE new file mode 100644 index 00000000..e7d57816 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/NOTICE @@ -0,0 +1,13 @@ +Copyright 2024 gachouchani1999 + +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/contracts/forwarding/astroport-forwarding/README.md b/contracts/forwarding/astroport-forwarding/README.md new file mode 100644 index 00000000..b4b01a7e --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/README.md @@ -0,0 +1,4 @@ +# Escrow Contract +The Escrow smart contract is a simple contract that holds one type of token. Each integrated chain will have these escrows deployed, holding the liquidity for the tokens. Refer to the following resources to learn more about the Escrow Contract: +- [Architecture](https://docs.euclidprotocol.io/docs/Architecture%20Overview/Architecture/Integrated%20Chains%20Layer/escrows) +- [Detailed Breakdown of the Escrow's available messages](https://docs.euclidprotocol.io/docs/Euclid%20Smart%20Contracts/CosmWasm/Escrow) \ No newline at end of file diff --git a/contracts/forwarding/astroport-forwarding/src/bin/schema.rs b/contracts/forwarding/astroport-forwarding/src/bin/schema.rs new file mode 100644 index 00000000..0bf83056 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/bin/schema.rs @@ -0,0 +1,17 @@ +use std::env::current_dir; + +use cosmwasm_schema::{export_schema_with_title, schema_for, write_api}; +use forwarding::msgs::astroport::{Cw20HookMsg, ExecuteMsg, InstantiateMsg, QueryMsg}; + +fn main() { + let mut out_dir = current_dir().unwrap(); + out_dir.push("schema"); + out_dir.push("raw"); + write_api! { + instantiate: InstantiateMsg, + execute: ExecuteMsg, + query: QueryMsg, + } + + export_schema_with_title(&schema_for!(Cw20HookMsg), &out_dir, "cw20receive"); +} diff --git a/contracts/forwarding/astroport-forwarding/src/contract.rs b/contracts/forwarding/astroport-forwarding/src/contract.rs new file mode 100644 index 00000000..c64e72b8 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/contract.rs @@ -0,0 +1,65 @@ +use std::borrow::BorrowMut; + +#[cfg(not(feature = "library"))] +use cosmwasm_std::entry_point; +use cosmwasm_std::{Binary, Deps, DepsMut, Env, MessageInfo, Reply, Response, StdError}; + +use cw2::set_contract_version; +use euclid::error::ContractError; + +use crate::{ + execute::{execute_cw20_receive, execute_forward}, + reply::{on_astro_swap_reply, ASTRO_SWAP_REPLY_ID}, + state::{State, STATE}, +}; + +use forwarding::msgs::astroport::{ExecuteMsg, InstantiateMsg, QueryMsg}; + +// version info for migration info +const CONTRACT_NAME: &str = "crates.io:astroport-forwarding"; +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, +) -> Result { + let state = State { + astro_router_address: msg.astro_router.clone(), + }; + STATE.save(deps.storage, &state)?; + set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; + Ok(Response::new() + .add_attribute("method", "instantiate") + .add_attribute("astro_router", msg.astro_router)) +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn execute( + mut deps: DepsMut, + env: Env, + info: MessageInfo, + msg: ExecuteMsg, +) -> Result { + match msg { + ExecuteMsg::Swap(msg) => execute_forward(deps.borrow_mut(), &env, &info, msg), + ExecuteMsg::Receive(msg) => execute_cw20_receive(deps.borrow_mut(), &env, &info, msg), + } +} + +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn query(_deps: Deps, _env: Env, msg: QueryMsg) -> Result { + match msg {} +} +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn reply(deps: DepsMut, env: Env, msg: Reply) -> Result { + match msg.id { + ASTRO_SWAP_REPLY_ID => on_astro_swap_reply(deps, env, msg), + id => Err(ContractError::Std(StdError::generic_err(format!( + "Unknown reply id: {}", + id + )))), + } +} diff --git a/contracts/forwarding/astroport-forwarding/src/execute.rs b/contracts/forwarding/astroport-forwarding/src/execute.rs new file mode 100644 index 00000000..f7affc28 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/execute.rs @@ -0,0 +1,115 @@ +use cosmwasm_std::{ + coin, ensure, from_json, to_json_binary, DepsMut, Env, MessageInfo, Response, SubMsg, Uint128, + WasmMsg, +}; +use cw20::{Cw20ExecuteMsg, Cw20ReceiveMsg}; +use euclid::{error::ContractError, token::TokenType}; +use forwarding::msgs::astroport::{Cw20HookMsg, SwapMsg}; + +use astroport::router::ExecuteMsg as AstroportExecuteMsg; + +use crate::{ + reply::ASTRO_SWAP_REPLY_ID, + state::{ForwardingState, FORWARDING_STATE, STATE}, +}; + +pub fn execute_cw20_receive( + deps: &mut DepsMut, + env: &Env, + info: &MessageInfo, + msg: Cw20ReceiveMsg, +) -> Result { + let amount = msg.amount; + let from_token = TokenType::Smart { + contract_address: info.sender.to_string(), + }; + + let msg: Cw20HookMsg = from_json(msg.msg)?; + match msg { + Cw20HookMsg::Swap(swap_msg) => swap(deps, env, info, swap_msg, from_token, amount), + } +} + +pub fn execute_forward( + deps: &mut DepsMut, + env: &Env, + info: &MessageInfo, + msg: SwapMsg, +) -> Result { + ensure!( + info.funds.len() == 1, + ContractError::new("only one token is supported") + ); + let from_token = TokenType::Native { + denom: info.funds[0].denom.to_string(), + }; + let from_amount = info.funds[0].amount; + + swap(deps, env, info, msg, from_token, from_amount) +} + +pub fn swap( + deps: &mut DepsMut, + env: &Env, + _info: &MessageInfo, + swap_msg: SwapMsg, + from_token: TokenType, + from_amount: Uint128, +) -> Result { + let state = STATE.load(deps.storage)?; + + let operations = swap_msg + .operations + .ok_or(ContractError::new("operations is required"))?; + ensure!( + !operations.is_empty(), + ContractError::new("min 1 operation is required") + ); + + let astro_execute_msg = AstroportExecuteMsg::ExecuteSwapOperations { + operations, + minimum_receive: Some(swap_msg.minimum_receive), + to: None, + max_spread: swap_msg.max_spread, + }; + + let previous_balance = swap_msg + .to_token + .get_balance(deps.as_ref(), env.contract.address.to_string())?; + + FORWARDING_STATE.save( + deps.storage, + &ForwardingState { + from_token: from_token.clone(), + to_token: swap_msg.to_token, + from_amount, + previous_balance, + min_received: swap_msg.minimum_receive, + forwarding_message: swap_msg.forwarding_message, + reciepient: swap_msg.reciepient, + }, + )?; + + let msg = match from_token { + TokenType::Native { denom } => WasmMsg::Execute { + contract_addr: state.astro_router_address.to_string(), + msg: to_json_binary(&astro_execute_msg)?, + funds: vec![coin(from_amount.u128(), denom)], + }, + TokenType::Smart { contract_address } => { + let send_msg = Cw20ExecuteMsg::Send { + contract: state.astro_router_address.to_string(), + amount: from_amount, + msg: to_json_binary(&astro_execute_msg)?, + }; + WasmMsg::Execute { + contract_addr: contract_address, + msg: to_json_binary(&send_msg)?, + funds: vec![], + } + } + _ => return Err(ContractError::new("unsupported token type")), + }; + + Ok(Response::new().add_submessage(SubMsg::reply_always(msg, ASTRO_SWAP_REPLY_ID))) +} diff --git a/contracts/forwarding/astroport-forwarding/src/lib.rs b/contracts/forwarding/astroport-forwarding/src/lib.rs new file mode 100644 index 00000000..fa7c3584 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/lib.rs @@ -0,0 +1,8 @@ +#![allow(clippy::too_many_arguments)] + +pub mod contract; +pub mod execute; +pub mod migrate; +pub mod query; +pub mod reply; +pub mod state; diff --git a/contracts/forwarding/astroport-forwarding/src/migrate.rs b/contracts/forwarding/astroport-forwarding/src/migrate.rs new file mode 100644 index 00000000..6dea066b --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/migrate.rs @@ -0,0 +1,9 @@ +use cosmwasm_std::{entry_point, DepsMut, Env, Response}; +use euclid::{error::ContractError, msgs::vlp::MigrateMsg}; + +/// This is the migrate entry point for the contract. +/// Currently, it does not perform any migration logic and simply returns an empty response. +#[cfg_attr(not(feature = "library"), entry_point)] +pub fn migrate(_deps: DepsMut, _env: Env, _msg: MigrateMsg) -> Result { + Ok(Response::default()) +} diff --git a/contracts/forwarding/astroport-forwarding/src/query.rs b/contracts/forwarding/astroport-forwarding/src/query.rs new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/query.rs @@ -0,0 +1 @@ + diff --git a/contracts/forwarding/astroport-forwarding/src/reply.rs b/contracts/forwarding/astroport-forwarding/src/reply.rs new file mode 100644 index 00000000..cf9e0026 --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/reply.rs @@ -0,0 +1,44 @@ +use cosmwasm_std::{ensure, DepsMut, Env, Reply, Response, SubMsgResult}; +use euclid::error::ContractError; + +use crate::state::FORWARDING_STATE; + +pub const ASTRO_SWAP_REPLY_ID: u64 = 1; + +pub fn on_astro_swap_reply(deps: DepsMut, env: Env, msg: Reply) -> Result { + match msg.result.clone() { + SubMsgResult::Err(err) => Err(ContractError::new(&format!( + "Astroport swap failed: {}", + err + ))), + SubMsgResult::Ok(..) => { + let forwarding_state = FORWARDING_STATE.load(deps.storage)?; + FORWARDING_STATE.remove(deps.storage); + let new_balance = forwarding_state + .to_token + .get_balance(deps.as_ref(), env.contract.address.to_string())?; + + let swap_amount = new_balance.checked_sub(forwarding_state.previous_balance)?; + + ensure!( + swap_amount >= forwarding_state.min_received, + ContractError::MinReceived { + expected: forwarding_state.min_received, + received: swap_amount, + } + ); + + let transfer_msg = forwarding_state.to_token.create_transfer_msg( + swap_amount, + forwarding_state.reciepient.to_string(), + None, + forwarding_state.forwarding_message, + )?; + + Ok(Response::new() + .add_attribute("action", "reply_astro_swap") + .add_attribute("swap_amount", swap_amount.to_string()) + .add_message(transfer_msg)) + } + } +} diff --git a/contracts/forwarding/astroport-forwarding/src/state.rs b/contracts/forwarding/astroport-forwarding/src/state.rs new file mode 100644 index 00000000..d9fe307c --- /dev/null +++ b/contracts/forwarding/astroport-forwarding/src/state.rs @@ -0,0 +1,24 @@ +use cosmwasm_schema::cw_serde; +use cosmwasm_std::{Addr, Binary, Uint128}; +use cw_storage_plus::Item; +use euclid::token::TokenType; + +#[cw_serde] +pub struct State { + pub astro_router_address: Addr, +} + +pub const STATE: Item = Item::new("state"); + +#[cw_serde] +pub struct ForwardingState { + pub from_token: TokenType, + pub to_token: TokenType, + pub from_amount: Uint128, + pub previous_balance: Uint128, + pub min_received: Uint128, + pub forwarding_message: Option, + pub reciepient: Addr, +} + +pub const FORWARDING_STATE: Item = Item::new("forwarding_state"); diff --git a/contracts/hub/router/src/contract.rs b/contracts/hub/router/src/contract.rs index 6f64d4da..c388f5c0 100644 --- a/contracts/hub/router/src/contract.rs +++ b/contracts/hub/router/src/contract.rs @@ -135,7 +135,7 @@ pub fn execute( ibc_receive_internal_call(&mut deps, env, info, receive_msg) } ExecuteMsg::IbcCallbackAckAndTimeout { ack } => { - ibc_ack_packet_internal_call(deps, env, ack) + ibc_ack_packet_internal_call(deps, info, env, ack) } ExecuteMsg::UpdateLock {} => execute_update_lock(deps, info), ExecuteMsg::NativeReceiveCallback { msg, chain_uid } => { diff --git a/contracts/hub/router/src/execute.rs b/contracts/hub/router/src/execute.rs index 02534c71..ca012a87 100644 --- a/contracts/hub/router/src/execute.rs +++ b/contracts/hub/router/src/execute.rs @@ -320,7 +320,6 @@ pub fn execute_release_escrow( // Ensure that the amount desired doesn't exceed the current balance while !remaining_withdraw_amount.is_zero() && cross_chain_addresses_iterator.peek().is_some() { let cross_chain_address = cross_chain_addresses_iterator - .clone() .next() .ok_or(ContractError::new("Cross Chain Address Iter Failed"))?; let chain = @@ -343,7 +342,7 @@ pub fn execute_release_escrow( .may_load(deps.storage)? .unwrap_or(Uint128::zero()); - let release_amount = if remaining_withdraw_amount.ge(&escrow_balance) { + let mut release_amount = if remaining_withdraw_amount.ge(&escrow_balance) { escrow_balance } else { remaining_withdraw_amount @@ -351,29 +350,24 @@ pub fn execute_release_escrow( match cross_chain_address.limit { Some(Limit::LessThanOrEqual(limit)) => { - ensure!( - release_amount.le(&limit), - ContractError::LimitExceeded { - limit, - amount: release_amount - } - ); + release_amount = release_amount.min(limit); } Some(Limit::Equal(limit)) => { ensure!( - release_amount.eq(&limit), - ContractError::AmountMismatch { - expected: limit, - received: release_amount + release_amount.ge(&limit), + ContractError::InsufficientAmount { + min_amount: limit, + amount: release_amount } ); + release_amount = limit; } Some(Limit::GreaterThanOrEqual(limit)) => { ensure!( release_amount.ge(&limit), - ContractError::InsufficientAmount { - min_amount: limit, - amount: release_amount + ContractError::AmountMismatch { + expected: limit, + received: release_amount } ); } diff --git a/contracts/hub/router/src/ibc/ack_and_timeout.rs b/contracts/hub/router/src/ibc/ack_and_timeout.rs index 31bf648a..8ded3af3 100644 --- a/contracts/hub/router/src/ibc/ack_and_timeout.rs +++ b/contracts/hub/router/src/ibc/ack_and_timeout.rs @@ -1,8 +1,8 @@ #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ - from_json, Binary, CosmosMsg, DepsMut, Env, IbcBasicResponse, IbcPacketAckMsg, - IbcPacketTimeoutMsg, Response, StdError, StdResult, SubMsg, Uint128, WasmMsg, + ensure, from_json, Binary, CosmosMsg, DepsMut, Env, IbcBasicResponse, IbcPacketAckMsg, + IbcPacketTimeoutMsg, MessageInfo, Response, StdError, StdResult, SubMsg, Uint128, WasmMsg, }; use cosmwasm_std::{to_json_binary, IbcAcknowledgement}; use euclid::chain::{Chain, ChainType, ChainUid, CrossChainUser}; @@ -48,9 +48,14 @@ pub fn ibc_packet_ack( pub fn ibc_ack_packet_internal_call( deps: DepsMut, + info: MessageInfo, env: Env, ack: IbcPacketAckMsg, ) -> Result { + ensure!( + info.sender == env.contract.address, + ContractError::Unauthorized {} + ); // Parse the ack based on request let msg: HubIbcExecuteMsg = from_json(ack.original_packet.data)?; diff --git a/contracts/hub/router/src/reply.rs b/contracts/hub/router/src/reply.rs index cda562a0..7f9a9249 100644 --- a/contracts/hub/router/src/reply.rs +++ b/contracts/hub/router/src/reply.rs @@ -269,24 +269,29 @@ pub fn on_swap_reply(deps: DepsMut, env: Env, msg: Reply) -> Result, refund_address: Option, ) -> Result { + // Clean any old refund address + REFUND_ADDRESS.remove(deps.storage); + REFUND_ASSETS.remove(deps.storage); + // Only the factory can call this function let mut state = STATE.load(deps.storage)?; + if let Some(ref refund_address) = refund_address { + deps.api + .addr_validate(refund_address) + .map_err(|_| ContractError::InvalidAddress { + address: refund_address.to_string(), + msg: "Invalid refund address".to_string(), + })?; + REFUND_ADDRESS.save(deps.storage, refund_address)?; + } ensure!( info.sender == state.factory_address, ContractError::Unauthorized {} @@ -233,145 +246,50 @@ pub fn execute_withdraw( let mut allowed_denoms = ALLOWED_DENOMS.load(deps.storage)?.into_iter().peekable(); if let Some(preferred_denom) = preferred_denom { ensure!( - allowed_denoms - .find(|denom| denom.get_key() == preferred_denom.get_key()) - .is_some(), + allowed_denoms.any(|denom| denom.get_key() == preferred_denom.get_key()), ContractError::UnsupportedDenomination {} ); - let denom_balance = DENOM_TO_AMOUNT.load(deps.storage, preferred_denom.get_key())?; - ensure!( - denom_balance.ge(&amount), - ContractError::new("Insufficient balance in preferred denom",) - ); + // Only allow the preferred denom, remove all other denoms + allowed_denoms = vec![preferred_denom].into_iter().peekable(); + } + + // Ensure that the amount desired doesn't exceed the current balance + while !remaining_withdraw_amount.is_zero() && allowed_denoms.peek().is_some() { + let denom = allowed_denoms + .next() + .ok_or(ContractError::new("Denom Iter Faiiled"))?; + + let denom_balance = DENOM_TO_AMOUNT.load(deps.storage, denom.get_key())?; - let transfer_amount = remaining_withdraw_amount; + let transfer_amount = if remaining_withdraw_amount.ge(&denom_balance) { + denom_balance + } else { + remaining_withdraw_amount + }; remaining_withdraw_amount = remaining_withdraw_amount.checked_sub(transfer_amount)?; DENOM_TO_AMOUNT.save( deps.storage, - preferred_denom.get_key(), + denom.get_key(), &denom_balance.checked_sub(transfer_amount)?, )?; - if let Some(forwarding_message) = forwarding_message { - match preferred_denom { - TokenType::Native { denom } => { - let forwarding_msg = CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: recipient.to_string(), - msg: forwarding_message.clone(), - funds: vec![coin(amount.u128(), denom.clone())], - }); - forwarding_messages.push(SubMsg::reply_always( - forwarding_msg, - FORWARDING_MESSAGE_REPLY_ID, - )); - let mut refund_assets = REFUND_ASSETS.load(deps.storage).unwrap_or_default(); - refund_assets.push(coin(amount.u128(), denom)); - REFUND_ASSETS.save(deps.storage, &refund_assets)?; - } - TokenType::Smart { contract_address } => { - let forwarding_msg = CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: contract_address.clone(), - msg: to_json_binary(&Cw20ExecuteMsg::Send { - contract: recipient.clone().into_string(), - amount, - msg: forwarding_message, - })?, - funds: vec![], - }); - forwarding_messages.push(SubMsg::reply_always( - forwarding_msg, - FORWARDING_MESSAGE_REPLY_ID, - )); - let mut refund_assets = REFUND_ASSETS.load(deps.storage).unwrap_or_default(); - refund_assets.push(coin(amount.u128(), contract_address)); - REFUND_ASSETS.save(deps.storage, &refund_assets)?; - } - TokenType::Voucher {} => {} - } - - if let Some(refund_address) = refund_address { - REFUND_ADDRESS.save(deps.storage, &refund_address)?; - } + + let send_msg = denom.create_transfer_msg( + transfer_amount, + recipient.to_string(), + None, + forwarding_message.clone(), + )?; + if forwarding_message.is_some() { + forwarding_messages.push(SubMsg::reply_always(send_msg, FORWARDING_MESSAGE_REPLY_ID)); + let mut refund_assets = REFUND_ASSETS.load(deps.storage).unwrap_or_default(); + refund_assets.push((denom, transfer_amount)); + REFUND_ASSETS.save(deps.storage, &refund_assets)?; } else { - let send_msg = preferred_denom.create_transfer_msg( - transfer_amount, - recipient.to_string(), - None, - )?; messages.push(send_msg); } - } else { - // Ensure that the amount desired doesn't exceed the current balance - while !remaining_withdraw_amount.is_zero() && allowed_denoms.peek().is_some() { - let denom = allowed_denoms - .next() - .ok_or(ContractError::new("Denom Iter Faiiled"))?; - - let denom_balance = DENOM_TO_AMOUNT.load(deps.storage, denom.get_key())?; - - let transfer_amount = if remaining_withdraw_amount.ge(&denom_balance) { - denom_balance - } else { - remaining_withdraw_amount - }; - - remaining_withdraw_amount = remaining_withdraw_amount.checked_sub(transfer_amount)?; - - DENOM_TO_AMOUNT.save( - deps.storage, - denom.get_key(), - &denom_balance.checked_sub(transfer_amount)?, - )?; - if let Some(ref forwarding_message) = forwarding_message { - match denom { - TokenType::Native { denom } => { - let forwarding_msg = CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: recipient.to_string(), - msg: forwarding_message.clone(), - funds: vec![coin(amount.u128(), denom.clone())], - }); - forwarding_messages.push(SubMsg::reply_always( - forwarding_msg, - FORWARDING_MESSAGE_REPLY_ID, - )); - let mut refund_assets = - REFUND_ASSETS.load(deps.storage).unwrap_or_default(); - refund_assets.push(coin(amount.u128(), denom)); - REFUND_ASSETS.save(deps.storage, &refund_assets)?; - } - TokenType::Smart { contract_address } => { - let forwarding_msg = CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: contract_address.clone(), - msg: to_json_binary(&Cw20ExecuteMsg::Send { - contract: recipient.clone().into_string(), - amount, - msg: forwarding_message.clone(), - })?, - funds: vec![], - }); - forwarding_messages.push(SubMsg::reply_always( - forwarding_msg, - FORWARDING_MESSAGE_REPLY_ID, - )); - let mut refund_assets = - REFUND_ASSETS.load(deps.storage).unwrap_or_default(); - refund_assets.push(coin(amount.u128(), contract_address)); - REFUND_ASSETS.save(deps.storage, &refund_assets)?; - } - TokenType::Voucher {} => {} - } - - if let Some(ref refund_address) = refund_address { - REFUND_ADDRESS.save(deps.storage, &refund_address)?; - } - } else { - let send_msg = - denom.create_transfer_msg(transfer_amount, recipient.to_string(), None)?; - messages.push(send_msg); - } - } } // After all the transfer messages, ensure that total amount that needs to be sent is zero diff --git a/contracts/liquidity/escrow/src/reply.rs b/contracts/liquidity/escrow/src/reply.rs index 222cbb13..9999e889 100644 --- a/contracts/liquidity/escrow/src/reply.rs +++ b/contracts/liquidity/escrow/src/reply.rs @@ -1,46 +1,41 @@ use crate::state::{REFUND_ADDRESS, REFUND_ASSETS}; -use cosmwasm_std::{to_json_binary, CosmosMsg, DepsMut, Reply, Response, SubMsgResult, WasmMsg}; -use cw20::Cw20ExecuteMsg; +use cosmwasm_std::{DepsMut, Reply, Response, SubMsgResult}; use euclid::error::ContractError; pub const FORWARDING_MESSAGE_REPLY_ID: u64 = 1; pub fn handle_refund(deps: DepsMut, msg: Reply) -> Result { + // Get the first refund asset and pop it from the list + let refund_assets = REFUND_ASSETS.load(deps.storage).unwrap_or_default(); + + // Remove the first refund asset from the list + let (current_refund, remaining_refund_assets) = refund_assets + .split_first() + .ok_or(ContractError::new("Didn't find any refund assets"))?; + REFUND_ASSETS.save(deps.storage, &remaining_refund_assets.to_vec())?; + + let refund_address = REFUND_ADDRESS.may_load(deps.storage)?; + match msg.result.clone() { SubMsgResult::Err(err) => { - let refund_address = REFUND_ADDRESS.load(deps.storage).unwrap(); - let refund_assets = REFUND_ASSETS.load(deps.storage).unwrap_or_default(); - - let mut refund_msgs = Vec::new(); - for refund_asset in refund_assets { - let refund_msg = match deps.api.addr_validate(&refund_asset.denom) { - Ok(cw20_address) => CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: cw20_address.into_string(), - msg: to_json_binary(&Cw20ExecuteMsg::Transfer { - recipient: refund_address.clone(), - amount: refund_asset.amount, - })?, - funds: vec![], - }), - Err(_) => CosmosMsg::Bank(cosmwasm_std::BankMsg::Send { - to_address: refund_address.clone(), - amount: vec![refund_asset], - }), - }; - refund_msgs.push(refund_msg); + if let Some(refund_address) = refund_address { + let refund_msg = current_refund.0.create_transfer_msg( + current_refund.1, + refund_address, + None, + None, + )?; + Ok(Response::new() + .add_message(refund_msg) + .add_attribute("action", "forwarding_message") + .add_attribute("error", err)) + } else { + Err(ContractError::new(&format!( + "No refund address found: Forward message failed with error: {}", + err + ))) } - REFUND_ADDRESS.remove(deps.storage); - REFUND_ASSETS.remove(deps.storage); - - Ok(Response::new() - .add_messages(refund_msgs) - .add_attribute("action", "forwarding_message") - .add_attribute("error", err)) - } - SubMsgResult::Ok(_res) => { - REFUND_ADDRESS.remove(deps.storage); - REFUND_ASSETS.remove(deps.storage); - Ok(Response::new().add_attribute("action", "forwarding_message")) } + SubMsgResult::Ok(_res) => Ok(Response::new().add_attribute("action", "forwarding_message")), } } diff --git a/contracts/liquidity/escrow/src/state.rs b/contracts/liquidity/escrow/src/state.rs index 23769ab9..c82c2410 100644 --- a/contracts/liquidity/escrow/src/state.rs +++ b/contracts/liquidity/escrow/src/state.rs @@ -1,5 +1,5 @@ use cosmwasm_schema::cw_serde; -use cosmwasm_std::{Addr, Coin, Uint128}; +use cosmwasm_std::{Addr, Uint128}; use cw_storage_plus::{Item, Map}; use euclid::token::{Token, TokenType}; #[cw_serde] @@ -12,5 +12,5 @@ pub struct State { pub const STATE: Item = Item::new("state"); pub const ALLOWED_DENOMS: Item> = Item::new("allowed_denoms"); pub const REFUND_ADDRESS: Item = Item::new("refund_address"); -pub const REFUND_ASSETS: Item> = Item::new("refund_assets"); +pub const REFUND_ASSETS: Item> = Item::new("refund_assets"); pub const DENOM_TO_AMOUNT: Map = Map::new("denom_to_amount"); diff --git a/contracts/liquidity/factory/src/contract.rs b/contracts/liquidity/factory/src/contract.rs index 3e37fbbc..6a0ca2f2 100644 --- a/contracts/liquidity/factory/src/contract.rs +++ b/contracts/liquidity/factory/src/contract.rs @@ -7,6 +7,7 @@ use cw2::set_contract_version; use euclid::chain::CrossChainUser; use euclid::error::ContractError; use euclid::fee::DenomFees; +use euclid::token::TokenType; use euclid_ibc::msg::CHAIN_IBC_EXECUTE_MSG_QUEUE_RANGE; use crate::execute::{ @@ -85,9 +86,10 @@ pub fn execute( timeout, ), ExecuteMsg::ExecuteSwapRequest { + sender, asset_in, - amount_in, asset_out, + mut amount_in, min_amount_out, timeout, swaps, @@ -95,15 +97,31 @@ pub fn execute( partner_fee, } => { let state = STATE.load(deps.storage)?; - let sender = CrossChainUser { + let mut verified_sender = CrossChainUser { address: info.sender.to_string(), chain_uid: state.chain_uid, }; + + // If token is not a voucher, verify custom sender and use it. Using custom sender is security issue if voucher is used + if !asset_in.token_type.is_voucher() { + verified_sender = sender.unwrap_or(verified_sender); + } + + // If this asset is native, lets get the actual amount of funds sent because these amount can vary depending on forwarding contract swaps + if let TokenType::Native { denom } = &asset_in.token_type { + amount_in = info + .funds + .iter() + .find(|fund| fund.denom == *denom) + .ok_or(ContractError::InsufficientFunds {})? + .amount; + } + execute_swap_request( &mut deps, env, info, - sender, + verified_sender, asset_in, amount_in, asset_out, @@ -204,7 +222,7 @@ pub fn execute( ), ExecuteMsg::Receive(msg) => receive_cw20(deps, env, info, msg), ExecuteMsg::IbcCallbackAckAndTimeout { ack } => { - ibc::ack_and_timeout::ibc_ack_packet_internal_call(deps, env, ack) + ibc::ack_and_timeout::ibc_ack_packet_internal_call(deps, info, env, ack) } ExecuteMsg::IbcCallbackReceive { receive_msg } => { ibc::receive::ibc_receive_internal_call(deps, env, receive_msg) diff --git a/contracts/liquidity/factory/src/execute.rs b/contracts/liquidity/factory/src/execute.rs index 231067f0..bbc6bf1a 100644 --- a/contracts/liquidity/factory/src/execute.rs +++ b/contracts/liquidity/factory/src/execute.rs @@ -110,6 +110,7 @@ pub fn execute_request_pool_creation( token.amount, env.contract.address.clone().to_string(), Some(sender.address.clone()), + None, )?; msgs.push(msg); } @@ -323,6 +324,7 @@ pub fn add_liquidity_request( token.amount, env.contract.address.clone().to_string(), Some(sender.address.clone()), + None, )?; msgs.push(msg); } diff --git a/contracts/liquidity/factory/src/ibc/ack_and_timeout.rs b/contracts/liquidity/factory/src/ibc/ack_and_timeout.rs index f8199d7d..5b47d031 100644 --- a/contracts/liquidity/factory/src/ibc/ack_and_timeout.rs +++ b/contracts/liquidity/factory/src/ibc/ack_and_timeout.rs @@ -1,9 +1,9 @@ #[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ - from_json, to_json_binary, Binary, CosmosMsg, DepsMut, Env, IbcAcknowledgement, - IbcBasicResponse, IbcPacketAckMsg, IbcPacketTimeoutMsg, Int256, ReplyOn, Response, StdError, - StdResult, SubMsg, WasmMsg, + ensure, from_json, to_json_binary, Binary, CosmosMsg, DepsMut, Env, IbcAcknowledgement, + IbcBasicResponse, IbcPacketAckMsg, IbcPacketTimeoutMsg, Int256, MessageInfo, ReplyOn, Response, + StdError, StdResult, SubMsg, WasmMsg, }; use cw20::Cw20Coin; use euclid::{ @@ -58,9 +58,14 @@ pub fn ibc_packet_ack( pub fn ibc_ack_packet_internal_call( deps: DepsMut, + info: MessageInfo, env: Env, ack: IbcPacketAckMsg, ) -> Result { + ensure!( + info.sender == env.contract.address, + ContractError::Unauthorized {} + ); let msg: ChainIbcExecuteMsg = from_json(&ack.original_packet.data)?; reusable_internal_ack_call(deps, env, msg, ack.acknowledgement.data, false) } @@ -520,6 +525,7 @@ fn ack_add_liquidity( token_info.amount, sender.to_string(), None, + None, )?; msgs.push(msg); } @@ -653,6 +659,7 @@ fn ack_swap_request( swap_info.partner_fee_amount, swap_info.partner_fee_recipient.to_string(), None, + None, )?; response = response.add_message(partner_send_msg) } @@ -682,6 +689,7 @@ fn ack_swap_request( .checked_add(swap_info.partner_fee_amount)?, sender.to_string(), None, + None, )?; response = response.add_message(msg); } @@ -733,6 +741,7 @@ fn ack_deposit_token_request( deposit_info.amount_in, sender.to_string(), None, + None, )?; Ok(Response::new() diff --git a/contracts/liquidity/factory/src/query.rs b/contracts/liquidity/factory/src/query.rs index 49b50a86..c8e62980 100644 --- a/contracts/liquidity/factory/src/query.rs +++ b/contracts/liquidity/factory/src/query.rs @@ -83,7 +83,7 @@ pub fn query_all_pools(deps: Deps) -> Result { let pools = PAIR_TO_VLP .range(deps.storage, None, None, cosmwasm_std::Order::Ascending) .flat_map(|item| -> Result<_, ContractError> { - let item = item.unwrap(); + let item = item?; Ok(PoolVlpResponse { pair: Pair::new(item.0 .0, item.0 .1)?, vlp: item.1, diff --git a/contracts/liquidity/factory/src/reply.rs b/contracts/liquidity/factory/src/reply.rs index cfa75056..f1c8ff2a 100644 --- a/contracts/liquidity/factory/src/reply.rs +++ b/contracts/liquidity/factory/src/reply.rs @@ -35,15 +35,12 @@ pub fn on_escrow_instantiate_reply(deps: DepsMut, msg: Reply) -> Result { - let deposit_msg = token - .token_type - .create_escrow_msg(token.amount, escrow_address)?; - response = response.add_message(deposit_msg); - PENDING_DEPOSIT_TOKEN.remove(deps.storage, token.token); - } - None => {} + if let Some(token) = pending_deposit_token { + let deposit_msg = token + .token_type + .create_escrow_msg(token.amount, escrow_address)?; + response = response.add_message(deposit_msg); + PENDING_DEPOSIT_TOKEN.remove(deps.storage, token.token); } Ok(response) diff --git a/packages/euclid/src/error.rs b/packages/euclid/src/error.rs index d8d394ba..07141a65 100644 --- a/packages/euclid/src/error.rs +++ b/packages/euclid/src/error.rs @@ -243,6 +243,14 @@ pub enum ContractError { #[error("Invalid expiration")] InvalidExpiration {}, // END CW20 ERRORS + #[error("Min received {received} is less than expected {expected}")] + MinReceived { + expected: Uint128, + received: Uint128, + }, + + #[error("Invalid Address: {address} {msg}")] + InvalidAddress { address: String, msg: String }, } impl ContractError { diff --git a/packages/euclid/src/msgs/factory/msg.rs b/packages/euclid/src/msgs/factory/msg.rs index 10ba5233..f5e8ca34 100644 --- a/packages/euclid/src/msgs/factory/msg.rs +++ b/packages/euclid/src/msgs/factory/msg.rs @@ -29,6 +29,7 @@ pub enum ExecuteMsg { timeout: Option, }, ExecuteSwapRequest { + sender: Option, asset_in: TokenWithDenom, amount_in: Uint128, asset_out: Token, diff --git a/packages/euclid/src/token.rs b/packages/euclid/src/token.rs index ec43e3d7..64222581 100644 --- a/packages/euclid/src/token.rs +++ b/packages/euclid/src/token.rs @@ -3,8 +3,8 @@ use std::ops::Deref; use cosmwasm_schema::cw_serde; use cosmwasm_std::{ - coin, ensure, forward_ref_partial_eq, to_json_binary, Addr, BankMsg, Coin, CosmosMsg, Deps, - StdError, StdResult, Uint128, WasmMsg, + coin, ensure, forward_ref_partial_eq, to_json_binary, Addr, BankMsg, Binary, Coin, CosmosMsg, + Deps, StdError, StdResult, Uint128, WasmMsg, }; use cw_storage_plus::{Key, KeyDeserialize, Prefixer, PrimaryKey}; @@ -335,29 +335,65 @@ impl TokenType { amount: Uint128, recipient: String, allowance: Option, + forwarding_message: Option, ) -> Result { let msg = match self.clone() { - TokenType::Native { denom } => CosmosMsg::Bank(BankMsg::Send { - to_address: recipient, - amount: vec![Coin { - denom: denom.to_string(), - amount, - }], - }), - TokenType::Smart { contract_address } => CosmosMsg::Wasm(WasmMsg::Execute { - contract_addr: contract_address.to_string(), - msg: match allowance { - Some(owner) => to_json_binary(&cw20_base::msg::ExecuteMsg::TransferFrom { - owner, - recipient, - amount, - })?, - None => { - to_json_binary(&cw20_base::msg::ExecuteMsg::Transfer { recipient, amount })? - } - }, - funds: vec![], - }), + TokenType::Native { denom } => { + if let Some(forwarding_message) = forwarding_message { + CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: recipient.to_string(), + msg: forwarding_message.clone(), + funds: vec![coin(amount.u128(), denom.clone())], + }) + } else { + CosmosMsg::Bank(BankMsg::Send { + to_address: recipient, + amount: vec![Coin { + denom: denom.to_string(), + amount, + }], + }) + } + } + TokenType::Smart { contract_address } => { + if let Some(forwarding_message) = forwarding_message { + CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: contract_address.to_string(), + msg: match allowance { + Some(owner) => to_json_binary(&cw20_base::msg::ExecuteMsg::SendFrom { + owner, + amount, + contract: recipient.to_string(), + msg: forwarding_message.clone(), + })?, + None => to_json_binary(&cw20_base::msg::ExecuteMsg::Send { + contract: recipient.to_string(), + msg: forwarding_message.clone(), + amount, + })?, + }, + funds: vec![], + }) + } else { + CosmosMsg::Wasm(WasmMsg::Execute { + contract_addr: contract_address.to_string(), + msg: match allowance { + Some(owner) => { + to_json_binary(&cw20_base::msg::ExecuteMsg::TransferFrom { + owner, + recipient, + amount, + })? + } + None => to_json_binary(&cw20_base::msg::ExecuteMsg::Transfer { + recipient, + amount, + })?, + }, + funds: vec![], + }) + } + } TokenType::Voucher { .. } => { return Err(ContractError::new("Voucher can only be transferred in vsl")); } @@ -434,9 +470,10 @@ impl TokenWithDenom { amount: Uint128, recipient: String, allowance: Option, + forwarding_message: Option, ) -> Result { self.token_type - .create_transfer_msg(amount, recipient, allowance) + .create_transfer_msg(amount, recipient, allowance, forwarding_message) } pub fn create_escrow_msg( diff --git a/packages/euclid/src/utils/fund_manager.rs b/packages/euclid/src/utils/fund_manager.rs index 946b74de..de61819a 100644 --- a/packages/euclid/src/utils/fund_manager.rs +++ b/packages/euclid/src/utils/fund_manager.rs @@ -43,7 +43,10 @@ impl FundManager { self.get(denom).ge(&amount), ContractError::InsufficientFunds {} ); - *self.funds.get_mut(denom).unwrap() -= amount; + *self + .funds + .get_mut(denom) + .ok_or(ContractError::new("Denom not found"))? -= amount; Ok(()) } diff --git a/packages/forwarding/Cargo.toml b/packages/forwarding/Cargo.toml new file mode 100644 index 00000000..305de43f --- /dev/null +++ b/packages/forwarding/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "forwarding" +version = "0.1.0" +edition = "2021" + + +[features] +# use library feature to disable all instantiate/execute/query exports +library = [] + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[lib] +crate-type = ["cdylib", "rlib"] + +[dependencies] +cosmwasm-std = { workspace = true } +cw-storage-plus = { workspace = true } +cosmwasm-schema = { workspace = true } +serde = { workspace = true } +schemars = { workspace = true } +cw20 = { workspace = true } + +euclid = { workspace = true } + +astroport = { git = "https://github.com/astroport-fi/astroport-core", branch = "main" } +cw-orch = "=0.24.1" diff --git a/packages/forwarding/src/lib.rs b/packages/forwarding/src/lib.rs new file mode 100644 index 00000000..c6d7262a --- /dev/null +++ b/packages/forwarding/src/lib.rs @@ -0,0 +1 @@ +pub mod msgs; diff --git a/packages/forwarding/src/msgs/astroport.rs b/packages/forwarding/src/msgs/astroport.rs new file mode 100644 index 00000000..9b5b4919 --- /dev/null +++ b/packages/forwarding/src/msgs/astroport.rs @@ -0,0 +1,36 @@ +use astroport::router::SwapOperation; +use cosmwasm_schema::{cw_serde, QueryResponses}; +use cosmwasm_std::{Addr, Binary, Decimal, Uint128}; +use cw20::Cw20ReceiveMsg; +use euclid::token::TokenType; + +#[cw_serde] +pub struct InstantiateMsg { + pub astro_router: Addr, +} + +#[cw_serde] +#[derive(cw_orch::ExecuteFns)] +pub enum ExecuteMsg { + Swap(SwapMsg), + Receive(Cw20ReceiveMsg), +} + +#[cw_serde] +pub enum Cw20HookMsg { + Swap(SwapMsg), +} + +#[cw_serde] +#[derive(cw_orch::QueryFns, QueryResponses)] +pub enum QueryMsg {} + +#[cw_serde] +pub struct SwapMsg { + pub operations: Option>, + pub max_spread: Option, + pub minimum_receive: Uint128, + pub to_token: TokenType, + pub forwarding_message: Option, + pub reciepient: Addr, +} diff --git a/packages/forwarding/src/msgs/mod.rs b/packages/forwarding/src/msgs/mod.rs new file mode 100644 index 00000000..e474cfcd --- /dev/null +++ b/packages/forwarding/src/msgs/mod.rs @@ -0,0 +1 @@ +pub mod astroport; diff --git a/tests-integration/src/tests/factory.rs b/tests-integration/src/tests/factory.rs index af723f39..ef0f58bb 100644 --- a/tests-integration/src/tests/factory.rs +++ b/tests-integration/src/tests/factory.rs @@ -9,7 +9,7 @@ use cw_orch::prelude::{ use cw_orch_interchain::{prelude::*, types::IbcPacketOutcome, InterchainEnv}; use escrow::{mock::mock_escrow, EscrowContract}; use euclid::{ - chain::ChainUid, + chain::{ChainUid, CrossChainUser, CrossChainUserWithLimit}, error::ContractError, fee::{DenomFees, BPS_1_PERCENT}, msgs::{ @@ -19,10 +19,12 @@ use euclid::{ RegisterFactoryChainIbc, RegisterFactoryChainNative, TokenDenom, TokenDenomsResponse, VlpResponse, }, - virtual_balance::GetStateResponse, + virtual_balance::{GetBalanceResponse, GetStateResponse}, vlp::GetLiquidityResponse, }, + swap::NextSwapPair, token::{Pair, PairWithDenomAndAmount, Token, TokenWithDenom, TokenWithDenomAndAmount}, + virtual_balance::BalanceKey, }; use factory::{ mock::{mock_factory, MockFactory}, @@ -294,8 +296,7 @@ fn test_create_pool_with_funds() { .unwrap(); // For testing a successful outcome of the first packet sent out in the tx, you can use: - if let IbcPacketOutcome::Success { ack_tx, .. } = &packet_lifetime.packets[0].outcome { - println!("{:?}", ack_tx.tx_id.response.events); + if let IbcPacketOutcome::Success { .. } = &packet_lifetime.packets[0].outcome { // Packet has been successfully acknowledged and decoded, the transaction has gone through correctly } else { panic!("packet timed out"); @@ -358,12 +359,10 @@ fn test_create_pool_with_funds() { ); virtual_balance_nibiru.set_address(&Addr::unchecked("contract1")); - let vbalance_query: GetStateResponse = virtual_balance_nibiru + let _vbalance_query: GetStateResponse = virtual_balance_nibiru .query(&euclid::msgs::virtual_balance::QueryMsg::GetState {}) .unwrap(); - println!("vbalance state is: {:?}", vbalance_query); - // Osmo escrow contract escrow_osmosis.set_address(&Addr::unchecked("contract1")); let escrow_query: EscrowStateResponse = escrow_osmosis @@ -613,12 +612,10 @@ fn test_create_pool_with_funds() { ); virtual_balance_nibiru.set_address(&Addr::unchecked("contract1")); - let vbalance_query: GetStateResponse = virtual_balance_nibiru + let _vbalance_query: GetStateResponse = virtual_balance_nibiru .query(&euclid::msgs::virtual_balance::QueryMsg::GetState {}) .unwrap(); - println!("vbalance state is: {:?}", vbalance_query); - // Nibiru escrow contract escrow_nibiru.set_address(&Addr::unchecked("contract6")); let escrow_query: EscrowStateResponse = escrow_nibiru @@ -714,6 +711,144 @@ fn test_create_pool_with_funds() { total_amount: Uint128::from(100_000u128 * 2), } ); + // Test swap + let eucl_token = TokenWithDenom { + token: Token::create("eucl".to_string()).unwrap(), + token_type: euclid::token::TokenType::Native { + denom: "eucl".to_string(), + }, + }; + let nibi_token = TokenWithDenom { + token: Token::create("nibi".to_string()).unwrap(), + token_type: euclid::token::TokenType::Native { + denom: "nibi".to_string(), + }, + }; + factory_nibiru + .execute( + &euclid::msgs::factory::ExecuteMsg::ExecuteSwapRequest { + sender: None, + asset_in: eucl_token.clone(), + amount_in: Uint128::from(1_000u128), + asset_out: nibi_token.token.clone(), + min_amount_out: Uint128::from(9000u128), + timeout: None, + swaps: vec![NextSwapPair { + token_in: eucl_token.token.clone(), + token_out: nibi_token.token, + test_fail: None, + }], + cross_chain_addresses: vec![CrossChainUserWithLimit { + user: CrossChainUser { + address: sender.clone(), + chain_uid: ChainUid::create("nibiru".to_string()).unwrap(), + }, + limit: None, + preferred_denom: None, + refund_address: None, + forwarding_message: None, + }], + partner_fee: None, + }, + Some(&[coin(1_000u128, "eucl")]), + ) + .unwrap(); + + // Check balances after swap + let escrow_query: EscrowStateResponse = escrow_nibiru + .query(&euclid::msgs::escrow::QueryMsg::State {}) + .unwrap(); + assert_eq!( + escrow_query, + EscrowStateResponse { + token: Token::create("nibi".to_string()).unwrap(), + factory_address: Addr::unchecked("contract3"), + // Total amount decreased by 9506 + total_amount: Uint128::from((100_000u128 * 2) - 9506), + } + ); + // This is the escrow for the Euclid token + escrow_nibiru.set_address(&Addr::unchecked("contract4")); + let escrow_query: EscrowStateResponse = escrow_nibiru + .query(&euclid::msgs::escrow::QueryMsg::State {}) + .unwrap(); + assert_eq!( + escrow_query, + EscrowStateResponse { + token: Token::create("eucl".to_string()).unwrap(), + factory_address: Addr::unchecked("contract3"), + // Total amount increased by 1000 + total_amount: Uint128::from((10_000u128 * 2) + 1000), + } + ); + + // Test deposit + factory_nibiru + .execute( + &euclid::msgs::factory::ExecuteMsg::DepositToken { + amount_in: Uint128::from(100u128), + asset_in: eucl_token.clone(), + recipient: None, + timeout: None, + }, + Some(&[coin(100, "eucl")]), + ) + .unwrap(); + + let virtual_balance_query: GetBalanceResponse = virtual_balance_nibiru + .query(&euclid::msgs::virtual_balance::QueryMsg::GetBalance { + balance_key: BalanceKey { + cross_chain_user: CrossChainUser { + address: sender.clone(), + chain_uid: ChainUid::create("nibiru".to_string()).unwrap(), + }, + token_id: eucl_token.token.to_string(), + }, + }) + .unwrap(); + assert_eq!( + virtual_balance_query, + GetBalanceResponse { + amount: Uint128::from(100u128), + } + ); + + // Test withdraw + factory_nibiru + .withdraw_virtual_balance( + Uint128::new(50), + vec![CrossChainUserWithLimit { + user: CrossChainUser { + address: sender.clone(), + chain_uid: ChainUid::create("nibiru".to_string()).unwrap(), + }, + limit: None, + preferred_denom: None, + refund_address: None, + forwarding_message: None, + }], + Token::create("eucl".to_string()).unwrap(), + None, + ) + .unwrap(); + + let virtual_balance_query: GetBalanceResponse = virtual_balance_nibiru + .query(&euclid::msgs::virtual_balance::QueryMsg::GetBalance { + balance_key: BalanceKey { + cross_chain_user: CrossChainUser { + address: sender.clone(), + chain_uid: ChainUid::create("nibiru".to_string()).unwrap(), + }, + token_id: eucl_token.token.to_string(), + }, + }) + .unwrap(); + assert_eq!( + virtual_balance_query, + GetBalanceResponse { + amount: Uint128::from(50u128), + } + ); } #[test] diff --git a/tests-integration/src/tests/virtual_balance.rs b/tests-integration/src/tests/virtual_balance.rs index 3fbd9f85..de088e28 100644 --- a/tests-integration/src/tests/virtual_balance.rs +++ b/tests-integration/src/tests/virtual_balance.rs @@ -43,7 +43,7 @@ fn test_proper_instantiation() { ); let token_id_response = - MockVirtualBalance::query_state(&mock_virtual_balance, &mut virtual_balance); + MockVirtualBalance::query_state(&mock_virtual_balance, &virtual_balance); let expected_token_id = GetStateResponse { state: State { router: mock_router.addr().clone().into_string(), diff --git a/tests-integration/src/tests/vlp.rs b/tests-integration/src/tests/vlp.rs index d867a723..dc2f8204 100644 --- a/tests-integration/src/tests/vlp.rs +++ b/tests-integration/src/tests/vlp.rs @@ -90,7 +90,7 @@ fn test_proper_instantiation() { "admin".to_string(), ); - let token_id_response = MockVlp::query_state(&mock_vlp, &mut vlp); + let token_id_response = MockVlp::query_state(&mock_vlp, &vlp); let expected_token_id = GetStateResponse { pair, router: mock_router.addr().clone().into_string(),