Skip to content

Commit

Permalink
auth check
Browse files Browse the repository at this point in the history
  • Loading branch information
jbernal87 committed Feb 29, 2024
1 parent be67c71 commit 21a8bc7
Show file tree
Hide file tree
Showing 6 changed files with 194 additions and 25 deletions.
1 change: 0 additions & 1 deletion Cargo.lock

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

2 changes: 1 addition & 1 deletion contracts/injective-cosmwasm-mock/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ serde = { version = "1.0.196", default-features = false, features =
thiserror = { version = "1.0.56" }
protobuf = "3.3.0"
prost = "0.11.9"
injective-protobuf = { path = "../../packages/injective-protobuf" }
injective-std = { version = "0.1.5" }

[dev-dependencies]
injective-test-tube = "1.1.7"
Expand Down
61 changes: 40 additions & 21 deletions contracts/injective-cosmwasm-mock/src/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ use crate::{
error::ContractError,
msg::{ExecuteMsg, InstantiateMsg, QueryMsg},
};
use cosmwasm_std::{to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, SubMsg};
use cosmwasm_std::{to_json_binary, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, SubMsg, ReplyOn, Reply};
use cw2::set_contract_version;
use injective_cosmwasm::{create_deposit_msg, InjectiveMsgWrapper, InjectiveQuerier, InjectiveQueryWrapper};
use injective_cosmwasm::{create_deposit_msg, create_spot_market_order_msg, InjectiveMsgWrapper, InjectiveQuerier, InjectiveQueryWrapper, OrderInfo, OrderType, SpotOrder};


#[cfg(not(feature = "library"))]
use cosmwasm_std::entry_point;
use injective_std::types::injective::exchange::v1beta1::MsgCreateSpotLimitOrder;
use injective_math::FPDecimal;

const CONTRACT_NAME: &str = "crates.io:injective:dummy";
const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION");
Expand All @@ -34,25 +34,28 @@ pub fn execute(
Ok(Response::new().add_message(create_deposit_msg(env.contract.address, subaccount_id, amount)))
}
ExecuteMsg::TestTraderTransientSpotOrders { market_id, subaccount_id } => {
Ok(Response::new().add_submessage( SubMsg::reply_on_success {
let order_info = OrderInfo{
subaccount_id,
fee_recipient: None,
price: FPDecimal::must_from_str("1"),
quantity: FPDecimal::must_from_str("1"),
cid: None,
};
let spot_order = SpotOrder{
market_id,
order_info,
order_type: OrderType::Buy,
trigger_price: None
};
let spot_order_message = create_spot_market_order_msg(info.sender, spot_order);

let spot_order_message = SubMsg{
id: CREATE_SPOT_ORDER_REPLY_ID,
msg:
MsgCreateSpotLimitOrder {
sender: info.sender.to_string(),
order: Some(injective_std::types::injective::exchange::v1beta1::SpotOrder {
market_id: market_id.into(),
order_info: Some(injective_std::types::injective::exchange::v1beta1::OrderInfo {
subaccount_id: subaccount_id.to_string(),
fee_recipient: info.sender.to_string(),
price: "10".to_string(),
quantity: "10".to_string(),
}),
order_type: 1,
trigger_price: "".to_string(),
}),
},
}))

msg: spot_order_message,
gas_limit: None,
reply_on: ReplyOn::Success,
};
Ok(Response::new().add_submessage(spot_order_message))
}
ExecuteMsg::TestTraderTransientDerivativeOrders { market_id, subaccount_id } => {

Check warning on line 60 in contracts/injective-cosmwasm-mock/src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `market_id`

Check warning on line 60 in contracts/injective-cosmwasm-mock/src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `subaccount_id`

Check warning on line 60 in contracts/injective-cosmwasm-mock/src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `market_id`

Check warning on line 60 in contracts/injective-cosmwasm-mock/src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `subaccount_id`
// to_json_binary(&querier.query_trader_transient_derivative_orders(&market_id, &subaccount_id)?)
Expand Down Expand Up @@ -136,3 +139,19 @@ pub fn query(deps: Deps<InjectiveQueryWrapper>, _env: Env, msg: QueryMsg) -> Std
}
}
}


