Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Connector cleanup #374

Merged
merged 29 commits into from
Dec 8, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
6d27234
Added Eth-connector comments and renamde some constants
mrLSD Nov 22, 2021
88d6ae2
Changed eth-connector contract init instance and comments
mrLSD Nov 23, 2021
c5e3d7f
Analized code and added TODO's for next changes. Changes for Trasfer …
mrLSD Nov 23, 2021
5b7e98e
Fix ft_transaction
mrLSD Nov 24, 2021
d8d2038
Introduce Fee type
mrLSD Nov 25, 2021
ee9c2c2
Added Fee type, and change everywhere. Added changes for deposit_even…
mrLSD Nov 25, 2021
4013225
Fix all Fee type dependency. Modified logic: prepare_message_for_on_t…
mrLSD Nov 25, 2021
fb6d780
Fix eth-connecotr tests
mrLSD Nov 25, 2021
2894a28
Changes for Balance type
mrLSD Nov 26, 2021
61e0743
Cleanup imports
mrLSD Nov 26, 2021
c87c17b
Fix standalone/mocks tests
mrLSD Nov 26, 2021
8ba55ed
Added earlt verification to deposit_event for TokenMessageData
mrLSD Nov 26, 2021
cb89024
Extend comments. FungibleToken - cleanup and introduce new type
mrLSD Nov 26, 2021
819a541
Reorgonize TODO's
mrLSD Nov 26, 2021
7f3266d
Changed functions: get_recipient, init_contract
mrLSD Nov 30, 2021
3056329
deposit_event - check u128 overflow
mrLSD Nov 30, 2021
29326b0
parse OnTrasfer: changed Fee to 32 bytes
mrLSD Nov 30, 2021
3fffee6
Fix test_deposit_with_0x_prefix
mrLSD Dec 1, 2021
ca790c5
deposit_event refactoring
mrLSD Dec 1, 2021
5aec1e5
Rename OnTransferMessageData -> FtTransferMessageData
mrLSD Dec 2, 2021
7e32715
Wei types - added try_into_u128
mrLSD Dec 2, 2021
a6425b4
Extend Result types for try_into_u128
mrLSD Dec 2, 2021
fb85325
Remove redundant Result types for Engine and try_into_u128 - just cha…
mrLSD Dec 2, 2021
def83bf
Simplify BalanceOverflowError, remove From<Fee> for u128
mrLSD Dec 3, 2021
7361b93
Update engine/src/connector.rs
mrLSD Dec 3, 2021
cf997bf
Update engine/src/fungible_token.rs
mrLSD Dec 3, 2021
a31ec8f
Remove redundant Add<Fee> u128 implementations
mrLSD Dec 3, 2021
7a0f163
Merge branch 'feat/connector-cleanup' of github.com:aurora-is-near/au…
mrLSD Dec 3, 2021
721dcf2
Merge branch 'develop' of github.com:aurora-is-near/aurora-engine int…
mrLSD Dec 7, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion Cargo.lock

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

1 change: 0 additions & 1 deletion engine-precompiles/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@ wee_alloc = { version = "0.4.5", default-features = false }
logos = { version = "0.12", default-features = false, features = ["export_derive"] }
ethabi = { git = "https://github.com/darwinia-network/ethabi", branch = "xavier-no-std", default-features = false }
hex = { version = "0.4", default-features = false, features = ["alloc"] }
byte-slice-cast = { version = "1.0", default-features = false }
rjson = { git = "https://github.com/aurora-is-near/rjson", rev = "cc3da949", default-features = false, features = ["integer"] }

