Skip to content

Commit

Permalink
Remove Default trait bound from engine IO (#342)
Browse files Browse the repository at this point in the history
  • Loading branch information
birchmd committed Nov 10, 2021
1 parent 965b403 commit fe13e1d
Show file tree
Hide file tree
Showing 6 changed files with 145 additions and 149 deletions.
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 @@ -246,7 +246,7 @@ impl AuroraRunner {
&[crate::prelude::storage::EthConnectorStorageId::FungibleToken as u8],
);
let ft_value = {
let mut current_ft: FungibleToken<aurora_engine_sdk::near_runtime::Runtime> = trie
let mut current_ft: FungibleToken = trie
.get(&ft_key)
.map(|bytes| FungibleToken::try_from_slice(&bytes).unwrap())
.unwrap_or_default();
Expand Down
21 changes: 12 additions & 9 deletions engine/src/connector.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::admin_controlled::{AdminControlled, PausedMask};
use crate::deposit_event::DepositedEvent;
use crate::engine::Engine;
use crate::fungible_token::{FungibleToken, FungibleTokenMetadata};
use crate::fungible_token::{FungibleToken, FungibleTokenMetadata, FungibleTokenOps};
use crate::json::parse_json;
use crate::parameters::{
BalanceOfCallArgs, BalanceOfEthCallArgs, FinishDepositCallArgs, InitCallArgs,
Expand Down Expand Up @@ -29,10 +29,9 @@ pub const UNPAUSE_ALL: PausedMask = 0;
pub const PAUSE_DEPOSIT: PausedMask = 1 << 0;
pub const PAUSE_WITHDRAW: PausedMask = 1 << 1;

#[derive(BorshSerialize, BorshDeserialize)]
pub struct EthConnectorContract<I: IO + Default> {
pub struct EthConnectorContract<I: IO> {
contract: EthConnector,
ft: FungibleToken<I>,
ft: FungibleTokenOps<I>,
paused_mask: PausedMask,
io: I,
}
Expand Down Expand Up @@ -62,11 +61,15 @@ pub struct OnTransferMessageData {
pub fee: U256,
}

impl<I: IO + Default + Copy> EthConnectorContract<I> {
impl<I: IO + Copy> EthConnectorContract<I> {
pub fn get_instance(io: I) -> Self {
Self {
contract: Self::get_contract_data(&io, &EthConnectorStorageId::Contract),
ft: Self::get_contract_data(&io, &EthConnectorStorageId::FungibleToken),
ft: Self::get_contract_data::<FungibleToken>(
&io,
&EthConnectorStorageId::FungibleToken,
)
.ops(io),
paused_mask: Self::get_contract_data(&io, &EthConnectorStorageId::PausedMask),
io,
}
Expand Down Expand Up @@ -103,7 +106,7 @@ impl<I: IO + Default + Copy> EthConnectorContract<I> {

let current_account_id = sdk::current_account_id();
let owner_id = AccountId::try_from(current_account_id).unwrap();
let mut ft = FungibleToken::new();
let mut ft = FungibleTokenOps::new(io);
// Register FT account for current contract
ft.internal_register_account(&owner_id);

Expand Down Expand Up @@ -599,7 +602,7 @@ impl<I: IO + Default + Copy> EthConnectorContract<I> {
fn save_ft_contract(&mut self) {
self.io.write_borsh(
&Self::get_contract_key(&EthConnectorStorageId::FungibleToken),
&self.ft,
&self.ft.data(),
);
}

Expand Down Expand Up @@ -644,7 +647,7 @@ impl<I: IO + Default + Copy> EthConnectorContract<I> {
}
}

impl<I: IO + Default + Copy> AdminControlled for EthConnectorContract<I> {
impl<I: IO + Copy> AdminControlled for EthConnectorContract<I> {
fn get_paused(&self) -> PausedMask {
self.paused_mask
}
Expand Down
101 changes: 58 additions & 43 deletions engine/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,16 @@ use evm::{Config, CreateScheme, ExitError, ExitFatal, ExitReason};
use crate::connector::EthConnectorContract;
#[cfg(feature = "contract")]
use crate::contract::current_address;
use crate::map::{BijectionMap, LookupMap};
use crate::map::BijectionMap;
use aurora_engine_sdk::io::{StorageIntermediate, IO};
use aurora_engine_sdk::near_runtime::Runtime;

use crate::parameters::{NewCallArgs, TransactionStatus};
use crate::prelude::precompiles::native::{ExitToEthereum, ExitToNear};
use crate::prelude::precompiles::Precompiles;
use crate::prelude::{
address_to_key, bytes_to_key, sdk, storage_to_key, u256_to_arr, AccountId, Address,
BorshDeserialize, BorshSerialize, KeyPrefix, KeyPrefixU8, PromiseArgs, PromiseCreateArgs,
TryFrom, TryInto, Vec, Wei, ERC20_MINT_SELECTOR, H256, U256,
BorshDeserialize, BorshSerialize, KeyPrefix, PromiseArgs, PromiseCreateArgs, TryFrom, TryInto,
Vec, Wei, ERC20_MINT_SELECTOR, H256, U256,
};
use crate::transaction::NormalizedEthTransaction;

Expand Down Expand Up @@ -201,6 +200,30 @@ impl From<BalanceOverflow> for GasPaymentError {
}
}

pub struct ERC20Address(Address);
impl AsRef<[u8]> for ERC20Address {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl From<Vec<u8>> for ERC20Address {
fn from(bytes: Vec<u8>) -> Self {
Self(Address::from_slice(&bytes))
}
}

pub struct NEP141Account(AccountId);
impl AsRef<[u8]> for NEP141Account {
fn as_ref(&self) -> &[u8] {
self.0.as_bytes()
}
}
impl From<Vec<u8>> for NEP141Account {
fn from(bytes: Vec<u8>) -> Self {
Self(AccountId::try_from(bytes).unwrap())
}
}

pub const ERR_INVALID_NEP141_ACCOUNT_ID: &str = "ERR_INVALID_NEP141_ACCOUNT_ID";

#[derive(Debug)]
Expand Down Expand Up @@ -273,7 +296,7 @@ impl StackExecutorParams {
}
}

fn make_executor<'a, I: IO + Default + Copy>(
fn make_executor<'a, I: IO + Copy>(
&'a self,
engine: &'a Engine<I>,
) -> executor::StackExecutor<'static, 'a, executor::MemoryStackState<Engine<I>>, Precompiles>
Expand Down Expand Up @@ -305,9 +328,6 @@ pub struct EngineState {
pub bridge_prover_id: AccountId,
/// How many blocks after staging upgrade can deploy it.
pub upgrade_delay_blocks: u64,
/// Mapping between relayer account id and relayer evm address
pub relayers_evm_addresses:
LookupMap<Runtime, { KeyPrefix::RelayerEvmAddressMap as KeyPrefixU8 }>,
}

impl From<NewCallArgs> for EngineState {
Expand All @@ -317,7 +337,6 @@ impl From<NewCallArgs> for EngineState {
owner_id: args.owner_id,
bridge_prover_id: args.bridge_prover_id,
upgrade_delay_blocks: args.upgrade_delay_blocks,
relayers_evm_addresses: LookupMap::default(),
}
}
}
Expand All @@ -335,7 +354,7 @@ pub(crate) const CONFIG: &Config = &Config::london();
/// Key for storing the state of the engine.
const STATE_KEY: &[u8; 5] = b"STATE";

impl<I: IO + Copy + Default> Engine<I> {
impl<I: IO + Copy> Engine<I> {
pub fn new(origin: Address, io: I) -> Result<Self, EngineStateError> {
Engine::get_state(&io).map(|state| Self::new_with_state(state, origin, io))
}
Expand Down Expand Up @@ -687,46 +706,52 @@ impl<I: IO + Copy + Default> Engine<I> {
status.into_result(result)
}

fn relayer_key(account_id: &[u8]) -> Vec<u8> {
bytes_to_key(KeyPrefix::RelayerEvmAddressMap, account_id)
}

pub fn register_relayer(&mut self, account_id: &[u8], evm_address: Address) {
self.state
.relayers_evm_addresses
.insert_raw(account_id, evm_address.as_bytes());
let key = Self::relayer_key(account_id);
self.io.write_storage(&key, evm_address.as_bytes());
}

#[allow(dead_code)]
pub fn get_relayer(&self, account_id: &[u8]) -> Option<Address> {
self.state
.relayers_evm_addresses
.get_raw(account_id)
.map(|result| Address(result.as_slice().try_into().unwrap()))
let key = Self::relayer_key(account_id);
self.io
.read_storage(&key)
.map(|v| Address::from_slice(&v.to_vec()))
}

pub fn nep141_erc20_map(io: I) -> BijectionMap<NEP141Account, ERC20Address, I> {
BijectionMap::new(KeyPrefix::Nep141Erc20Map, KeyPrefix::Erc20Nep141Map, io)
}

pub fn register_token(
&mut self,
erc20_token: &[u8],
nep141_token: &[u8],
erc20_token: Address,
nep141_token: AccountId,
) -> Result<(), RegisterTokenError> {
match Self::get_erc20_from_nep141(self.io, nep141_token) {
match Self::get_erc20_from_nep141(&self.io, &nep141_token) {
Err(GetErc20FromNep141Error::Nep141NotFound) => (),
Err(GetErc20FromNep141Error::InvalidNep141AccountId) => {
return Err(RegisterTokenError::InvalidNep141AccountId);
}
Ok(_) => return Err(RegisterTokenError::TokenAlreadyRegistered),
}

Self::nep141_erc20_map(self.io).insert(nep141_token, erc20_token);
let erc20_token = ERC20Address(erc20_token);
let nep141_token = NEP141Account(nep141_token);
Self::nep141_erc20_map(self.io).insert(&nep141_token, &erc20_token);
Ok(())
}

pub fn get_erc20_from_nep141(
io: I,
nep141_account_id: &[u8],
io: &I,
nep141_account_id: &AccountId,
) -> Result<Vec<u8>, GetErc20FromNep141Error> {
AccountId::try_from(nep141_account_id)
.map_err(|_| GetErc20FromNep141Error::InvalidNep141AccountId)?;

Self::nep141_erc20_map(io)
.lookup_left(nep141_account_id)
let key = bytes_to_key(KeyPrefix::Nep141Erc20Map, nep141_account_id.as_bytes());
io.read_storage(&key)
.map(|v| v.to_vec())
.ok_or(GetErc20FromNep141Error::Nep141NotFound)
}

Expand Down Expand Up @@ -786,10 +811,10 @@ impl<I: IO + Copy + Default> Engine<I> {
(recipient, fee)
};

let token = sdk::predecessor_account_id();
let token = AccountId::try_from(sdk::predecessor_account_id()).unwrap();
let erc20_token = Address(unwrap_res_or_finish!(
unwrap_res_or_finish!(
Self::get_erc20_from_nep141(self.io, &token),
Self::get_erc20_from_nep141(&self.io, &token),
output_on_fail,
self.io
)
Expand Down Expand Up @@ -877,16 +902,6 @@ impl<I: IO + Copy + Default> Engine<I> {
self.io.return_output(b"\"0\"");
}

pub fn nep141_erc20_map(
io: I,
) -> BijectionMap<
I,
{ KeyPrefix::Nep141Erc20Map as KeyPrefixU8 },
{ KeyPrefix::Erc20Nep141Map as KeyPrefixU8 },
> {
BijectionMap { io }
}

fn filter_promises_from_logs<T: IntoIterator<Item = Log>>(logs: T) -> Vec<ResultLog> {
logs.into_iter()
.filter_map(|log| {
Expand Down Expand Up @@ -983,7 +998,7 @@ pub fn compute_block_hash(chain_id: [u8; 32], block_height: u64, account_id: &[u
sdk::sha256(&data)
}

impl<I: IO + Default + Copy> evm::backend::Backend for Engine<I> {
impl<I: IO + Copy> evm::backend::Backend for Engine<I> {
/// Returns the "effective" gas price (as defined by EIP-1559)
fn gas_price(&self) -> U256 {
self.gas_price
Expand Down Expand Up @@ -1114,7 +1129,7 @@ impl<I: IO + Default + Copy> evm::backend::Backend for Engine<I> {
}
}

impl<J: IO + Default + Copy> ApplyBackend for Engine<J> {
impl<J: IO + Copy> ApplyBackend for Engine<J> {
fn apply<A, I, L>(&mut self, values: A, _logs: L, delete_empty: bool)
where
A: IntoIterator<Item = Apply<I>>,
Expand Down
39 changes: 34 additions & 5 deletions engine/src/fungible_token.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,29 @@ const GAS_FOR_RESOLVE_TRANSFER: Gas = 5_000_000_000_000;
const GAS_FOR_FT_ON_TRANSFER: Gas = 10_000_000_000_000;

#[derive(Debug, Default, BorshDeserialize, BorshSerialize)]
pub struct FungibleToken<I: IO + Default> {
pub struct FungibleToken {
/// Total ETH supply on Near (nETH as NEP-141 token)
pub total_eth_supply_on_near: Balance,

/// Total ETH supply on Aurora (ETH in Aurora EVM)
pub total_eth_supply_on_aurora: Balance,

/// The storage size in bytes for one account.
pub account_storage_usage: StorageUsage,
}

impl FungibleToken {
pub fn ops<I: IO>(self, io: I) -> FungibleTokenOps<I> {
FungibleTokenOps {
total_eth_supply_on_near: self.total_eth_supply_on_near,
total_eth_supply_on_aurora: self.total_eth_supply_on_aurora,
account_storage_usage: self.account_storage_usage,
io,
}
}
}

pub struct FungibleTokenOps<I: IO> {
/// Total ETH supply on Near (nETH as NEP-141 token)
pub total_eth_supply_on_near: Balance,

Expand All @@ -24,7 +46,6 @@ pub struct FungibleToken<I: IO + Default> {
/// The storage size in bytes for one account.
pub account_storage_usage: StorageUsage,

#[borsh_skip]
io: I,
}

Expand Down Expand Up @@ -89,9 +110,17 @@ impl From<FungibleTokenMetadata> for JsonValue {
}
}

impl<I: IO + Copy + Default> FungibleToken<I> {
pub fn new() -> Self {
Self::default()
impl<I: IO + Copy> FungibleTokenOps<I> {
pub fn new(io: I) -> Self {
FungibleToken::default().ops(io)
}

pub fn data(&self) -> FungibleToken {
FungibleToken {
total_eth_supply_on_near: self.total_eth_supply_on_near,
total_eth_supply_on_aurora: self.total_eth_supply_on_aurora,
account_storage_usage: self.account_storage_usage,
}
}

/// Balance of nETH (ETH on NEAR token)
Expand Down
11 changes: 5 additions & 6 deletions engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,9 +416,7 @@ mod contract {
};

sdk::log!(crate::prelude::format!("Deployed ERC-20 in Aurora at: {:#?}", address).as_str());
engine
.register_token(address.as_bytes(), args.nep141.as_bytes())
.sdk_unwrap();
engine.register_token(address, args.nep141).sdk_unwrap();
io.return_output(&address.as_bytes().try_to_vec().sdk_expect("ERR_SERIALIZE"));

// TODO: charge for storage
Expand Down Expand Up @@ -741,7 +739,7 @@ mod contract {
let args: GetErc20FromNep141CallArgs = io.read_input_borsh().sdk_unwrap();

io.return_output(
Engine::get_erc20_from_nep141(io, args.nep141.as_bytes())
Engine::get_erc20_from_nep141(&io, &args.nep141)
.sdk_unwrap()
.as_slice(),
);
Expand All @@ -750,11 +748,12 @@ mod contract {
#[no_mangle]
pub extern "C" fn get_nep141_from_erc20() {
let mut io = Runtime;
let erc20_address: crate::engine::ERC20Address = io.read_input().to_vec().into();
io.return_output(
Engine::nep141_erc20_map(io)
.lookup_right(io.read_input().to_vec().as_slice())
.lookup_right(&erc20_address)
.sdk_expect("ERC20_NOT_FOUND")
.as_slice(),
.as_ref(),
);
}

Expand Down
Loading

0 comments on commit fe13e1d

Please sign in to comment.