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

feat: EVM account binding #761

Merged
merged 18 commits into from
Feb 20, 2024
Merged
Show file tree
Hide file tree
Changes from 12 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
33 changes: 31 additions & 2 deletions Cargo.lock

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

3 changes: 3 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ members = [
'pallets/democracy',
'runtime/hydradx/src/evm/evm-utility/macro',
'pallets/referrals',
'pallets/evm-accounts',
]

[workspace.dependencies]
Expand Down Expand Up @@ -80,6 +81,8 @@ pallet-bonds = { path = "pallets/bonds", default-features = false}
pallet-lbp = { path = "pallets/lbp", default-features = false}
pallet-xyk = { path = "pallets/xyk", default-features = false}
pallet-referrals = { path = "pallets/referrals", default-features = false}
pallet-evm-accounts = { path = "pallets/evm-accounts", default-features = false}
pallet-evm-accounts-rpc-runtime-api = { path = "pallets/evm-accounts/rpc/runtime-api", default-features = false}

hydra-dx-build-script-utils = { path = "utils/build-script-utils", default-features = false }
scraper = { path = "scraper", default-features = false }
Expand Down
5 changes: 2 additions & 3 deletions integration-tests/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "runtime-integration-tests"
version = "1.17.3"
version = "1.17.4"
description = "Integration tests"
authors = ["GalacticCouncil"]
edition = "2021"
Expand All @@ -21,8 +21,6 @@ pallet-omnipool-liquidity-mining = { workspace = true }
pallet-bonds = { workspace = true }
pallet-stableswap = { workspace = true }
pallet-referrals = { workspace = true }

# Warehouse dependencies
pallet-asset-registry = { workspace = true }
hydradx-traits = { workspace = true }
pallet-transaction-multi-payment = { workspace = true, features = ["evm"] }
Expand All @@ -38,6 +36,7 @@ pallet-dynamic-fees = { workspace = true }
pallet-staking = { workspace = true}
pallet-lbp = { workspace = true}
pallet-xyk = { workspace = true}
pallet-evm-accounts = { workspace = true}

pallet-treasury = { workspace = true }
pallet-democracy = { workspace = true }
Expand Down
227 changes: 226 additions & 1 deletion integration-tests/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ use hydradx_runtime::{
multicurrency::{Action, MultiCurrencyPrecompile},
Address, Bytes, EvmAddress, HydraDXPrecompiles,
},
AssetRegistry, Balances, CallFilter, Currencies, RuntimeCall, RuntimeOrigin, Tokens, TransactionPause, EVM,
AssetRegistry, Balances, CallFilter, Currencies, EVMAccounts, RuntimeCall, RuntimeOrigin, Tokens, TransactionPause,
EVM,
};
use orml_traits::MultiCurrency;
use pallet_evm::*;
Expand All @@ -24,6 +25,230 @@ use xcm_emulator::TestExt;

const TREASURY_ACCOUNT_INIT_BALANCE: Balance = 1000 * UNITS;

