diff --git a/engine-precompiles/src/blake2.rs b/engine-precompiles/src/blake2.rs
index a6a300e03..2ba6b0b66 100644
--- a/engine-precompiles/src/blake2.rs
+++ b/engine-precompiles/src/blake2.rs
@@ -1,7 +1,7 @@
use evm::{Context, ExitError};
use crate::prelude::types::EthGas;
-use crate::prelude::{mem, Address, Borrowed, TryInto};
+use crate::prelude::{mem, types::Address, Borrowed, TryInto};
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};
/// Blake2 costs.
diff --git a/engine-precompiles/src/bn128.rs b/engine-precompiles/src/bn128.rs
index 5422ed2cd..ccb5073a4 100644
--- a/engine-precompiles/src/bn128.rs
+++ b/engine-precompiles/src/bn128.rs
@@ -1,5 +1,5 @@
-use crate::prelude::types::EthGas;
-use crate::prelude::{Address, Borrowed, PhantomData, Vec};
+use crate::prelude::types::{Address, EthGas};
+use crate::prelude::{Borrowed, PhantomData, Vec};
use crate::{Byzantium, EvmPrecompileResult, HardFork, Istanbul, Precompile, PrecompileOutput};
use evm::{Context, ExitError};
diff --git a/engine-precompiles/src/hash.rs b/engine-precompiles/src/hash.rs
index d096c3cb8..6a545f145 100644
--- a/engine-precompiles/src/hash.rs
+++ b/engine-precompiles/src/hash.rs
@@ -1,7 +1,7 @@
#[cfg(feature = "contract")]
use crate::prelude::sdk;
-use crate::prelude::types::EthGas;
-use crate::prelude::{vec, Address};
+use crate::prelude::types::{Address, EthGas};
+use crate::prelude::vec;
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};
use evm::{Context, ExitError};
diff --git a/engine-precompiles/src/identity.rs b/engine-precompiles/src/identity.rs
index 371d7747b..27e2b31a5 100644
--- a/engine-precompiles/src/identity.rs
+++ b/engine-precompiles/src/identity.rs
@@ -1,5 +1,4 @@
-use crate::prelude::types::EthGas;
-use crate::prelude::Address;
+use crate::prelude::types::{Address, EthGas};
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};
use evm::{Context, ExitError};
diff --git a/engine-precompiles/src/lib.rs b/engine-precompiles/src/lib.rs
index 2b02c6380..786b31cc8 100644
--- a/engine-precompiles/src/lib.rs
+++ b/engine-precompiles/src/lib.rs
@@ -23,10 +23,10 @@ use crate::identity::Identity;
use crate::modexp::ModExp;
use crate::native::{ExitToEthereum, ExitToNear};
use crate::prelude::types::EthGas;
-use crate::prelude::{Vec, H256};
+use crate::prelude::{Vec, H160, H256};
use crate::random::RandomSeed;
use crate::secp256k1::ECRecover;
-use aurora_engine_types::{account_id::AccountId, vec, Address, BTreeMap, Box};
+use aurora_engine_types::{account_id::AccountId, types::Address, vec, BTreeMap, Box};
use evm::backend::Log;
use evm::executor;
use evm::{Context, ExitError, ExitSucceed};
@@ -106,20 +106,20 @@ pub struct Precompiles(pub prelude::BTreeMap
>);
impl executor::PrecompileSet for Precompiles {
fn execute(
&self,
- address: prelude::Address,
+ address: prelude::H160,
input: &[u8],
gas_limit: Option,
context: &Context,
is_static: bool,
) -> Option> {
- self.0.get(&address).map(|p| {
+ self.0.get(&Address::new(address)).map(|p| {
p.run(input, gas_limit.map(EthGas::new), context, is_static)
.map_err(|exit_status| executor::PrecompileFailure::Error { exit_status })
})
}
- fn is_precompile(&self, address: prelude::Address) -> bool {
- self.0.contains_key(&address)
+ fn is_precompile(&self, address: prelude::H160) -> bool {
+ self.0.contains_key(&Address::new(address))
}
}
@@ -259,13 +259,13 @@ impl Precompiles {
}
}
-/// const fn for making an address by concatenating the bytes from two given numbers,
+/// fn for making an address by concatenating the bytes from two given numbers,
/// Note that 32 + 128 = 160 = 20 bytes (the length of an address). This function is used
/// as a convenience for specifying the addresses of the various precompiles.
-pub const fn make_address(x: u32, y: u128) -> prelude::Address {
+pub const fn make_address(x: u32, y: u128) -> prelude::types::Address {
let x_bytes = x.to_be_bytes();
let y_bytes = y.to_be_bytes();
- prelude::Address([
+ prelude::types::Address::new(H160([
x_bytes[0],
x_bytes[1],
x_bytes[2],
@@ -286,7 +286,7 @@ pub const fn make_address(x: u32, y: u128) -> prelude::Address {
y_bytes[13],
y_bytes[14],
y_bytes[15],
- ])
+ ]))
}
const fn make_h256(x: u128, y: u128) -> prelude::H256 {
@@ -330,7 +330,9 @@ const fn make_h256(x: u128, y: u128) -> prelude::H256 {
#[cfg(test)]
mod tests {
+ use crate::prelude::H160;
use crate::{prelude, Byzantium, Istanbul};
+ use prelude::types::Address;
use rand::Rng;
#[test]
@@ -354,25 +356,25 @@ mod tests {
let mut rng = rand::thread_rng();
for _ in 0..u8::MAX {
- let address: prelude::Address = prelude::Address(rng.gen());
+ let address = Address::new(H160(rng.gen()));
let (x, y) = split_address(address);
assert_eq!(address, super::make_address(x, y))
}
}
- fn u8_to_address(x: u8) -> prelude::Address {
+ fn u8_to_address(x: u8) -> Address {
let mut bytes = [0u8; 20];
bytes[19] = x;
- prelude::Address(bytes)
+ Address::new(H160(bytes))
}
// Inverse function of `super::make_address`.
- fn split_address(a: prelude::Address) -> (u32, u128) {
+ fn split_address(a: Address) -> (u32, u128) {
let mut x_bytes = [0u8; 4];
let mut y_bytes = [0u8; 16];
- x_bytes.copy_from_slice(&a[0..4]);
- y_bytes.copy_from_slice(&a[4..20]);
+ x_bytes.copy_from_slice(&a.raw()[0..4]);
+ y_bytes.copy_from_slice(&a.raw()[4..20]);
(u32::from_be_bytes(x_bytes), u128::from_be_bytes(y_bytes))
}
diff --git a/engine-precompiles/src/modexp.rs b/engine-precompiles/src/modexp.rs
index eac9735df..f0442d0e7 100644
--- a/engine-precompiles/src/modexp.rs
+++ b/engine-precompiles/src/modexp.rs
@@ -1,7 +1,7 @@
-use crate::prelude::{Address, PhantomData, Vec, U256};
+use crate::prelude::{PhantomData, Vec, U256};
use crate::{Berlin, Byzantium, EvmPrecompileResult, HardFork, Precompile, PrecompileOutput};
-use crate::prelude::types::EthGas;
+use crate::prelude::types::{Address, EthGas};
use evm::{Context, ExitError};
use num::{BigUint, Integer};
diff --git a/engine-precompiles/src/native.rs b/engine-precompiles/src/native.rs
index 303e99260..a1fb20909 100644
--- a/engine-precompiles/src/native.rs
+++ b/engine-precompiles/src/native.rs
@@ -6,7 +6,7 @@ use crate::prelude::{
sdk,
storage::{bytes_to_key, KeyPrefix},
types::Yocto,
- vec, BorshSerialize, Cow, String, ToString, TryFrom, TryInto, Vec, H160, U256,
+ vec, BorshSerialize, Cow, String, ToString, TryFrom, TryInto, Vec, U256,
};
#[cfg(all(feature = "error_refund", feature = "contract"))]
use crate::prelude::{
@@ -14,8 +14,7 @@ use crate::prelude::{
types,
};
-use crate::prelude::types::EthGas;
-use crate::prelude::Address;
+use crate::prelude::types::{Address, EthGas};
use crate::PrecompileOutput;
use aurora_engine_types::account_id::AccountId;
#[cfg(feature = "contract")]
@@ -45,7 +44,7 @@ mod costs {
}
pub mod events {
- use crate::prelude::{vec, Address, String, ToString, H256, U256};
+ use crate::prelude::{types::Address, vec, String, ToString, H160, H256, U256};
/// Derived from event signature (see tests::test_exit_signatures)
pub const EXIT_TO_NEAR_SIGNATURE: H256 = crate::make_h256(
@@ -62,7 +61,7 @@ pub mod events {
/// which ERC-20 token is being withdrawn. However, ETH is not an ERC-20 token
/// So we need to have some other address to fill this field. This constant is
/// used for this purpose.
- pub const ETH_ADDRESS: Address = Address([0; 20]);
+ pub const ETH_ADDRESS: Address = Address::new(H160([0; 20]));
/// ExitToNear(
/// Address indexed sender,
@@ -128,7 +127,7 @@ pub mod events {
fn encode_address(a: Address) -> H256 {
let mut result = [0u8; 32];
- result[12..].copy_from_slice(a.as_ref());
+ result[12..].copy_from_slice(a.as_bytes());
H256(result)
}
@@ -253,7 +252,7 @@ impl Precompile for ExitToNear {
) -> EvmPrecompileResult {
#[cfg(feature = "error_refund")]
fn parse_input(input: &[u8]) -> (Address, &[u8]) {
- let refund_address = Address::from_slice(&input[1..21]);
+ let refund_address = Address::from_array(&input[1..21]);
(refund_address, &input[21..])
}
#[cfg(not(feature = "error_refund"))]
@@ -302,7 +301,7 @@ impl Precompile for ExitToNear {
context.apparent_value.as_u128()
),
events::ExitToNear {
- sender: context.caller,
+ sender: Address::new(context.caller),
erc20_address: events::ETH_ADDRESS,
dest: dest_account.to_string(),
amount: context.apparent_value,
@@ -346,8 +345,8 @@ impl Precompile for ExitToNear {
amount.as_u128()
),
events::ExitToNear {
- sender: erc20_address,
- erc20_address,
+ sender: Address::new(erc20_address),
+ erc20_address: Address::new(erc20_address),
dest: receiver_account_id.to_string(),
amount,
},
@@ -365,11 +364,11 @@ impl Precompile for ExitToNear {
let erc20_address = if flag == 0 {
None
} else {
- Some(exit_event.erc20_address.0)
+ Some(exit_event.erc20_address)
};
#[cfg(feature = "error_refund")]
let refund_args = RefundCallArgs {
- recipient_address: refund_address.0,
+ recipient_address: refund_address,
erc20_address,
amount: types::u256_to_arr(&exit_event.amount),
};
@@ -398,13 +397,13 @@ impl Precompile for ExitToNear {
let promise = PromiseArgs::Create(transfer_promise);
let promise_log = Log {
- address: Self::ADDRESS,
+ address: Self::ADDRESS.raw(),
topics: Vec::new(),
data: promise.try_to_vec().unwrap(),
};
let exit_event_log = exit_event.encode();
let exit_event_log = Log {
- address: Self::ADDRESS,
+ address: Self::ADDRESS.raw(),
topics: exit_event_log.topics,
data: exit_event_log.data,
};
@@ -489,7 +488,7 @@ impl Precompile for ExitToEthereum {
//
// Input slice format:
// eth_recipient (20 bytes) - the address of recipient which will receive ETH on Ethereum
- let recipient_address = input
+ let recipient_address: Address = input
.try_into()
.map_err(|_| ExitError::Other(Cow::from("ERR_INVALID_RECIPIENT_ADDRESS")))?;
(
@@ -503,9 +502,9 @@ impl Precompile for ExitToEthereum {
.try_to_vec()
.map_err(|_| ExitError::Other(Cow::from("ERR_INVALID_AMOUNT")))?,
events::ExitToEth {
- sender: context.caller,
+ sender: Address::new(context.caller),
erc20_address: events::ETH_ADDRESS,
- dest: H160(recipient_address),
+ dest: recipient_address,
amount: context.apparent_value,
},
)
@@ -536,7 +535,9 @@ impl Precompile for ExitToEthereum {
// Parse ethereum address in hex
let eth_recipient: String = hex::encode(input.to_vec());
// unwrap cannot fail since we checked the length already
- let recipient_address = input.try_into().unwrap();
+ let recipient_address = Address::try_from_slice(input).map_err(|_| {
+ ExitError::Other(crate::prelude::Cow::from("ERR_WRONG_ADDRESS"))
+ })?;
(
nep141_address,
@@ -550,9 +551,9 @@ impl Precompile for ExitToEthereum {
.as_bytes()
.to_vec(),
events::ExitToEth {
- sender: erc20_address,
- erc20_address,
- dest: H160(recipient_address),
+ sender: Address::new(erc20_address),
+ erc20_address: Address::new(erc20_address),
+ dest: recipient_address,
amount,
},
)
@@ -577,13 +578,13 @@ impl Precompile for ExitToEthereum {
let promise = PromiseArgs::Create(withdraw_promise).try_to_vec().unwrap();
let promise_log = Log {
- address: Self::ADDRESS,
+ address: Self::ADDRESS.raw(),
topics: Vec::new(),
data: promise,
};
let exit_event_log = exit_event.encode();
let exit_event_log = Log {
- address: Self::ADDRESS,
+ address: Self::ADDRESS.raw(),
topics: exit_event_log.topics,
data: exit_event_log.data,
};
diff --git a/engine-precompiles/src/random.rs b/engine-precompiles/src/random.rs
index 014b7ee8a..b71f2509e 100644
--- a/engine-precompiles/src/random.rs
+++ b/engine-precompiles/src/random.rs
@@ -1,6 +1,6 @@
use super::{EvmPrecompileResult, Precompile};
-use crate::prelude::types::EthGas;
-use crate::prelude::{Address, H256};
+use crate::prelude::types::{Address, EthGas};
+use crate::prelude::H256;
use crate::PrecompileOutput;
use evm::{Context, ExitError};
diff --git a/engine-precompiles/src/secp256k1.rs b/engine-precompiles/src/secp256k1.rs
index 14f11d87c..3ef3cd7e8 100644
--- a/engine-precompiles/src/secp256k1.rs
+++ b/engine-precompiles/src/secp256k1.rs
@@ -1,7 +1,6 @@
-use crate::prelude::types::EthGas;
+use crate::prelude::types::{Address, EthGas};
use crate::prelude::{sdk, vec, Borrowed, H256};
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};
-use ethabi::Address;
use evm::{Context, ExitError};
mod costs {
@@ -45,7 +44,8 @@ fn internal_impl(hash: H256, signature: &[u8]) -> Result {
if let Ok(public_key) = secp256k1::recover(&hash, &signature, &recovery_id) {
// recover returns a 65-byte key, but addresses come from the raw 64-byte key
let r = sha3::Keccak256::digest(&public_key.serialize()[1..]);
- return Ok(Address::from_slice(&r[12..]));
+ return Address::try_from_slice(&r[12..])
+ .map_err(|_| ExitError::Other(Borrowed("ERR_INCORRECT_ADDRESS")));
}
}
@@ -132,8 +132,10 @@ mod tests {
let signature =
&hex::decode("b9f0bb08640d3c1c00761cdd0121209268f6fd3816bc98b9e6f3cc77bf82b69812ac7a61788a0fdc0e19180f14c945a8e1088a27d92a74dce81c0981fb6447441b")
.unwrap();
- let signer =
- Address::from_slice(&hex::decode("1563915e194D8CfBA1943570603F7606A3115508").unwrap());
+ let signer = Address::try_from_slice(
+ &hex::decode("1563915e194D8CfBA1943570603F7606A3115508").unwrap(),
+ )
+ .unwrap();
assert!(ecverify(hash, &signature, signer));
}
diff --git a/engine-sdk/src/lib.rs b/engine-sdk/src/lib.rs
index e4d256cc5..ead525f94 100644
--- a/engine-sdk/src/lib.rs
+++ b/engine-sdk/src/lib.rs
@@ -97,7 +97,7 @@ pub fn ecrecover(hash: H256, signature: &[u8]) -> Result
exports::keccak256(u64::MAX, RECOVER_REGISTER_ID, KECCACK_REGISTER_ID);
let keccak_hash_bytes = [0u8; 32];
exports::read_register(KECCACK_REGISTER_ID, keccak_hash_bytes.as_ptr() as u64);
- Ok(Address::from_slice(&keccak_hash_bytes[12..]))
+ Ok(Address::try_from_slice(&keccak_hash_bytes[12..]).map_err(|_| ECRecoverErr)?)
} else {
Err(ECRecoverErr)
}
diff --git a/engine-sdk/src/prelude.rs b/engine-sdk/src/prelude.rs
index 359551455..799b5ec86 100644
--- a/engine-sdk/src/prelude.rs
+++ b/engine-sdk/src/prelude.rs
@@ -1,3 +1,3 @@
-pub use aurora_engine_types::types::{NearGas, PromiseResult, STORAGE_PRICE_PER_BYTE};
-pub use aurora_engine_types::{vec, Address, Vec, H256};
+pub use aurora_engine_types::types::{Address, NearGas, PromiseResult, STORAGE_PRICE_PER_BYTE};
+pub use aurora_engine_types::{vec, Vec, H256};
pub use borsh::{BorshDeserialize, BorshSerialize};
diff --git a/engine-sdk/src/types.rs b/engine-sdk/src/types.rs
index ce595ea69..571019922 100644
--- a/engine-sdk/src/types.rs
+++ b/engine-sdk/src/types.rs
@@ -23,7 +23,7 @@ pub fn keccak(data: &[u8]) -> H256 {
}
pub fn near_account_to_evm_address(addr: &[u8]) -> Address {
- Address::from_slice(&keccak(addr)[12..])
+ Address::try_from_slice(&keccak(addr)[12..]).unwrap()
}
#[cfg(feature = "contract")]
diff --git a/engine-standalone-storage/src/relayer_db/types.rs b/engine-standalone-storage/src/relayer_db/types.rs
index 0fdc1dc9b..254ee0a26 100644
--- a/engine-standalone-storage/src/relayer_db/types.rs
+++ b/engine-standalone-storage/src/relayer_db/types.rs
@@ -2,7 +2,8 @@ use aurora_engine::transaction::{
legacy::{LegacyEthSignedTransaction, TransactionLegacy},
EthTransactionKind,
};
-use aurora_engine_types::{types::Wei, Address, H256, U256};
+use aurora_engine_types::types::{Address, Wei};
+use aurora_engine_types::{H256, U256};
use std::convert::TryFrom;
use std::io::{Cursor, Read};
use std::time::SystemTime;
@@ -177,7 +178,7 @@ impl From for TransactionRow {
near_hash,
near_receipt_hash,
from,
- to: to.map(Address::from_slice),
+ to: to.map(|arr| Address::try_from_slice(arr).unwrap()),
nonce,
gas_price,
gas_limit,
@@ -225,7 +226,7 @@ fn get_hash(row: &postgres::Row, field: &str) -> H256 {
fn get_address(row: &postgres::Row, field: &str) -> Address {
let value: &[u8] = row.get(field);
- Address::from_slice(value)
+ Address::try_from_slice(value).unwrap()
}
fn get_timestamp(row: &postgres::Row, field: &str) -> Option {
diff --git a/engine-tests/src/benches/eth_deploy_code.rs b/engine-tests/src/benches/eth_deploy_code.rs
index 6a7311a56..2c83d28b0 100644
--- a/engine-tests/src/benches/eth_deploy_code.rs
+++ b/engine-tests/src/benches/eth_deploy_code.rs
@@ -1,7 +1,7 @@
use criterion::{BatchSize, BenchmarkId, Criterion, Throughput};
use secp256k1::SecretKey;
-use crate::prelude::types::Wei;
+use crate::prelude::Wei;
use crate::test_utils::{
address_from_secret_key, create_deploy_transaction, deploy_evm, sign_transaction, SUBMIT,
};
diff --git a/engine-tests/src/benches/eth_erc20.rs b/engine-tests/src/benches/eth_erc20.rs
index 369307298..137a16c7b 100644
--- a/engine-tests/src/benches/eth_erc20.rs
+++ b/engine-tests/src/benches/eth_erc20.rs
@@ -15,7 +15,7 @@ pub(crate) fn eth_erc20_benchmark(c: &mut Criterion) {
let source_account = SecretKey::random(&mut rng);
runner.create_address(
address_from_secret_key(&source_account),
- crate::prelude::types::Wei::new_u64(INITIAL_BALANCE),
+ crate::prelude::Wei::new_u64(INITIAL_BALANCE),
INITIAL_NONCE.into(),
);
let calling_account_id = "some-account.near";
diff --git a/engine-tests/src/benches/eth_standard_precompiles.rs b/engine-tests/src/benches/eth_standard_precompiles.rs
index 2aeea79f1..e07fa1c27 100644
--- a/engine-tests/src/benches/eth_standard_precompiles.rs
+++ b/engine-tests/src/benches/eth_standard_precompiles.rs
@@ -2,7 +2,7 @@ use crate::prelude::U256;
use criterion::{BatchSize, BenchmarkId, Criterion};
use secp256k1::SecretKey;
-use crate::prelude::types::Wei;
+use crate::prelude::Wei;
use crate::test_utils::standard_precompiles::{PrecompilesConstructor, PrecompilesContract};
use crate::test_utils::{address_from_secret_key, deploy_evm, sign_transaction, SUBMIT};
diff --git a/engine-tests/src/benches/eth_transfer.rs b/engine-tests/src/benches/eth_transfer.rs
index 8aa443a24..3aa7fdf45 100644
--- a/engine-tests/src/benches/eth_transfer.rs
+++ b/engine-tests/src/benches/eth_transfer.rs
@@ -1,7 +1,7 @@
use criterion::{BatchSize, Criterion};
use secp256k1::SecretKey;
-use crate::prelude::types::Wei;
+use crate::prelude::Wei;
use crate::test_utils::{address_from_secret_key, create_eth_transaction, deploy_evm, SUBMIT};
const INITIAL_BALANCE: Wei = Wei::new_u64(1000);
diff --git a/engine-tests/src/benches/nft_pagination.rs b/engine-tests/src/benches/nft_pagination.rs
index 8d8e38d65..90b819f29 100644
--- a/engine-tests/src/benches/nft_pagination.rs
+++ b/engine-tests/src/benches/nft_pagination.rs
@@ -1,5 +1,4 @@
-use crate::prelude::types::Wei;
-use crate::prelude::{Address, U256};
+use crate::prelude::{Address, Wei, U256};
use crate::test_utils::{self, solidity};
use aurora_engine::transaction::legacy::TransactionLegacy;
use secp256k1::SecretKey;
@@ -134,7 +133,7 @@ impl MarketPlace {
self.0.call_method_with_args(
"minar",
&[
- ethabi::Token::Address(recipient),
+ ethabi::Token::Address(recipient.raw()),
ethabi::Token::String(data),
ethabi::Token::Uint(price.raw()),
],
diff --git a/engine-tests/src/test_utils/erc20.rs b/engine-tests/src/test_utils/erc20.rs
index 57cc38f69..a499d1608 100644
--- a/engine-tests/src/test_utils/erc20.rs
+++ b/engine-tests/src/test_utils/erc20.rs
@@ -78,7 +78,7 @@ impl ERC20 {
.function("mint")
.unwrap()
.encode_input(&[
- ethabi::Token::Address(recipient),
+ ethabi::Token::Address(recipient.raw()),
ethabi::Token::Uint(amount),
])
.unwrap();
@@ -100,7 +100,7 @@ impl ERC20 {
.function("transfer")
.unwrap()
.encode_input(&[
- ethabi::Token::Address(recipient),
+ ethabi::Token::Address(recipient.raw()),
ethabi::Token::Uint(amount),
])
.unwrap();
@@ -120,7 +120,10 @@ impl ERC20 {
.abi
.function("approve")
.unwrap()
- .encode_input(&[ethabi::Token::Address(spender), ethabi::Token::Uint(amount)])
+ .encode_input(&[
+ ethabi::Token::Address(spender.raw()),
+ ethabi::Token::Uint(amount),
+ ])
.unwrap();
TransactionLegacy {
nonce,
@@ -138,7 +141,7 @@ impl ERC20 {
.abi
.function("balanceOf")
.unwrap()
- .encode_input(&[ethabi::Token::Address(address)])
+ .encode_input(&[ethabi::Token::Address(address.raw())])
.unwrap();
TransactionLegacy {
nonce,
diff --git a/engine-tests/src/test_utils/exit_precompile.rs b/engine-tests/src/test_utils/exit_precompile.rs
index 76484930e..a52b688df 100644
--- a/engine-tests/src/test_utils/exit_precompile.rs
+++ b/engine-tests/src/test_utils/exit_precompile.rs
@@ -30,7 +30,7 @@ impl TesterConstructor {
.abi
.constructor()
.unwrap()
- .encode_input(self.0.code.clone(), &[ethabi::Token::Address(token)])
+ .encode_input(self.0.code.clone(), &[ethabi::Token::Address(token.raw())])
.unwrap();
TransactionLegacy {
@@ -200,7 +200,7 @@ impl Tester {
signer,
"withdrawEthToEthereum",
amount,
- &[ethabi::Token::Address(DEST_ADDRESS)],
+ &[ethabi::Token::Address(DEST_ADDRESS.raw())],
)
}
}
diff --git a/engine-tests/src/test_utils/mod.rs b/engine-tests/src/test_utils/mod.rs
index b03f777ea..2b97db496 100644
--- a/engine-tests/src/test_utils/mod.rs
+++ b/engine-tests/src/test_utils/mod.rs
@@ -1,3 +1,4 @@
+use aurora_engine::parameters::ViewCallArgs;
use aurora_engine_types::account_id::AccountId;
use aurora_engine_types::types::NEP141Wei;
use borsh::{BorshDeserialize, BorshSerialize};
@@ -13,9 +14,7 @@ use rlp::RlpStream;
use secp256k1::{self, Message, PublicKey, SecretKey};
use crate::prelude::fungible_token::{FungibleToken, FungibleTokenMetadata};
-use crate::prelude::parameters::{
- InitCallArgs, NewCallArgs, SubmitResult, TransactionStatus, ViewCallArgs,
-};
+use crate::prelude::parameters::{InitCallArgs, NewCallArgs, SubmitResult, TransactionStatus};
use crate::prelude::transaction::{
eip_1559::{self, SignedTransaction1559, Transaction1559},
eip_2930::{self, SignedTransaction2930, Transaction2930},
@@ -377,7 +376,7 @@ impl AuroraRunner {
assert!(maybe_err.is_none());
let submit_result =
SubmitResult::try_from_slice(&output.unwrap().return_data.as_value().unwrap()).unwrap();
- let address = Address::from_slice(&unwrap_success(submit_result));
+ let address = Address::try_from_slice(&unwrap_success(submit_result)).unwrap();
let contract_constructor: ContractConstructor = contract_constructor.into();
DeployedContract {
abi: contract_constructor.abi,
@@ -421,7 +420,7 @@ impl AuroraRunner {
pub fn get_storage(&self, address: Address, key: H256) -> H256 {
let input = aurora_engine::parameters::GetStorageAtArgs {
- address: address.0,
+ address,
key: key.0,
};
let (outcome, maybe_error) =
@@ -655,8 +654,8 @@ pub(crate) fn create_eth_transaction(
pub(crate) fn as_view_call(tx: TransactionLegacy, sender: Address) -> ViewCallArgs {
ViewCallArgs {
- sender: sender.0,
- address: tx.to.unwrap().0,
+ sender,
+ address: tx.to.unwrap(),
amount: tx.value.to_bytes(),
input: tx.data,
}
@@ -734,7 +733,7 @@ pub(crate) fn sign_eip_1559_transaction(
pub(crate) fn address_from_secret_key(sk: &SecretKey) -> Address {
let pk = PublicKey::from_secret_key(sk);
let hash = sdk::keccak(&pk.serialize()[1..]);
- Address::from_slice(&hash[12..])
+ Address::try_from_slice(&hash[12..]).unwrap()
}
pub(crate) fn parse_eth_gas(output: &VMOutcome) -> u64 {
@@ -763,7 +762,7 @@ pub(crate) fn address_from_hex(address: &str) -> Address {
hex::decode(address).unwrap()
};
- Address::from_slice(&bytes)
+ Address::try_from_slice(&bytes).unwrap()
}
pub(crate) fn as_account_id(account_id: &str) -> near_primitives_core::types::AccountId {
diff --git a/engine-tests/src/test_utils/one_inch/liquidity_protocol.rs b/engine-tests/src/test_utils/one_inch/liquidity_protocol.rs
index 4de97a372..ed2f84833 100644
--- a/engine-tests/src/test_utils/one_inch/liquidity_protocol.rs
+++ b/engine-tests/src/test_utils/one_inch/liquidity_protocol.rs
@@ -38,7 +38,8 @@ impl<'a> Helper<'a> {
})
.unwrap();
- let deployer_address = Address::from_slice(test_utils::unwrap_success_slice(&result));
+ let deployer_address =
+ Address::try_from_slice(test_utils::unwrap_success_slice(&result)).unwrap();
let deployer = PoolDeployer(solidity::DeployedContract {
abi,
address: deployer_address,
@@ -63,15 +64,15 @@ impl<'a> Helper<'a> {
constructor.deploy_with_args(
nonce,
&[
- ethabi::Token::Address(signer_address),
- ethabi::Token::Address(pool_deployer.0.address),
- ethabi::Token::Address(signer_address),
+ ethabi::Token::Address(signer_address.raw()),
+ ethabi::Token::Address(pool_deployer.0.address.raw()),
+ ethabi::Token::Address(signer_address.raw()),
],
)
})
.unwrap();
- let address = Address::from_slice(test_utils::unwrap_success_slice(&result));
+ let address = Address::try_from_slice(test_utils::unwrap_success_slice(&result)).unwrap();
let pool_factory = PoolFactory(constructor.deployed_at(address));
(result, profile, pool_factory)
@@ -94,15 +95,16 @@ impl<'a> Helper<'a> {
pool_factory.0.call_method_with_args(
"deploy",
&[
- ethabi::Token::Address(token_a),
- ethabi::Token::Address(token_b),
+ ethabi::Token::Address(token_a.raw()),
+ ethabi::Token::Address(token_b.raw()),
],
nonce,
)
})
.unwrap();
- let address = Address::from_slice(&test_utils::unwrap_success_slice(&result)[12..32]);
+ let address =
+ Address::try_from_slice(&test_utils::unwrap_success_slice(&result)[12..32]).unwrap();
let pool = Pool(constructor.deployed_at(address));
(result, profile, pool)
@@ -178,11 +180,11 @@ impl<'a> Helper<'a> {
pool,
"swap",
&[
- ethabi::Token::Address(args.src_token),
- ethabi::Token::Address(args.dst_token),
+ ethabi::Token::Address(args.src_token.raw()),
+ ethabi::Token::Address(args.dst_token.raw()),
ethabi::Token::Uint(args.amount),
ethabi::Token::Uint(args.min_amount),
- ethabi::Token::Address(args.referral),
+ ethabi::Token::Address(args.referral.raw()),
],
)
}
diff --git a/engine-tests/src/test_utils/self_destruct.rs b/engine-tests/src/test_utils/self_destruct.rs
index a4acb6947..1d62e2fdd 100644
--- a/engine-tests/src/test_utils/self_destruct.rs
+++ b/engine-tests/src/test_utils/self_destruct.rs
@@ -75,7 +75,7 @@ impl SelfDestructFactory {
let result = runner.submit_transaction(&signer.secret_key, tx).unwrap();
let result = test_utils::unwrap_success(result);
- Address::from_slice(&result[12..])
+ Address::try_from_slice(&result[12..]).unwrap()
}
}
diff --git a/engine-tests/src/test_utils/standalone/mocks/mod.rs b/engine-tests/src/test_utils/standalone/mocks/mod.rs
index 71b508aef..f71f2fc75 100644
--- a/engine-tests/src/test_utils/standalone/mocks/mod.rs
+++ b/engine-tests/src/test_utils/standalone/mocks/mod.rs
@@ -4,8 +4,8 @@ use aurora_engine::fungible_token::FungibleTokenMetadata;
use aurora_engine::parameters::{FinishDepositCallArgs, InitCallArgs, NewCallArgs};
use aurora_engine_sdk::env::{Env, DEFAULT_PREPAID_GAS};
use aurora_engine_sdk::io::IO;
-use aurora_engine_types::types::{NEP141Wei, NearGas};
-use aurora_engine_types::{account_id::AccountId, types::Wei, Address, H256, U256};
+use aurora_engine_types::types::{Address, NEP141Wei, NearGas, Wei};
+use aurora_engine_types::{account_id::AccountId, H256, U256};
use engine_standalone_storage::{BlockMetadata, Storage};
use near_sdk_sim::DEFAULT_GAS;
@@ -61,7 +61,7 @@ pub fn init_evm(mut io: I, env: &E, chain_id: u64) {
let connector_args = InitCallArgs {
prover_account: test_utils::str_to_account_id("prover.near"),
- eth_custodian_address: hex::encode(Ð_CUSTODIAN_ADDRESS),
+ eth_custodian_address: ETH_CUSTODIAN_ADDRESS.encode(),
metadata: FungibleTokenMetadata::default(),
};
@@ -87,7 +87,7 @@ pub fn mint_evm_account(
let aurora_account_id = env.current_account_id();
let mut engine = engine::Engine::new(address, aurora_account_id.clone(), io, env).unwrap();
let state_change = evm::backend::Apply::Modify {
- address,
+ address: address.raw(),
basic: evm::backend::Basic {
balance: balance.raw(),
nonce,
diff --git a/engine-tests/src/test_utils/standalone/mod.rs b/engine-tests/src/test_utils/standalone/mod.rs
index f2f3b59ac..df0cefedb 100644
--- a/engine-tests/src/test_utils/standalone/mod.rs
+++ b/engine-tests/src/test_utils/standalone/mod.rs
@@ -2,8 +2,8 @@ use aurora_engine::engine;
use aurora_engine::parameters::{CallArgs, DeployErc20TokenArgs, SubmitResult, TransactionStatus};
use aurora_engine::transaction::legacy::{LegacyEthSignedTransaction, TransactionLegacy};
use aurora_engine_sdk::env::{self, Env};
-use aurora_engine_types::types::NearGas;
-use aurora_engine_types::{types::Wei, Address, H256, U256};
+use aurora_engine_types::types::{Address, NearGas, Wei};
+use aurora_engine_types::{H256, U256};
use borsh::BorshDeserialize;
use engine_standalone_storage::engine_state;
use engine_standalone_storage::{BlockMetadata, Diff, Storage};
@@ -50,7 +50,7 @@ impl StandaloneRunner {
let env = &mut self.env;
let transaction_hash = {
let bytes = [
- address.as_ref(),
+ address.raw().as_ref(),
&balance.to_bytes(),
&aurora_engine_types::types::u256_to_arr(&nonce),
]
@@ -184,7 +184,7 @@ impl StandaloneRunner {
.unwrap();
io.finish().commit(storage, &mut self.cumulative_diff);
Ok(SubmitResult::new(
- TransactionStatus::Succeed(address.as_ref().to_vec()),
+ TransactionStatus::Succeed(address.raw().as_ref().to_vec()),
0,
Vec::new(),
))
diff --git a/engine-tests/src/test_utils/uniswap.rs b/engine-tests/src/test_utils/uniswap.rs
index 4d951ade8..9e1d68016 100644
--- a/engine-tests/src/test_utils/uniswap.rs
+++ b/engine-tests/src/test_utils/uniswap.rs
@@ -112,9 +112,9 @@ impl PositionManagerConstructor {
.encode_input(
self.0.code.clone(),
&[
- ethabi::Token::Address(factory),
- ethabi::Token::Address(wrapped_eth),
- ethabi::Token::Address(token_descriptor),
+ ethabi::Token::Address(factory.raw()),
+ ethabi::Token::Address(wrapped_eth.raw()),
+ ethabi::Token::Address(token_descriptor.raw()),
],
)
.unwrap();
@@ -143,8 +143,8 @@ impl Factory {
.function("createPool")
.unwrap()
.encode_input(&[
- ethabi::Token::Address(token_a),
- ethabi::Token::Address(token_b),
+ ethabi::Token::Address(token_a.raw()),
+ ethabi::Token::Address(token_b.raw()),
ethabi::Token::Uint(fee),
])
.unwrap();
@@ -213,8 +213,8 @@ impl PositionManager {
.function("mint")
.unwrap()
.encode_input(&[ethabi::Token::Tuple(vec![
- ethabi::Token::Address(params.token0),
- ethabi::Token::Address(params.token1),
+ ethabi::Token::Address(params.token0.raw()),
+ ethabi::Token::Address(params.token1.raw()),
ethabi::Token::Uint(params.fee.into()),
ethabi::Token::Int(tick_lower),
ethabi::Token::Int(tick_upper),
@@ -222,7 +222,7 @@ impl PositionManager {
ethabi::Token::Uint(params.amount1_desired),
ethabi::Token::Uint(params.amount0_min),
ethabi::Token::Uint(params.amount1_min),
- ethabi::Token::Address(params.recipient),
+ ethabi::Token::Address(params.recipient.raw()),
ethabi::Token::Uint(params.deadline),
])])
.unwrap();
@@ -276,8 +276,8 @@ impl SwapRouterConstructor {
.encode_input(
self.0.code.clone(),
&[
- ethabi::Token::Address(factory),
- ethabi::Token::Address(wrapped_eth),
+ ethabi::Token::Address(factory.raw()),
+ ethabi::Token::Address(wrapped_eth.raw()),
],
)
.unwrap();
@@ -315,10 +315,10 @@ impl SwapRouter {
.function("exactOutputSingle")
.unwrap()
.encode_input(&[ethabi::Token::Tuple(vec![
- ethabi::Token::Address(params.token_in),
- ethabi::Token::Address(params.token_out),
+ ethabi::Token::Address(params.token_in.raw()),
+ ethabi::Token::Address(params.token_out.raw()),
ethabi::Token::Uint(params.fee.into()),
- ethabi::Token::Address(params.recipient),
+ ethabi::Token::Address(params.recipient.raw()),
ethabi::Token::Uint(params.deadline),
ethabi::Token::Uint(params.amount_out),
ethabi::Token::Uint(params.amount_in_max),
diff --git a/engine-tests/src/test_utils/weth.rs b/engine-tests/src/test_utils/weth.rs
index da5390cf6..aae6eba6a 100644
--- a/engine-tests/src/test_utils/weth.rs
+++ b/engine-tests/src/test_utils/weth.rs
@@ -1,5 +1,6 @@
use aurora_engine::transaction::legacy::TransactionLegacy;
-use aurora_engine_types::{types::Wei, Address, U256};
+use aurora_engine_types::types::{Address, Wei};
+use aurora_engine_types::U256;
use crate::test_utils::solidity;
diff --git a/engine-tests/src/tests/access_lists.rs b/engine-tests/src/tests/access_lists.rs
index 93ef7f779..35fccaf3a 100644
--- a/engine-tests/src/tests/access_lists.rs
+++ b/engine-tests/src/tests/access_lists.rs
@@ -26,11 +26,13 @@ fn test_access_list_tx_encoding_decoding() {
data: vec![0],
access_list: vec![
AccessTuple {
- address: test_utils::address_from_hex("0x095e7baea6a6c7c4c2dfeb977efac326af552d87"),
+ address: test_utils::address_from_hex("0x095e7baea6a6c7c4c2dfeb977efac326af552d87")
+ .raw(),
storage_keys: vec![H256::zero(), one()],
},
AccessTuple {
- address: test_utils::address_from_hex("0x195e7baea6a6c7c4c2dfeb977efac326af552d87"),
+ address: test_utils::address_from_hex("0x195e7baea6a6c7c4c2dfeb977efac326af552d87")
+ .raw(),
storage_keys: vec![H256::zero()],
},
],
diff --git a/engine-tests/src/tests/contract_call.rs b/engine-tests/src/tests/contract_call.rs
index f52572461..83c219f10 100644
--- a/engine-tests/src/tests/contract_call.rs
+++ b/engine-tests/src/tests/contract_call.rs
@@ -4,7 +4,7 @@ use crate::test_utils::{origin, AuroraRunner, Signer};
use crate::test_utils;
use crate::test_utils::exit_precompile::{Tester, TesterConstructor, DEST_ACCOUNT, DEST_ADDRESS};
-fn setup_test() -> (AuroraRunner, Signer, [u8; 20], Tester) {
+fn setup_test() -> (AuroraRunner, Signer, Address, Tester) {
let mut runner = AuroraRunner::new();
let token = runner.deploy_erc20_token(&"tt.testnet".to_string());
let mut signer = test_utils::Signer::random();
@@ -49,7 +49,6 @@ fn hello_world_solidity() {
#[test]
fn withdraw() {
let (mut runner, mut signer, token, tester) = setup_test();
- let token = Address(token);
let test_data = vec![
(true, "call_contract tt.testnet.ft_transfer"),
@@ -86,20 +85,20 @@ fn withdraw() {
} else {
// transferred to 0xE0f5206BBD039e7b0592d8918820024e2a7437b9 (defined in Tester.sol)
let address = hex::decode("E0f5206BBD039e7b0592d8918820024e2a7437b9").unwrap();
- let address = Address::from_slice(&address);
+ let address = Address::try_from_slice(&address).unwrap();
ethabi::LogParam {
name: "dest".to_string(),
- value: ethabi::Token::Address(address),
+ value: ethabi::Token::Address(address.raw()),
}
};
let expected_event = vec![
ethabi::LogParam {
name: "sender".to_string(),
- value: ethabi::Token::Address(token),
+ value: ethabi::Token::Address(token.raw()),
},
ethabi::LogParam {
name: "erc20_address".to_string(),
- value: ethabi::Token::Address(token),
+ value: ethabi::Token::Address(token.raw()),
},
dest,
ethabi::LogParam {
@@ -188,11 +187,13 @@ fn withdraw_eth() {
let mut expected_event = vec![
ethabi::LogParam {
name: "sender".to_string(),
- value: ethabi::Token::Address(tester.contract.address),
+ value: ethabi::Token::Address(tester.contract.address.raw()),
},
ethabi::LogParam {
name: "erc20_address".to_string(),
- value: ethabi::Token::Address(aurora_engine_precompiles::native::events::ETH_ADDRESS),
+ value: ethabi::Token::Address(
+ aurora_engine_precompiles::native::events::ETH_ADDRESS.raw(),
+ ),
},
ethabi::LogParam {
name: "dest".to_string(),
@@ -215,7 +216,7 @@ fn withdraw_eth() {
.unwrap();
expected_event[2] = ethabi::LogParam {
name: "dest".to_string(),
- value: ethabi::Token::Address(DEST_ADDRESS),
+ value: ethabi::Token::Address(DEST_ADDRESS.raw()),
};
expected_event[3] = ethabi::LogParam {
name: "amount".to_string(),
diff --git a/engine-tests/src/tests/eip1559.rs b/engine-tests/src/tests/eip1559.rs
index 239c5b33b..78092b61b 100644
--- a/engine-tests/src/tests/eip1559.rs
+++ b/engine-tests/src/tests/eip1559.rs
@@ -132,7 +132,7 @@ fn example_transaction() -> Transaction1559 {
value: Wei::zero(),
data: vec![0],
access_list: vec![AccessTuple {
- address: test_utils::address_from_hex(CONTRACT_ADDRESS),
+ address: test_utils::address_from_hex(CONTRACT_ADDRESS).raw(),
storage_keys: vec![H256::zero(), one()],
}],
}
diff --git a/engine-tests/src/tests/erc20_connector.rs b/engine-tests/src/tests/erc20_connector.rs
index be75b0938..8212de2ff 100644
--- a/engine-tests/src/tests/erc20_connector.rs
+++ b/engine-tests/src/tests/erc20_connector.rs
@@ -1,4 +1,4 @@
-use crate::prelude::{Address, Balance, RawAddress, TryInto, Wei, WeiU256, U256};
+use crate::prelude::{Address, Balance, TryInto, Wei, WeiU256, U256};
use crate::test_utils;
use crate::test_utils::{create_eth_transaction, origin, AuroraRunner};
use aurora_engine::parameters::{CallArgs, FunctionCallArgsV2, SubmitResult};
@@ -61,7 +61,7 @@ fn create_ethereum_address() -> Address {
pub struct EthereumAddress {
pub secret_key: SecretKey,
- pub address: RawAddress,
+ pub address: Address,
}
impl test_utils::AuroraRunner {
@@ -91,7 +91,7 @@ impl test_utils::AuroraRunner {
CallResult { outcome, error }
}
- pub fn evm_call(&mut self, contract: RawAddress, input: Vec, origin: String) -> CallResult {
+ pub fn evm_call(&mut self, contract: Address, input: Vec, origin: String) -> CallResult {
self.make_call(
"call",
origin,
@@ -109,15 +109,16 @@ impl test_utils::AuroraRunner {
self.make_call("submit", origin, rlp::encode(&input).to_vec())
}
- pub fn deploy_erc20_token(&mut self, nep141: &String) -> RawAddress {
+ pub fn deploy_erc20_token(&mut self, nep141: &String) -> Address {
let result = self.make_call("deploy_erc20_token", origin(), nep141.try_to_vec().unwrap());
result.check_ok();
- Vec::::try_from_slice(result.value().as_slice())
+ let raw_address: [u8; 20] = Vec::::try_from_slice(result.value().as_slice())
.unwrap()
.try_into()
- .unwrap()
+ .unwrap();
+ Address::try_from_slice(&raw_address).unwrap()
}
pub fn create_account(&mut self) -> EthereumAddress {
@@ -131,8 +132,8 @@ impl test_utils::AuroraRunner {
}
}
- pub fn balance_of(&mut self, token: RawAddress, target: RawAddress, origin: String) -> U256 {
- let input = build_input("balanceOf(address)", &[Token::Address(target.into())]);
+ pub fn balance_of(&mut self, token: Address, target: Address, origin: String) -> U256 {
+ let input = build_input("balanceOf(address)", &[Token::Address(target.raw())]);
let result = self.evm_call(token, input, origin);
result.check_ok();
let output = test_utils::unwrap_success(result.submit_result());
@@ -141,15 +142,15 @@ impl test_utils::AuroraRunner {
pub fn mint(
&mut self,
- token: RawAddress,
- target: RawAddress,
+ token: Address,
+ target: Address,
amount: u64,
origin: String,
) -> CallResult {
let input = build_input(
"mint(address,uint256)",
&[
- Token::Address(target.into()),
+ Token::Address(target.raw()),
Token::Uint(U256::from(amount).into()),
],
);
@@ -159,7 +160,7 @@ impl test_utils::AuroraRunner {
}
#[allow(dead_code)]
- pub fn admin(&mut self, token: RawAddress, origin: String) -> CallResult {
+ pub fn admin(&mut self, token: Address, origin: String) -> CallResult {
let input = build_input("admin()", &[]);
let result = self.evm_call(token, input, origin);
result.check_ok();
@@ -168,9 +169,9 @@ impl test_utils::AuroraRunner {
pub fn transfer_erc20(
&mut self,
- token: RawAddress,
+ token: Address,
sender: SecretKey,
- receiver: RawAddress,
+ receiver: Address,
amount: u64,
origin: String,
) -> CallResult {
@@ -178,7 +179,7 @@ impl test_utils::AuroraRunner {
let input = build_input(
"transfer(address,uint256)",
&[
- Token::Address(receiver.into()),
+ Token::Address(receiver.raw()),
Token::Uint(U256::from(amount)),
],
);
@@ -222,7 +223,7 @@ impl test_utils::AuroraRunner {
self.make_call(
"register_relayer",
relayer_account_id,
- relayer_address.as_fixed_bytes().try_to_vec().unwrap(),
+ relayer_address.try_to_vec().unwrap(),
)
}
}
@@ -273,7 +274,7 @@ fn test_ft_on_transfer() {
let balance = runner.balance_of(token, recipient, origin());
assert_eq!(balance, U256::from(0));
- let res = runner.ft_on_transfer(nep141, alice.clone(), alice, amount, hex::encode(recipient));
+ let res = runner.ft_on_transfer(nep141, alice.clone(), alice, amount, recipient.encode());
// Transaction should succeed so return amount is 0
assert_eq!(res, "\"0\"");
@@ -290,7 +291,7 @@ fn test_ft_on_transfer_fail() {
let recipient = runner.create_account().address;
- let res = runner.ft_on_transfer(nep141, alice.clone(), alice, amount, hex::encode(recipient));
+ let res = runner.ft_on_transfer(nep141, alice.clone(), alice, amount, recipient.encode());
// Transaction should fail so it must return everything
assert_eq!(res, format!("\"{}\"", amount.to_string()));
@@ -327,7 +328,7 @@ fn test_relayer_charge_fee() {
alice.clone(),
alice,
amount,
- hex::encode(recipient) + &hex::encode(fee_encoded),
+ recipient.encode() + &hex::encode(fee_encoded),
);
let recipient_balance_end = runner.get_balance(recipient.into());
@@ -390,7 +391,7 @@ fn test_transfer_erc20_token() {
// Note: `AuroraRunner` is not suitable for these tests because
// it does not execute promises; but `near-sdk-sim` does.
mod sim_tests {
- use crate::prelude::{types::Wei, Address, WeiU256, U256};
+ use crate::prelude::{Wei, WeiU256, U256};
use crate::test_utils;
use crate::test_utils::erc20::{ERC20Constructor, ERC20};
use crate::test_utils::exit_precompile::TesterConstructor;
@@ -398,6 +399,7 @@ mod sim_tests {
use aurora_engine::parameters::{
CallArgs, DeployErc20TokenArgs, FunctionCallArgsV2, SubmitResult,
};
+ use aurora_engine_types::types::Address;
use borsh::BorshSerialize;
use near_sdk_sim::UserAccount;
use serde_json::json;
@@ -603,7 +605,7 @@ mod sim_tests {
aurora
.call(
"mint_account",
- &(signer_address.0, signer.nonce, INITIAL_ETH_BALANCE)
+ &(signer_address, signer.nonce, INITIAL_ETH_BALANCE)
.try_to_vec()
.unwrap(),
)
@@ -626,7 +628,8 @@ mod sim_tests {
let constructor = TesterConstructor::load();
let deploy_data = constructor.deploy(0, Address::zero()).data;
let submit_result: SubmitResult = aurora.call("deploy_code", &deploy_data).unwrap_borsh();
- let tester_address = Address::from_slice(&test_utils::unwrap_success(submit_result));
+ let tester_address =
+ Address::try_from_slice(&test_utils::unwrap_success(submit_result)).unwrap();
TestExitToNearEthContext {
signer,
@@ -651,7 +654,7 @@ mod sim_tests {
aurora
.call(
"mint_account",
- &(ft_owner_address.0, 0u64, INITIAL_ETH_BALANCE)
+ &(ft_owner_address, 0u64, INITIAL_ETH_BALANCE)
.try_to_vec()
.unwrap(),
)
@@ -718,7 +721,7 @@ mod sim_tests {
],
);
let call_args = CallArgs::V2(FunctionCallArgsV2 {
- contract: erc20.0.address.0,
+ contract: erc20.0.address,
value: WeiU256::default(),
input,
});
@@ -758,7 +761,7 @@ mod sim_tests {
let mint_tx = erc20.mint(dest, amount.into(), 0.into());
let call_args = CallArgs::V2(FunctionCallArgsV2 {
- contract: erc20.0.address.0,
+ contract: erc20.0.address,
value: WeiU256::default(),
input: mint_tx.data,
});
@@ -789,7 +792,7 @@ mod sim_tests {
fn erc20_balance(erc20: &ERC20, address: Address, aurora: &AuroraAccount) -> U256 {
let balance_tx = erc20.balance_of(address, 0.into());
let call_args = CallArgs::V2(FunctionCallArgsV2 {
- contract: erc20.0.address.0,
+ contract: erc20.0.address,
value: WeiU256::default(),
input: balance_tx.data,
});
@@ -807,7 +810,7 @@ mod sim_tests {
};
let result = aurora.call("deploy_erc20_token", &args.try_to_vec().unwrap());
let addr_bytes: Vec = result.unwrap_borsh();
- let address = Address::from_slice(&addr_bytes);
+ let address = Address::try_from_slice(&addr_bytes).unwrap();
let abi = ERC20Constructor::load().0.abi;
ERC20(crate::test_utils::solidity::DeployedContract { abi, address })
}
diff --git a/engine-tests/src/tests/eth_connector.rs b/engine-tests/src/tests/eth_connector.rs
index 147fd07ac..3882dd12b 100644
--- a/engine-tests/src/tests/eth_connector.rs
+++ b/engine-tests/src/tests/eth_connector.rs
@@ -1,4 +1,4 @@
-use crate::prelude::EthAddress;
+use crate::prelude::Address;
use crate::prelude::WithdrawCallArgs;
use crate::test_utils::str_to_account_id;
use aurora_engine::admin_controlled::{PausedMask, ERR_PAUSED};
@@ -98,12 +98,8 @@ fn init_contract(
contract_account
}
-fn validate_eth_address(address: &str) -> EthAddress {
- let data = hex::decode(address).unwrap();
- assert_eq!(data.len(), 20);
- let mut result = [0u8; 20];
- result.copy_from_slice(&data);
- result
+fn validate_eth_address(address: &str) -> Address {
+ Address::decode(address).unwrap()
}
fn call_deposit_eth_to_near(
@@ -192,10 +188,10 @@ fn get_eth_on_near_balance(master_account: &UserAccount, acc: &str, contract: &s
val.parse().unwrap()
}
-fn get_eth_balance(master_account: &UserAccount, address: EthAddress, contract: &str) -> u128 {
+fn get_eth_balance(master_account: &UserAccount, address: Address, contract: &str) -> u128 {
#[derive(BorshSerialize, BorshDeserialize)]
pub struct BalanceOfEthCallArgs {
- pub address: EthAddress,
+ pub address: Address,
}
let balance = master_account.view(
@@ -412,7 +408,11 @@ fn test_ft_transfer_call_eth() {
let transfer_amount = 50;
let fee: u128 = 30;
let mut msg = U256::from(fee).as_byte_slice().to_vec();
- msg.append(&mut validate_eth_address(RECIPIENT_ETH_ADDRESS).to_vec());
+ msg.append(
+ &mut validate_eth_address(RECIPIENT_ETH_ADDRESS)
+ .as_bytes()
+ .to_vec(),
+ );
let message = [CONTRACT_ACC, hex::encode(msg).as_str()].join(":");
let res = contract.call(
@@ -597,15 +597,10 @@ fn test_deposit_with_0x_prefix() {
use aurora_engine::deposit_event::TokenMessageData;
let (master_account, contract) = init(CUSTODIAN_ADDRESS);
- let eth_custodian_address: [u8; 20] = {
- let mut buf = [0u8; 20];
- let bytes = hex::decode(CUSTODIAN_ADDRESS).unwrap();
- buf.copy_from_slice(&bytes);
- buf
- };
- let recipient_address = [10u8; 20];
+ let eth_custodian_address: Address = Address::decode(&CUSTODIAN_ADDRESS.to_string()).unwrap();
+ let recipient_address = Address::from_array([10u8; 20]);
let deposit_amount = 17;
- let recipient_address_encoded = hex::encode(&recipient_address);
+ let recipient_address_encoded = recipient_address.encode();
// Note the 0x prefix before the deposit address.
let message = [CONTRACT_ACC, ":", "0x", &recipient_address_encoded].concat();
@@ -616,7 +611,7 @@ fn test_deposit_with_0x_prefix() {
let deposit_event = aurora_engine::deposit_event::DepositedEvent {
eth_custodian_address,
- sender: [0u8; 20],
+ sender: Address::zero(),
token_message_data,
amount: NEP141Wei::new(deposit_amount),
fee,
@@ -628,7 +623,7 @@ fn test_deposit_with_0x_prefix() {
anonymous: false,
};
let log_entry = aurora_engine::log_entry::LogEntry {
- address: eth_custodian_address.into(),
+ address: eth_custodian_address.raw(),
topics: vec![
event_schema.signature(),
// the sender is not important
@@ -718,7 +713,11 @@ fn test_ft_transfer_call_without_relayer() {
let transfer_amount = 50;
let fee: u128 = 30;
let mut msg = U256::from(fee).as_byte_slice().to_vec();
- msg.append(&mut validate_eth_address(RECIPIENT_ETH_ADDRESS).to_vec());
+ msg.append(
+ &mut validate_eth_address(RECIPIENT_ETH_ADDRESS)
+ .as_bytes()
+ .to_vec(),
+ );
let relayer_id = "relayer.root";
let message = [relayer_id, hex::encode(msg).as_str()].join(":");
let res = contract.call(
@@ -774,7 +773,11 @@ fn test_ft_transfer_call_fee_greater_than_amount() {
let transfer_amount = 10;
let fee: u128 = transfer_amount + 10;
let mut msg = fee.to_be_bytes().to_vec();
- msg.append(&mut validate_eth_address(RECIPIENT_ETH_ADDRESS).to_vec());
+ msg.append(
+ &mut validate_eth_address(RECIPIENT_ETH_ADDRESS)
+ .as_bytes()
+ .to_vec(),
+ );
let relayer_id = "relayer.root";
let message = [relayer_id, hex::encode(msg).as_str()].join(":");
let res = contract.call(
diff --git a/engine-tests/src/tests/meta_parsing.rs b/engine-tests/src/tests/meta_parsing.rs
index 5648cc771..2c6689018 100644
--- a/engine-tests/src/tests/meta_parsing.rs
+++ b/engine-tests/src/tests/meta_parsing.rs
@@ -47,8 +47,8 @@ fn encode_meta_call_function_args(
v: 27,
nonce: u256_to_arr(&nonce),
fee_amount: fee_amount.to_bytes(),
- fee_address: fee_address.0,
- contract_address: contract_address.0,
+ fee_address,
+ contract_address,
value: value.to_bytes(),
method_def: method_def.to_string(),
args,
@@ -65,9 +65,7 @@ fn public_key_to_address(public_key: PublicKey) -> Address {
PublicKey::SECP256K1(pubkey) => {
let pk: [u8; 64] = pubkey.into();
let bytes = keccak(&pk.to_vec());
- let mut result = Address::zero();
- result.as_bytes_mut().copy_from_slice(&bytes[12..]);
- result
+ Address::try_from_slice(&bytes[12..]).unwrap()
}
}
}
@@ -84,7 +82,7 @@ fn test_meta_parsing() {
chain_id,
U256::from(14),
Wei::new_u64(6),
- Address::from_slice(&[0u8; 20]),
+ Address::try_from_slice(&[0u8; 20]).unwrap(),
signer_addr.clone(),
Wei::zero(),
"adopt(uint256 petId)",
@@ -104,7 +102,7 @@ fn test_meta_parsing() {
chain_id,
U256::from(14),
Wei::new_u64(6),
- Address::from_slice(&[0u8; 20]),
+ Address::try_from_slice(&[0u8; 20]).unwrap(),
signer_addr.clone(),
Wei::zero(),
"adopt(uint256 petId,PetObj petObject)PetObj(string petName,address owner)",
diff --git a/engine-tests/src/tests/sanity.rs b/engine-tests/src/tests/sanity.rs
index cd9435ca4..1c82323ae 100644
--- a/engine-tests/src/tests/sanity.rs
+++ b/engine-tests/src/tests/sanity.rs
@@ -57,7 +57,7 @@ fn test_deploy_contract() {
test_utils::create_deploy_transaction(code.clone(), nonce)
})
.unwrap();
- let address = Address::from_slice(test_utils::unwrap_success_slice(&result));
+ let address = Address::try_from_slice(test_utils::unwrap_success_slice(&result)).unwrap();
// Confirm the code stored at that address is equal to the input code.
let stored_code = runner.get_code(address);
@@ -123,7 +123,7 @@ fn test_log_address() {
.submit_with_signer(&mut signer, |nonce| {
caller_contract.call_method_with_args(
"greet",
- &[ethabi::Token::Address(greet_contract.address)],
+ &[ethabi::Token::Address(greet_contract.address.raw())],
nonce,
)
})
@@ -132,7 +132,7 @@ fn test_log_address() {
// Address included in the log should come from the contract emitting the log,
// not the contract that invoked the call.
let log_address = result.logs.first().unwrap().address;
- assert_eq!(Address(log_address), greet_contract.address);
+ assert_eq!(log_address, greet_contract.address);
}
#[test]
@@ -204,7 +204,7 @@ fn test_override_state() {
}
})
.unwrap();
- let address = Address::from_slice(&test_utils::unwrap_success(result));
+ let address = Address::try_from_slice(&test_utils::unwrap_success(result)).unwrap();
let contract = contract.deployed_at(address);
// define functions to interact with the contract
@@ -217,7 +217,7 @@ fn test_override_state() {
.unwrap();
match result {
crate::prelude::parameters::TransactionStatus::Succeed(bytes) => {
- Address::from_slice(&bytes[12..32])
+ Address::try_from_slice(&bytes[12..32]).unwrap()
}
_ => panic!("tx failed"),
}
@@ -237,7 +237,7 @@ fn test_override_state() {
};
// Assert the initial state is 0
- assert_eq!(get_address(&runner), Address([0; 20]));
+ assert_eq!(get_address(&runner), Address::new(H160([0; 20])));
post_address(&mut runner, &mut account1);
// Assert the address matches the first caller
assert_eq!(get_address(&runner), account1_address);
@@ -517,6 +517,7 @@ fn initialize_transfer() -> (test_utils::AuroraRunner, test_utils::Signer, Addre
(runner, signer, dest_address)
}
+use aurora_engine_types::H160;
use sha3::Digest;
#[test]
@@ -621,7 +622,7 @@ fn test_eth_transfer_insufficient_balance_sim() {
// Run transaction which will fail (transfer more than current balance)
let nonce = signer.use_nonce();
let tx = test_utils::transfer(
- Address([1; 20]),
+ Address::new(H160([1; 20])),
INITIAL_BALANCE + INITIAL_BALANCE,
nonce.into(),
);
@@ -652,7 +653,7 @@ fn test_eth_transfer_charging_gas_not_enough_balance_sim() {
// Run transaction which will fail (not enough balance to cover gas)
let nonce = signer.use_nonce();
- let mut tx = test_utils::transfer(Address([1; 20]), TRANSFER_AMOUNT, nonce.into());
+ let mut tx = test_utils::transfer(Address::new(H160([1; 20])), TRANSFER_AMOUNT, nonce.into());
tx.gas_limit = 3_000_000.into();
tx.gas_price = GAS_PRICE.into();
let signed_tx = test_utils::sign_transaction(
@@ -680,7 +681,7 @@ fn initialize_evm_sim() -> (state_migration::AuroraAccount, test_utils::Signer,
let signer = test_utils::Signer::random();
let address = test_utils::address_from_secret_key(&signer.secret_key);
- let args = (address.0, INITIAL_NONCE, INITIAL_BALANCE.raw().low_u64());
+ let args = (address, INITIAL_NONCE, INITIAL_BALANCE.raw().low_u64());
aurora
.call("mint_account", &args.try_to_vec().unwrap())
.assert_success();
@@ -703,7 +704,7 @@ fn query_address_sim(
method: &str,
aurora: &state_migration::AuroraAccount,
) -> U256 {
- let x = aurora.call(method, &address.0);
+ let x = aurora.call(method, address.as_bytes());
match &x.outcome().status {
near_sdk_sim::transaction::ExecutionStatus::SuccessValue(b) => U256::from_big_endian(&b),
other => panic!("Unexpected outcome: {:?}", other),
diff --git a/engine-tests/src/tests/standalone/json_snapshot.rs b/engine-tests/src/tests/standalone/json_snapshot.rs
index 45e191089..0325cd799 100644
--- a/engine-tests/src/tests/standalone/json_snapshot.rs
+++ b/engine-tests/src/tests/standalone/json_snapshot.rs
@@ -1,5 +1,6 @@
use crate::test_utils::standalone;
-use aurora_engine_types::{Address, U256};
+use aurora_engine_types::types::Address;
+use aurora_engine_types::{H160, U256};
use engine_standalone_storage::json_snapshot;
const NONCE_PREFIX: [u8; 2] = [0x07, 0x01];
@@ -40,5 +41,5 @@ fn test_consume_snapshot() {
fn address_from_key(key: &[u8]) -> Address {
let mut result = [0u8; 20];
result.copy_from_slice(&key[2..22]);
- Address(result)
+ Address::new(H160(result))
}
diff --git a/engine-tests/src/tests/standalone/sanity.rs b/engine-tests/src/tests/standalone/sanity.rs
index b043e6607..f537951d5 100644
--- a/engine-tests/src/tests/standalone/sanity.rs
+++ b/engine-tests/src/tests/standalone/sanity.rs
@@ -1,8 +1,8 @@
use crate::test_utils::standalone::mocks::{promise, storage};
use aurora_engine::engine;
use aurora_engine_sdk::env::DEFAULT_PREPAID_GAS;
-use aurora_engine_types::types::Wei;
-use aurora_engine_types::{account_id::AccountId, Address, H256, U256};
+use aurora_engine_types::types::{Address, Wei};
+use aurora_engine_types::{account_id::AccountId, H160, H256, U256};
use std::sync::RwLock;
#[test]
@@ -20,7 +20,7 @@ fn test_deploy_code() {
bridge_prover_id: "mr_the_prover".parse().unwrap(),
upgrade_delay_blocks: 0,
};
- let origin = Address([0u8; 20]);
+ let origin = Address::new(H160([0u8; 20]));
let storage = RwLock::new(storage::Storage::default());
let io = storage::StoragePointer(&storage);
let env = aurora_engine_sdk::env::Fixed {
@@ -50,7 +50,9 @@ fn test_deploy_code() {
// execution was successful
let contract_address = match result.unwrap().status {
- aurora_engine::parameters::TransactionStatus::Succeed(bytes) => Address::from_slice(&bytes),
+ aurora_engine::parameters::TransactionStatus::Succeed(bytes) => {
+ Address::try_from_slice(&bytes).unwrap()
+ }
other => panic!("Unexpected status: {:?}", other),
};
diff --git a/engine-tests/src/tests/standalone/storage.rs b/engine-tests/src/tests/standalone/storage.rs
index 5fd0606d4..7c963591f 100644
--- a/engine-tests/src/tests/standalone/storage.rs
+++ b/engine-tests/src/tests/standalone/storage.rs
@@ -1,6 +1,7 @@
use aurora_engine::engine;
use aurora_engine_sdk::env::Timestamp;
-use aurora_engine_types::{types::Wei, Address, H256, U256};
+use aurora_engine_types::types::{Address, Wei};
+use aurora_engine_types::{H256, U256};
use engine_standalone_storage::BlockMetadata;
use crate::test_utils::standalone::{mocks, storage::create_db};
@@ -236,9 +237,7 @@ fn test_transaction_index() {
aurora_engine_types::storage::KeyPrefix::Balance,
&[1u8; 20],
);
- let value = aurora_engine_types::types::Wei::new_u64(159)
- .to_bytes()
- .to_vec();
+ let value = crate::prelude::Wei::new_u64(159).to_bytes().to_vec();
tmp.modify(key, value);
tmp
};
diff --git a/engine-tests/src/tests/standalone/sync.rs b/engine-tests/src/tests/standalone/sync.rs
index dc73bfec9..b12a93fd6 100644
--- a/engine-tests/src/tests/standalone/sync.rs
+++ b/engine-tests/src/tests/standalone/sync.rs
@@ -1,7 +1,7 @@
use aurora_engine::deposit_event::TokenMessageData;
use aurora_engine_sdk::env::{Env, Timestamp};
-use aurora_engine_types::types::{Balance, Fee, NEP141Wei};
-use aurora_engine_types::{account_id::AccountId, types::Wei, Address, H256, U256};
+use aurora_engine_types::types::{Address, Balance, Fee, NEP141Wei, Wei};
+use aurora_engine_types::{account_id::AccountId, H160, H256, U256};
use borsh::BorshSerialize;
use engine_standalone_storage::sync;
@@ -40,7 +40,7 @@ fn test_consume_block_message() {
fn test_consume_deposit_message() {
let (mut runner, block_message) = initialize();
- let recipient_address = Address([22u8; 20]);
+ let recipient_address = Address::new(H160([22u8; 20]));
let deposit_amount = Wei::new_u64(123_456_789);
let proof = mock_proof(recipient_address, deposit_amount);
@@ -97,11 +97,11 @@ fn test_consume_deploy_message() {
position: 0,
})
.unwrap();
- let mut deployed_address = Address([0u8; 20]);
+ let mut deployed_address = Address::zero();
for (key, value) in diff.iter() {
match value.value() {
Some(bytes) if bytes == code.as_slice() => {
- deployed_address.0.copy_from_slice(&key[2..22]);
+ deployed_address = Address::try_from_slice(&key[2..22]).unwrap();
break;
}
_ => continue,
@@ -119,7 +119,7 @@ fn test_consume_deploy_erc20_message() {
let token: AccountId = "some_nep141.near".parse().unwrap();
let mint_amount: u128 = 555_555;
- let dest_address = Address([170u8; 20]);
+ let dest_address = Address::new(H160([170u8; 20]));
let args = aurora_engine::parameters::DeployErc20TokenArgs {
nep141: token.clone(),
@@ -180,7 +180,7 @@ fn test_consume_deploy_erc20_message() {
let deployed_token = test_utils::erc20::ERC20(
test_utils::erc20::ERC20Constructor::load()
.0
- .deployed_at(Address::from_slice(&erc20_address)),
+ .deployed_at(Address::try_from_slice(&erc20_address).unwrap()),
);
let signer = test_utils::Signer::random();
let tx = deployed_token.balance_of(dest_address, signer.nonce.into());
@@ -200,7 +200,7 @@ fn test_consume_ft_on_transfer_message() {
let mint_amount = 8_675_309;
let fee = Wei::zero();
- let dest_address = Address([221u8; 20]);
+ let dest_address = Address::new(H160([221u8; 20]));
// Mint ETH on Aurora per the bridge workflow
let args = aurora_engine::parameters::NEP141FtOnTransferArgs {
@@ -245,7 +245,7 @@ fn test_consume_call_message() {
let initial_balance = Wei::new_u64(800_000);
let transfer_amount = Wei::new_u64(115_321);
let caller_address = aurora_engine_sdk::types::near_account_to_evm_address(caller.as_bytes());
- let recipient_address = Address([1u8; 20]);
+ let recipient_address = Address::new(H160([1u8; 20]));
runner.mint_account(caller_address, initial_balance, U256::zero(), None);
runner.env.block_height += 1;
@@ -290,7 +290,7 @@ fn test_consume_submit_message() {
let initial_balance = Wei::new_u64(800_000);
let transfer_amount = Wei::new_u64(115_321);
let signer_address = test_utils::address_from_secret_key(&signer.secret_key);
- let recipient_address = Address([1u8; 20]);
+ let recipient_address = Address::new(H160([1u8; 20]));
runner.mint_account(signer_address, initial_balance, signer.nonce.into(), None);
runner.env.block_height += 1;
@@ -335,14 +335,14 @@ fn mock_proof(recipient_address: Address, deposit_amount: Wei) -> aurora_engine:
let eth_custodian_address = test_utils::standalone::mocks::ETH_CUSTODIAN_ADDRESS;
let fee = Fee::new(NEP141Wei::new(0));
- let message = ["aurora", ":", hex::encode(&recipient_address).as_str()].concat();
+ let message = ["aurora", ":", recipient_address.encode().as_str()].concat();
let token_message_data: TokenMessageData =
TokenMessageData::parse_event_message_and_prepare_token_message_data(&message, fee)
.unwrap();
let deposit_event = aurora_engine::deposit_event::DepositedEvent {
- eth_custodian_address: eth_custodian_address.0,
- sender: [0u8; 20],
+ eth_custodian_address,
+ sender: Address::new(H160([0u8; 20])),
token_message_data,
amount: NEP141Wei::new(deposit_amount.raw().as_u128()),
fee,
@@ -354,7 +354,7 @@ fn mock_proof(recipient_address: Address, deposit_amount: Wei) -> aurora_engine:
anonymous: false,
};
let log_entry = aurora_engine::log_entry::LogEntry {
- address: eth_custodian_address,
+ address: eth_custodian_address.raw(),
topics: vec![
event_schema.signature(),
// the sender is not important
@@ -382,7 +382,7 @@ fn simple_transfer_args(
transfer_amount: Wei,
) -> aurora_engine::parameters::CallArgs {
aurora_engine::parameters::CallArgs::V2(aurora_engine::parameters::FunctionCallArgsV2 {
- contract: dest_address.0,
+ contract: dest_address,
value: transfer_amount.to_bytes(),
input: Vec::new(),
})
diff --git a/engine-tests/src/tests/standalone/tracing.rs b/engine-tests/src/tests/standalone/tracing.rs
index 1ac5a27c5..b3beb4646 100644
--- a/engine-tests/src/tests/standalone/tracing.rs
+++ b/engine-tests/src/tests/standalone/tracing.rs
@@ -1,5 +1,6 @@
use aurora_engine_sdk::env::Env;
-use aurora_engine_types::{types::Wei, Address, H256, U256};
+use aurora_engine_types::types::{Address, Wei};
+use aurora_engine_types::{H256, U256};
use engine_standalone_tracing::{sputnik, types::TransactionTrace};
use serde::Deserialize;
use std::path::Path;
@@ -20,9 +21,9 @@ fn test_evm_tracing_with_storage() {
let mut signer = test_utils::Signer::random();
let signer_address = test_utils::address_from_secret_key(&signer.secret_key);
let sender_address =
- Address::from_slice(&hex::decode("304ee8ae14eceb3a544dff53a27eb1bb1aaa471f").unwrap());
+ Address::decode(&"304ee8ae14eceb3a544dff53a27eb1bb1aaa471f".to_string()).unwrap();
let weth_address =
- Address::from_slice(&hex::decode("c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap());
+ Address::decode(&"c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2".to_string()).unwrap();
// Initialize EVM
runner.init_evm_with_chain_id(1);
@@ -34,7 +35,8 @@ fn test_evm_tracing_with_storage() {
let result = runner
.submit_transaction(&signer.secret_key, deploy_tx)
.unwrap();
- let contract_address = Address::from_slice(test_utils::unwrap_success_slice(&result));
+ let contract_address =
+ Address::try_from_slice(test_utils::unwrap_success_slice(&result)).unwrap();
// Move it over to the same address as it exists on mainnet
let mut diff = engine_standalone_storage::Diff::default();
@@ -139,7 +141,8 @@ fn test_evm_tracing() {
let result = runner
.submit_transaction(&signer.secret_key, deploy_tx)
.unwrap();
- let contract_address = Address::from_slice(test_utils::unwrap_success_slice(&result));
+ let contract_address =
+ Address::try_from_slice(test_utils::unwrap_success_slice(&result)).unwrap();
// Interact with contract (and trace execution)
let tx = aurora_engine::transaction::legacy::TransactionLegacy {
diff --git a/engine-tests/src/tests/uniswap.rs b/engine-tests/src/tests/uniswap.rs
index ba4a2d94e..3885fa0c8 100644
--- a/engine-tests/src/tests/uniswap.rs
+++ b/engine-tests/src/tests/uniswap.rs
@@ -9,6 +9,7 @@ use crate::test_utils::{
AuroraRunner, ExecutionProfile, Signer,
};
use aurora_engine_types::types::Wei;
+use aurora_engine_types::H160;
use secp256k1::SecretKey;
const INITIAL_BALANCE: u64 = 1000;
@@ -96,7 +97,7 @@ impl UniswapTestContext {
c.deploy(
factory.0.address,
weth_address,
- Address([0; 20]),
+ Address::new(H160([0; 20])),
nonce.into(),
)
},
@@ -147,9 +148,8 @@ impl UniswapTestContext {
.unwrap();
assert!(result.status.is_ok(), "Failed to create pool");
- let mut address = [0u8; 20];
- address.copy_from_slice(&test_utils::unwrap_success(result)[12..]);
- let pool = Pool::from_address(Address(address));
+ let address = Address::try_from_slice(&test_utils::unwrap_success(result)[12..]).unwrap();
+ let pool = Pool::from_address(address);
// 2^96 corresponds to a price ratio of 1
let result = self
@@ -232,7 +232,8 @@ impl UniswapTestContext {
token_in: token_in.0.address,
token_out: token_out.0.address,
fee: POOL_FEE,
- recipient: Address([0; 20]),
+
+ recipient: Address::new(H160([0; 20])),
deadline: U256::MAX,
amount_out,
amount_in_max: U256::from(100) * amount_out,
diff --git a/engine-types/src/lib.rs b/engine-types/src/lib.rs
index 731a17a22..8c8b37415 100644
--- a/engine-types/src/lib.rs
+++ b/engine-types/src/lib.rs
@@ -43,12 +43,3 @@ mod v0 {
}
pub use v0::*;
-
-/// See: https://ethereum-magicians.org/t/increasing-address-size-from-20-to-32-bytes/5485
-pub type Address = H160;
-
-#[allow(non_snake_case, dead_code)]
-// Gets around the fact that you can't contract pub fields with types.
-pub const fn Address(input: [u8; 20]) -> Address {
- H160(input)
-}
diff --git a/engine-types/src/parameters.rs b/engine-types/src/parameters.rs
index 200f2751f..7781d1936 100644
--- a/engine-types/src/parameters.rs
+++ b/engine-types/src/parameters.rs
@@ -53,14 +53,14 @@ pub struct PromiseBatchAction {
/// withdraw NEAR eth-connector call args
#[derive(Debug, BorshSerialize, BorshDeserialize)]
pub struct WithdrawCallArgs {
- pub recipient_address: EthAddress,
+ pub recipient_address: Address,
pub amount: NEP141Wei,
}
/// withdraw NEAR eth-connector call args
#[derive(BorshSerialize, BorshDeserialize)]
pub struct RefundCallArgs {
- pub recipient_address: EthAddress,
- pub erc20_address: Option,
+ pub recipient_address: Address,
+ pub erc20_address: Option,
pub amount: RawU256,
}
diff --git a/engine-types/src/storage.rs b/engine-types/src/storage.rs
index 9a6827a96..94ba85d45 100644
--- a/engine-types/src/storage.rs
+++ b/engine-types/src/storage.rs
@@ -1,3 +1,4 @@
+use crate::types::Address;
use crate::*;
use borsh::{BorshDeserialize, BorshSerialize};
@@ -65,7 +66,7 @@ pub fn address_to_key(prefix: KeyPrefix, address: &Address) -> [u8; 22] {
let mut result = [0u8; 22];
result[0] = VersionPrefix::V1 as u8;
result[1] = prefix as u8;
- result[2..22].copy_from_slice(&address.0);
+ result[2..22].copy_from_slice(address.as_bytes());
result
}
@@ -97,7 +98,7 @@ fn normal_storage_key(address: &Address, key: &H256) -> [u8; 54] {
let mut result = [0u8; 54];
result[0] = VersionPrefix::V1 as u8;
result[1] = KeyPrefix::Storage as u8;
- result[2..22].copy_from_slice(&address.0);
+ result[2..22].copy_from_slice(address.as_bytes());
result[22..54].copy_from_slice(&key.0);
result
}
@@ -107,7 +108,7 @@ fn generation_storage_key(address: &Address, key: &H256, generation: u32) -> [u8
let mut result = [0u8; 58];
result[0] = VersionPrefix::V1 as u8;
result[1] = KeyPrefix::Storage as u8;
- result[2..22].copy_from_slice(&address.0);
+ result[2..22].copy_from_slice(address.as_bytes());
result[22..26].copy_from_slice(&generation.to_le_bytes());
result[26..58].copy_from_slice(&key.0);
result
diff --git a/engine-types/src/types/address.rs b/engine-types/src/types/address.rs
new file mode 100755
index 000000000..1ac94cc31
--- /dev/null
+++ b/engine-types/src/types/address.rs
@@ -0,0 +1,172 @@
+use crate::{format, String, TryFrom, H160};
+use borsh::maybestd::io;
+use borsh::{BorshDeserialize, BorshSerialize};
+
+/// Base Eth Address type
+#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
+pub struct Address(H160);
+
+impl Address {
+ /// Construct Address from H160
+ pub const fn new(val: H160) -> Self {
+ Self(val)
+ }
+
+ /// Get raw H160 data
+ pub fn raw(&self) -> H160 {
+ self.0
+ }
+
+ /// Encode address to string
+ pub fn encode(&self) -> String {
+ hex::encode(self.0.as_bytes())
+ }
+
+ pub fn decode(address: &str) -> Result {
+ if address.len() != 40 {
+ return Err(error::AddressError::IncorrectLength);
+ }
+ let mut result = [0u8; 20];
+ hex::decode_to_slice(address, &mut result)
+ .map_err(|_| error::AddressError::FailedDecodeHex)?;
+ Ok(Address::new(H160(result)))
+ }
+
+ pub fn as_bytes(&self) -> &[u8] {
+ self.0.as_bytes()
+ }
+
+ pub fn try_from_slice(raw_addr: &[u8]) -> Result {
+ if raw_addr.len() != 20 {
+ return Err(error::AddressError::IncorrectLength);
+ }
+ Ok(Self::new(H160::from_slice(raw_addr)))
+ }
+
+ pub fn from_array(array: [u8; 20]) -> Self {
+ Self(H160(array))
+ }
+
+ pub const fn zero() -> Self {
+ Address::new(H160([0u8; 20]))
+ }
+}
+
+impl TryFrom<&[u8]> for Address {
+ type Error = error::AddressError;
+
+ fn try_from(raw_addr: &[u8]) -> Result {
+ Self::try_from_slice(raw_addr).map_err(|_| error::AddressError::IncorrectLength)
+ }
+}
+
+impl BorshSerialize for Address {
+ fn serialize(&self, writer: &mut W) -> io::Result<()> {
+ writer.write_all(self.0.as_bytes())
+ }
+}
+
+impl BorshDeserialize for Address {
+ fn deserialize(buf: &mut &[u8]) -> io::Result {
+ if buf.len() < 20 {
+ return Err(io::Error::new(
+ io::ErrorKind::Other,
+ format!("{}", error::AddressError::IncorrectLength),
+ ));
+ }
+ // Guaranty no panics. The length checked early
+ let address = Self(H160::from_slice(&buf[..20]));
+ *buf = &buf[20..];
+ Ok(address)
+ }
+}
+
+impl Default for Address {
+ fn default() -> Self {
+ Address::zero()
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn test_address_serializer() {
+ let eth_address = "096DE9C2B8A5B8c22cEe3289B101f6960d68E51E";
+ // borsh serialize
+ let serialized_addr =
+ Address::new(H160::from_slice(&hex::decode(eth_address).unwrap()[..]))
+ .try_to_vec()
+ .unwrap();
+ assert_eq!(serialized_addr.len(), 20);
+
+ let addr = Address::try_from_slice(&serialized_addr).unwrap();
+ assert_eq!(
+ addr.encode(),
+ "096DE9C2B8A5B8c22cEe3289B101f6960d68E51E".to_lowercase()
+ );
+ }
+
+ #[test]
+ fn test_address_decode() {
+ // Test compatibility with previous typ RawAddress.
+ // It was: type RawAddress = [u8;20];
+ let eth_address_vec =
+ hex::decode("096DE9C2B8A5B8c22cEe3289B101f6960d68E51E".to_string()).unwrap();
+ let mut eth_address = [0u8; 20];
+ eth_address.copy_from_slice(ð_address_vec[..]);
+
+ let aurora_eth_address =
+ Address::decode(&"096DE9C2B8A5B8c22cEe3289B101f6960d68E51E".to_string()).unwrap();
+ assert_eq!(eth_address, aurora_eth_address.as_bytes());
+
+ let serialized_addr = eth_address.try_to_vec().unwrap();
+ let aurora_serialized_addr = aurora_eth_address.try_to_vec().unwrap();
+
+ assert_eq!(serialized_addr.len(), 20);
+ assert_eq!(aurora_serialized_addr.len(), 20);
+ assert_eq!(serialized_addr, aurora_serialized_addr);
+
+ // Used serialized data from `RawAddress`
+ let addr = Address::try_from_slice(&serialized_addr).unwrap();
+ assert_eq!(
+ addr.encode(),
+ "096DE9C2B8A5B8c22cEe3289B101f6960d68E51E".to_lowercase()
+ );
+ }
+
+ #[test]
+ fn test_wrong_address_19() {
+ let serialized_addr = [0u8; 19];
+ let addr = Address::try_from_slice(&serialized_addr);
+ let err = addr.unwrap_err();
+ matches!(err, error::AddressError::IncorrectLength);
+ }
+}
+
+pub mod error {
+ use crate::{fmt, String};
+
+ #[derive(Eq, Hash, Clone, Debug, PartialEq)]
+ pub enum AddressError {
+ FailedDecodeHex,
+ IncorrectLength,
+ }
+
+ impl AsRef<[u8]> for AddressError {
+ fn as_ref(&self) -> &[u8] {
+ match self {
+ Self::FailedDecodeHex => b"FAILED_DECODE_ETH_ADDRESS",
+ Self::IncorrectLength => b"ETH_WRONG_ADDRESS_LENGTH",
+ }
+ }
+ }
+
+ impl fmt::Display for AddressError {
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ let msg = String::from_utf8(self.as_ref().to_vec()).unwrap();
+ write!(f, "{}", msg)
+ }
+ }
+}
diff --git a/engine-types/src/types/mod.rs b/engine-types/src/types/mod.rs
index d566056d5..f33b8c7d9 100644
--- a/engine-types/src/types/mod.rs
+++ b/engine-types/src/types/mod.rs
@@ -1,21 +1,21 @@
-use crate::{str, vec, Address, String, Vec, U256};
+use crate::{str, vec, String, Vec, U256};
+pub mod address;
pub mod balance;
pub mod fee;
pub mod gas;
pub mod wei;
+pub use address::*;
pub use balance::*;
pub use fee::*;
pub use gas::*;
pub use wei::*;
-pub type RawAddress = [u8; 20];
pub type RawU256 = [u8; 32];
// Big-endian large integer type.
pub type RawH256 = [u8; 32]; // Unformatted binary data of fixed length.
-pub type EthAddress = [u8; 20];
pub type StorageUsage = u64;
/// Selector to call mint function in ERC 20 contract
@@ -39,17 +39,6 @@ impl AsRef<[u8]> for AddressValidationError {
}
}
-/// Validate Ethereum address from string and return Result data EthAddress or Error data
-pub fn validate_eth_address(address: String) -> Result {
- let data = hex::decode(address).map_err(|_| AddressValidationError::FailedDecodeHex)?;
- if data.len() != 20 {
- return Err(AddressValidationError::IncorrectLength);
- }
- let mut result = [0u8; 20];
- result.copy_from_slice(&data);
- Ok(result)
-}
-
pub const STORAGE_PRICE_PER_BYTE: u128 = 10_000_000_000_000_000_000;
// 1e19yN, 0.00001N
pub const ERR_FAILED_PARSE: &str = "ERR_FAILED_PARSE";
diff --git a/engine/src/connector.rs b/engine/src/connector.rs
index 68d1707c4..5451bd577 100644
--- a/engine/src/connector.rs
+++ b/engine/src/connector.rs
@@ -9,18 +9,16 @@ use crate::parameters::{
StorageWithdrawCallArgs, TransferCallArgs, TransferCallCallArgs, WithdrawResult,
};
use crate::prelude::{
- format, sdk, str, validate_eth_address, AccountId, Address, BorshDeserialize, BorshSerialize,
- EthAddress, EthConnectorStorageId, KeyPrefix, NearGas, PromiseResult, ToString, Vec,
- WithdrawCallArgs, Yocto, ERR_FAILED_PARSE, H160,
+ address::error::AddressError, NEP141Wei, Wei, U256, ZERO_NEP141_WEI, ZERO_WEI,
};
use crate::prelude::{
- AddressValidationError, PromiseBatchAction, PromiseCreateArgs, PromiseWithCallbackArgs,
+ format, sdk, str, AccountId, Address, BorshDeserialize, BorshSerialize, EthConnectorStorageId,
+ KeyPrefix, NearGas, PromiseResult, ToString, Vec, WithdrawCallArgs, Yocto, ERR_FAILED_PARSE,
};
+use crate::prelude::{PromiseBatchAction, PromiseCreateArgs, PromiseWithCallbackArgs};
use crate::proof::Proof;
use aurora_engine_sdk::env::Env;
use aurora_engine_sdk::io::{StorageIntermediate, IO};
-use aurora_engine_types::types::{NEP141Wei, Wei, ZERO_NEP141_WEI, ZERO_WEI};
-use primitive_types::U256;
pub const ERR_NOT_ENOUGH_BALANCE_FOR_FEE: &str = "ERR_NOT_ENOUGH_BALANCE_FOR_FEE";
/// Indicate zero attached balance for promise call
@@ -57,7 +55,7 @@ pub struct EthConnector {
/// It used in the Deposit flow, to verify log entry form incoming proof.
pub prover_account: AccountId,
/// It is Eth address, used in the Deposit and Withdraw logic.
- pub eth_custodian_address: EthAddress,
+ pub eth_custodian_address: Address,
}
impl EthConnectorContract {
@@ -146,7 +144,7 @@ impl EthConnectorContract {
sdk::log!(&format!(
"Deposit started: from {} to recipient {:?} with amount: {:?} and fee {:?}",
- hex::encode(event.sender),
+ event.sender.encode(),
event.token_message_data.get_recipient(),
event.amount,
event.fee
@@ -154,8 +152,8 @@ impl EthConnectorContract {
sdk::log!(&format!(
"Event's address {}, custodian address {}",
- hex::encode(&event.eth_custodian_address),
- hex::encode(&self.contract.eth_custodian_address),
+ event.eth_custodian_address.encode(),
+ self.contract.eth_custodian_address.encode(),
));
if event.eth_custodian_address != self.contract.eth_custodian_address {
@@ -293,7 +291,7 @@ impl EthConnectorContract {
address: &Address,
amount: Wei,
) -> Result<(), fungible_token::error::WithdrawError> {
- self.burn_eth_on_aurora(address.0, amount)?;
+ self.burn_eth_on_aurora(address, amount)?;
self.save_ft_contract();
Ok(())
}
@@ -327,13 +325,13 @@ impl EthConnectorContract {
/// Mint ETH tokens
fn mint_eth_on_aurora(
&mut self,
- owner_id: EthAddress,
+ owner_id: Address,
amount: Wei,
) -> Result<(), fungible_token::error::DepositError> {
sdk::log!(&format!(
"Mint {} ETH tokens for: {}",
amount,
- hex::encode(owner_id)
+ owner_id.encode()
));
self.ft.internal_deposit_eth_to_aurora(owner_id, amount)
}
@@ -341,13 +339,13 @@ impl EthConnectorContract {
/// Burn ETH tokens
fn burn_eth_on_aurora(
&mut self,
- address: EthAddress,
+ address: &Address,
amount: Wei,
) -> Result<(), fungible_token::error::WithdrawError> {
sdk::log!(&format!(
"Burn {} ETH tokens for: {}",
amount,
- hex::encode(address)
+ address.encode()
));
self.ft.internal_withdraw_eth_from_aurora(address, amount)
}
@@ -411,13 +409,13 @@ impl EthConnectorContract {
pub fn ft_balance_of_eth_on_aurora(
&mut self,
args: BalanceOfEthCallArgs,
- ) -> Result<(), crate::prelude::types::error::BalanceOverflowError> {
+ ) -> Result<(), crate::prelude::types::balance::error::BalanceOverflowError> {
let balance = self
.ft
- .internal_unwrap_balance_of_eth_on_aurora(args.address);
+ .internal_unwrap_balance_of_eth_on_aurora(&args.address);
sdk::log!(&format!(
"Balance of ETH [{}]: {}",
- hex::encode(args.address),
+ args.address.encode(),
balance
));
self.io
@@ -498,7 +496,7 @@ impl EthConnectorContract {
// Note: It can't overflow because the total supply doesn't change during transfer.
let amount_for_check = self
.ft
- .internal_unwrap_balance_of_eth_on_aurora(message_data.recipient);
+ .internal_unwrap_balance_of_eth_on_aurora(&message_data.recipient);
if amount_for_check
.checked_add(Wei::from(args.amount))
.is_none()
@@ -607,7 +605,7 @@ impl EthConnectorContract {
// Mint fee to relayer
let relayer = engine.get_relayer(message_data.relayer.as_bytes());
match (wei_fee, relayer) {
- (fee, Some(H160(evm_relayer_address))) if fee > ZERO_WEI => {
+ (fee, Some(evm_relayer_address)) if fee > ZERO_WEI => {
self.mint_eth_on_aurora(
message_data.recipient,
Wei::new(U256::from(args.amount.as_u128())) - fee,
@@ -703,11 +701,11 @@ fn get_contract_data(io: &I, suffix: &EthConnectorSt
pub fn set_contract_data(
io: &mut I,
args: SetContractDataCallArgs,
-) -> Result {
+) -> Result {
// Get initial contract arguments
let contract_data = EthConnector {
prover_account: args.prover_account,
- eth_custodian_address: validate_eth_address(args.eth_custodian_address)?,
+ eth_custodian_address: Address::decode(&args.eth_custodian_address)?,
};
// Save eth-connector specific data
io.write_borsh(
@@ -732,7 +730,8 @@ pub fn get_metadata(io: &I) -> Option {
}
pub mod error {
- use crate::prelude::types::{error::BalanceOverflowError, AddressValidationError};
+ use aurora_engine_types::types::address::error::AddressError;
+ use aurora_engine_types::types::balance::error::BalanceOverflowError;
use crate::deposit_event::error::ParseOnTransferMessageError;
use crate::{deposit_event, fungible_token};
@@ -746,7 +745,7 @@ pub mod error {
EventParseFailed(deposit_event::error::ParseError),
CustodianAddressMismatch,
InsufficientAmountForFee,
- InvalidAddress(AddressValidationError),
+ InvalidAddress(AddressError),
}
impl AsRef<[u8]> for DepositError {
@@ -854,7 +853,7 @@ pub mod error {
pub enum InitContractError {
AlreadyInitialized,
- InvalidCustodianAddress(AddressValidationError),
+ InvalidCustodianAddress(AddressError),
}
impl AsRef<[u8]> for InitContractError {
diff --git a/engine/src/deposit_event.rs b/engine/src/deposit_event.rs
index 59f3da946..7b8b886b2 100644
--- a/engine/src/deposit_event.rs
+++ b/engine/src/deposit_event.rs
@@ -2,9 +2,10 @@ use crate::deposit_event::error::ParseEventMessageError;
use crate::log_entry::LogEntry;
use crate::prelude::account_id::AccountId;
use crate::prelude::{
- validate_eth_address, vec, AddressValidationError, BorshDeserialize, BorshSerialize,
- EthAddress, Fee, NEP141Wei, String, ToString, TryFrom, TryInto, Vec, U256,
+ vec, Address, BorshDeserialize, BorshSerialize, Fee, NEP141Wei, String, ToString, TryFrom,
+ TryInto, Vec, U256,
};
+use aurora_engine_types::types::address::error::AddressError;
use byte_slice_cast::AsByteSlice;
use ethabi::{Event, EventParam, Hash, Log, ParamType, RawLog};
@@ -18,7 +19,7 @@ pub type EventParams = Vec;
#[cfg_attr(not(target_arch = "wasm32"), derive(Debug))]
pub struct FtTransferMessageData {
pub relayer: AccountId,
- pub recipient: EthAddress,
+ pub recipient: Address,
pub fee: Fee,
}
@@ -58,8 +59,7 @@ impl FtTransferMessageData {
let fee: Fee = fee_u128.into();
// Get recipient Eth address from message slice
- let mut recipient: EthAddress = Default::default();
- recipient.copy_from_slice(&msg[32..52]);
+ let recipient = Address::try_from_slice(&msg[32..52]).unwrap();
Ok(FtTransferMessageData {
relayer: account_id,
@@ -75,7 +75,7 @@ impl FtTransferMessageData {
// it means 32 bytes for fee data
let mut data = U256::from(self.fee.as_u128()).as_byte_slice().to_vec();
// Second data section should contain Eth address
- data.extend(self.recipient);
+ data.extend(self.recipient.as_bytes());
// Add `:` separator between relayer_id and data message
[self.relayer.as_ref(), &hex::encode(data)].join(":")
}
@@ -96,16 +96,16 @@ impl FtTransferMessageData {
recipient
.strip_prefix("0x")
.ok_or(ParseEventMessageError::EthAddressValidationError(
- AddressValidationError::FailedDecodeHex,
+ AddressError::FailedDecodeHex,
))?
.to_string()
} else {
recipient
};
- let recipient_address = validate_eth_address(address)
- .map_err(ParseEventMessageError::EthAddressValidationError)?;
+ let recipient_address =
+ Address::decode(&address).map_err(ParseEventMessageError::EthAddressValidationError)?;
// Second data section should contain Eth address
- data.extend(recipient_address);
+ data.extend(recipient_address.as_bytes());
// Add `:` separator between relayer_id and data message
//Ok([relayer_account_id.as_ref(), &hex::encode(data)].join(":"))
Ok(Self {
@@ -182,7 +182,7 @@ impl TokenMessageData {
/// Ethereum event
pub struct EthEvent {
- pub eth_custodian_address: EthAddress,
+ pub eth_custodian_address: Address,
pub log: Log,
}
@@ -200,7 +200,7 @@ impl EthEvent {
anonymous: false,
};
let log_entry: LogEntry = rlp::decode(data).map_err(|_| error::DecodeError::RlpFailed)?;
- let eth_custodian_address = log_entry.address.0;
+ let eth_custodian_address = Address::new(log_entry.address);
let topics = log_entry.topics.iter().map(|h| Hash::from(h.0)).collect();
let raw_log = RawLog {
@@ -220,8 +220,8 @@ impl EthEvent {
/// Data that was emitted by Deposited event.
pub struct DepositedEvent {
- pub eth_custodian_address: EthAddress,
- pub sender: EthAddress,
+ pub eth_custodian_address: Address,
+ pub sender: Address,
pub token_message_data: TokenMessageData,
pub amount: NEP141Wei,
pub fee: Fee,
@@ -258,12 +258,13 @@ impl DepositedEvent {
pub fn from_log_entry_data(data: &[u8]) -> Result {
let event = EthEvent::fetch_log_entry_data(DEPOSITED_EVENT, Self::event_params(), data)
.map_err(error::ParseError::LogParseFailed)?;
- let sender = event.log.params[0]
+ let raw_sender = event.log.params[0]
.value
.clone()
.into_address()
.ok_or(error::ParseError::InvalidSender)?
.0;
+ let sender = Address::from_array(raw_sender);
// parse_event_message
let event_message_data: String = event.log.params[1].value.clone().to_string();
@@ -322,7 +323,7 @@ pub mod error {
pub enum ParseEventMessageError {
TooManyParts,
InvalidAccount,
- EthAddressValidationError(AddressValidationError),
+ EthAddressValidationError(AddressError),
ParseMessageError(ParseOnTransferMessageError),
}
diff --git a/engine/src/engine.rs b/engine/src/engine.rs
index b0d80f761..877c3d5c1 100644
--- a/engine/src/engine.rs
+++ b/engine/src/engine.rs
@@ -16,7 +16,7 @@ use crate::prelude::precompiles::Precompiles;
use crate::prelude::{
address_to_key, bytes_to_key, sdk, storage_to_key, u256_to_arr, vec, AccountId, Address,
BorshDeserialize, BorshSerialize, KeyPrefix, PromiseArgs, PromiseCreateArgs, ToString, TryFrom,
- TryInto, Vec, Wei, ERC20_MINT_SELECTOR, H256, U256,
+ TryInto, Vec, Wei, ERC20_MINT_SELECTOR, H160, H256, U256,
};
use crate::transaction::{EthTransactionKind, NormalizedEthTransaction};
use aurora_engine_precompiles::PrecompileConstructorContext;
@@ -239,7 +239,9 @@ impl TryFrom> for ERC20Address {
fn try_from(bytes: Vec) -> Result {
if bytes.len() == 20 {
- Ok(Self(Address::from_slice(&bytes)))
+ Ok(Self(
+ Address::try_from_slice(&bytes).map_err(|_| AddressParseError)?,
+ ))
} else {
Err(AddressParseError)
}
@@ -474,7 +476,7 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
input: Vec,
handler: &mut P,
) -> EngineResult {
- let origin = self.origin();
+ let origin = Address::new(self.origin());
let value = Wei::zero();
self.deploy_code(origin, value, input, u64::MAX, Vec::new(), handler)
}
@@ -485,7 +487,7 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
value: Wei,
input: Vec,
gas_limit: u64,
- access_list: Vec<(Address, Vec)>, // See EIP-2930
+ access_list: Vec<(H160, Vec)>, // See EIP-2930
handler: &mut P,
) -> EngineResult {
let executor_params = StackExecutorParams::new(
@@ -494,9 +496,11 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
self.env.random_seed(),
);
let mut executor = executor_params.make_executor(self);
- let address = executor.create_address(CreateScheme::Legacy { caller: origin });
+ let address = executor.create_address(CreateScheme::Legacy {
+ caller: origin.raw(),
+ });
let (exit_reason, result) = (
- executor.transact_create(origin, value.raw(), input, gas_limit, access_list),
+ executor.transact_create(origin.raw(), value.raw(), input, gas_limit, access_list),
address,
);
@@ -523,15 +527,15 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
args: CallArgs,
handler: &mut P,
) -> EngineResult {
- let origin = self.origin();
+ let origin = Address::new(self.origin());
match args {
CallArgs::V2(call_args) => {
- let contract = Address(call_args.contract);
+ let contract = call_args.contract;
let value = call_args.value.into();
let input = call_args.input;
self.call(
- origin,
- contract,
+ &origin,
+ &contract,
value,
input,
u64::MAX,
@@ -540,12 +544,12 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
)
}
CallArgs::V1(call_args) => {
- let contract = Address(call_args.contract);
+ let contract = call_args.contract;
let value = Wei::zero();
let input = call_args.input;
self.call(
- origin,
- contract,
+ &origin,
+ &contract,
value,
input,
u64::MAX,
@@ -559,12 +563,12 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
#[allow(clippy::too_many_arguments)]
pub fn call(
&mut self,
- origin: Address,
- contract: Address,
+ origin: &Address,
+ contract: &Address,
value: Wei,
input: Vec,
gas_limit: u64,
- access_list: Vec<(Address, Vec)>, // See EIP-2930
+ access_list: Vec<(H160, Vec)>, // See EIP-2930
handler: &mut P,
) -> EngineResult {
let executor_params = StackExecutorParams::new(
@@ -573,14 +577,20 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
self.env.random_seed(),
);
let mut executor = executor_params.make_executor(self);
- let (exit_reason, result) =
- executor.transact_call(origin, contract, value.raw(), input, gas_limit, access_list);
+ let (exit_reason, result) = executor.transact_call(
+ origin.raw(),
+ contract.raw(),
+ value.raw(),
+ input,
+ gas_limit,
+ access_list,
+ );
let used_gas = executor.used_gas();
let status = match exit_reason.into_result(result) {
Ok(status) => status,
Err(e) => {
- increment_nonce(&mut self.io, &origin);
+ increment_nonce(&mut self.io, origin);
return Err(e.with_gas_used(used_gas));
}
};
@@ -596,16 +606,16 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
}
pub fn view_with_args(&self, args: ViewCallArgs) -> Result {
- let origin = Address::from_slice(&args.sender);
- let contract = Address::from_slice(&args.address);
+ let origin = &args.sender;
+ let contract = &args.address;
let value = U256::from_big_endian(&args.amount);
self.view(origin, contract, Wei::new(value), args.input, u64::MAX)
}
pub fn view(
&self,
- origin: Address,
- contract: Address,
+ origin: &Address,
+ contract: &Address,
value: Wei,
input: Vec,
gas_limit: u64,
@@ -616,8 +626,14 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
self.env.random_seed(),
);
let mut executor = executor_params.make_executor(self);
- let (status, result) =
- executor.transact_call(origin, contract, value.raw(), input, gas_limit, Vec::new());
+ let (status, result) = executor.transact_call(
+ origin.raw(),
+ contract.raw(),
+ value.raw(),
+ input,
+ gas_limit,
+ Vec::new(),
+ );
status.into_result(result)
}
@@ -632,9 +648,8 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
pub fn get_relayer(&self, account_id: &[u8]) -> Option {
let key = Self::relayer_key(account_id);
- self.io
- .read_storage(&key)
- .map(|v| Address::from_slice(&v.to_vec()))
+ let raw_addr = self.io.read_storage(&key).map(|v| v.to_vec())?;
+ Address::try_from_slice(&raw_addr[..]).ok()
}
pub fn register_token(
@@ -670,8 +685,8 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
handler: &mut P,
) -> EngineResult {
self.call(
- sender,
- receiver,
+ &sender,
+ &receiver,
value,
Vec::new(),
gas_limit,
@@ -709,11 +724,11 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
let mut message = args.msg.as_bytes();
assert_or_finish!(message.len() >= 40, output_on_fail, self.io);
- let recipient = Address(unwrap_res_or_finish!(
+ let recipient = Address::new(H160(unwrap_res_or_finish!(
hex::decode(&message[..40]).unwrap().as_slice().try_into(),
output_on_fail,
self.io
- ));
+ )));
message = &message[40..];
let fee = if message.is_empty() {
@@ -728,7 +743,7 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
(recipient, fee)
};
- let erc20_token = Address(unwrap_res_or_finish!(
+ let erc20_token = Address::from_array(unwrap_res_or_finish!(
unwrap_res_or_finish!(
get_erc20_from_nep141(&self.io, token),
output_on_fail,
@@ -762,15 +777,15 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
let selector = ERC20_MINT_SELECTOR;
let tail = ethabi::encode(&[
- ethabi::Token::Address(recipient),
+ ethabi::Token::Address(recipient.raw()),
ethabi::Token::Uint(U256::from(args.amount.as_u128())),
]);
let erc20_admin_address = current_address(current_account_id);
unwrap_res_or_finish!(
self.call(
- erc20_admin_address,
- erc20_token,
+ &erc20_admin_address,
+ &erc20_token,
Wei::zero(),
[selector, tail.as_slice()].concat(),
u64::MAX,
@@ -888,8 +903,8 @@ pub fn submit(
.collect();
let result = if let Some(receiver) = transaction.to {
engine.call(
- sender,
- receiver,
+ &sender,
+ &receiver,
transaction.value,
transaction.data,
gas_limit,
@@ -1028,7 +1043,7 @@ pub fn deploy_erc20_token(
ethabi::Token::String("Empty".to_string()),
ethabi::Token::String("EMPTY".to_string()),
ethabi::Token::Uint(ethabi::Uint::from(0)),
- ethabi::Token::Address(erc20_admin_address),
+ ethabi::Token::Address(erc20_admin_address.raw()),
]);
let address = match Engine::deploy_code_with_input(
@@ -1037,7 +1052,9 @@ pub fn deploy_erc20_token(
handler,
) {
Ok(result) => match result.status {
- TransactionStatus::Succeed(ret) => Address(ret.as_slice().try_into().unwrap()),
+ TransactionStatus::Succeed(ret) => {
+ Address::new(H160(ret.as_slice().try_into().unwrap()))
+ }
other => return Err(DeployErc20Error::Failed(other)),
},
Err(e) => return Err(DeployErc20Error::Engine(e)),
@@ -1240,7 +1257,9 @@ where
{
logs.into_iter()
.filter_map(|log| {
- if log.address == ExitToNear::ADDRESS || log.address == ExitToEthereum::ADDRESS {
+ if log.address == ExitToNear::ADDRESS.raw()
+ || log.address == ExitToEthereum::ADDRESS.raw()
+ {
if log.topics.is_empty() {
if let Ok(promise) = PromiseArgs::try_from_slice(&log.data) {
match promise {
@@ -1295,8 +1314,8 @@ impl<'env, I: IO + Copy, E: Env> evm::backend::Backend for Engine<'env, I, E> {
}
/// Returns the origin address that created the contract.
- fn origin(&self) -> Address {
- self.origin
+ fn origin(&self) -> H160 {
+ self.origin.raw()
}
/// Returns a block hash from a given index.
@@ -1339,8 +1358,8 @@ impl<'env, I: IO + Copy, E: Env> evm::backend::Backend for Engine<'env, I, E> {
/// account, being 0x4444588443C3a91288c5002483449Aba1054192b.
///
/// See: https://doc.aurora.dev/develop/compat/evm#coinbase
- fn block_coinbase(&self) -> Address {
- Address([
+ fn block_coinbase(&self) -> H160 {
+ H160([
0x44, 0x44, 0x58, 0x84, 0x43, 0xC3, 0xa9, 0x12, 0x88, 0xc5, 0x00, 0x24, 0x83, 0x44,
0x9A, 0xba, 0x10, 0x54, 0x19, 0x2b,
])
@@ -1385,12 +1404,13 @@ impl<'env, I: IO + Copy, E: Env> evm::backend::Backend for Engine<'env, I, E> {
}
/// Checks if an address exists.
- fn exists(&self, address: Address) -> bool {
- !is_account_empty(&self.io, &address)
+ fn exists(&self, address: H160) -> bool {
+ !is_account_empty(&self.io, &Address::new(address))
}
/// Returns basic account information.
- fn basic(&self, address: Address) -> Basic {
+ fn basic(&self, address: H160) -> Basic {
+ let address = Address::new(address);
Basic {
nonce: get_nonce(&self.io, &address),
balance: get_balance(&self.io, &address).raw(),
@@ -1398,12 +1418,13 @@ impl<'env, I: IO + Copy, E: Env> evm::backend::Backend for Engine<'env, I, E> {
}
/// Returns the code of the contract from an address.
- fn code(&self, address: Address) -> Vec {
- get_code(&self.io, &address)
+ fn code(&self, address: H160) -> Vec {
+ get_code(&self.io, &Address::new(address))
}
/// Get storage value of address at index.
- fn storage(&self, address: Address, index: H256) -> H256 {
+ fn storage(&self, address: H160, index: H256) -> H256 {
+ let address = Address::new(address);
let generation = get_generation(&self.io, &address);
get_storage(&self.io, &address, &index, generation)
}
@@ -1413,7 +1434,7 @@ impl<'env, I: IO + Copy, E: Env> evm::backend::Backend for Engine<'env, I, E> {
/// Since SputnikVM collects storage changes in memory until the transaction is over,
/// the "original storage" will always be the same as the storage because no values
/// are written to storage until after the transaction is complete.
- fn original_storage(&self, address: Address, index: H256) -> Option {
+ fn original_storage(&self, address: H160, index: H256) -> Option {
Some(self.storage(address, index))
}
}
@@ -1436,6 +1457,7 @@ impl<'env, J: IO + Copy, E: Env> ApplyBackend for Engine<'env, J, E> {
storage,
reset_storage,
} => {
+ let address = Address::new(address);
let generation = get_generation(&self.io, &address);
set_nonce(&mut self.io, &address, &basic.nonce);
set_balance(&mut self.io, &address, &Wei::new(basic.balance));
@@ -1482,6 +1504,7 @@ impl<'env, J: IO + Copy, E: Env> ApplyBackend for Engine<'env, J, E> {
}
}
Apply::Delete { address } => {
+ let address = Address::new(address);
let generation = get_generation(&self.io, &address);
remove_account(&mut self.io, &address, generation);
writes_counter += 1;
diff --git a/engine/src/fungible_token.rs b/engine/src/fungible_token.rs
index 7324e13a2..d15960a95 100644
--- a/engine/src/fungible_token.rs
+++ b/engine/src/fungible_token.rs
@@ -5,9 +5,9 @@ use crate::parameters::{NEP141FtOnTransferArgs, ResolveTransferCallArgs, Storage
use crate::prelude::account_id::AccountId;
use crate::prelude::Wei;
use crate::prelude::{
- sdk, storage, vec, Address, BTreeMap, Balance, BorshDeserialize, BorshSerialize, EthAddress,
- NearGas, PromiseAction, PromiseBatchAction, PromiseCreateArgs, PromiseResult,
- PromiseWithCallbackArgs, StorageBalanceBounds, StorageUsage, String, ToString, TryInto, Vec,
+ sdk, storage, vec, Address, BTreeMap, Balance, BorshDeserialize, BorshSerialize, NearGas,
+ PromiseAction, PromiseBatchAction, PromiseCreateArgs, PromiseResult, PromiseWithCallbackArgs,
+ StorageBalanceBounds, StorageUsage, String, ToString, TryInto, Vec,
};
use aurora_engine_sdk::io::{StorageIntermediate, IO};
use aurora_engine_types::types::{NEP141Wei, Yocto, ZERO_NEP141_WEI, ZERO_YOCTO};
@@ -152,8 +152,8 @@ impl FungibleTokenOps {
}
/// Balance of ETH (ETH on Aurora)
- pub fn internal_unwrap_balance_of_eth_on_aurora(&self, address: EthAddress) -> Wei {
- engine::get_balance(&self.io, &Address(address))
+ pub fn internal_unwrap_balance_of_eth_on_aurora(&self, address: &Address) -> Wei {
+ engine::get_balance(&self.io, address)
}
/// Internal ETH deposit to NEAR - nETH (NEP-141)
@@ -179,14 +179,14 @@ impl FungibleTokenOps {
/// Internal ETH deposit to Aurora
pub fn internal_deposit_eth_to_aurora(
&mut self,
- address: EthAddress,
+ address: Address,
amount: Wei,
) -> Result<(), error::DepositError> {
- let balance = self.internal_unwrap_balance_of_eth_on_aurora(address);
+ let balance = self.internal_unwrap_balance_of_eth_on_aurora(&address);
let new_balance = balance
.checked_add(amount)
.ok_or(error::DepositError::BalanceOverflow)?;
- engine::set_balance(&mut self.io, &Address(address), &new_balance);
+ engine::set_balance(&mut self.io, &address, &new_balance);
self.total_eth_supply_on_aurora = self
.total_eth_supply_on_aurora
.checked_add(amount)
@@ -217,14 +217,14 @@ impl FungibleTokenOps {
/// Withdraw ETH tokens
pub fn internal_withdraw_eth_from_aurora(
&mut self,
- address: EthAddress,
+ address: &Address,
amount: Wei,
) -> Result<(), error::WithdrawError> {
let balance = self.internal_unwrap_balance_of_eth_on_aurora(address);
let new_balance = balance
.checked_sub(amount)
.ok_or(error::WithdrawError::InsufficientFunds)?;
- engine::set_balance(&mut self.io, &Address(address), &new_balance);
+ engine::set_balance(&mut self.io, address, &new_balance);
self.total_eth_supply_on_aurora = self
.total_eth_supply_on_aurora
.checked_sub(amount)
@@ -595,7 +595,7 @@ impl FungibleTokenOps {
}
pub mod error {
- use crate::prelude::types::error::BalanceOverflowError;
+ use crate::prelude::types::balance::error::BalanceOverflowError;
const TOTAL_SUPPLY_OVERFLOW: &[u8; 25] = b"ERR_TOTAL_SUPPLY_OVERFLOW";
const BALANCE_OVERFLOW: &[u8; 20] = b"ERR_BALANCE_OVERFLOW";
diff --git a/engine/src/lib.rs b/engine/src/lib.rs
index 76bbcb9f8..320a08fdb 100644
--- a/engine/src/lib.rs
+++ b/engine/src/lib.rs
@@ -69,6 +69,7 @@ mod contract {
use crate::connector::{self, EthConnectorContract};
use crate::engine::{self, current_address, Engine, EngineState};
use crate::fungible_token::FungibleTokenMetadata;
+ use crate::json::parse_json;
use crate::parameters::{
self, CallArgs, DeployErc20TokenArgs, GetErc20FromNep141CallArgs, GetStorageAtArgs,
InitCallArgs, IsUsedProofCallArgs, NEP141FtOnTransferArgs, NewCallArgs,
@@ -78,22 +79,19 @@ mod contract {
#[cfg(feature = "evm_bully")]
use crate::parameters::{BeginBlockArgs, BeginChainArgs};
use crate::prelude::account_id::AccountId;
- use aurora_engine_sdk::env::Env;
- use aurora_engine_sdk::io::{StorageIntermediate, IO};
- use aurora_engine_sdk::near_runtime::Runtime;
- use aurora_engine_sdk::promise::PromiseHandler;
- use aurora_engine_types::types::Yocto;
-
- use crate::json::parse_json;
use crate::prelude::parameters::RefundCallArgs;
use crate::prelude::sdk::types::{
near_account_to_evm_address, SdkExpect, SdkProcess, SdkUnwrap,
};
use crate::prelude::storage::{bytes_to_key, KeyPrefix};
use crate::prelude::{
- sdk, u256_to_arr, vec, Address, PromiseResult, ToString, TryFrom, TryInto, Vec, Wei,
+ sdk, u256_to_arr, vec, Address, PromiseResult, ToString, TryFrom, TryInto, Vec, Wei, Yocto,
ERC20_MINT_SELECTOR, ERR_FAILED_PARSE, H256, U256,
};
+ use aurora_engine_sdk::env::Env;
+ use aurora_engine_sdk::io::{StorageIntermediate, IO};
+ use aurora_engine_sdk::near_runtime::Runtime;
+ use aurora_engine_sdk::promise::PromiseHandler;
#[cfg(feature = "integration-test")]
use crate::prelude::NearGas;
@@ -282,8 +280,8 @@ mod contract {
let mut engine =
Engine::new_with_state(state, meta_call_args.sender, current_account_id, io, &io);
let result = engine.call(
- meta_call_args.sender,
- meta_call_args.contract_address,
+ &meta_call_args.sender,
+ &meta_call_args.contract_address,
meta_call_args.value,
meta_call_args.input,
u64::MAX, // TODO: is there a gas limit with meta calls?
@@ -309,7 +307,10 @@ mod contract {
&io,
)
.sdk_unwrap();
- engine.register_relayer(predecessor_account_id.as_bytes(), Address(relayer_address));
+ engine.register_relayer(
+ predecessor_account_id.as_bytes(),
+ Address::from_array(relayer_address),
+ );
}
/// Allow receiving NEP141 tokens to the EVM contract.
@@ -391,20 +392,20 @@ mod contract {
let erc20_admin_address = current_address(¤t_account_id);
let mut engine =
Engine::new(erc20_admin_address, current_account_id, io, &io).sdk_unwrap();
- let erc20_address = Address(erc20_address);
- let refund_address = Address(args.recipient_address);
+ let erc20_address = erc20_address;
+ let refund_address = args.recipient_address;
let amount = U256::from_big_endian(&args.amount);
let selector = ERC20_MINT_SELECTOR;
let mint_args = ethabi::encode(&[
- ethabi::Token::Address(refund_address),
+ ethabi::Token::Address(refund_address.raw()),
ethabi::Token::Uint(amount),
]);
engine
.call(
- erc20_admin_address,
- erc20_address,
+ &erc20_admin_address,
+ &erc20_address,
Wei::zero(),
[selector, mint_args.as_slice()].concat(),
u64::MAX,
@@ -418,16 +419,19 @@ mod contract {
let exit_address = aurora_engine_precompiles::native::ExitToNear::ADDRESS;
let mut engine =
Engine::new(exit_address, current_account_id, io, &io).sdk_unwrap();
- let refund_address = Address(args.recipient_address);
+ let refund_address = args.recipient_address;
let amount = Wei::new(U256::from_big_endian(&args.amount));
engine
.call(
- exit_address,
- refund_address,
+ &exit_address,
+ &refund_address,
amount,
Vec::new(),
u64::MAX,
- vec![(exit_address, Vec::new()), (refund_address, Vec::new())],
+ vec![
+ (exit_address.raw(), Vec::new()),
+ (refund_address.raw(), Vec::new()),
+ ],
&mut Runtime,
)
.sdk_unwrap()
@@ -448,13 +452,7 @@ mod contract {
let mut io = Runtime;
let args: ViewCallArgs = io.read_input_borsh().sdk_unwrap();
let current_account_id = io.current_account_id();
- let engine = Engine::new(
- Address::from_slice(&args.sender),
- current_account_id,
- io,
- &io,
- )
- .sdk_unwrap();
+ let engine = Engine::new(args.sender, current_account_id, io, &io).sdk_unwrap();
let result = Engine::view_with_args(&engine, args).sdk_unwrap();
io.return_output(&result.try_to_vec().sdk_expect("ERR_SERIALIZE"));
}
@@ -476,7 +474,7 @@ mod contract {
pub extern "C" fn get_code() {
let mut io = Runtime;
let address = io.read_input_arr20().sdk_unwrap();
- let code = engine::get_code(&io, &Address(address));
+ let code = engine::get_code(&io, &Address::from_array(address));
io.return_output(&code)
}
@@ -484,7 +482,7 @@ mod contract {
pub extern "C" fn get_balance() {
let mut io = Runtime;
let address = io.read_input_arr20().sdk_unwrap();
- let balance = engine::get_balance(&io, &Address(address));
+ let balance = engine::get_balance(&io, &Address::from_array(address));
io.return_output(&balance.to_bytes())
}
@@ -492,7 +490,7 @@ mod contract {
pub extern "C" fn get_nonce() {
let mut io = Runtime;
let address = io.read_input_arr20().sdk_unwrap();
- let nonce = engine::get_nonce(&io, &Address(address));
+ let nonce = engine::get_nonce(&io, &Address::from_array(address));
io.return_output(&u256_to_arr(&nonce))
}
@@ -500,9 +498,9 @@ mod contract {
pub extern "C" fn get_storage_at() {
let mut io = Runtime;
let args: GetStorageAtArgs = io.read_input_borsh().sdk_unwrap();
- let address = Address(args.address);
+ let address = args.address;
let generation = engine::get_generation(&io, &address);
- let value = engine::get_storage(&io, &Address(args.address), &H256(args.key), generation);
+ let value = engine::get_storage(&io, &args.address, &H256(args.key), generation);
io.return_output(&value.0)
}
@@ -522,8 +520,8 @@ mod contract {
for account_balance in args.genesis_alloc {
engine::set_balance(
&mut io,
- &Address(account_balance.address),
- &crate::prelude::types::Wei::new(U256::from(account_balance.balance)),
+ &account_balance.address,
+ &crate::prelude::Wei::new(U256::from(account_balance.balance)),
)
}
// return new chain ID
@@ -854,13 +852,13 @@ mod contract {
let mut io = Runtime;
let args: ([u8; 20], u64, u64) = io.read_input_borsh().sdk_expect("ERR_ARGS");
- let address = Address(args.0);
+ let address = Address::from_array(args.0);
let nonce = U256::from(args.1);
let balance = NEP141Wei::new(args.2 as u128);
let current_account_id = io.current_account_id();
let mut engine = Engine::new(address, current_account_id, io, &io).sdk_unwrap();
let state_change = evm::backend::Apply::Modify {
- address,
+ address: address.raw(),
basic: evm::backend::Basic {
balance: U256::from(balance.as_u128()),
nonce,
diff --git a/engine/src/meta_parsing.rs b/engine/src/meta_parsing.rs
index 269ae454c..f464f36cc 100644
--- a/engine/src/meta_parsing.rs
+++ b/engine/src/meta_parsing.rs
@@ -2,7 +2,7 @@ use crate::parameters::MetaCallArgs;
use crate::prelude::precompiles::secp256k1::ecrecover;
use crate::prelude::{
keccak, u256_to_arr, vec, Address, BorshDeserialize, Box, HashMap, InternalMetaCallArgs,
- RawU256, String, ToOwned, ToString, Vec, Wei, H256, U256,
+ RawU256, String, ToOwned, ToString, Vec, Wei, H160, H256, U256,
};
use ethabi::{encode, Token as ABIToken};
use logos::Logos;
@@ -160,7 +160,7 @@ pub fn method_sig_to_abi(method_sig: &str) -> [u8; 4] {
pub fn encode_address(addr: Address) -> Vec {
let mut bytes = vec![0u8; 12];
- bytes.extend_from_slice(&addr.0);
+ bytes.extend_from_slice(&addr.raw().as_bytes());
bytes
}
@@ -369,9 +369,11 @@ fn eip_712_hash_argument(
ArgType::Uint | ArgType::Int | ArgType::Bool => eip_712_rlp_value(value, |b| {
Ok(u256_to_arr(&U256::from_big_endian(b)).to_vec())
}),
- ArgType::Address => {
- eip_712_rlp_value(value, |b| Ok(encode_address(Address::from_slice(b))))
- }
+ ArgType::Address => eip_712_rlp_value(value, |b| {
+ Ok(encode_address(
+ Address::try_from_slice(b).map_err(|_| ParsingError::ArgumentParseError)?,
+ ))
+ }),
ArgType::Array { inner, .. } => eip_712_rlp_list(value, |l| {
let mut r = vec![];
for element in l {
@@ -447,7 +449,7 @@ fn arg_to_abi_token(
value_to_abi_token(arg, |b| Ok(ABIToken::Uint(U256::from_big_endian(b))))
}
ArgType::Address => {
- value_to_abi_token(arg, |b| Ok(ABIToken::Address(Address::from_slice(b))))
+ value_to_abi_token(arg, |b| Ok(ABIToken::Address(H160::from_slice(&b[..]))))
}
ArgType::Array {
inner,
@@ -578,8 +580,8 @@ pub fn parse_meta_call(
MetaCallArgs::try_from_slice(&args).map_err(|_| ParsingError::ArgumentParseError)?;
let nonce = U256::from(meta_tx.nonce);
let fee_amount = Wei::new(U256::from(meta_tx.fee_amount));
- let fee_address = Address::from(meta_tx.fee_address);
- let contract_address = Address::from(meta_tx.contract_address);
+ let fee_address = meta_tx.fee_address;
+ let contract_address = meta_tx.contract_address;
let value = Wei::new(U256::from(meta_tx.value));
let mut result = InternalMetaCallArgs {
diff --git a/engine/src/parameters.rs b/engine/src/parameters.rs
index 6e2769860..8bb400659 100644
--- a/engine/src/parameters.rs
+++ b/engine/src/parameters.rs
@@ -3,8 +3,8 @@ use crate::fungible_token::FungibleTokenMetadata;
use crate::json::{JsonError, JsonValue};
use crate::prelude::account_id::AccountId;
use crate::prelude::{
- format, Balance, BorshDeserialize, BorshSerialize, EthAddress, RawAddress, RawH256, RawU256,
- String, ToString, TryFrom, Vec, WeiU256,
+ format, Address, Balance, BorshDeserialize, BorshSerialize, RawH256, RawU256, String, ToString,
+ TryFrom, Vec, WeiU256,
};
use crate::proof::Proof;
use aurora_engine_types::types::{Fee, NEP141Wei, Yocto};
@@ -32,8 +32,8 @@ pub struct MetaCallArgs {
pub v: u8,
pub nonce: RawU256,
pub fee_amount: RawU256,
- pub fee_address: RawAddress,
- pub contract_address: RawAddress,
+ pub fee_address: Address,
+ pub contract_address: Address,
pub value: RawU256,
pub method_def: String,
pub args: Vec,
@@ -42,7 +42,7 @@ pub struct MetaCallArgs {
/// Borsh-encoded log for use in a `SubmitResult`.
#[derive(Debug, BorshSerialize, BorshDeserialize)]
pub struct ResultLog {
- pub address: RawAddress,
+ pub address: Address,
pub topics: Vec,
pub data: Vec,
}
@@ -55,7 +55,7 @@ impl From for ResultLog {
.map(|topic| topic.0)
.collect::>();
ResultLog {
- address: log.address.0,
+ address: Address::new(log.address),
topics,
data: log.data,
}
@@ -134,7 +134,7 @@ impl SubmitResult {
/// Borsh-encoded parameters for the engine `call` function.
#[derive(BorshSerialize, BorshDeserialize, Debug, PartialEq, Eq, Clone)]
pub struct FunctionCallArgsV2 {
- pub contract: RawAddress,
+ pub contract: Address,
/// Wei compatible Borsh-encoded value field to attach an ETH balance to the transaction
pub value: WeiU256,
pub input: Vec,
@@ -143,7 +143,7 @@ pub struct FunctionCallArgsV2 {
/// Legacy Borsh-encoded parameters for the engine `call` function, to provide backward type compatibility
#[derive(BorshSerialize, BorshDeserialize, Debug, PartialEq, Eq, Clone)]
pub struct FunctionCallArgsV1 {
- pub contract: RawAddress,
+ pub contract: Address,
pub input: Vec,
}
@@ -176,8 +176,8 @@ impl CallArgs {
/// Borsh-encoded parameters for the `view` function.
#[derive(BorshSerialize, BorshDeserialize, Debug, Eq, PartialEq)]
pub struct ViewCallArgs {
- pub sender: RawAddress,
- pub address: RawAddress,
+ pub sender: Address,
+ pub address: Address,
pub amount: RawU256,
pub input: Vec,
}
@@ -194,7 +194,7 @@ pub type GetErc20FromNep141CallArgs = DeployErc20TokenArgs;
/// Borsh-encoded parameters for the `get_storage_at` function.
#[derive(BorshSerialize, BorshDeserialize)]
pub struct GetStorageAtArgs {
- pub address: RawAddress,
+ pub address: Address,
pub key: RawH256,
}
@@ -202,7 +202,7 @@ pub struct GetStorageAtArgs {
#[cfg(feature = "evm_bully")]
#[derive(BorshSerialize, BorshDeserialize)]
pub struct AccountBalance {
- pub address: RawAddress,
+ pub address: Address,
pub balance: RawU256,
}
@@ -221,7 +221,7 @@ pub struct BeginBlockArgs {
/// The current block's hash (for replayer use).
pub hash: RawU256,
/// The current block's beneficiary address.
- pub coinbase: RawAddress,
+ pub coinbase: Address,
/// The current block's timestamp (in seconds since the Unix epoch).
pub timestamp: RawU256,
/// The current block's number (the genesis block is number zero).
@@ -274,7 +274,7 @@ pub struct DepositCallArgs {
/// Proof data
pub proof: Proof,
/// Optional relayer address
- pub relayer_eth_account: Option,
+ pub relayer_eth_account: Option,
}
/// Eth-connector isUsedProof arguments
@@ -289,8 +289,8 @@ pub struct IsUsedProofCallArgs {
#[cfg_attr(not(target_arch = "wasm32"), derive(BorshDeserialize))]
pub struct WithdrawResult {
pub amount: NEP141Wei,
- pub recipient_id: RawAddress,
- pub eth_custodian_address: RawAddress,
+ pub recipient_id: Address,
+ pub eth_custodian_address: Address,
}
/// Fungible token storage balance
@@ -335,13 +335,13 @@ pub struct FinishDepositCallArgs {
#[derive(Default, BorshDeserialize, BorshSerialize, Clone)]
pub struct DepositEthCallArgs {
pub proof: Proof,
- pub relayer_eth_account: EthAddress,
+ pub relayer_eth_account: Address,
}
/// Finish deposit NEAR eth-connector call args
#[derive(BorshSerialize, BorshDeserialize)]
pub struct FinishDepositEthCallArgs {
- pub new_owner_id: EthAddress,
+ pub new_owner_id: Address,
pub amount: NEP141Wei,
pub fee: Balance,
pub relayer_eth_account: AccountId,
@@ -460,7 +460,7 @@ pub struct BalanceOfCallArgs {
#[derive(BorshSerialize, BorshDeserialize)]
pub struct BalanceOfEthCallArgs {
- pub address: EthAddress,
+ pub address: Address,
}
impl TryFrom for BalanceOfCallArgs {
@@ -475,7 +475,7 @@ impl TryFrom for BalanceOfCallArgs {
#[derive(BorshSerialize, BorshDeserialize)]
pub struct RegisterRelayerCallArgs {
- pub address: EthAddress,
+ pub address: Address,
}
#[derive(BorshSerialize, BorshDeserialize)]
@@ -539,8 +539,8 @@ mod tests {
#[test]
fn test_roundtrip_view_call() {
let x = ViewCallArgs {
- sender: [1; 20],
- address: [2; 20],
+ sender: Address::from_array([1; 20]),
+ address: Address::from_array([2; 20]),
amount: [3; 32],
input: vec![1, 2, 3],
};
@@ -552,12 +552,12 @@ mod tests {
#[test]
fn test_call_args_deserialize() {
let new_input = FunctionCallArgsV2 {
- contract: [0u8; 20],
+ contract: Address::from_array([0u8; 20]),
value: WeiU256::default(),
input: Vec::new(),
};
let legacy_input = FunctionCallArgsV1 {
- contract: [0u8; 20],
+ contract: Address::from_array([0u8; 20]),
input: Vec::new(),
};
diff --git a/engine/src/transaction/eip_1559.rs b/engine/src/transaction/eip_1559.rs
index f7bd8b4f2..74bac5d0f 100644
--- a/engine/src/transaction/eip_1559.rs
+++ b/engine/src/transaction/eip_1559.rs
@@ -1,8 +1,6 @@
use crate::prelude::precompiles::secp256k1::ecrecover;
-use crate::prelude::Wei;
-use crate::prelude::{Vec, U256};
+use crate::prelude::{Address, Vec, Wei, U256};
use crate::transaction::eip_2930::AccessTuple;
-use ethabi::Address;
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
/// Type indicator (per EIP-1559)
@@ -45,7 +43,7 @@ impl Transaction1559 {
s.append(&self.gas_limit);
match self.to.as_ref() {
None => s.append(&""),
- Some(address) => s.append(address),
+ Some(address) => s.append(&address.raw()),
};
s.append(&self.value.raw());
s.append(&self.data);
diff --git a/engine/src/transaction/eip_2930.rs b/engine/src/transaction/eip_2930.rs
index 56b46e9e4..cfd491839 100644
--- a/engine/src/transaction/eip_2930.rs
+++ b/engine/src/transaction/eip_2930.rs
@@ -1,6 +1,5 @@
use crate::prelude::precompiles::secp256k1::ecrecover;
-use crate::prelude::Wei;
-use crate::prelude::{sdk, Address, Vec, H256, U256};
+use crate::prelude::{sdk, Address, Vec, Wei, H160, H256, U256};
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
/// Type indicator (per EIP-2718) for access list transactions
@@ -8,7 +7,7 @@ pub const TYPE_BYTE: u8 = 0x01;
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct AccessTuple {
- pub address: Address,
+ pub address: H160,
pub storage_keys: Vec,
}
@@ -56,7 +55,7 @@ impl Transaction2930 {
s.append(&self.gas_limit);
match self.to.as_ref() {
None => s.append(&""),
- Some(address) => s.append(address),
+ Some(address) => s.append(&address.raw()),
};
s.append(&self.value.raw());
s.append(&self.data);
diff --git a/engine/src/transaction/legacy.rs b/engine/src/transaction/legacy.rs
index 4bf6c14be..fcc97aaa3 100644
--- a/engine/src/transaction/legacy.rs
+++ b/engine/src/transaction/legacy.rs
@@ -1,6 +1,5 @@
use crate::prelude::precompiles::secp256k1::ecrecover;
-use crate::prelude::Wei;
-use crate::prelude::{sdk, Address, Vec, U256};
+use crate::prelude::{sdk, Address, Vec, Wei, U256};
use rlp::{Decodable, DecoderError, Encodable, Rlp, RlpStream};
#[derive(Debug, Eq, PartialEq, Clone)]
@@ -27,7 +26,7 @@ impl TransactionLegacy {
s.append(&self.gas_limit);
match self.to.as_ref() {
None => s.append(&""),
- Some(address) => s.append(address),
+ Some(address) => s.append(&address.raw()),
};
s.append(&self.value.raw());
s.append(&self.data);
@@ -107,7 +106,7 @@ impl Encodable for LegacyEthSignedTransaction {
s.append(&self.transaction.gas_limit);
match self.transaction.to.as_ref() {
None => s.append(&""),
- Some(address) => s.append(address),
+ Some(address) => s.append(&address.raw()),
};
s.append(&self.transaction.value.raw());
s.append(&self.transaction.data);
@@ -200,8 +199,6 @@ mod tests {
fn address_from_arr(arr: &[u8]) -> Address {
assert_eq!(arr.len(), 20);
- let mut address = [0u8; 20];
- address.copy_from_slice(&arr);
- Address::from(address)
+ Address::try_from_slice(arr).unwrap()
}
}
diff --git a/engine/src/transaction/mod.rs b/engine/src/transaction/mod.rs
index 01036c1cb..347c3e780 100644
--- a/engine/src/transaction/mod.rs
+++ b/engine/src/transaction/mod.rs
@@ -1,5 +1,5 @@
-use crate::prelude::Wei;
-use crate::prelude::{vec, Address, TryFrom, Vec, U256};
+use crate::prelude::types::{Address, Wei};
+use crate::prelude::{vec, TryFrom, Vec, H160, U256};
use eip_2930::AccessTuple;
use rlp::{Decodable, DecoderError, Rlp};
@@ -188,11 +188,12 @@ fn rlp_extract_to(rlp: &Rlp<'_>, index: usize) -> Result