Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 158 additions & 0 deletions contracts/simple_dex/Cargo.lock

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

5 changes: 4 additions & 1 deletion contracts/simple_dex/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ openbrush = { git = "https://github.com/Supercolony-net/openbrush-contracts.git"
access_control = { path = "../access_control", default-features = false, features = ["ink-as-dependency"] }
game_token = { path = "../game_token", default-features = false, features = ["ink-as-dependency"] }

[dev-dependencies]
proptest = "1.0"

[lib]
name = "simple_dex"
path = "lib.rs"
Expand All @@ -47,4 +50,4 @@ std = [
ink-as-dependency = []

[profile.dev]
codegen-units = 16
codegen-units = 16
44 changes: 43 additions & 1 deletion contracts/simple_dex/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -375,8 +375,22 @@ mod simple_dex {
let balance_token_in = self.balance_of(token_in, this)?;
let balance_token_out = self.balance_of(token_out, this)?;

Self::_out_given_in(
amount_token_in,
balance_token_in,
balance_token_out,
self.swap_fee_percentage,
)
}

fn _out_given_in(
amount_token_in: Balance,
balance_token_in: Balance,
balance_token_out: Balance,
swap_fee_percentage: Balance,
) -> Result<Balance, DexError> {
let op0 = amount_token_in
.checked_mul(self.swap_fee_percentage)
.checked_mul(swap_fee_percentage)
.ok_or(DexError::Arithmethic)?;

let op1 = balance_token_in
Expand All @@ -395,6 +409,8 @@ mod simple_dex {

balance_token_out
.checked_sub(op4)
// If the division is not even, leave the 1 unit of dust in the exchange instead of paying it out.
.and_then(|result| result.checked_sub(if op3 % op2 > 0 { 1 } else { 0 }))
.ok_or(DexError::Arithmethic)
}

Expand Down Expand Up @@ -509,4 +525,30 @@ mod simple_dex {
SimpleDex::new()
}
}

#[cfg(test)]
mod test {
use proptest::prelude::*;

use super::*;

proptest! {
#[test]
fn rounding_benefits_dex(
balance_token_a in 1..1000u128,
balance_token_b in 1..1000u128,
pay_token_a in 1..1000u128,
fee_percentage in 0..10u128
) {
let get_token_b =
SimpleDex::_out_given_in(pay_token_a, balance_token_a, balance_token_b, fee_percentage).unwrap();
let balance_token_a = balance_token_a + pay_token_a;
let balance_token_b = balance_token_b - get_token_b;
let get_token_a =
SimpleDex::_out_given_in(get_token_b, balance_token_b, balance_token_a, fee_percentage).unwrap();

assert!(get_token_a <= pay_token_a);
}
}
}
}