mod account_conversion {
use super::*;
use frame_support::{assert_noop, assert_ok};
use pretty_assertions::assert_eq;

#[test]
fn eth_address_should_convert_to_truncated_address_when_not_bound() {
TestNet::reset();

Hydra::execute_with(|| {
let evm_address = EVMAccounts::evm_address(&Into::<AccountId>::into(ALICE));
// truncated address
let substrate_address: AccountId = EVMAccounts::get_truncated_account_id(evm_address);

assert_eq!(ExtendedAddressMapping::into_account_id(evm_address), substrate_address);

assert_eq!(EVMAccounts::get_account_id(evm_address), substrate_address);
assert_eq!(EVMAccounts::bound_account_id(evm_address), None);
});
}

#[test]
fn eth_address_should_convert_to_full_address_when_bound() {
TestNet::reset();

Hydra::execute_with(|| {
let substrate_address: AccountId = Into::<AccountId>::into(ALICE);
let evm_address = EVMAccounts::evm_address(&substrate_address);

assert_ok!(EVMAccounts::bind_evm_address(hydradx_runtime::RuntimeOrigin::signed(
substrate_address.clone()
)));

assert_eq!(ExtendedAddressMapping::into_account_id(evm_address), substrate_address);

assert_eq!(EVMAccounts::get_account_id(evm_address), substrate_address);
assert_eq!(EVMAccounts::bound_account_id(evm_address), Some(substrate_address));
});
}

#[test]
fn bind_address_should_fail_when_already_bound() {
TestNet::reset();

Hydra::execute_with(|| {
assert_ok!(EVMAccounts::bind_evm_address(hydradx_runtime::RuntimeOrigin::signed(
ALICE.into()
)),);

assert_noop!(
EVMAccounts::bind_evm_address(hydradx_runtime::RuntimeOrigin::signed(ALICE.into())),
pallet_evm_accounts::Error::<hydradx_runtime::Runtime>::AddressAlreadyBound,
);
});
}

#[test]
fn bind_address_should_fail_when_nonce_is_not_zero() {
use pallet_evm_accounts::EvmNonceProvider;
TestNet::reset();

Hydra::execute_with(|| {
// Arrange
let evm_address = EVMAccounts::evm_address(&Into::<AccountId>::into(ALICE));
let truncated_address = EVMAccounts::get_truncated_account_id(evm_address);

assert_ok!(hydradx_runtime::Currencies::update_balance(
hydradx_runtime::RuntimeOrigin::root(),
truncated_address,
WETH,
100 * UNITS as i128,
));

let data =
hex!["4d0045544800d1820d45118d78d091e685490c674d7596e62d1f0000000000000000140000000f0000c16ff28623"]
.to_vec();

// Act
assert_ok!(EVM::call(
evm_signed_origin(evm_address),
evm_address,
DISPATCH_ADDR,
data,
U256::from(0),
1000000,
gas_price(),
None,
Some(U256::zero()),
[].into()
));

// Assert
assert!(hydradx_runtime::evm::EvmNonceProvider::get_nonce(evm_address) != U256::zero());

assert_noop!(
EVMAccounts::bind_evm_address(hydradx_runtime::RuntimeOrigin::signed(ALICE.into())),
pallet_evm_accounts::Error::<hydradx_runtime::Runtime>::NonZeroNonce,
);
});
}

#[test]
fn truncated_address_should_be_used_in_evm_precompile_when_not_bound() {
TestNet::reset();

Hydra::execute_with(|| {
//Arrange
let evm_address = EVMAccounts::evm_address(&Into::<AccountId>::into(ALICE));
let truncated_address = EVMAccounts::get_truncated_account_id(evm_address);

assert_ok!(hydradx_runtime::Currencies::update_balance(
hydradx_runtime::RuntimeOrigin::root(),
truncated_address,
HDX,
100 * UNITS as i128,
));

let data = EvmDataWriter::new_with_selector(Action::BalanceOf)
.write(Address::from(evm_address))
.build();

let mut handle = MockHandle {
input: data,
context: Context {
address: evm_address,
caller: evm_address,
apparent_value: U256::from(0),
},
core_address: native_asset_ethereum_address(),
is_static: true,
};

//Act
let result = MultiCurrencyPrecompile::<hydradx_runtime::Runtime>::execute(&mut handle);

//Assert

// 100 * UNITS, balance of truncated_address
let expected_output = hex! {"
00000000000000000000000000000000 000000000000000000005AF3107A4000
"};

assert_eq!(
result,
Ok(PrecompileOutput {
exit_status: ExitSucceed::Returned,
output: expected_output.to_vec()
})
);
});
}

#[test]
fn full_address_should_be_used_in_evm_precompile_when_bound() {
TestNet::reset();

Hydra::execute_with(|| {
//Arrange
let evm_address = EVMAccounts::evm_address(&Into::<AccountId>::into(ALICE));

let data = EvmDataWriter::new_with_selector(Action::BalanceOf)
.write(Address::from(evm_address))
.build();

let mut handle = MockHandle {
input: data,
context: Context {
address: evm_address,
caller: evm_address,
apparent_value: U256::from(0),
},
core_address: native_asset_ethereum_address(),
is_static: true,
};

//Act
assert_ok!(EVMAccounts::bind_evm_address(hydradx_runtime::RuntimeOrigin::signed(
ALICE.into()
)),);

let result = MultiCurrencyPrecompile::<hydradx_runtime::Runtime>::execute(&mut handle);

//Assert

// 1000 * UNITS, balance of ALICE
let expected_output = hex! {"
00000000000000000000000000000000 000000000000000000038D7EA4C68000
"};
assert_eq!(
result,
Ok(PrecompileOutput {
exit_status: ExitSucceed::Returned,
output: expected_output.to_vec()
})
);
});
}

#[test]
fn bind_evm_address_tx_cost_should_be_increased_by_fee_multiplier() {
// the fee multiplier is in the pallet evm accounts config and the desired fee is 10 HDX
use pallet_transaction_payment::{Multiplier, NextFeeMultiplier};
use primitives::constants::currency::UNITS;
use sp_runtime::FixedPointNumber;

TestNet::reset();

Hydra::execute_with(|| {
let call = pallet_evm_accounts::Call::<hydradx_runtime::Runtime>::bind_evm_address {};
let info = call.get_dispatch_info();
// convert to outer call
let call = hydradx_runtime::RuntimeCall::EVMAccounts(call);
let len = call.using_encoded(|e| e.len()) as u32;

NextFeeMultiplier::<hydradx_runtime::Runtime>::put(Multiplier::saturating_from_integer(1));
let fee_raw = hydradx_runtime::TransactionPayment::compute_fee_details(len, &info, 0);
let fee = fee_raw.final_fee();

// simple test that the fee is approximately 10 HDX
assert!(fee / UNITS == 10);
});
}
}

mod currency_precompile {
use super::*;
use pretty_assertions::assert_eq;
Expand Down
2 changes: 1 addition & 1 deletion integration-tests/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ mod transact_call_filter;
mod vesting;
mod xcm_defer;
mod xcm_rate_limiter;
mod xyk;

#[macro_export]
macro_rules! assert_balance {
Expand All @@ -37,4 +38,3 @@ macro_rules! assert_reserved_balance {
assert_eq!(Currencies::reserved_balance($asset, &$who), $amount);
}};
}
mod xyk;
9 changes: 6 additions & 3 deletions integration-tests/src/polkadot_test_net.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
pub use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin};
use hex_literal::hex;
use hydradx_runtime::{evm::WETH_ASSET_LOCATION, Referrals, RuntimeOrigin};
use pallet_evm::AddressMapping;
use pallet_referrals::{FeeDistribution, Level};
pub use polkadot_primitives::v5::{BlockNumber, MAX_CODE_SIZE, MAX_POV_SIZE};
use polkadot_runtime_parachains::configuration::HostConfiguration;
Expand All @@ -33,18 +32,22 @@ pub const CHARLIE: [u8; 32] = [6u8; 32];
pub const DAVE: [u8; 32] = [7u8; 32];
pub const UNKNOWN: [u8; 32] = [8u8; 32];

// Private key: 42d8d953e4f9246093a33e9ca6daa078501012f784adfe4bbed57918ff13be14
// Address: 0x222222ff7Be76052e023Ec1a306fCca8F9659D80
// Account Id: 45544800222222ff7be76052e023ec1a306fcca8f9659d800000000000000000
// SS58(63): 7KATdGakyhfBGnAt3XVgXTL7cYjzRXeSZHezKNtENcbwWibb
pub fn evm_address() -> H160 {
hex!["222222ff7Be76052e023Ec1a306fCca8F9659D80"].into()
}
pub fn evm_account() -> AccountId {
ExtendedAddressMapping::into_account_id(evm_address())
hydradx_runtime::EVMAccounts::get_truncated_account_id(evm_address())
}

pub fn evm_address2() -> H160 {
hex!["222222ff7Be76052e023Ec1a306fCca8F9659D81"].into()
}
pub fn evm_account2() -> AccountId {
ExtendedAddressMapping::into_account_id(evm_address2())
hydradx_runtime::EVMAccounts::get_truncated_account_id(evm_address2())
}
pub fn evm_signed_origin(address: H160) -> RuntimeOrigin {
// account has to be truncated to spoof it as an origin
Expand Down
Loading
Loading