Skip to content

Commit

Permalink
big refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
dzmitry-lahoda committed Mar 11, 2024
1 parent a3879d3 commit 202e3eb
Show file tree
Hide file tree
Showing 9 changed files with 154 additions and 133 deletions.
86 changes: 4 additions & 82 deletions mantis/node/src/bin/mantis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ use mantis_node::{
cosmwasm::{smart_query, to_exec_signed, to_exec_signed_with_fund},
*,
},
mantis::randomize_order,
solve::randomize_order,
},
prelude::*,
solver::{orderbook::OrderList, solution::Solution},
Expand Down Expand Up @@ -127,73 +127,7 @@ async fn main() {
}
}

/// `assets` - is comma separate list. each entry is amount u64 glued with alphanumeric denomination
/// that is splitted into array of CosmWasm coins.
/// one coin is chosen as given,
/// from remaining 2 other coins one is chosen as wanted
/// amount of count is randomized around values
///
/// `write_client`
/// `order_contract` - orders are formed for give and want, and send to orders contract.
/// timeout is also randomized starting from 10 to 100 blocks
///
/// Also calls `timeout` so old orders are cleaned.
async fn simulate_order(
write_client: &mut CosmWasmWriteClient,
cosmos_query_client: &mut CosmosQueryClient,
order_contract: String,
coins_pair: String,
signing_key: &cosmrs::crypto::secp256k1::SigningKey,
rpc: &str,
tip: &Tip,
gas: Gas,
) {
println!("========================= simulate_order =========================");
let (msg, fund) = randomize_order(coins_pair, tip.block);

println!("msg: {:?}", msg);

let auth_info = simulate_and_set_fee(signing_key, &tip.account, gas).await;

let msg = to_exec_signed_with_fund(signing_key, order_contract, msg, fund);

let result = tx_broadcast_single_signed_msg(
msg.to_any().expect("proto"),
auth_info,
rpc,
signing_key,
&tip,
)
.await;

println!("simulated tx {:?}", result.height)
}

async fn cleanup(
write_client: &mut CosmWasmWriteClient,
cosmos_query_client: &mut CosmosQueryClient,
order_contract: String,
signing_key: &cosmrs::crypto::secp256k1::SigningKey,
rpc: &str,
tip: &Tip,
gas: Gas,
) {
println!("========================= cleanup =========================");
let auth_info = simulate_and_set_fee(signing_key, &tip.account, gas).await;
let msg = cw_mantis_order::ExecMsg::Timeout {
orders: vec![],
solutions: vec![],
};
let msg = to_exec_signed(signing_key, order_contract, msg);
tx_broadcast_single_signed_msg(
msg.to_any().expect("proto"),
auth_info,
rpc,
signing_key,
tip,
)
.await;
}

