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

fix EVM <=> TAO balance transfer precision #984

Merged
merged 20 commits into from
Nov 15, 2024
Merged
Show file tree
Hide file tree
Changes from 14 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
101 changes: 91 additions & 10 deletions runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1119,18 +1119,34 @@ parameter_types! {
const EVM_DECIMALS_FACTOR: u64 = 1_000_000_000_u64;

pub struct SubtensorEvmBalanceConverter;

impl BalanceConverter for SubtensorEvmBalanceConverter {
/// Convert from Substrate balance (u64) to EVM balance (U256)
fn into_evm_balance(value: U256) -> Option<U256> {
U256::from(UniqueSaturatedInto::<u128>::unique_saturated_into(value))
value
.checked_mul(U256::from(EVM_DECIMALS_FACTOR))
.and_then(|evm_value| {
// Ensure the result fits within the maximum U256 value
if evm_value <= U256::MAX {
Some(evm_value)
} else {
None
}
})
}

/// Convert from EVM balance (U256) to Substrate balance (u64)
fn into_substrate_balance(value: U256) -> Option<U256> {
if value <= U256::from(u64::MAX) {
value.checked_div(U256::from(EVM_DECIMALS_FACTOR))
} else {
None
}
value
.checked_div(U256::from(EVM_DECIMALS_FACTOR))
.and_then(|substrate_value| {
// Ensure the result fits within the TAO balance type (u64)
if substrate_value <= U256::from(u64::MAX) {
Some(substrate_value)
} else {
None
}
})
}
}

Expand Down Expand Up @@ -2003,9 +2019,6 @@ impl_runtime_apis! {
}
}

// #[cfg(test)]
// mod tests {

#[test]
fn check_whitelist() {
use crate::*;
Expand All @@ -2028,4 +2041,72 @@ fn check_whitelist() {
// System Events
assert!(whitelist.contains("26aa394eea5630e07c48ae0c9558cef780d41e5e16056765bc8461851072c9d7"));
}
// }

#[test]
fn test_into_substrate_balance_valid() {
// Valid conversion within u64 range
let evm_balance = U256::from(1_000_000_000_000_000_000u128); // 1 TAO in EVM
let expected_substrate_balance = U256::from(1_000_000_000u128); // 1 TAO in Substrate

let result = SubtensorEvmBalanceConverter::into_substrate_balance(evm_balance);
assert_eq!(result, Some(expected_substrate_balance));
}

#[test]
fn test_into_substrate_balance_large_value() {
// Maximum valid balance for u64
let evm_balance = U256::from(u64::MAX) * U256::from(EVM_DECIMALS_FACTOR); // Max u64 TAO in EVM
let expected_substrate_balance = U256::from(u64::MAX);

let result = SubtensorEvmBalanceConverter::into_substrate_balance(evm_balance);
assert_eq!(result, Some(expected_substrate_balance));
}

#[test]
fn test_into_substrate_balance_exceeds_u64() {
// EVM balance that exceeds u64 after conversion
let evm_balance = (U256::from(u64::MAX) + U256::from(1)) * U256::from(EVM_DECIMALS_FACTOR);

let result = SubtensorEvmBalanceConverter::into_substrate_balance(evm_balance);
assert_eq!(result, None); // Exceeds u64, should return None
}

#[test]
fn test_into_substrate_balance_precision_loss() {
// EVM balance with precision loss
let evm_balance = U256::from(1_000_000_000_123_456_789u128); // 1 TAO + extra precision in EVM
let expected_substrate_balance = U256::from(1_000_000_000u128); // Truncated to 1 TAO in Substrate

let result = SubtensorEvmBalanceConverter::into_substrate_balance(evm_balance);
assert_eq!(result, Some(expected_substrate_balance));
}

#[test]
fn test_into_substrate_balance_zero_value() {
// Zero balance should convert to zero
let evm_balance = U256::from(0);
let expected_substrate_balance = U256::from(0);

let result = SubtensorEvmBalanceConverter::into_substrate_balance(evm_balance);
assert_eq!(result, Some(expected_substrate_balance));
}

#[test]
fn test_into_evm_balance_valid() {
// Valid conversion from Substrate to EVM
let substrate_balance = U256::from(1_000_000_000u128); // 1 TAO in Substrate
let expected_evm_balance = U256::from(1_000_000_000_000_000_000u128); // 1 TAO in EVM

let result = SubtensorEvmBalanceConverter::into_evm_balance(substrate_balance);
assert_eq!(result, Some(expected_evm_balance));
}

#[test]
fn test_into_evm_balance_overflow() {
// Substrate balance larger than u64::MAX but valid within U256
let substrate_balance = U256::from(u64::MAX) + U256::from(1); // Large balance
let expected_evm_balance = substrate_balance * U256::from(EVM_DECIMALS_FACTOR);

let result = SubtensorEvmBalanceConverter::into_evm_balance(substrate_balance);
assert_eq!(result, Some(expected_evm_balance)); // Should return the scaled value
}
28 changes: 19 additions & 9 deletions runtime/src/precompiles/balance_transfer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,28 +25,38 @@ impl BalanceTransferPrecompile {
// Forward all received value to the destination address
let amount: U256 = handle.context().apparent_value;

// This is hardcoded hashed address mapping of
// 0x0000000000000000000000000000000000000800 to ss58 public key
// i.e. the contract sends funds it received to the destination address
// from the method parameter
let address_bytes_src: [u8; 32] = [
// Use BalanceConverter to convert EVM amount to Substrate balance
let amount_sub =
<Runtime as pallet_evm::Config>::BalanceConverter::into_substrate_balance(amount)
.ok_or(ExitError::OutOfFund)?;

if amount_sub.is_zero() {
return Ok(PrecompileOutput {
exit_status: ExitSucceed::Returned,
output: vec![],
});
}

// This is a hardcoded hashed address mapping of
// 0x0000000000000000000000000000000000000800 to an ss58 public key
// i.e., the contract sends funds it received to the destination address
// from the method parameter.
const ADDRESS_BYTES_SRC: [u8; 32] = [
0x07, 0xec, 0x71, 0x2a, 0x5d, 0x38, 0x43, 0x4d, 0xdd, 0x03, 0x3f, 0x8f, 0x02, 0x4e,
0xcd, 0xfc, 0x4b, 0xb5, 0x95, 0x1c, 0x13, 0xc3, 0x08, 0x5c, 0x39, 0x9c, 0x8a, 0x5f,
0x62, 0x93, 0x70, 0x5d,
];
let address_bytes_dst: &[u8] = get_slice(txdata, 4, 36)?;
let account_id_src = bytes_to_account_id(&address_bytes_src)?;
let account_id_src = bytes_to_account_id(&ADDRESS_BYTES_SRC)?;
let account_id_dst = bytes_to_account_id(address_bytes_dst)?;
let amount_sub =
<Runtime as pallet_evm::Config>::BalanceConverter::into_substrate_balance(amount)
.ok_or(ExitError::OutOfFund)?;

let call =
RuntimeCall::Balances(pallet_balances::Call::<Runtime>::transfer_allow_death {
dest: account_id_dst.into(),
value: amount_sub.unique_saturated_into(),
});

// Dispatch the call
let result = call.dispatch(RawOrigin::Signed(account_id_src).into());
if result.is_err() {
return Err(PrecompileFailure::Error {
Expand Down
Loading