Skip to content
This repository has been archived by the owner on Mar 13, 2023. It is now read-only.

Commit

Permalink
Release Pangolin.221 (#599)
Browse files Browse the repository at this point in the history
* Move RawAccountBasic to test mod

* Change ExistentialDeposit to zero

* Evm pallet code clean

* Fix js test

* Format code
  • Loading branch information
boundless-forest authored Apr 21, 2021
1 parent e3a42af commit 4d16da0
Show file tree
Hide file tree
Showing 7 changed files with 69 additions and 140 deletions.
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.

2 changes: 1 addition & 1 deletion bin/node/runtime/pangolin/src/pallets/balances.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ pub type NegativeImbalance = <Pallet<Runtime, RingInstance> as Currency<
>>::NegativeImbalance;

frame_support::parameter_types! {
pub const ExistentialDeposit: Balance = 1 * COIN;
pub const ExistentialDeposit: Balance = 0;
pub const MaxLocks: u32 = 50;
}
impl Config<RingInstance> for Runtime {
Expand Down
1 change: 0 additions & 1 deletion client/dvm/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ rand = { version = "0.7" }
rlp = { version = "0.5.0" }
sha3 = { version = "0.8" }
# darwinia
darwinia-evm = { path = "../../../frame/evm" }
dc-consensus = { path = "../consensus" }
dc-db = { path = "../db" }
dp-rpc = { path = "../../../primitives/rpc" }
Expand Down
7 changes: 2 additions & 5 deletions client/dvm/rpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,6 @@ mod eth;
mod eth_pubsub;
mod overrides;

pub use overrides::{OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override, StorageOverride};
// --- darwinia ---
use darwinia_evm::ExitReason;
// --- std ---
pub use eth::{
EthApi, EthApiServer, EthFilterApi, EthFilterApiServer, EthTask, NetApi, NetApiServer, Web3Api,
Web3ApiServer,
Expand All @@ -31,8 +27,9 @@ use ethereum::{
Transaction as EthereumTransaction, TransactionMessage as EthereumTransactionMessage,
};
use ethereum_types::H160;
use evm::ExitError;
use evm::{ExitError, ExitReason};
use jsonrpc_core::{Error, ErrorCode, Value};
pub use overrides::{OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override, StorageOverride};

pub mod frontier_backend_client {

Expand Down
131 changes: 3 additions & 128 deletions frame/evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ pub use dp_evm::{
use frame_support::{
decl_error, decl_event, decl_module, decl_storage,
dispatch::DispatchResultWithPostInfo,
traits::{Currency, ExistenceRequirement, Get},
traits::{Currency, Get},
weights::{Pays, PostDispatchInfo, Weight},
};
use frame_system::RawOrigin;
use sp_core::{Hasher, H160, H256, U256};
use sp_core::{H160, H256, U256};
use sp_runtime::{
traits::{BadOrigin, UniqueSaturatedInto},
AccountId32, DispatchResult,
Expand All @@ -46,8 +46,7 @@ use sp_std::vec::Vec;
// --- std ---
#[cfg(feature = "std")]
use codec::{Decode, Encode};
use evm::Config as EvmConfig;
pub use evm::{ExitError, ExitFatal, ExitReason, ExitRevert, ExitSucceed};
use evm::{Config as EvmConfig, ExitError, ExitReason};
#[cfg(feature = "std")]
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -82,52 +81,6 @@ pub trait EnsureAddressOrigin<OuterOrigin> {
) -> Result<Self::Success, OuterOrigin>;
}

/// Ensure that the EVM address is the same as the Substrate address. This only works if the account
/// ID is `H160`.
pub struct EnsureAddressSame;

impl<OuterOrigin> EnsureAddressOrigin<OuterOrigin> for EnsureAddressSame
where
OuterOrigin: Into<Result<RawOrigin<H160>, OuterOrigin>> + From<RawOrigin<H160>>,
{
type Success = H160;

fn try_address_origin(address: &H160, origin: OuterOrigin) -> Result<H160, OuterOrigin> {
origin.into().and_then(|o| match o {
RawOrigin::Signed(who) if &who == address => Ok(who),
r => Err(OuterOrigin::from(r)),
})
}
}

/// Ensure that the origin is root.
pub struct EnsureAddressRoot<AccountId>(sp_std::marker::PhantomData<AccountId>);

impl<OuterOrigin, AccountId> EnsureAddressOrigin<OuterOrigin> for EnsureAddressRoot<AccountId>
where
OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>> + From<RawOrigin<AccountId>>,
{
type Success = ();

fn try_address_origin(_address: &H160, origin: OuterOrigin) -> Result<(), OuterOrigin> {
origin.into().and_then(|o| match o {
RawOrigin::Root => Ok(()),
r => Err(OuterOrigin::from(r)),
})
}
}

/// Ensure that the origin never happens.
pub struct EnsureAddressNever<AccountId>(sp_std::marker::PhantomData<AccountId>);

impl<OuterOrigin, AccountId> EnsureAddressOrigin<OuterOrigin> for EnsureAddressNever<AccountId> {
type Success = AccountId;

fn try_address_origin(_address: &H160, origin: OuterOrigin) -> Result<AccountId, OuterOrigin> {
Err(origin)
}
}

/// Ensure that the address is truncated hash of the origin. Only works if the account id is
/// `AccountId32`.
pub struct EnsureAddressTruncated;
Expand All @@ -152,29 +105,6 @@ pub trait AddressMapping<A> {
fn into_account_id(address: H160) -> A;
}

/// Identity address mapping.
pub struct IdentityAddressMapping;

impl AddressMapping<H160> for IdentityAddressMapping {
fn into_account_id(address: H160) -> H160 {
address
}
}

/// Hashed address mapping.
pub struct HashedAddressMapping<H>(sp_std::marker::PhantomData<H>);

impl<H: Hasher<Out = H256>> AddressMapping<AccountId32> for HashedAddressMapping<H> {
fn into_account_id(address: H160) -> AccountId32 {
let mut data = [0u8; 24];
data[0..4].copy_from_slice(b"evm:");
data[4..24].copy_from_slice(&address[..]);
let hash = H::hash(&data);

AccountId32::from(Into::<[u8; 32]>::into(hash))
}
}

pub struct ConcatAddressMapping;

/// The ConcatAddressMapping used for transfer from evm 20-length to substrate 32-length address
Expand All @@ -199,61 +129,6 @@ pub trait AccountBasic {
fn transfer(source: &H160, target: &H160, value: U256) -> Result<(), ExitError>;
}

pub struct RawAccountBasic<T>(sp_std::marker::PhantomData<T>);

impl<T: Config> AccountBasic for RawAccountBasic<T> {
/// Get the account basic in EVM format.
fn account_basic(address: &H160) -> Account {
let account_id = T::AddressMapping::into_account_id(*address);

let nonce = <frame_system::Pallet<T>>::account_nonce(&account_id);
let balance = T::RingCurrency::free_balance(&account_id);

Account {
nonce: U256::from(UniqueSaturatedInto::<u128>::unique_saturated_into(nonce)),
balance: U256::from(UniqueSaturatedInto::<u128>::unique_saturated_into(balance)),
}
}

fn mutate_account_basic(address: &H160, new: Account) {
let account_id = T::AddressMapping::into_account_id(*address);
let current = T::RingAccountBasic::account_basic(address);

if current.nonce < new.nonce {
// ASSUME: in one single EVM transaction, the nonce will not increase more than
// `u128::max_value()`.
for _ in 0..(new.nonce - current.nonce).low_u128() {
<frame_system::Pallet<T>>::inc_account_nonce(&account_id);
}
}

if current.balance > new.balance {
let diff = current.balance - new.balance;
T::RingCurrency::slash(&account_id, diff.low_u128().unique_saturated_into());
} else if current.balance < new.balance {
let diff = new.balance - current.balance;
T::RingCurrency::deposit_creating(&account_id, diff.low_u128().unique_saturated_into());
}
}

fn transfer(source: &H160, target: &H160, value: U256) -> Result<(), ExitError> {
let source_account_id = T::AddressMapping::into_account_id(*source);
let target_account_id = T::AddressMapping::into_account_id(*target);
let value = value.low_u128().unique_saturated_into();
let res = T::RingCurrency::transfer(
&source_account_id,
&target_account_id,
value,
ExistenceRequirement::AllowDeath,
);

match res {
Ok(()) => Ok(()),
Err(_) => Err(ExitError::Other("Transfer error".into())),
}
}
}

/// A mapping function that converts Ethereum gas to Substrate weight
pub trait GasWeightMapping {
fn gas_to_weight(gas: u64) -> Weight;
Expand Down
65 changes: 62 additions & 3 deletions frame/evm/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use crate::{self as darwinia_evm, *};
use frame_support::{assert_ok, traits::GenesisBuild};
use frame_system::mocking::*;
use sp_core::{Blake2Hasher, H256};
use sp_core::H256;
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
Expand Down Expand Up @@ -96,13 +96,72 @@ impl IssuingHandler for EmptyIssuingHandler {
}
}

pub struct RawAccountBasic<T>(sp_std::marker::PhantomData<T>);

impl<T: Config> AccountBasic for RawAccountBasic<T> {
/// Get the account basic in EVM format.
fn account_basic(address: &H160) -> Account {
let account_id = T::AddressMapping::into_account_id(*address);

let nonce = <frame_system::Pallet<T>>::account_nonce(&account_id);
let balance = T::RingCurrency::free_balance(&account_id);

Account {
nonce: U256::from(UniqueSaturatedInto::<u128>::unique_saturated_into(nonce)),
balance: U256::from(UniqueSaturatedInto::<u128>::unique_saturated_into(balance)),
}
}

fn mutate_account_basic(address: &H160, new: Account) {
let account_id = T::AddressMapping::into_account_id(*address);
let current = T::RingAccountBasic::account_basic(address);

if current.nonce < new.nonce {
// ASSUME: in one single EVM transaction, the nonce will not increase more than
// `u128::max_value()`.
for _ in 0..(new.nonce - current.nonce).low_u128() {
<frame_system::Pallet<T>>::inc_account_nonce(&account_id);
}
}

if current.balance > new.balance {
let diff = current.balance - new.balance;
T::RingCurrency::slash(&account_id, diff.low_u128().unique_saturated_into());
} else if current.balance < new.balance {
let diff = new.balance - current.balance;
T::RingCurrency::deposit_creating(&account_id, diff.low_u128().unique_saturated_into());
}
}

fn transfer(_source: &H160, _target: &H160, _value: U256) -> Result<(), ExitError> {
Ok(())
}
}

/// Ensure that the origin is root.
pub struct EnsureAddressRoot<AccountId>(sp_std::marker::PhantomData<AccountId>);

impl<OuterOrigin, AccountId> EnsureAddressOrigin<OuterOrigin> for EnsureAddressRoot<AccountId>
where
OuterOrigin: Into<Result<RawOrigin<AccountId>, OuterOrigin>> + From<RawOrigin<AccountId>>,
{
type Success = ();

fn try_address_origin(_address: &H160, origin: OuterOrigin) -> Result<(), OuterOrigin> {
origin.into().and_then(|o| match o {
RawOrigin::Root => Ok(()),
r => Err(OuterOrigin::from(r)),
})
}
}

impl Config for Test {
type FeeCalculator = FixedGasPrice;
type GasWeightMapping = ();
type CallOrigin = EnsureAddressRoot<Self::AccountId>;
type WithdrawOrigin = EnsureAddressNever<Self::AccountId>;
type WithdrawOrigin = EnsureAddressTruncated;

type AddressMapping = HashedAddressMapping<Blake2Hasher>;
type AddressMapping = ConcatAddressMapping;
type RingCurrency = Ring;
type KtonCurrency = Kton;

Expand Down
2 changes: 1 addition & 1 deletion script_tests/tests/1_test-transfer.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ describe("Test Transfer Balance", function () {
const balanceTo = await web3.utils.fromWei(await web3.eth.getBalance(addressTo2), "ether");

expect(balanceFrom).to.be.equal("123446.78895799999999999");
expect(balanceTo).to.be.equal("0");
expect(balanceTo).to.be.equal("0.0000000000000001");
expect(await web3.eth.getTransactionCount(addressFrom, "latest")).to.eq(2);
});

Expand Down

0 comments on commit 4d16da0

Please sign in to comment.