/// gets orders, groups by pairs
/// solves them using algorithm
Expand All @@ -214,7 +148,9 @@ async fn solve(
println!("========================= solve =========================");
let all_orders = get_all_orders(order_contract, cosmos_query_client, tip).await;
if !all_orders.is_empty() {
let cows_per_pair = mantis_node::mantis::mantis::do_cows(all_orders);
let cows_per_pair = mantis_node::mantis::solve::do_cows(all_orders);
let cows_cvm = mantis_node::mantis::solve::route(cows_per_pair, all_orders);
let cvm_rest = mantis_node::mantis::cosmos::client::get_cvm_routing_data(rpc).await;
for (cows, optimal_price) in cows_per_pair {
send_solution(
cows,
Expand Down Expand Up @@ -261,17 +197,3 @@ async fn send_solution(
println!("result: {:?}", result);
}

async fn get_all_orders(
order_contract: &String,
cosmos_query_client: &mut CosmWasmReadClient,
tip: &Tip,
) -> Vec<OrderItem> {
let query = cw_mantis_order::QueryMsg::GetAllOrders {};
let all_orders = smart_query::<_, Vec<OrderItem>>(order_contract, query, cosmos_query_client)
.await
.into_iter()
.filter(|x| x.msg.timeout > tip.block.value())
.collect::<Vec<OrderItem>>();
println!("all_orders: {:?}", all_orders);
all_orders
}
4 changes: 3 additions & 1 deletion mantis/node/src/mantis/args.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,9 @@ pub struct SharedArgs {

#[derive(clap::Parser, Debug)]
pub struct SimulateArgs {

#[arg(flatten)]
pub shared: SharedArgs,

/// CVM contract on Centauri. Optional, only if consider routing via cross chain CVM.
#[arg(long)]
pub cvm_contract: Option<String>,
Expand Down
31 changes: 31 additions & 0 deletions mantis/node/src/mantis/autopilot.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@

async fn cleanup(
write_client: &mut CosmWasmWriteClient,
cosmos_query_client: &mut CosmosQueryClient,
order_contract: String,
signing_key: &cosmrs::crypto::secp256k1::SigningKey,
rpc: &str,
tip: &Tip,
gas: Gas,
) {
println!("========================= cleanup =========================");
let auth_info = simulate_and_set_fee(signing_key, &tip.account, gas).await;
let msg = cw_mantis_order::ExecMsg::Timeout {
orders: vec![],
solutions: vec![],
};
let msg = to_exec_signed(signing_key, order_contract, msg);
tx_broadcast_single_signed_msg(
msg.to_any().expect("proto"),
auth_info,
rpc,
signing_key,
tip,
)
.await;
}

/// move protocol forwards, cranks auctions ending and also cleans up old orders
async fn move(){

}
14 changes: 14 additions & 0 deletions mantis/node/src/mantis/indexer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
async fn get_all_orders(
order_contract: &String,
cosmos_query_client: &mut CosmWasmReadClient,
tip: &Tip,
) -> Vec<OrderItem> {
let query = cw_mantis_order::QueryMsg::GetAllOrders {};
let all_orders = smart_query::<_, Vec<OrderItem>>(order_contract, query, cosmos_query_client)
.await
.into_iter()
.filter(|x| x.msg.timeout > tip.block.value())
.collect::<Vec<OrderItem>>();
println!("all_orders: {:?}", all_orders);
all_orders
}
2 changes: 1 addition & 1 deletion mantis/node/src/mantis/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pub mod args;
pub mod cosmos;
pub mod mantis;
pub mod solve;
pub mod blackbox;
94 changes: 94 additions & 0 deletions mantis/node/src/mantis/simulate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
use cosmrs::tendermint::block::Height;
use cw_mantis_order::{OrderItem, OrderSolution, OrderSubMsg};

use crate::{
prelude::*,
solver::{orderbook::OrderList, solution::Solution, types::OrderType},
};

use super::cosmos::client::timeout;

pub fn randomize_order(
coins_pair: String,
tip: Height,
) -> (cw_mantis_order::ExecMsg, cosmrs::Coin) {
let coins: Vec<_> = coins_pair
.split(',')
.map(|x| cosmwasm_std::Coin::from_str(x).expect("coin"))
.collect();

let coins = if rand::random::<bool>() {
(coins[0].clone(), coins[1].clone())
} else {
(coins[1].clone(), coins[0].clone())
};
let coin_0_random = randomize_coin(coins.0.amount.u128());
let coin_1_random = randomize_coin(coins.1.amount.u128());

let msg = cw_mantis_order::ExecMsg::Order {
msg: OrderSubMsg {
wants: cosmwasm_std::Coin {
amount: coin_0_random.into(),
denom: coins.0.denom.clone(),
},
transfer: None,
timeout: timeout(tip, 100),
min_fill: None,
},
};
let fund = cosmrs::Coin {
amount: coin_1_random.into(),
denom: cosmrs::Denom::from_str(&coins.1.denom).expect("denom"),
};
(msg, fund)
}

fn randomize_coin(coin_0_amount: u128) -> u128 {
let delta_0 = 1.max(coin_0_amount / 10);
let coin_0_random = rand_distr::Uniform::new(coin_0_amount - delta_0, coin_0_amount + delta_0);
let coin_0_random: u128 = coin_0_random.sample(&mut rand::thread_rng());
coin_0_random
}


/// `assets` - is comma separate list. each entry is amount u64 glued with alphanumeric denomination
/// that is splitted into array of CosmWasm coins.
/// one coin is chosen as given,
/// from remaining 2 other coins one is chosen as wanted
/// amount of count is randomized around values
///
/// `write_client`
/// `order_contract` - orders are formed for give and want, and send to orders contract.
/// timeout is also randomized starting from 10 to 100 blocks
///
/// Also calls `timeout` so old orders are cleaned.
async fn simulate_order(
write_client: &mut CosmWasmWriteClient,
cosmos_query_client: &mut CosmosQueryClient,
order_contract: String,
coins_pair: String,
signing_key: &cosmrs::crypto::secp256k1::SigningKey,
rpc: &str,
tip: &Tip,
gas: Gas,
) {
println!("========================= simulate_order =========================");
let (msg, fund) = randomize_order(coins_pair, tip.block);

println!("msg: {:?}", msg);

let auth_info = simulate_and_set_fee(signing_key, &tip.account, gas).await;

let msg = to_exec_signed_with_fund(signing_key, order_contract, msg, fund);

let result = tx_broadcast_single_signed_msg(
msg.to_any().expect("proto"),
auth_info,
rpc,
signing_key,
&tip,
)
.await;

println!("simulated tx {:?}", result.height)
}
Original file line number Diff line number Diff line change
Expand Up @@ -88,45 +88,3 @@ fn decimal_to_fraction(amount: Decimal) -> (u64, u64) {
)
}
}

pub fn randomize_order(
coins_pair: String,
tip: Height,
) -> (cw_mantis_order::ExecMsg, cosmrs::Coin) {
let coins: Vec<_> = coins_pair
.split(',')
.map(|x| cosmwasm_std::Coin::from_str(x).expect("coin"))
.collect();

let coins = if rand::random::<bool>() {
(coins[0].clone(), coins[1].clone())
} else {
(coins[1].clone(), coins[0].clone())
};
let coin_0_random = randomize_coin(coins.0.amount.u128());
let coin_1_random = randomize_coin(coins.1.amount.u128());

let msg = cw_mantis_order::ExecMsg::Order {
msg: OrderSubMsg {
wants: cosmwasm_std::Coin {
amount: coin_0_random.into(),
denom: coins.0.denom.clone(),
},
transfer: None,
timeout: timeout(tip, 100),
min_fill: None,
},
};
let fund = cosmrs::Coin {
amount: coin_1_random.into(),
denom: cosmrs::Denom::from_str(&coins.1.denom).expect("denom"),
};
(msg, fund)
}

fn randomize_coin(coin_0_amount: u128) -> u128 {
let delta_0 = 1.max(coin_0_amount / 10);
let coin_0_random = rand_distr::Uniform::new(coin_0_amount - delta_0, coin_0_amount + delta_0);
let coin_0_random: u128 = coin_0_random.sample(&mut rand::thread_rng());
coin_0_random
}
File renamed without changes.
14 changes: 7 additions & 7 deletions mantis/node/tests/mantis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
use cosmrs::tendermint::block::Height;
use cosmwasm_std::{testing::*, Addr, Binary, Coin, CustomQuery, DepsMut, MessageInfo, Uint128};
use cw_mantis_order::{sv::*, OrderItem, OrderSubMsg, SolutionSubMsg};
use mantis_node::{mantis::mantis::randomize_order, prelude::*};
use mantis_node::{mantis::solve::randomize_order, prelude::*};

#[test]
fn cows_scenarios() {
Expand Down Expand Up @@ -43,7 +43,7 @@ fn cows_scenarios() {
let orders: Binary =
cw_mantis_order::entry_points::query(deps.as_ref(), env.clone(), msg).unwrap();
let orders: Vec<OrderItem> = serde_json_wasm::from_slice(orders.as_slice()).unwrap();
let cows = mantis_node::mantis::mantis::do_cows(orders);
let cows = mantis_node::mantis::solve::do_cows(orders);
assert!(cows.is_empty());

// order 2 perfect match
Expand All @@ -63,7 +63,7 @@ fn cows_scenarios() {

/// try solve
let orders = query_all_orders(&deps, &env);
let cows_per_pair = mantis_node::mantis::mantis::do_cows(orders);
let cows_per_pair = mantis_node::mantis::solve::do_cows(orders);
do_solve(cows_per_pair, &mut deps, &env, info.clone());

let orders = query_all_orders(&deps, &env);
Expand Down Expand Up @@ -131,7 +131,7 @@ fn cows_scenarios() {

// solving
let orders = query_all_orders(&deps, &env);
let cows_per_pair = mantis_node::mantis::mantis::do_cows(orders);
let cows_per_pair = mantis_node::mantis::solve::do_cows(orders);
do_solve(cows_per_pair, &mut deps, &env, info.clone());
let orders = query_all_orders(&deps, &env);
assert!(orders.is_empty());
Expand Down Expand Up @@ -170,7 +170,7 @@ fn cows_scenarios() {

// second half
let orders = query_all_orders(&deps, &env);
let cows_per_pair = mantis_node::mantis::mantis::do_cows(orders);
let cows_per_pair = mantis_node::mantis::solve::do_cows(orders);
do_solve(cows_per_pair, &mut deps, &env, info.clone());
let orders = query_all_orders(&deps, &env);
assert!(!orders.is_empty());
Expand All @@ -191,7 +191,7 @@ fn cows_scenarios() {

// solving
let orders = query_all_orders(&deps, &env);
let cows_per_pair = mantis_node::mantis::mantis::do_cows(orders);
let cows_per_pair = mantis_node::mantis::solve::do_cows(orders);
do_solve(cows_per_pair, &mut deps, &env, info.clone());
let orders = query_all_orders(&deps, &env);
assert!(orders.is_empty());
Expand All @@ -214,7 +214,7 @@ fn cows_scenarios() {
}

let orders = query_all_orders(&deps, &env);
let cows_per_pair = mantis_node::mantis::mantis::do_cows(orders);
let cows_per_pair = mantis_node::mantis::solve::do_cows(orders);
let responses = do_solve(cows_per_pair, &mut deps, &env, info.clone());
let orders = query_all_orders(&deps, &env);
println!("solved {}", orders.len());
Expand Down

0 comments on commit 202e3eb

Please sign in to comment.