Skip to content

Commit

Permalink
Merge pull request #8 from ComposableFi/dz/6
Browse files Browse the repository at this point in the history
bug: fixing simulator randomness and roudning
  • Loading branch information
dzmitry-lahoda authored Nov 22, 2023
2 parents b2ede69 + e3010f8 commit 800e3a2
Show file tree
Hide file tree
Showing 14 changed files with 256 additions and 113 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions contracts/cosmwasm/order/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,5 @@ cvm = { path = "../../../crates/cvm", default-features = false, features = [
"std",
"json-schema",
] }

tuples ={ workspace = true }
44 changes: 31 additions & 13 deletions contracts/cosmwasm/order/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod prelude;
mod store;
mod types;

use prelude::*;
use store::*;
pub use types::*;

Expand Down Expand Up @@ -247,28 +248,32 @@ impl OrderContract<'_> {
let at_least_one = all_orders.first().expect("at least one");

// normalize pair
let mut ab = [
let mut ab = (
at_least_one.given().denom.clone(),
at_least_one.wants().denom.clone(),
];
ab.sort();
let [a, b] = ab;
);
ab.sort_selection();

// add solution to total solutions
let possible_solution = SolutionItem {
pair: (a.clone(), b.clone()),
pair: ab.clone(),
msg,
block_added: ctx.env.block.height,
};

