Skip to content

Commit

Permalink
Merge pull request #18 from confio/simplify-binding-calls
Browse files Browse the repository at this point in the history
Simplify binding calls
  • Loading branch information
ethanfrey authored Mar 29, 2022
2 parents 0842640 + 65f55ed commit 14d0f13
Show file tree
Hide file tree
Showing 10 changed files with 18 additions and 128 deletions.
6 changes: 3 additions & 3 deletions Cargo.lock

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

4 changes: 2 additions & 2 deletions contracts/reflect/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "osmo-reflect"
version = "0.4.1"
version = "0.5.0"
authors = ["Ethan Frey <[email protected]>"]
edition = "2018"
description = "Reflect messages to use for test cases - based on cw-mask"
Expand All @@ -19,7 +19,7 @@ backtraces = ["cosmwasm-std/backtraces"]
[dependencies]
cosmwasm-std = { version = "1.0.0-beta6", features = ["staking", "stargate"] }
cosmwasm-storage = "1.0.0-beta6"
osmo-bindings = { version = "0.4.1", path = "../../packages/bindings" }
osmo-bindings = { version = "0.5.0", path = "../../packages/bindings" }
schemars = "0.8.1"
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
thiserror = "1.0"
Expand Down
8 changes: 1 addition & 7 deletions contracts/reflect/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ mod tests {
};
use cosmwasm_std::{
coin, coins, from_binary, AllBalanceResponse, BankMsg, BankQuery, Binary, Coin, Event,
StakingMsg, StdError, SubMsgExecutionResponse, Uint128,
StakingMsg, StdError, SubMsgExecutionResponse,
};
use cosmwasm_std::{OwnedDeps, SubMsgResult, SystemError};
use std::marker::PhantomData;
Expand Down Expand Up @@ -277,12 +277,6 @@ mod tests {
amount: coins(1, "token"),
}
.into(),
OsmosisMsg::MintTokens {
sub_denom: "bonus".to_string(),
amount: Uint128::new(123456789),
recipient: "creator".to_string(),
}
.into(),
StakingMsg::Delegate {
validator: String::from("validator"),
amount: coin(100, "ustake"),
Expand Down
4 changes: 2 additions & 2 deletions packages/bindings-test/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "osmo-bindings-test"
version = "0.4.1"
version = "0.5.0"
authors = ["Ethan Frey <[email protected]>"]
edition = "2018"
description = "Multitest (and other test helpers) support for Osmosis-specific contracts"
Expand All @@ -9,7 +9,7 @@ homepage = "https://osmosis.zone"
license = "Apache-2.0"

[dependencies]
osmo-bindings = { version = "0.4.1", path = "../bindings" }
osmo-bindings = { version = "0.5.0", path = "../bindings" }
cosmwasm-std = { version = "1.0.0-beta6" }
schemars = "0.8"
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
Expand Down
87 changes: 4 additions & 83 deletions packages/bindings-test/src/multitest.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use cw_multi_test::{
use cw_storage_plus::Map;

use osmo_bindings::{
EstimatePriceResponse, FullDenomResponse, OsmosisMsg, OsmosisQuery, PoolStateResponse,
SpotPriceResponse, SwapAmount, SwapAmountWithLimit,
EstimatePriceResponse, OsmosisMsg, OsmosisQuery, PoolStateResponse, SpotPriceResponse,
SwapAmount, SwapAmountWithLimit,
};

pub const POOLS: Map<u64, Pool> = Map::new("pools");
Expand Down Expand Up @@ -174,11 +174,6 @@ pub struct OsmosisModule {}
pub const BLOCK_TIME: u64 = 5;

impl OsmosisModule {
fn build_denom(&self, contract: &Addr, sub_denom: &str) -> String {
// TODO: validation assertion on sub_denom
format!("cw/{}/{}", contract, sub_denom)
}

/// Used to mock out the response for TgradeQuery::ValidatorVotes
pub fn set_pool(&self, storage: &mut dyn Storage, pool_id: u64, pool: &Pool) -> StdResult<()> {
POOLS.save(storage, pool_id, pool)
Expand All @@ -204,24 +199,6 @@ impl Module for OsmosisModule {
QueryC: CustomQuery + DeserializeOwned + 'static,
{
match msg {
OsmosisMsg::MintTokens {
sub_denom,
amount,
recipient,
} => {
let denom = self.build_denom(&sender, &sub_denom);
let mint = BankSudo::Mint {
to_address: recipient,
amount: coins(amount.u128(), &denom),
};
router.sudo(api, storage, block, mint.into())?;

let data = Some(to_binary(&FullDenomResponse { denom })?);
Ok(AppResponse {
data,
events: vec![],
})
}
OsmosisMsg::Swap {
first,
route,
Expand Down Expand Up @@ -284,22 +261,13 @@ impl Module for OsmosisModule {

fn query(
&self,
api: &dyn Api,
_api: &dyn Api,
storage: &dyn Storage,
_querier: &dyn Querier,
_block: &BlockInfo,
request: OsmosisQuery,
) -> anyhow::Result<Binary> {
match request {
OsmosisQuery::FullDenom {
contract,
sub_denom,
} => {
let contract = api.addr_validate(&contract)?;
let denom = self.build_denom(&contract, &sub_denom);
let res = FullDenomResponse { denom };
Ok(to_binary(&res)?)
}
OsmosisQuery::PoolState { id } => {
let pool = POOLS.load(storage, id)?;
let res = pool.into_response(id);
Expand All @@ -314,7 +282,7 @@ impl Module for OsmosisModule {
Ok(to_binary(&SpotPriceResponse { price })?)
}
OsmosisQuery::EstimateSwap {
contract: _sender,
sender: _sender,
first,
route,
amount,
Expand Down Expand Up @@ -425,53 +393,6 @@ mod tests {
use cw_multi_test::Executor;
use osmo_bindings::Swap;

#[test]
fn mint_token() {
let contract = Addr::unchecked("govner");
let rcpt = Addr::unchecked("townies");
let sub_denom = "fundz";

let mut app = OsmosisApp::new();

// no tokens
let start = app.wrap().query_all_balances(rcpt.as_str()).unwrap();
assert_eq!(start, vec![]);

// let's find the mapping
let FullDenomResponse { denom } = app
.wrap()
.query(
&OsmosisQuery::FullDenom {
contract: contract.to_string(),
sub_denom: sub_denom.to_string(),
}
.into(),
)
.unwrap();
assert_ne!(denom, sub_denom);
assert!(denom.len() > 10);

// prepare to mint
let amount = Uint128::new(1234567);
let msg = OsmosisMsg::MintTokens {
sub_denom: sub_denom.to_string(),
amount,
recipient: rcpt.to_string(),
};

// simulate contract calling
app.execute(contract, msg.into()).unwrap();

// we got tokens!
let end = app.wrap().query_balance(rcpt.as_str(), &denom).unwrap();
let expected = Coin { denom, amount };
assert_eq!(end, expected);

// but no minting of unprefixed version
let empty = app.wrap().query_balance(rcpt.as_str(), sub_denom).unwrap();
assert_eq!(empty.amount, Uint128::zero());
}

#[test]
fn query_pool() {
let coin_a = coin(6_000_000u128, "osmo");
Expand Down
2 changes: 1 addition & 1 deletion packages/bindings/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "osmo-bindings"
version = "0.4.1"
version = "0.5.0"
authors = ["Ethan Frey <[email protected]>"]
edition = "2018"
description = "Bindings for CustomMsg and CustomQuery for the Osmosis blockchain"
Expand Down
4 changes: 1 addition & 3 deletions packages/bindings/examples/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ use std::fs::create_dir_all;
use cosmwasm_schema::{export_schema, remove_schemas, schema_for};

use osmo_bindings::{
EstimatePriceResponse, FullDenomResponse, OsmosisMsg, OsmosisQuery, PoolStateResponse,
SpotPriceResponse,
EstimatePriceResponse, OsmosisMsg, OsmosisQuery, PoolStateResponse, SpotPriceResponse,
};

fn main() {
Expand All @@ -16,7 +15,6 @@ fn main() {

export_schema(&schema_for!(OsmosisMsg), &out_dir);
export_schema(&schema_for!(OsmosisQuery), &out_dir);
export_schema(&schema_for!(FullDenomResponse), &out_dir);
export_schema(&schema_for!(PoolStateResponse), &out_dir);
export_schema(&schema_for!(SpotPriceResponse), &out_dir);
export_schema(&schema_for!(EstimatePriceResponse), &out_dir);
Expand Down
4 changes: 1 addition & 3 deletions packages/bindings/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ mod query;
mod types;

pub use msg::OsmosisMsg;
pub use query::{
EstimatePriceResponse, FullDenomResponse, OsmosisQuery, PoolStateResponse, SpotPriceResponse,
};
pub use query::{EstimatePriceResponse, OsmosisQuery, PoolStateResponse, SpotPriceResponse};
pub use types::{Step, Swap, SwapAmount, SwapAmountWithLimit};

// This is a signal, such that any contract that imports these helpers will only run on the
Expand Down
13 changes: 1 addition & 12 deletions packages/bindings/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,12 @@ use serde::{Deserialize, Serialize};

use crate::types::SwapAmountWithLimit;
use crate::{Step, Swap};
use cosmwasm_std::{CosmosMsg, CustomMsg, Uint128};
use cosmwasm_std::{CosmosMsg, CustomMsg};

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
/// A number of Custom messages that can call into the Osmosis bindings
pub enum OsmosisMsg {
/// Contracts can mint native tokens that have an auto-generated denom
/// namespaced under the contract's address. A contract may create any number
/// of independent sub-denoms.
/// Returns FullDenomResponse in the data field of the Response
MintTokens {
/// Must be 2-32 alphanumeric characters
/// FIXME: revisit actual requirements in SDK
sub_denom: String,
amount: Uint128,
recipient: String,
},
/// Swap over one or more pools
/// Returns EstimatePriceResponse in the data field of the Response
Swap {
Expand Down
14 changes: 2 additions & 12 deletions packages/bindings/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,6 @@ use cosmwasm_std::{Coin, CustomQuery, Decimal, Uint128};
#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
#[serde(rename_all = "snake_case")]
pub enum OsmosisQuery {
/// Given a sub-denom minted by a contract via `OsmosisMsg::MintTokens`,
/// returns the full denom as used by `BankMsg::Send`.
/// You may call `FullDenom { contract: env.contract.address, sub_denom }` to find the denom issued
/// by the current contract.
FullDenom { contract: String, sub_denom: String },
/// For a given pool ID, list all tokens traded on it with current liquidity (spot).
/// As well as the total number of LP shares and their denom
PoolState { id: u64 },
Expand All @@ -25,7 +20,7 @@ pub enum OsmosisQuery {
/// Warning: this can easily be manipulated via sandwich attacks, do not use as price oracle.
/// We will add TWAP for more robust price feed.
EstimateSwap {
contract: String,
sender: String,
first: Swap,
route: Vec<Step>,
amount: SwapAmount,
Expand All @@ -52,19 +47,14 @@ impl OsmosisQuery {
amount: SwapAmount,
) -> Self {
OsmosisQuery::EstimateSwap {
contract: contract.into(),
sender: contract.into(),
first: Swap::new(pool_id, denom_in, denom_out),
amount,
route: vec![],
}
}
}

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct FullDenomResponse {
pub denom: String,
}

#[derive(Serialize, Deserialize, Clone, PartialEq, JsonSchema, Debug)]
pub struct PoolStateResponse {
/// The various assets that be swapped. Including current liquidity.
Expand Down

0 comments on commit 14d0f13

Please sign in to comment.