[dev-dependencies]
Expand Down
2 changes: 1 addition & 1 deletion engine-standalone-storage/src/relayer_db/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ mod test {
.unwrap();
let mut io = storage.access_engine_storage_at_position(block_height, 0, &[]);
engine::set_state(&mut io, engine_state.clone());
connector::EthConnectorContract::init_contract(
connector::EthConnectorContract::create_contract(
io,
engine_state.owner_id.clone(),
parameters::InitCallArgs {
Expand Down
4 changes: 2 additions & 2 deletions engine-standalone-storage/src/sync/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ pub fn consume_message(storage: &mut crate::Storage, message: Message) -> Result
engine::Engine::new(relayer_address, env.current_account_id(), io, &env)?;

if env.predecessor_account_id == env.current_account_id {
connector::EthConnectorContract::get_instance(io)
connector::EthConnectorContract::init_instance(io)
.ft_on_transfer(&engine, &args)?;
} else {
engine.receive_erc20_tokens(
Expand All @@ -123,7 +123,7 @@ pub fn consume_message(storage: &mut crate::Storage, message: Message) -> Result
}

TransactionKind::Deposit(raw_proof) => {
let mut connector_contract = connector::EthConnectorContract::get_instance(io);
let mut connector_contract = connector::EthConnectorContract::init_instance(io);
let promise_args = connector_contract.deposit(
raw_proof,
env.current_account_id(),
Expand Down
2 changes: 1 addition & 1 deletion engine-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ aurora-engine-precompiles = { path = "../engine-precompiles", default-features =
engine-standalone-storage = { path = "../engine-standalone-storage", default-features = false }
engine-standalone-tracing = { path = "../engine-standalone-tracing", default-features = false }
borsh = { version = "0.8.2", default-features = false }
byte-slice-cast = { version = "1.0", default-features = false }
sha3 = { version = "0.9.1", default-features = false }
evm = { git = "https://github.com/aurora-is-near/sputnikvm.git", default-features = false, features = ["std", "tracing"] }
evm-runtime = { git = "https://github.com/aurora-is-near/sputnikvm.git", default-features = false, features = ["std", "tracing"] }
Expand All @@ -30,6 +29,7 @@ rlp = { version = "0.5.0", default-features = false }
[dev-dependencies]
base64 = "0.13.0"
bstr = "0.2"
byte-slice-cast = { version = "1.0", default-features = false }
ethabi = { git = "https://github.com/darwinia-network/ethabi", branch = "xavier-no-std" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
Expand Down
6 changes: 3 additions & 3 deletions engine-tests/src/test_utils/standalone/mocks/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ pub fn init_evm<I: IO + Copy, E: Env>(mut io: I, env: &E) {
metadata: FungibleTokenMetadata::default(),
};

aurora_engine::connector::EthConnectorContract::init_contract(
aurora_engine::connector::EthConnectorContract::create_contract(
io,
env.current_account_id(),
connector_args,
Expand Down Expand Up @@ -102,7 +102,7 @@ pub fn mint_evm_account<I: IO + Copy, E: Env>(
amount: balance.raw().low_u128(),
proof_key: String::new(),
relayer_id: aurora_account_id.clone(),
fee: 0,
fee: 0.into(),
msg: None,
};

Expand All @@ -113,7 +113,7 @@ pub fn mint_evm_account<I: IO + Copy, E: Env>(
);
io.remove_storage(&proof_key);

aurora_engine::connector::EthConnectorContract::get_instance(io)
aurora_engine::connector::EthConnectorContract::init_instance(io)
.finish_deposit(
aurora_account_id.clone(),
aurora_account_id.clone(),
Expand Down
45 changes: 25 additions & 20 deletions engine-tests/src/tests/eth_connector.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use crate::prelude::EthAddress;
use crate::prelude::WithdrawCallArgs;
use crate::prelude::U256;
use crate::test_utils::str_to_account_id;
use aurora_engine::admin_controlled::{PausedMask, ERR_PAUSED};
use aurora_engine::connector::{
Expand All @@ -10,8 +9,10 @@ use aurora_engine::fungible_token::FungibleTokenMetadata;
use aurora_engine::parameters::{
InitCallArgs, NewCallArgs, RegisterRelayerCallArgs, WithdrawResult,
};
use aurora_engine_types::types::Fee;
use borsh::{BorshDeserialize, BorshSerialize};
use byte_slice_cast::AsByteSlice;
use ethabi::ethereum_types::U256;
use near_sdk::test_utils::accounts;
use near_sdk_sim::transaction::ExecutionStatus;
use near_sdk_sim::{to_yocto, ExecutionResult, UserAccount, DEFAULT_GAS, STORAGE_AMOUNT};
Expand Down Expand Up @@ -409,9 +410,10 @@ fn test_ft_transfer_call_eth() {
res.assert_success();

let transfer_amount = 50;
let fee = 30;
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());

let message = [CONTRACT_ACC, hex::encode(msg).as_str()].join(":");
let res = contract.call(
CONTRACT_ACC.parse().unwrap(),
Expand Down Expand Up @@ -592,6 +594,7 @@ fn test_ft_transfer_call_without_message() {

#[test]
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] = {
Expand All @@ -601,20 +604,22 @@ fn test_deposit_with_0x_prefix() {
buf
};
let recipient_address = [10u8; 20];
let deposit_amount = U256::from(17);
let deposit_amount = 17;
let recipient_address_encoded = hex::encode(&recipient_address);

// Note the 0x prefix before the deposit address.
let message = [CONTRACT_ACC, ":", "0x", &recipient_address_encoded].concat();
let fee: Fee = 0.into();
let token_message_data =
TokenMessageData::parse_event_message_and_prepare_token_message_data(&message, fee)
.unwrap();

let deposit_event = aurora_engine::deposit_event::DepositedEvent {
eth_custodian_address,
sender: [0u8; 20],
// Note the 0x prefix before the deposit address.
recipient: [
CONTRACT_ACC,
":",
"0x",
hex::encode(&recipient_address).as_str(),
]
.concat(),
token_message_data,
amount: deposit_amount,
fee: U256::zero(),
fee,
};

let event_schema = ethabi::Event {
Expand All @@ -630,9 +635,9 @@ fn test_deposit_with_0x_prefix() {
crate::prelude::H256::zero(),
],
data: ethabi::encode(&[
ethabi::Token::String(deposit_event.recipient),
ethabi::Token::Uint(deposit_event.amount),
ethabi::Token::Uint(deposit_event.fee),
ethabi::Token::String(message),
ethabi::Token::Uint(U256::from(deposit_event.amount)),
ethabi::Token::Uint(U256::from(deposit_event.fee.into_u128())),
]),
};
let proof = Proof {
Expand All @@ -655,9 +660,9 @@ fn test_deposit_with_0x_prefix() {
res.assert_success();

let aurora_balance = get_eth_on_near_balance(&master_account, CONTRACT_ACC, CONTRACT_ACC);
assert_eq!(aurora_balance, deposit_amount.low_u128());
assert_eq!(aurora_balance, deposit_amount);
let address_balance = get_eth_balance(&master_account, recipient_address, CONTRACT_ACC);
assert_eq!(address_balance, deposit_amount.low_u128());
assert_eq!(address_balance, deposit_amount);
}

#[test]
Expand Down Expand Up @@ -711,7 +716,7 @@ fn test_ft_transfer_call_without_relayer() {
assert_eq!(balance, DEPOSITED_FEE);

let transfer_amount = 50;
let fee = 30;
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());
let relayer_id = "relayer.root";
Expand Down Expand Up @@ -767,8 +772,8 @@ fn test_ft_transfer_call_fee_greater_than_amount() {
call_deposit_eth_to_near(&contract, CONTRACT_ACC);

let transfer_amount = 10;
let fee = transfer_amount + 10;
let mut msg = U256::from(fee).as_byte_slice().to_vec();
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());
let relayer_id = "relayer.root";
let message = [relayer_id, hex::encode(msg).as_str()].join(":");
Expand Down
21 changes: 15 additions & 6 deletions engine-tests/src/tests/standalone/sync.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use aurora_engine::deposit_event::TokenMessageData;
use aurora_engine_sdk::env::{Env, Timestamp};
use aurora_engine_types::types::Fee;
use aurora_engine_types::{account_id::AccountId, types::Wei, Address, H256, U256};
use borsh::BorshSerialize;
use engine_standalone_storage::sync;
Expand Down Expand Up @@ -331,12 +333,19 @@ fn test_consume_submit_message() {

fn mock_proof(recipient_address: Address, deposit_amount: Wei) -> aurora_engine::proof::Proof {
let eth_custodian_address = test_utils::standalone::mocks::ETH_CUSTODIAN_ADDRESS;

let fee = Fee::new(0);
let message = ["aurora", ":", hex::encode(&recipient_address).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],
recipient: ["aurora", ":", hex::encode(&recipient_address).as_str()].concat(),
amount: deposit_amount.raw(),
fee: U256::zero(),
token_message_data,
amount: deposit_amount.raw().as_u128(),
fee,
};

let event_schema = ethabi::Event {
Expand All @@ -352,9 +361,9 @@ fn mock_proof(recipient_address: Address, deposit_amount: Wei) -> aurora_engine:
crate::prelude::H256::zero(),
],
data: ethabi::encode(&[
ethabi::Token::String(deposit_event.recipient),
ethabi::Token::Uint(deposit_event.amount),
ethabi::Token::Uint(deposit_event.fee),
ethabi::Token::String(message),
ethabi::Token::Uint(U256::from(deposit_event.amount)),
ethabi::Token::Uint(U256::from(deposit_event.fee.into_u128())),
]),
};
aurora_engine::proof::Proof {
Expand Down
96 changes: 90 additions & 6 deletions engine-types/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ use borsh::{BorshDeserialize, BorshSerialize};

use crate::fmt::Formatter;

// TODO: introduce new Balance type for more strict typing
mrLSD marked this conversation as resolved.
Show resolved Hide resolved
pub type Balance = u128;
pub type RawAddress = [u8; 20];
pub type RawU256 = [u8; 32]; // Big-endian large integer type.
pub type RawU256 = [u8; 32];
// Big-endian large integer type.
pub type RawH256 = [u8; 32]; // Unformatted binary data of fixed length.

// TODO: introduce new type. Add encode/decode/validation methods
pub type EthAddress = [u8; 20];
pub type StorageUsage = u64;
/// Wei compatible Borsh-encoded raw value to attach an ETH balance to the transaction
Expand Down Expand Up @@ -104,6 +108,44 @@ impl Mul<EthGas> for u64 {
}
}

#[derive(
Default, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, BorshSerialize, BorshDeserialize,
)]
/// Engine `fee` type which wraps an underlying u128.
pub struct Fee(u128);

impl Display for Fee {
fn fmt(&self, f: &mut Formatter<'_>) -> crate::fmt::Result {
self.0.fmt(f)
}
}

impl Fee {
/// Constructs a new `Fee` with a given u128 value.
pub const fn new(fee: u128) -> Fee {
Self(fee)
}

/// Consumes `Fee` and returns the underlying type.
pub fn into_u128(self) -> u128 {
self.0
}
}

impl Add<Fee> for Fee {
type Output = Fee;

fn add(self, rhs: Fee) -> Self::Output {
Fee(self.0 + rhs.0)
}
}

impl From<u128> for Fee {
fn from(fee: u128) -> Self {
Self(fee)
}
}

/// Selector to call mint function in ERC 20 contract
///
/// keccak("mint(address,uint256)".as_bytes())[..4];
Expand All @@ -125,7 +167,7 @@ impl AsRef<[u8]> for AddressValidationError {
}
}

/// Validate Etherium address from string and return EthAddress
/// Validate Ethereum address from string and return Result data EthAddress or Error data
pub fn validate_eth_address(address: String) -> Result<EthAddress, AddressValidationError> {
let data = hex::decode(address).map_err(|_| AddressValidationError::FailedDecodeHex)?;
if data.len() != 20 {
Expand Down Expand Up @@ -183,6 +225,13 @@ impl Wei {
pub fn checked_add(self, rhs: Self) -> Option<Self> {
self.0.checked_add(rhs.0).map(Self)
}

/// Try convert U256 to u128 with checking overflow.
/// NOTICE: Error can contain only overflow
pub fn try_into_u128(self) -> Result<u128, error::BalanceOverflowError> {
use crate::TryInto;
self.0.try_into().map_err(|_| error::BalanceOverflowError)
}
}

impl Display for Wei {
Expand Down Expand Up @@ -214,10 +263,8 @@ impl From<WeiU256> for Wei {
}
}

#[derive(BorshSerialize, BorshDeserialize)]
pub struct U128(pub u128);

pub const STORAGE_PRICE_PER_BYTE: u128 = 10_000_000_000_000_000_000; // 1e19yN, 0.00001N
pub const STORAGE_PRICE_PER_BYTE: u128 = 10_000_000_000_000_000_000;
// 1e19yN, 0.00001N
mrLSD marked this conversation as resolved.
Show resolved Hide resolved
pub const ERR_FAILED_PARSE: &str = "ERR_FAILED_PARSE";
pub const ERR_INVALID_ETH_ADDRESS: &str = "ERR_INVALID_ETH_ADDRESS";

Expand Down Expand Up @@ -314,10 +361,31 @@ impl<T> Stack<T> {
self.stack
}
}

pub fn str_from_slice(inp: &[u8]) -> &str {
str::from_utf8(inp).unwrap()
}

pub mod error {
use crate::{fmt, String};

#[derive(Eq, Hash, Clone, Debug, PartialEq)]
pub struct BalanceOverflowError;

impl AsRef<[u8]> for BalanceOverflowError {
fn as_ref(&self) -> &[u8] {
b"ERR_BALANCE_OVERFLOW"
}
}

impl fmt::Display for BalanceOverflowError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let msg = String::from_utf8(self.as_ref().to_vec()).unwrap();
write!(f, "{}", msg)
}
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down Expand Up @@ -420,4 +488,20 @@ mod tests {
let wei_amount = U256::from(eth_amount) * U256::from(10).pow(18.into());
assert_eq!(Wei::from_eth(eth_amount.into()), Some(Wei::new(wei_amount)));
}

#[test]
fn test_fee_add() {
let fee = Fee::new(100);
assert_eq!(fee + fee, Fee::new(200));
assert_eq!(fee.add(200.into()), Fee::new(300));
}

#[test]
fn test_fee_from() {
let fee = Fee::new(100);
let fee2 = Fee::from(100u128);
assert_eq!(fee, fee2);
let res: u128 = fee.into_u128();
assert_eq!(res, 100);
}
}
Loading