self.solutions.save(
ctx.deps.storage,
&(a.clone(), b.clone(), ctx.info.sender.clone().to_string()),
&(
ab.clone().0,
ab.clone().1,
ctx.info.sender.clone().to_string(),
),
&possible_solution,
)?;
let solution_upserted = Event::new("mantis-solution-upserted")
.add_attribute("pair", &format!("{}{}", a, b))
.add_attribute("solver", &ctx.info.sender.to_string());
.add_attribute("token_a", ab.clone().0)
.add_attribute("token_b", ab.clone().1)
.add_attribute("solver_address", &ctx.info.sender.to_string());
ctx.deps.api.debug(&format!(
"mantis::solution::upserted {:?}",
&solution_upserted
Expand All @@ -277,7 +282,7 @@ impl OrderContract<'_> {
// get all solution for pair
let all_solutions: Result<Vec<SolutionItem>, _> = self
.solutions
.prefix((a.clone(), b.clone()))
.prefix(ab.clone())
.range(ctx.deps.storage, None, None, Order::Ascending)
.map(|r| r.map(|(_, solution)| solution))
.collect();
Expand All @@ -289,6 +294,7 @@ impl OrderContract<'_> {
// pick up optimal solution with solves with bank
let mut a_in = 0;
let mut b_in = 0;
let (a, b) = ab.clone();
let mut transfers = vec![];
let mut solution_item: SolutionItem = possible_solution;
for solution in all_solutions {
Expand Down Expand Up @@ -338,9 +344,15 @@ impl OrderContract<'_> {
};

let solution_chosen = Event::new("mantis-solution-chosen")
.add_attribute("pair", format!("{}{}", a, b))
.add_attribute("solver", ctx.info.sender.to_string());
let transfers = self.fill(ctx.deps.storage, transfers)?;
.add_attribute("token_a", ab.clone().0)
.add_attribute("token_b", ab.clone().1)
.add_attribute("solver_address", &ctx.info.sender.to_string());
let transfers = self.fill(
ctx.deps.storage,
transfers,
ctx.info.sender.to_string(),
solution_item.block_added,
)?;
ctx.deps
.api
.debug(&format!("mantis-solution-chosen: {:?}", &solution_chosen));
Expand Down Expand Up @@ -402,20 +414,26 @@ impl OrderContract<'_> {
&self,
storage: &mut dyn Storage,
cows: Vec<CowFilledOrder>,
solver_address: String,
solution_block_added: u64,
) -> StdResult<Vec<CowFillResult>> {
let mut results = vec![];
for (transfer, order) in cows.into_iter() {
let mut order: OrderItem = self.orders.load(storage, order.u128())?;
order.fill(&transfer);
order.fill(transfer.amount);
let event = if order.given.amount.is_zero() {
self.orders.remove(storage, order.order_id.u128());
Event::new("mantis-order-filled-full")
.add_attribute("order_id", order.order_id.to_string())
.add_attribute("solver_address", solver_address.clone())
.add_attribute("solution_block_added", solution_block_added.to_string())
} else {
self.orders.save(storage, order.order_id.u128(), &order)?;
Event::new("mantis-order-filled-parts")
.add_attribute("order_id", order.order_id.to_string())
.add_attribute("amount", transfer.amount.to_string())
.add_attribute("solver_address", solver_address.clone())
.add_attribute("solution_block_added", solution_block_added.to_string())
};
let transfer = BankMsg::Send {
to_address: order.owner.to_string(),
Expand Down
1 change: 1 addition & 0 deletions contracts/cosmwasm/order/src/prelude.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
pub use cosmwasm_schema::cw_serde;
pub use cosmwasm_std::Uint128;
pub use cosmwasm_std::{Addr, Coin};
pub use tuples::*;
26 changes: 15 additions & 11 deletions contracts/cosmwasm/order/src/types.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use cosmwasm_std::{ensure, BankMsg, Event, StdError, StdResult, Uint64};
use cosmwasm_std::{ensure, BankMsg, Event, OverflowError, StdError, StdResult, Uint64};
use cvm::{instruction::ExchangeId, network::NetworkId};

use crate::prelude::*;
Expand Down Expand Up @@ -31,9 +31,16 @@ pub struct OrderItem {
}

impl OrderItem {
pub fn fill(&mut self, transfer: &Coin) {
self.msg.wants.amount -= transfer.amount;
self.given.amount -= transfer.amount * self.given.amount / self.msg.wants.amount;
pub fn fill(&mut self, wanted_transfer: Uint128) {
// was given more or exact wanted - user happy
if wanted_transfer >= self.msg.wants.amount {
self.given.amount = <_>::default();
self.msg.wants.amount = <_>::default();
} else {
self.msg.wants.amount = self.msg.wants.amount - wanted_transfer;
let given_reduction = wanted_transfer * self.given.amount / self.msg.wants.amount;
self.given.amount = self.given.amount - given_reduction;
}
}
}

Expand Down Expand Up @@ -83,6 +90,8 @@ pub struct SolutionItem {
pub struct SolutionSubMsg {
#[serde(skip_serializing_if = "Vec::is_empty", default)]
pub cows: Vec<Cow>,
/// all CoWs ensured to be solved against one optimal price
pub optimal_price: (u64, u64),
/// must adhere Connection.fork_join_supported, for now it is always false (it restrict set of
/// routes possible)
#[serde(skip_serializing_if = "Option::is_none", default)]
Expand Down Expand Up @@ -128,14 +137,9 @@ pub struct SolvedOrder {
}

impl SolvedOrder {
/// if given less, it will be partial, validated via bank
/// if given more, it is over limit - user is happy, and total verified via bank
pub fn new(order: OrderItem, solution: Cow) -> StdResult<Self> {
ensure!(
order.msg.wants.amount <= solution.given,
StdError::generic_err(format!(
"user limit was not satisfied {order:?} {solution:?}"
))
);

Ok(Self { order, solution })
}

Expand Down
5 changes: 1 addition & 4 deletions devnet.sh
Original file line number Diff line number Diff line change
@@ -1,5 +1,2 @@
#!/bin/sh
#clear && cargo run --bin mantis -- --centauri "http://localhost:26657" --osmosis "localhost:36657" --neutron "localhost:46657" --cvm-contract "centauri1" --wallet "mnemonic" --order-contract "centauri1"


RUST_TRACE=trace cargo run --bin mantis -- --rpc-centauri "https://composable-rpc.polkachu.com:443" --grpc-centauri "https://composable-grpc.polkachu.com:22290" --osmosis "todo" --neutron "todo" --cvm-contract "centauri1wpf2szs4uazej8pe7g8vlck34u24cvxx7ys0esfq6tuw8yxygzuqpjsn0d" --wallet "$WALLET" --order-contract "centauri1lnyecncq9akyk8nk0qlppgrq6yxktr68483ahryn457x9ap4ty2sthjcyt" --simulate "1000000ppica,1ibc/EF48E6B1A1A19F47ECAEA62F5670C37C0580E86A9E88498B7E393EB6F49F33C0"
RUST_BACKTRACE=1 RUST_TRACE=trace cargo run --bin mantis -- --rpc-centauri "https://composable-rpc.polkachu.com:443" --grpc-centauri "https://composable-grpc.polkachu.com:22290" --osmosis "todo" --neutron "todo" --cvm-contract "centauri1wpf2szs4uazej8pe7g8vlck34u24cvxx7ys0esfq6tuw8yxygzuqpjsn0d" --wallet "$WALLET" --order-contract "centauri1cpcyl3nhp74vux7h9ux7egwm3gpy8tk3p556v90tt8le30z2qmvsft5ftk" --simulate "200000ppica,3ibc/EF48E6B1A1A19F47ECAEA62F5670C37C0580E86A9E88498B7E393EB6F49F33C0"
5 changes: 5 additions & 0 deletions flake.nix
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@
rust.rustc
devour-flake
];
shellHook = ''
if [[ -f ./.env ]]; then
source ./.env
fi
'';
};
formatter = pkgs.alejandra;
packages = rec {
Expand Down
Loading

0 comments on commit 800e3a2

Please sign in to comment.