Skip to content

Commit

Permalink
Merge branch 'develop' into feat/erc20-gas-token
Browse files Browse the repository at this point in the history
  • Loading branch information
aleksuss authored Feb 10, 2023
2 parents 3753523 + f6747cb commit a6a41ca
Show file tree
Hide file tree
Showing 21 changed files with 229 additions and 897 deletions.
7 changes: 1 addition & 6 deletions Cargo.lock

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

6 changes: 3 additions & 3 deletions engine-sdk/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl<T> ExpectUtf8<T> for Option<T> {
}

#[cfg(feature = "contract")]
impl<T, E> ExpectUtf8<T> for core::result::Result<T, E> {
impl<T, E> ExpectUtf8<T> for Result<T, E> {
fn expect_utf8(self, message: &[u8]) -> T {
match self {
Ok(t) => t,
Expand All @@ -67,7 +67,7 @@ impl<T> SdkExpect<T> for Option<T> {
}

#[cfg(feature = "contract")]
impl<T, E> SdkExpect<T> for core::result::Result<T, E> {
impl<T, E> SdkExpect<T> for Result<T, E> {
fn sdk_expect(self, msg: &str) -> T {
match self {
Ok(t) => t,
Expand All @@ -92,7 +92,7 @@ impl<T> SdkUnwrap<T> for Option<T> {
}

#[cfg(feature = "contract")]
impl<T, E: AsRef<[u8]>> SdkUnwrap<T> for core::result::Result<T, E> {
impl<T, E: AsRef<[u8]>> SdkUnwrap<T> for Result<T, E> {
fn sdk_unwrap(self) -> T {
match self {
Ok(t) => t,
Expand Down
2 changes: 1 addition & 1 deletion engine-tests/src/test_utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -686,7 +686,7 @@ pub(crate) fn create_deploy_transaction(contract_bytes: Vec<u8>, nonce: U256) ->

pub(crate) fn create_eth_transaction(
to: Option<Address>,
value: crate::prelude::Wei,
value: Wei,
data: Vec<u8>,
chain_id: Option<u64>,
secret_key: &SecretKey,
Expand Down
6 changes: 3 additions & 3 deletions engine-tests/src/tests/erc20_connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ pub struct EthereumAddress {
pub address: Address,
}

impl test_utils::AuroraRunner {
impl AuroraRunner {
pub fn new() -> Self {
test_utils::deploy_evm()
}
Expand Down Expand Up @@ -556,7 +556,7 @@ pub mod sim_tests {
tester_address,
aurora,
} = test_exit_to_near_eth_common();
let exit_account_id = "any.near".to_owned();
let exit_account_id = "any.near";

// call exit to near
let input = super::build_input(
Expand All @@ -582,7 +582,7 @@ pub mod sim_tests {
(INITIAL_ETH_BALANCE - ETH_EXIT_AMOUNT) as u128
);
assert_eq!(
nep_141_balance_of(exit_account_id.as_str(), &aurora.contract, &aurora),
nep_141_balance_of(exit_account_id, &aurora.contract, &aurora),
ETH_EXIT_AMOUNT as u128
);
assert_eq!(
Expand Down
34 changes: 10 additions & 24 deletions engine-tests/src/tests/eth_connector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -172,11 +172,6 @@ fn call_deposit_eth_to_aurora(master_account: &UserAccount, contract: &str) {
}

fn get_eth_on_near_balance(master_account: &UserAccount, acc: &str, contract: &str) -> u128 {
#[derive(BorshSerialize)]
pub struct BalanceOfCallArgs {
pub account_id: String,
}

let balance = master_account.view(
contract.parse().unwrap(),
"ft_balance_of",
Expand All @@ -188,15 +183,12 @@ fn get_eth_on_near_balance(master_account: &UserAccount, acc: &str, contract: &s
}

fn get_eth_balance(master_account: &UserAccount, address: Address, contract: &str) -> u128 {
#[derive(BorshSerialize, BorshDeserialize)]
pub struct BalanceOfEthCallArgs {
pub address: Address,
}

let balance = master_account.view(
contract.parse().unwrap(),
"ft_balance_of_eth",
&BalanceOfEthCallArgs { address }.try_to_vec().unwrap(),
&aurora_engine::parameters::BalanceOfEthCallArgs { address }
.try_to_vec()
.unwrap(),
);
let val_str = String::from_utf8(balance.unwrap()).unwrap();
let val = &val_str[1..val_str.len() - 1];
Expand Down Expand Up @@ -362,13 +354,10 @@ fn test_ft_transfer() {
res.assert_success();

let balance = get_eth_on_near_balance(&master_account, DEPOSITED_RECIPIENT, CONTRACT_ACC);
assert_eq!(
balance,
DEPOSITED_AMOUNT - DEPOSITED_FEE + transfer_amount as u128
);
assert_eq!(balance, DEPOSITED_AMOUNT - DEPOSITED_FEE + transfer_amount);

let balance = get_eth_on_near_balance(&master_account, CONTRACT_ACC, CONTRACT_ACC);
assert_eq!(balance, DEPOSITED_FEE - transfer_amount as u128);
assert_eq!(balance, DEPOSITED_FEE - transfer_amount);

let balance = total_supply(&master_account, CONTRACT_ACC);
assert_eq!(balance, DEPOSITED_AMOUNT);
Expand Down Expand Up @@ -539,7 +528,7 @@ fn test_ft_transfer_call_without_message() {
let dummy_ft_receiver = master_account.deploy(
&dummy_ft_receiver_bytes(),
"ft-rec.root".parse().unwrap(),
near_sdk_sim::STORAGE_AMOUNT,
STORAGE_AMOUNT,
);
let res = recipient_account.call(
CONTRACT_ACC.parse().unwrap(),
Expand Down Expand Up @@ -1309,13 +1298,10 @@ fn test_get_accounts_counter_and_transfer() {
res.assert_success();

let balance = get_eth_on_near_balance(&master_account, DEPOSITED_RECIPIENT, CONTRACT_ACC);
assert_eq!(
balance,
DEPOSITED_AMOUNT - DEPOSITED_FEE + transfer_amount as u128
);
assert_eq!(balance, DEPOSITED_AMOUNT - DEPOSITED_FEE + transfer_amount);

let balance = get_eth_on_near_balance(&master_account, CONTRACT_ACC, CONTRACT_ACC);
assert_eq!(balance, DEPOSITED_FEE - transfer_amount as u128);
assert_eq!(balance, DEPOSITED_FEE - transfer_amount);

let balance = total_supply(&master_account, CONTRACT_ACC);
assert_eq!(balance, DEPOSITED_AMOUNT);
Expand Down Expand Up @@ -1633,7 +1619,7 @@ fn test_ft_transfer_empty_value() {
eprintln!("{:#?}", promise.as_ref().unwrap().outcome().clone().status);
assert_execution_status_failure(
promise.as_ref().unwrap().outcome().clone().status,
"ERR_FAILED_PARSE_U128",
"cannot parse integer from empty string",
"Expected failure as empty string can't be parsed to u128",
);
}
Expand Down Expand Up @@ -1661,7 +1647,7 @@ fn test_ft_transfer_wrong_u128_json_type() {
eprintln!("{:#?}", promise.as_ref().unwrap().outcome().clone().status);
assert_execution_status_failure(
promise.as_ref().unwrap().outcome().clone().status,
"ERR_EXPECTED_STRING_GOT_NUMBER",
"Wait for a string but got: 200",
"Expected failure as number type can't be parsed to u128",
);
}
Expand Down
6 changes: 5 additions & 1 deletion engine-tests/src/tests/ghsa_3p69_m8gg_fwmf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,5 +44,9 @@ fn test_exploit_fix() {

let (_outcome, maybe_error) = runner.one_shot().call("view", "viewer", input);
let error_message = format!("{:?}", maybe_error);
assert!(error_message.contains("ERR_ILLEGAL_RETURN"));
assert!(
error_message.contains("ERR_ILLEGAL_RETURN"),
"{}",
error_message
);
}
10 changes: 4 additions & 6 deletions engine-tests/src/tests/sanity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -944,13 +944,11 @@ fn test_ft_metadata() {
let (maybe_outcome, maybe_error) = runner.call("ft_metadata", &account_id, Vec::new());
assert!(maybe_error.is_none());
let outcome = maybe_outcome.unwrap();
let json_value =
aurora_engine::json::parse_json(&outcome.return_data.as_value().unwrap()).unwrap();
let metadata =
serde_json::from_slice::<FungibleTokenMetadata>(&outcome.return_data.as_value().unwrap())
.unwrap();

assert_eq!(
json_value,
aurora_engine::json::JsonValue::from(FungibleTokenMetadata::default())
);
assert_eq!(metadata, FungibleTokenMetadata::default());
}

// Same as `test_eth_transfer_insufficient_balance` above, except runs through
Expand Down
5 changes: 1 addition & 4 deletions engine-tests/src/tests/standalone/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,10 +101,7 @@ fn test_consume_deposit_message() {
let ft_on_transfer_args = match outcome.maybe_result.unwrap().unwrap() {
sync::TransactionExecutionResult::Promise(promise_args) => {
let bytes = promise_args.base.args;
let json = aurora_engine::json::parse_json(&bytes).unwrap();
aurora_engine::parameters::NEP141FtOnTransferArgs::try_from(json)
.ok()
.unwrap()
serde_json::from_slice(&bytes).unwrap()
}
other => panic!("Unexpected result {:?}", other),
};
Expand Down
2 changes: 1 addition & 1 deletion engine-transactions/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ aurora-engine-sdk = { path = "../engine-sdk", default-features = false }
aurora-engine-precompiles = { path = "../engine-precompiles", default-features = false }
evm = { git = "https://github.com/aurora-is-near/sputnikvm.git", tag = "v0.37.4-aurora", default-features = false }
rlp = { version = "0.5.0", default-features = false }
serde = { version = "1", features = ["derive"], optional = true }
serde = { version = "1", default-features = false, features = ["alloc", "derive"], optional = true }

[dev-dependencies]
hex = { version = "0.4", default-features = false, features = ["alloc"] }
Expand Down
9 changes: 5 additions & 4 deletions engine-types/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,18 +15,19 @@ autobenches = false
[dependencies]
borsh = { version = "0.9.3", default-features = false }
hex = { version = "0.4", default-features = false, features = ["alloc"] }
primitive-types = { version = "0.12", default-features = false, features = ["rlp"] }
serde = { version = "1", features = ["derive"], optional = true }
primitive-types = { version = "0.12", default-features = false, features = ["rlp", "serde_no_std"] }
serde = { version = "1", default-features = false, features = ["alloc", "derive"] }
serde_json = { version = "1", default-features = false, features = ["alloc"] }

[dev-dependencies]
rand = "0.8.5"

[features]
default = ["std"]
std = ["borsh/std", "hex/std", "primitive-types/std"]
std = ["borsh/std", "hex/std", "primitive-types/std", "primitive-types/serde", "serde/std", "serde_json/std"]
# `primitive-types/std` is excluded because its `std` implementation includes a transitive
# dependency on `getrandom` which uses OS call to obtain entropy. Such calls are not
# available in Wasm, therefore we cannot use the `std` implementation of `primitive-types`
# in other Rust contracts.
contracts-std = ["borsh/std", "hex/std"]
impl-serde = ["primitive-types/impl-serde", "serde"]
impl-serde = ["primitive-types/impl-serde"]
15 changes: 13 additions & 2 deletions engine-types/src/account_id.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

use crate::{fmt, str, str::FromStr, Box, String, Vec};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Serialize};

pub const MIN_ACCOUNT_ID_LEN: usize = 2;
pub const MAX_ACCOUNT_ID_LEN: usize = 64;
Expand All @@ -12,9 +13,19 @@ pub const MAX_ACCOUNT_ID_LEN: usize = 64;
///
/// This guarantees all properly constructed AccountId's are valid for the NEAR network.
#[derive(
BorshSerialize, BorshDeserialize, Default, Eq, Ord, Hash, Clone, Debug, PartialEq, PartialOrd,
BorshSerialize,
BorshDeserialize,
Serialize,
Deserialize,
Default,
Eq,
Ord,
Hash,
Clone,
Debug,
PartialEq,
PartialOrd,
)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct AccountId(Box<str>);

impl AccountId {
Expand Down
4 changes: 1 addition & 3 deletions engine-types/src/types/address.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
use crate::{format, String, H160};
use borsh::maybestd::io;
use borsh::{BorshDeserialize, BorshSerialize};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

const ADDRESS_HEX_LENGTH: usize = 40;
const ADDRESS_BYTE_LENGTH: usize = 20;

/// Base Eth Address type
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Serialize, Deserialize)]
pub struct Address(H160);

impl Address {
Expand Down
76 changes: 74 additions & 2 deletions engine-types/src/types/balance.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use crate::fmt::Formatter;
use crate::{Add, Display, Sub};
use crate::{format, Add, Display, Sub, ToString};
use borsh::{BorshDeserialize, BorshSerialize};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

pub const ZERO_BALANCE: Balance = Balance::new(0);
pub const ZERO_YOCTO: Yocto = Yocto::new(0);
Expand Down Expand Up @@ -32,8 +33,47 @@ impl Balance {
}
}

impl Serialize for Balance {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let value = self.0.to_string();
serializer.serialize_str(&value)
}
}

impl<'de> Deserialize<'de> for Balance {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
D::Error: serde::de::Error,
{
use serde::de::Error;

let value = serde_json::Value::deserialize(deserializer)?;
Ok(Self(
value
.as_str()
.ok_or_else(|| Error::custom(format!("Wait for a string but got: {}", value)))
.and_then(|value| value.parse().map_err(Error::custom))?,
))
}
}

#[derive(
Default, BorshSerialize, BorshDeserialize, Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd,
Default,
BorshSerialize,
BorshDeserialize,
Serialize,
Deserialize,
Debug,
Clone,
Copy,
Eq,
PartialEq,
Ord,
PartialOrd,
)]
/// Near Yocto type which wraps an underlying u128.
/// 1 NEAR = 10^24 yoctoNEAR
Expand Down Expand Up @@ -92,3 +132,35 @@ pub mod error {
}
}
}

#[cfg(test)]
mod tests {
use super::Balance;
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize)]
struct SomeStruct {
balance: Balance,
}

#[test]
fn test_deserialize_balance() {
let json = r#"{"balance": "340282366920938463463374607431768211455"}"#;
let result: SomeStruct = serde_json::from_str(json).unwrap();
assert_eq!(result.balance, Balance::new(u128::MAX));

let json = r#"{"balance": "340282366920938463463374607431768211456"}"#; // Overflow
let result = serde_json::from_str::<SomeStruct>(json);
assert!(result.is_err());
}

#[test]
fn test_serialize_balance() {
let json = r#"{"balance":"340282366920938463463374607431768211455"}"#;
let result = SomeStruct {
balance: Balance::new(340282366920938463463374607431768211455),
};

assert_eq!(&serde_json::to_string(&result).unwrap(), json);
}
}
Loading

0 comments on commit a6a41ca

Please sign in to comment.