Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tokenize negative signed integers #333

Merged
merged 1 commit into from
Mar 24, 2020
Merged
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
23 changes: 21 additions & 2 deletions src/contract/tokens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,17 @@ macro_rules! int_tokenizable {
}

fn into_token(self) -> Token {
Token::$token(self.into())
// this should get optimized away by the compiler for unsigned integers
#[allow(unused_comparisons)]
let data = if self < 0 {
// NOTE: Rust does sign extension when converting from a
// signed integer to an unsigned integer, so:
// `-1u8 as u128 == u128::max_value()`
U256::from(self as u128) | U256([0, 0, u64::max_value(), u64::max_value()])
} else {
self.into()
};
Token::$token(data)
}
}
};
Expand Down Expand Up @@ -409,7 +419,7 @@ impl_fixed_types!(1024);

#[cfg(test)]
mod tests {
use super::Detokenize;
use super::{Detokenize, Tokenizable};
use crate::types::{Address, U256};
use ethabi::Token;

Expand Down Expand Up @@ -457,4 +467,13 @@ mod tests {
assert_eq!(data[2][0], 3);
assert_eq!(data[7][0], 8);
}

#[test]
fn should_sign_extend_negative_integers() {
assert_eq!((-1i8).into_token(), Token::Int(U256::MAX));
assert_eq!((-2i16).into_token(), Token::Int(U256::MAX - 1));
assert_eq!((-3i32).into_token(), Token::Int(U256::MAX - 2));
assert_eq!((-4i64).into_token(), Token::Int(U256::MAX - 3));
assert_eq!((-5i128).into_token(), Token::Int(U256::MAX - 4));
}
}