#[cfg_attr(not(feature = "library"), entry_point)]
pub fn reply(
deps: DepsMut<InjectiveQueryWrapper>,
env: Env,

Check warning on line 147 in contracts/injective-cosmwasm-mock/src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `env`

Check warning on line 147 in contracts/injective-cosmwasm-mock/src/contract.rs

View workflow job for this annotation

GitHub Actions / Test Suite

unused variable: `env`
msg: Reply,
) -> Result<Response, ContractError> {
match msg.id {
CREATE_SPOT_ORDER_REPLY_ID => {
deps.api.debug("I am here");
Ok(Default::default())
},
_ => Err(ContractError::UnrecognizedReply(msg.id)),
}
}
2 changes: 2 additions & 0 deletions contracts/injective-cosmwasm-mock/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,6 @@ use thiserror::Error;
pub enum ContractError {
#[error("{0}")]
Std(#[from] StdError),
#[error("Unrecognized reply id: {0}")]
UnrecognizedReply(u64),
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use injective_std::types::injective::exchange::v1beta1::{
};
use injective_test_tube::injective_cosmwasm::get_default_subaccount_id_for_checked_address;
use injective_test_tube::{Account, Exchange, Module, RunnerResult, Wasm};
use crate::utils::execute_all_authorizations;

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
Expand Down Expand Up @@ -739,7 +740,34 @@ fn test_query_derivative_orders_to_cancel_up_to_amount() {}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
fn test_query_trader_transient_spot_orders() {}
fn test_query_trader_transient_spot_orders() {
let env = Setup::new(ExchangeType::Spot);
let wasm = Wasm::new(&env.app);
let market_id = env.market_id.unwrap();

let subaccount_id = checked_address_to_subaccount_id(&Addr::unchecked(env.users[0].account.address()), 0u32);

execute_all_authorizations(
&env.app,
&env.users[0].account,
env.contract_address.clone(),
);

let res = wasm.execute(
&env.contract_address,
&ExecuteMsg::TestTraderTransientSpotOrders {
market_id: MarketId::new(market_id).unwrap(),
subaccount_id: subaccount_id.clone(),

},
&[],
&env.users[0].account,
);

println!("{:?}", res);
assert_eq!(1,2);

}

#[test]
#[cfg_attr(not(feature = "integration"), ignore)]
Expand Down
123 changes: 122 additions & 1 deletion contracts/injective-cosmwasm-mock/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use crate::msg::InstantiateMsg;
use cosmwasm_std::{coin, Addr, Coin};
use injective_cosmwasm::{checked_address_to_subaccount_id, SubaccountId};
use injective_math::{scale::Scaled, FPDecimal};
use injective_test_tube::{Account, Bank, Exchange, Gov, InjectiveTestApp, Insurance, Module, Oracle, SigningAccount, Wasm};
use injective_test_tube::{Account, Authz, Bank, Exchange, ExecuteResponse, Gov, InjectiveTestApp, Insurance, Module, Oracle, Runner, SigningAccount, Wasm};

use prost::Message;
use std::{collections::HashMap, str::FromStr};
Expand All @@ -24,6 +24,9 @@ use injective_std::{
injective::oracle::v1beta1::{GrantPriceFeederPrivilegeProposal, MsgRelayPriceFeedPrice},
},
};
use injective_std::shim::Timestamp;
use injective_std::types::cosmos::authz::v1beta1::{GenericAuthorization, Grant, MsgGrant, MsgRevoke, MsgRevokeResponse};
use injective_std::types::cosmos::bank::v1beta1::SendAuthorization;
use injective_test_tube::injective_cosmwasm::get_default_subaccount_id_for_checked_address;

pub const EXCHANGE_DECIMALS: i32 = 18i32;
Expand Down Expand Up @@ -539,6 +542,124 @@ pub fn add_perp_initial_liquidity(app: &InjectiveTestApp, market_id: String) {
add_derivative_orders(app, market_id, get_initial_perp_liquidity_orders_vector(), None);
}

pub fn revoke_authorization(
app: &InjectiveTestApp,
granter: &SigningAccount,
grantee: String,
msg_type_url: String,
) {
let _res: ExecuteResponse<MsgRevokeResponse> = app
.execute_multiple(
&[(
MsgRevoke {
granter: granter.address(),
grantee,
msg_type_url,
},
MsgRevoke::TYPE_URL,
)],
granter,
)
.unwrap();
}

pub fn create_generic_authorization(
app: &InjectiveTestApp,
granter: &SigningAccount,
grantee: String,
msg: String,
expiration: Option<Timestamp>,
) {
let authz = Authz::new(app);

let mut buf = vec![];
GenericAuthorization::encode(&GenericAuthorization { msg }, &mut buf).unwrap();

authz
.grant(
MsgGrant {
granter: granter.address(),
grantee,
grant: Some(Grant {
authorization: Some(Any {
type_url: "/cosmos.authz.v1beta1.GenericAuthorization".to_string(),
value: buf.clone(),
}),
expiration,
}),
},
granter,
)
.unwrap();
}

pub fn create_send_authorization(
app: &InjectiveTestApp,
granter: &SigningAccount,
grantee: String,
amount: BaseCoin,
expiration: Option<Timestamp>,
) {
let authz = Authz::new(app);

let mut buf = vec![];
SendAuthorization::encode(
&SendAuthorization {
spend_limit: vec![amount],
allow_list: vec![],
},
&mut buf,
)
.unwrap();

authz
.grant(
MsgGrant {
granter: granter.address(),
grantee,
grant: Some(Grant {
authorization: Some(Any {
type_url: "/cosmos.bank.v1beta1.SendAuthorization".to_string(),
value: buf.clone(),
}),
expiration,
}),
},
granter,
)
.unwrap();
}

pub fn execute_all_authorizations(
app: &InjectiveTestApp,
granter: &SigningAccount,
grantee: String,
) {
create_generic_authorization(
app,
granter,
grantee.clone(),
"/injective.exchange.v1beta1.MsgCreateSpotMarketOrder".to_string(),
None,
);

create_generic_authorization(
app,
granter,
grantee.clone(),
"/injective.exchange.v1beta1.MsgCreateDerivativeMarketOrder".to_string(),
None,
);

create_generic_authorization(
app,
granter,
grantee,
"/injective.exchange.v1beta1.MsgWithdraw".to_string(),
None,
);
}

// Human Utils
pub fn human_to_proto(raw_number: &str, decimals: i32) -> String {
FPDecimal::must_from_str(&raw_number.replace('_', "")).scaled(18 + decimals).to_string()
Expand Down

0 comments on commit 21a8bc7

Please sign in to comment.