Skip to content

Commit

Permalink
Add EVM query/msg types (#73)
Browse files Browse the repository at this point in the history
* Add EVM query/msg types

* cargo fmt
  • Loading branch information
codchen authored Mar 30, 2024
1 parent 6d20612 commit a2fb892
Show file tree
Hide file tree
Showing 11 changed files with 485 additions and 72 deletions.
64 changes: 35 additions & 29 deletions contracts/sei-tester/src/contract.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
use cosmwasm_std::to_json_binary;
#[cfg(not(feature = "library"))]
use cosmwasm_std::{
coin, entry_point, to_binary, BankMsg, Binary, Coin, Decimal, Deps, DepsMut, Env, MessageInfo,
Reply, Response, StdError, StdResult, SubMsg, SubMsgResponse, Uint128, Order as IteratorOrder, Attribute
coin, entry_point, Attribute, BankMsg, Binary, Coin, Decimal, Deps, DepsMut, Env, MessageInfo,
Order as IteratorOrder, Reply, Response, StdError, StdResult, SubMsg, SubMsgResponse, Uint128,
};
use cw_storage_plus::Bound;

use crate::{
msg::{ExecuteMsg, InstantiateMsg, QueryMsg},
state::{PARALLEL_VALS, USER_SUMS, VALUES},
types::{OrderData, PositionEffect},
state::{VALUES, USER_SUMS, PARALLEL_VALS},
};
use protobuf::Message;
use sei_cosmwasm::{
Expand Down Expand Up @@ -65,18 +66,22 @@ pub fn execute(
ExecuteMsg::Burn {} => burn(deps, env, info),
ExecuteMsg::ChangeAdmin {} => change_admin(deps, env, info),
ExecuteMsg::SetMetadata {} => set_metadata(deps, env, info),
ExecuteMsg::TestOccIteratorWrite { values } => test_occ_iterator_write(deps, env, info, values),
ExecuteMsg::TestOccIteratorRange { start, end } => test_occ_iterator_range(deps, env, info, start, end),
ExecuteMsg::TestOccIteratorWrite { values } => {
test_occ_iterator_write(deps, env, info, values)
}
ExecuteMsg::TestOccIteratorRange { start, end } => {
test_occ_iterator_range(deps, env, info, start, end)
}
ExecuteMsg::TestOccParallelism { value } => test_occ_parallelism(deps, env, info, value),
}
}

fn test_occ_iterator_write(
deps: DepsMut<SeiQueryWrapper>,
_env: Env,
info: MessageInfo,
_info: MessageInfo,
values: Vec<(u64, u64)>,
) -> Result<Response<SeiMsg>, StdError> {
) -> Result<Response<SeiMsg>, StdError> {
// writes all of the values (index, value) to the store
for (key, value) in values {
VALUES.save(deps.storage, key, &value)?;
Expand All @@ -90,15 +95,18 @@ fn test_occ_iterator_range(
info: MessageInfo,
start: u64,
end: u64,
) -> Result<Response<SeiMsg>, StdError> {
) -> Result<Response<SeiMsg>, StdError> {
// iterates through the `VALUES` and for all that exist, sums them and writes them to user_sums for the sender
let mut sum: u64 = 0;
let values: Vec<(u64, u64)> = VALUES.range(
deps.storage,
Some(Bound::inclusive(start)),
Some(Bound::inclusive(end)),
IteratorOrder::Ascending
).collect::<Result<Vec<(u64, u64)>, StdError>>().unwrap();
let values: Vec<(u64, u64)> = VALUES
.range(
deps.storage,
Some(Bound::inclusive(start)),
Some(Bound::inclusive(end)),
IteratorOrder::Ascending,
)
.collect::<Result<Vec<(u64, u64)>, StdError>>()
.unwrap();

let mut value_attrs: Vec<Attribute> = vec![];
for (key, val) in values {
Expand All @@ -110,22 +118,20 @@ fn test_occ_iterator_range(
Ok(Response::new()
.add_attribute("user", info.sender.to_string())
.add_attribute("sum", sum.to_string())
.add_attributes(value_attrs)
)
.add_attributes(value_attrs))
}

fn test_occ_parallelism(
deps: DepsMut<SeiQueryWrapper>,
_env: Env,
info: MessageInfo,
value: u64,
) -> Result<Response<SeiMsg>, StdError> {
) -> Result<Response<SeiMsg>, StdError> {
// writes the value to the store for the sender
PARALLEL_VALS.save(deps.storage, info.sender.clone(), &value)?;
Ok(Response::new()
.add_attribute("user", info.sender.to_string())
.add_attribute("val", value.to_string())
)
.add_attribute("val", value.to_string()))
}

pub fn place_orders(
Expand Down Expand Up @@ -385,29 +391,29 @@ pub fn handle_place_order_reply(
#[cfg_attr(not(feature = "library"), entry_point)]
pub fn query(deps: Deps<SeiQueryWrapper>, _env: Env, msg: QueryMsg) -> StdResult<Binary> {
match msg {
QueryMsg::ExchangeRates {} => to_binary(&query_exchange_rates(deps)?),
QueryMsg::ExchangeRates {} => to_json_binary(&query_exchange_rates(deps)?),
QueryMsg::OracleTwaps { lookback_seconds } => {
to_binary(&query_oracle_twaps(deps, lookback_seconds)?)
to_json_binary(&query_oracle_twaps(deps, lookback_seconds)?)
}
QueryMsg::DexTwaps {
contract_address,
lookback_seconds,
} => to_binary(&query_dex_twaps(deps, contract_address, lookback_seconds)?),
} => to_json_binary(&query_dex_twaps(deps, contract_address, lookback_seconds)?),
QueryMsg::OrderSimulation {
order,
contract_address,
} => to_binary(&query_order_simulation(deps, order, contract_address)?),
QueryMsg::Epoch {} => to_binary(&query_epoch(deps)?),
} => to_json_binary(&query_order_simulation(deps, order, contract_address)?),
QueryMsg::Epoch {} => to_json_binary(&query_epoch(deps)?),
QueryMsg::GetOrders {
contract_address,
account,
} => to_binary(&query_get_orders(deps, contract_address, account)?),
} => to_json_binary(&query_get_orders(deps, contract_address, account)?),
QueryMsg::GetOrderById {
contract_address,
price_denom,
asset_denom,
id,
} => to_binary(&query_get_order_by_id(
} => to_json_binary(&query_get_order_by_id(
deps,
contract_address,
price_denom,
Expand All @@ -418,17 +424,17 @@ pub fn query(deps: Deps<SeiQueryWrapper>, _env: Env, msg: QueryMsg) -> StdResult
contract_address,
price_denom,
asset_denom,
} => to_binary(&query_get_latest_price(
} => to_json_binary(&query_get_latest_price(
deps,
contract_address,
price_denom,
asset_denom,
)?),
QueryMsg::GetDenomAuthorityMetadata { denom } => {
to_binary(&query_denom_authority_metadata(deps, denom)?)
to_json_binary(&query_denom_authority_metadata(deps, denom)?)
}
QueryMsg::GetDenomsFromCreator { creator } => {
to_binary(&query_denoms_from_creator(deps, creator)?)
to_json_binary(&query_denoms_from_creator(deps, creator)?)
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion contracts/sei-tester/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod contract;
pub mod msg;
pub mod types;
pub mod state;
pub mod types;
13 changes: 3 additions & 10 deletions contracts/sei-tester/src/msg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,9 @@ pub enum ExecuteMsg {
Burn {},
ChangeAdmin {},
SetMetadata {},
TestOccIteratorWrite {
values: Vec<(u64,u64)>
},
TestOccIteratorRange {
start: u64,
end: u64,
},
TestOccParallelism {
value: u64,
}
TestOccIteratorWrite { values: Vec<(u64, u64)> },
TestOccIteratorRange { start: u64, end: u64 },
TestOccParallelism { value: u64 },
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
Expand Down
17 changes: 5 additions & 12 deletions contracts/sei-tester/src/state.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
use cosmwasm_std::{Addr, Decimal, Uint128, Uint64};
use cw_storage_plus::{Item, Map};
use schemars::JsonSchema;
use sei_cosmwasm::ExchangeRatesResponse;
use serde::{Deserialize, Serialize};
use cosmwasm_std::Addr;
use cw_storage_plus::Map;

pub const VALUES: Map<u64, u64> = Map::new("values");

pub const VALUES: Map<u64, u64> =
Map::new("values");
pub const USER_SUMS: Map<Addr, u64> = Map::new("user_sums");

pub const USER_SUMS: Map<Addr, u64> =
Map::new("user_sums");

pub const PARALLEL_VALS: Map<Addr, u64> =
Map::new("parallel_vals");
pub const PARALLEL_VALS: Map<Addr, u64> = Map::new("parallel_vals");
49 changes: 39 additions & 10 deletions contracts/sei-tester/tests/sei_tester_integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ use cw_multi_test::{
StakeKeeper, WasmKeeper,
};
use sei_cosmwasm::{
DenomOracleExchangeRatePair, DexPair, DexTwap, DexTwapsResponse, EpochResponse,
Cancellation, DenomOracleExchangeRatePair, DexPair, DexTwap, DexTwapsResponse, EpochResponse,
ExchangeRatesResponse, GetOrderByIdResponse, GetOrdersResponse, OracleExchangeRate,
OracleTwapsResponse, Order, OrderSimulationResponse, OrderStatus, OrderType, PositionDirection,
SeiMsg, SeiQuery, SeiQueryWrapper, SeiRoute, SudoMsg as SeiSudoMsg,
Expand Down Expand Up @@ -229,13 +229,6 @@ fn test_epoch_query() {
assert_eq!(res.epoch.current_epoch, 1);
assert_eq!(res.epoch.current_epoch_start_time, "".to_string());
assert_eq!(res.epoch.current_epoch_height, 1);

// // Also compiles but doesn't write to SeiModule
app.wasm_sudo(
sei_tester_addr.clone(),
&(SeiSudoMsg::NewBlock { epoch: 100 }),
)
.unwrap();
}

/// Dex Module - place and get orders
Expand Down Expand Up @@ -421,10 +414,24 @@ fn test_dex_module_integration_orders() {
// CancelOrders for a contract address that doesn't exist
let mut nonexistent_order_ids: Vec<u64> = Vec::new();
nonexistent_order_ids.push(3);
let cancellations: Vec<Cancellation> = nonexistent_order_ids
.iter()
.map(|id| -> Cancellation {
Cancellation {
id: *id,
contract_address: "test contract".to_string(),
price: Decimal::zero(),
price_denom: "pd".to_string(),
asset_denom: "ad".to_string(),
order_type: OrderType::Limit,
position_direction: PositionDirection::Long,
}
})
.collect();
let res = app.execute_multi(
Addr::unchecked(ADMIN),
vec![CosmosMsg::Custom(SeiMsg::CancelOrders {
order_ids: nonexistent_order_ids,
cancellations: cancellations,
contract_address: Addr::unchecked("fake_contract_addr".to_string()),
})],
);
Expand All @@ -434,11 +441,25 @@ fn test_dex_module_integration_orders() {
// CancelOrders for order id 1
let mut cancel_order_ids: Vec<u64> = Vec::new();
cancel_order_ids.push(0);
let cancellations: Vec<Cancellation> = cancel_order_ids
.iter()
.map(|id| -> Cancellation {
Cancellation {
id: *id,
contract_address: "test contract".to_string(),
price: Decimal::zero(),
price_denom: "pd".to_string(),
asset_denom: "ad".to_string(),
order_type: OrderType::Limit,
position_direction: PositionDirection::Long,
}
})
.collect();
let arr = app
.execute_multi(
Addr::unchecked(ADMIN),
vec![CosmosMsg::Custom(SeiMsg::CancelOrders {
order_ids: cancel_order_ids,
cancellations: cancellations,
contract_address: Addr::unchecked(&contract_addr),
})],
)
Expand Down Expand Up @@ -678,20 +699,23 @@ fn test_oracle_module_query_exchange_rate() {
oracle_exchange_rate: OracleExchangeRate {
exchange_rate: Decimal::percent(80),
last_update: Uint64::zero(),
last_update_timestamp: 0,
},
},
DenomOracleExchangeRatePair {
denom: "usei".to_string(),
oracle_exchange_rate: OracleExchangeRate {
exchange_rate: Decimal::percent(70),
last_update: Uint64::zero(),
last_update_timestamp: 0,
},
},
DenomOracleExchangeRatePair {
denom: "uusdc".to_string(),
oracle_exchange_rate: OracleExchangeRate {
exchange_rate: Decimal::percent(90),
last_update: Uint64::new(1),
last_update_timestamp: 0,
},
},
],
Expand All @@ -713,6 +737,7 @@ fn test_oracle_module_query_exchange_rate() {
OracleExchangeRate {
exchange_rate: Decimal::percent(70),
last_update: Uint64::zero(),
last_update_timestamp: 0,
}
);
}
Expand All @@ -722,6 +747,7 @@ fn test_oracle_module_query_exchange_rate() {
OracleExchangeRate {
exchange_rate: Decimal::percent(90),
last_update: Uint64::new(1),
last_update_timestamp: 0,
}
);
}
Expand All @@ -741,20 +767,23 @@ fn test_oracle_module_query_twaps() {
oracle_exchange_rate: OracleExchangeRate {
exchange_rate: Decimal::percent(80),
last_update: Uint64::new(1_571_797_411),
last_update_timestamp: 0,
},
},
DenomOracleExchangeRatePair {
denom: "usei".to_string(),
oracle_exchange_rate: OracleExchangeRate {
exchange_rate: Decimal::percent(70),
last_update: Uint64::zero(),
last_update_timestamp: 0,
},
},
DenomOracleExchangeRatePair {
denom: "uusdc".to_string(),
oracle_exchange_rate: OracleExchangeRate {
exchange_rate: Decimal::percent(90),
last_update: Uint64::new(1_571_797_415),
last_update_timestamp: 0,
},
},
],
Expand Down
1 change: 1 addition & 0 deletions packages/sei-cosmwasm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ schemars = "0.8.3"
serde = { version = "1.0.127", default-features = false, features = ["derive"] }
serde_repr = "0.1.8"
protobuf = { version = "=3.2.0", features = ["with-bytes"] }
cw20 = "1.1.2"

[dev-dependencies]
cosmwasm-schema = "1.0.0"
11 changes: 10 additions & 1 deletion packages/sei-cosmwasm/src/msg.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::sei_types::{Cancellation, DepositInfo, Metadata, Order, SettlementEntry};
use cosmwasm_std::{Addr, Coin, CosmosMsg, CustomMsg};
use cosmwasm_std::{Addr, Coin, CosmosMsg, CustomMsg, Uint128};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -41,6 +41,15 @@ pub enum SeiMsg {
SetMetadata {
metadata: Metadata,
},
DelegateCallEvm {
to: String,
data: String, // base64 encoded
},
CallEvm {
value: Uint128,
to: String,
data: String, // base64 encoded
},
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, JsonSchema)]
Expand Down
Loading

0 comments on commit a2fb892

Please sign in to comment.