evm
Abstract
This document defines the specification of the Ethereum Virtual Machine (EVM) as a Cosmos SDK module.
Since the introduction of Ethereum in 2015, the ability to control digital assets through smart contracts has attracted a large community of developers to build decentralized applications on the Ethereum Virtual Machine (EVM). This community is continuously creating extensive tooling and introducing standards, which are further increasing the adoption rate of EVM compatible technology.
The growth of EVM-based chains (e.g. Ethereum), however, has uncovered several scalability challenges that are often referred to as the trilemma of decentralization, security, and scalability. Developers are frustrated by high gas fees, slow transaction speed & throughput, and chain-specific governance that can only undergo slow change because of its wide range of deployed applications. A solution is required that eliminates these concerns for developers, who build applications within a familiar EVM environment.
The x/evm
module provides this EVM familiarity on a scalable, high-throughput Proof-of-Stake blockchain. It is built as a Cosmos SDK module which allows for the deployment of smart contracts, interaction with the EVM state machine (state transitions), and the use of EVM tooling. It can be used on Cosmos application-specific blockchains, which alleviate the aforementioned concerns through high transaction throughput via Tendermint Core, fast transaction finality, and horizontal scalability via IBC.
The x/evm
module is part of the ethermint library.
Contents
Module Architecture
NOTE: If you're not familiar with the overall module structure from the SDK modules, please check this document as prerequisite reading.
Concepts
EVM
The Ethereum Virtual Machine (EVM) is a computation engine which can be thought of as one single entity maintained by thousands of connected computers (nodes) running an Ethereum client. As a virtual machine (VM), the EVM is responsible for computing changes to the state deterministically regardless of its environment (hardware and OS). This means that every node has to get the exact same result given an identical starting state and transaction (tx).
The EVM is considered to be the part of the Ethereum protocol that handles the deployment and execution of smart contracts. To make a clear distinction:
The Ethereum protocol describes a blockchain, in which all Ethereum accounts and smart contracts live. It has only one canonical state (a data structure, which keeps all accounts) at any given block in the chain.
The EVM, however, is the state machine that defines the rules for computing a new valid state from block to block. It is an isolated runtime, which means that code running inside the EVM has no access to network, filesystem, or other processes (not external APIs).
The x/evm
module implements the EVM as a Cosmos SDK module. It allows users to interact with the EVM by submitting Ethereum txs and executing their containing messages on the given state to evoke a state transition.
State
The Ethereum state is a data structure, implemented as a Merkle Patricia Tree, that keeps all accounts on the chain. The EVM makes changes to this data structure resulting in a new state with a different state root. Ethereum can therefore be seen as a state chain that transitions from one state to another by executing transactions in a block using the EVM. A new block of txs can be described through its block header (parent hash, block number, time stamp, nonce, receipts,...).
Accounts
There are two types of accounts that can be stored in state at a given address:
Externally Owned Account (EOA): Has nonce (tx counter) and balance
Smart Contract: Has nonce, balance, (immutable) code hash, storage root (another Merkle Patricia Trie)
Smart contracts are just like regular accounts on the blockchain, which additionally store executable code in an Ethereum-specific binary format, known as EVM bytecode. They are typically written in an Ethereum high level language, such as Solidity, which is compiled down to EVM bytecode and deployed on the blockchain by submitting a transaction using an Ethereum client.
Architecture
The EVM operates as a stack-based machine. It's main architecture components consist of:
Virtual ROM: contract code is pulled into this read only memory when processing txs
Machine state (volatile): changes as the EVM runs and is wiped clean after processing each tx
Program counter (PC)
Gas: keeps track of how much gas is used
Stack and Memory: compute state changes
Access to account storage (persistent)
State Transitions with Smart Contracts
Typically smart contracts expose a public ABI, which is a list of supported ways a user can interact with a contract. To interact with a contract and invoke a state transition, a user will submit a tx carrying any amount of gas and a data payload formatted according to the ABI, specifying the type of interaction and any additional parameters. When the tx is received, the EVM executes the smart contracts' EVM bytecode using the tx payload.
Executing EVM bytecode
A contract's EVM bytecode consists of basic operations (add, multiply, store, etc...), called Opcodes. Each Opcode execution requires gas that needs to be paid with the tx. The EVM is therefore considered quasi-turing complete, as it allows any arbitrary computation, but the amount of computations during a contract execution is limited to the amount of gas provided in the tx. Each Opcode's gas cost reflects the cost of running these operations on actual computer hardware (e.g. ADD = 3gas
and SSTORE = 100gas
). To calculate the gas consumption of a tx, the gas cost is multiplied by the gas price, which can change depending on the demand of the network at the time. If the network is under heavy load, you might have to pay a higher gas price to get your tx executed. If the gas limit is hit (out of gas exception) no changes to the Ethereum state are applied, except that the sender's nonce increments and their balance goes down to pay for wasting the EVM's time.
Smart contracts can also call other smart contracts. Each call to a new contract creates a new instance of the EVM (including a new stack and memory). Each call passes the sandbox state to the next EVM. If the gas runs out, all state changes are discarded. Otherwise, they are kept.
For further reading, please refer to:
Neura as Geth implementation
Neura contains an implementation of the Ethereum protocol in Golang (Geth) as a Cosmos SDK module. Geth includes an implementation of the EVM to compute state transitions. Have a look at the go-ethereum source code to see how the EVM opcodes are implemented. Just as Geth can be run as an Ethereum node, Neura can be run as a node to compute state transitions with the EVM. Neura supports Geth's standard Ethereum JSON-RPC APIs in order to be Web3 and EVM compatible.
JSON-RPC
JSON-RPC is a stateless, lightweight remote procedure call (RPC) protocol. Primarily this specification defines several data structures and the rules around their processing. It is transport agnostic in that the concepts can be used within the same process, over sockets, over HTTP, or in many various message passing environments. It uses JSON (RFC 4627) as a data format.
StateDB
The StateDB
interface from go-ethereum represents an EVM database for full state querying. EVM state transitions are enabled by this interface, which in the x/evm
module is implemented by the Keeper
. The implementation of this interface is what makes Neura EVM-compatible.
Consensus Engine
The application using the x/evm
module interacts with the Tendermint Core Consensus Engine over an Application Blockchain Interface (ABCI). Together, the application and Tendermint Core form the programs that run a complete blockchain and combine business logic with decentralized data storage.
Ethereum transactions which are submitted to the x/evm
module take part in this consensus process before being executed and changing the application state. We encourage you to learn the basics of the Tendermint consensus engine in order to understand state transitions in detail.
Transaction Logs
On every x/evm
transaction, the result contains the Ethereum Log
s from the state machine execution that are used by the JSON-RPC Web3 server for filter querying and for processing the EVM Hooks.
The tx logs are stored in the transient store during tx execution and then emitted through cosmos events after the transaction has been processed. They can be queried via gRPC and JSON-RPC.
Block Bloom
Bloom is the bloom filter value in bytes for each block that can be used for filter queries. The block bloom value is stored in the transient store and then emitted through a cosmos event during EndBlock
processing. They can be queried via gRPC and JSON-RPC.
NOTE: Since they are not stored on state, Transaction Logs and Block Blooms are not persisted after upgrades. A user must use an archival node after upgrades in order to obtain legacy chain events.
State
This section gives you an overview of the objects stored in the x/evm
module state, functionalities that are derived from the go-ethereum StateDB
interface, and its implementation through the Keeper as well as the state implementation at genesis.
State Objects
The x/evm
module keeps the following objects in state:
State
Description | Key | Value | Store | |
---|---|---|---|---|
Code | Smart contract bytecode |
|
| KV |
Storage | Smart contract storage |
|
| KV |
Block Bloom | Block bloom filter, used to accumulate the bloom filter of current block, emitted to events at end blocker. |
|
| Transient |
Tx Index | Index of current transaction in current block. |
|
| Transient |
Log Size | Number of the logs emitted so far in current block. Used to decide the log index of following logs. |
|
| Transient |
Gas Used | Amount of gas used by ethereum messages of current cosmos-sdk tx, it's necessary when cosmos-sdk tx contains multiple ethereum messages. |
|
| Transient |
StateDB
The StateDB
interface is implemented by the StateDB
in the x/evm/statedb
module to represent an EVM database for full state querying of both contracts and accounts. Within the Ethereum protocol, StateDB
s are used to store anything within the IAVL tree and take care of caching and storing nested states.
The StateDB
in the x/evm
provides the following functionalities:
CRUD of Ethereum accounts
You can create EthAccount
instances from the provided address and set the value to store on the AccountKeeper
with createAccount()
. If an account with the given address already exists, this function also resets any preexisting code and storage associated with that address.
An account's coin balance can be managed through the BankKeeper
and can be read with GetBalance()
and updated with AddBalance()
and SubBalance()
.
GetBalance()
returns the EVM denomination balance of the provided address. The denomination is obtained from the module parameters.AddBalance()
adds the given amount to the address balance coin by minting new coins and transferring them to the address. The coin denomination is obtained from the module parameters.SubBalance()
subtracts the given amount from the address balance by transferring the coins to an escrow account and then burning them. The coin denomination is obtained from the module parameters. This function performs a no-op if the amount is negative or the user doesn't have enough funds for the transfer.
The nonce (or transaction sequence) can be obtained from the Account Sequence
via the auth module AccountKeeper
.
GetNonce()
retrieves the account with the given address and returns the tx sequence (i.e nonce). The function performs a no-op if the account is not found.SetNonce()
sets the given nonce as the sequence of the address' account. If the account doesn't exist, a new one will be created from the address.
The smart contract bytecode containing arbitrary contract logic is stored on the EVMKeeper
and it can be queried with GetCodeHash()
,GetCode()
& GetCodeSize()
and updated with SetCode()
.
GetCodeHash()
fetches the account from the store and returns its code hash. If the account doesn't exist or is not an EthAccount type, it returns the empty code hash value.GetCode()
returns the code byte array associated with the given address. If the code hash from the account is empty, this function returns nil.SetCode()
stores the code byte array to the application KVStore and sets the code hash to the given account. The code is deleted from the store if it is empty.GetCodeSize()
returns the size of the contract code associated with this object, or zero if none.
Gas refunded needs to be tracked and stored in a separate variable in order to add it subtract/add it from/to the gas used value after the EVM execution has finalized. The refund value is cleared on every transaction and at the end of every block.
AddRefund()
adds the given amount of gas to the in-memory refund value.SubRefund()
subtracts the given amount of gas from the in-memory refund value. This function will panic if gas amount is greater than the current refund.GetRefund()
returns the amount of gas available for return after the tx execution finalizes. This value is reset to 0 on every transaction.
The state is stored on the EVMKeeper
. It can be queried with GetCommittedState()
, GetState()
and updated with SetState()
.
GetCommittedState()
returns the value set in store for the given key hash. If the key is not registered this function returns the empty hash.GetState()
returns the in-memory dirty state for the given key hash, if not exist load the committed value from KVStore.SetState()
sets the given hashes (key, value) to the state. If the value hash is empty, this function deletes the key from the state, the new value is kept in dirty state at first, and will be committed to KVStore in the end.
Accounts can also be set to a suicide state. When a contract commits suicide, the account is marked as suicided, when committing the code, storage and account are deleted (from the next block and forward).
Suicide()
marks the given account as suicided and clears the account balance of the EVM tokens.HasSuicided()
queries the in-memory flag to check if the account has been marked as suicided in the current transaction. Accounts that are suicided will be returned as non-nil during queries and "cleared" after the block has been committed.
To check account existence use Exist()
and Empty()
.
Exist()
returns true if the given account exists in store or if it has been marked as suicided.Empty()
returns true if the address meets the following conditions:nonce is 0
balance amount for evm denom is 0
account code hash is empty
EIP2930 functionality
Supports a transaction type that contains an access list, a list of addresses and storage keys, that the transaction plans to access. The access list state is kept in memory and discarded after the transaction committed.
PrepareAccessList()
handles the preparatory steps for executing a state transition in regard to both EIP-2929 and EIP-2930. This method should only be called if Yolov3/Berlin/2929+2930 is applicable at the current number.Add sender to access list (EIP-2929)
Add destination to access list (EIP-2929)
Add precompiles to access list (EIP-2929)
Add the contents of the optional tx access list (EIP-2930)
AddressInAccessList()
returns true if the address is registered.SlotInAccessList()
checks if the address and the slots are registered.AddAddressToAccessList()
adds the given address to the access list. If the address is already in the access list, this function performs a no-op.AddSlotToAccessList()
adds the given (address, slot) to the access list. If the address and slot are already in the access list, this function performs a no-op.
Snapshot state and Revert functionality
The EVM uses state-reverting exceptions to handle errors. Such an exception will undo all changes made to the state in the current call (and all its sub-calls), and the caller could handle the error and don't propagate. You can use Snapshot()
to identify the current state with a revision and revert the state to a given revision with RevertToSnapshot()
to support this feature.
Snapshot()
creates a new snapshot and returns the identifier.RevertToSnapshot(rev)
undo all the modifications up to the snapshot identified asrev
.
Neura adapted the go-ethereum journal implementation to support this, it uses a list of journal logs to record all the state modification operations done so far, snapshot is consists of a unique id and an index in the log list, and to revert to a snapshot it just undoes the journal logs after the snapshot index in reversed order.
Ethereum Transaction logs
With AddLog()
you can append the given Ethereum Log
to the list of logs associated with the transaction hash kept in the current state. This function also fills in the tx hash, block hash, tx index and log index fields before setting the log to store.
Keeper
The EVM module Keeper
grants access to the EVM module state and implements statedb.Keeper
interface to support the StateDB
implementation. The Keeper contains a store key that allows the DB to write to a concrete subtree of the multistore that is only accessible by the EVM module. Instead of using a trie and database for querying and persistence (the StateDB
implementation), Neura uses the Cosmos KVStore
(key-value store) and Cosmos SDK Keeper
to facilitate state transitions.
To support the interface functionality, it imports 4 module Keepers:
auth
: CRUD accountsbank
: accounting (supply) and CRUD of balancesstaking
: query historical headersfee market
: EIP1559 base fee for processingDynamicFeeTx
after theLondon
hard fork has been activated on theChainConfig
parameters
Genesis State
The x/evm
module GenesisState
defines the state necessary for initializing the chain from a previous exported height. It contains the GenesisAccounts
and the module parameters
Genesis Accounts
The GenesisAccount
type corresponds to an adaptation of the Ethereum GenesisAccount
type. It defines an account to be initialized in the genesis state.
Its main difference is that the one on Neura uses a custom Storage
type that uses a slice instead of maps for the evm State
(due to non-determinism), and that it doesn't contain the private key field.
It is also important to note that since the auth
module on the Cosmos SDK manages the account state, the Address
field must correspond to an existing EthAccount
that is stored in the auth
's module Keeper
(i.e AccountKeeper
). Addresses use the EIP55 hex format on genesis.json
.
State Transitions
The x/evm
module allows for users to submit Ethereum transactions (Tx
) and execute their containing messages to evoke state transitions on the given state.
Users submit transactions client-side to broadcast it to the network. When the transaction is included in a block during consensus, it is executed server-side. We highly recommend to understand the basics of the Tendermint consensus engine to understand the State Transitions in detail.
Client-Side
Based on the
eth_sendTransaction
JSON-RPC
A user submits a transaction via one of the available JSON-RPC endpoints using an Ethereum-compatible client or wallet (eg Metamask, WalletConnect, Ledger, etc): a. eth (public) namespace:
eth_sendTransaction
eth_sendRawTransaction
b. personal (private) namespace:personal_sendTransaction
An instance of
MsgEthereumTx
is created after populating the RPC transaction usingSetTxDefaults
to fill missing tx arguments with default valuesThe
Tx
fields are validated (stateless) usingValidateBasic()
The
Tx
is signed using the key associated with the sender address and the latest ethereum hard fork (London
,Berlin
, etc) from theChainConfig
The
Tx
is built from the msg fields using the Cosmos Config builderJSON-RPC user receives a response with the
RLP
hash of the transaction fields. This hash is different from the default hash used by SDK Transactions that calculates thesha256
hash of the transaction bytes.
Server-Side
Once a block (containing the Tx
) has been committed during consensus, it is applied to the application in a series of ABCI msgs server-side.
Each Tx
is handled by the application by calling RunTx
. After a stateless validation on each sdk.Msg
in the Tx
, the AnteHandler
confirms whether the Tx
is an Ethereum or SDK transaction. As an Ethereum transaction it's containing msgs are then handled by the x/evm
module to update the application's state.
AnteHandler
The anteHandler
is run for every transaction. It checks if the Tx
is an Ethereum transaction and routes it to an internal ante handler. Here, Tx
s are handled using EthereumTx extension options to process them differently than normal Cosmos SDK transactions. The antehandler
runs through a series of options and their AnteHandle
functions for each Tx
:
EthSetUpContextDecorator()
is adapted from SetUpContextDecorator from cosmos-sdk, it ignores gas consumption by setting the gas meter to infiniteEthValidateBasicDecorator(evmKeeper)
validates the fields of an Ethereum type CosmosTx
msgEthSigVerificationDecorator(evmKeeper)
validates that the registered chain id is the same as the one on the message, and that the signer address matches the one defined on the message. It's not skipped for RecheckTx, because it setFrom
address which is critical from other ante handler to work. Failure in RecheckTx will prevent tx to be included into block, especially when CheckTx succeed, in which case user won't see the error message.EthAccountVerificationDecorator(ak, bankKeeper, evmKeeper)
will verify, that the sender balance is greater than the total transaction cost. The account will be set to store if it doesn't exist, i.e cannot be found on store. This AnteHandler decorator will fail if:any of the msgs is not a MsgEthereumTx
from address is empty
account balance is lower than the transaction cost
EthNonceVerificationDecorator(ak)
validates that the transaction nonces are valid and equivalent to the sender account’s current nonce.EthGasConsumeDecorator(evmKeeper)
validates that the Ethereum tx message has enough to cover intrinsic gas (during CheckTx only) and that the sender has enough balance to pay for the gas cost. Intrinsic gas for a transaction is the amount of gas that the transaction uses before the transaction is executed. The gas is a constant value plus any cost incurred by additional bytes of data supplied with the transaction. This AnteHandler decorator will fail if:the transaction contains more than one message
the message is not a MsgEthereumTx
sender account cannot be found
transaction's gas limit is lower than the intrinsic gas
user doesn't have enough balance to deduct the transaction fees (gas_limit * gas_price)
transaction or block gas meter runs out of gas
CanTransferDecorator(evmKeeper, feeMarketKeeper)
creates an EVM from the message and calls the BlockContext CanTransfer function to see if the address can execute the transaction.EthIncrementSenderSequenceDecorator(ak)
handles incrementing the sequence of the signer (i.e sender). If the transaction is a contract creation, the nonce will be incremented during the transaction execution and not within this AnteHandler decorator.
The options authante.NewMempoolFeeDecorator()
, authante.NewTxTimeoutHeightDecorator()
and authante.NewValidateMemoDecorator(ak)
are the same as for a Cosmos Tx
. See Cosmos docs for more on the anteHandler
.
EVM module
After authentication through the antehandler
, each sdk.Msg
(in this case MsgEthereumTx
) in the Tx
is delivered to the Msg Handler in the x/evm
module and runs through the following the steps:
Convert
Msg
to an ethereumTx
typeApply
Tx
withEVMConfig
and attempt to perform a state transition, that will only be persisted (committed) to the underlying KVStore if the transaction does not fail:Confirm that
EVMConfig
is createdCreate the ethereum signer using chain config value from
EVMConfig
Set the ethereum transaction hash to the (impermanent) transient store so that it's also available on the StateDB functions
Generate a new EVM instance
Confirm that EVM params for contract creation (
EnableCreate
) and contract execution (EnableCall
) are enabledApply message. If
To
address isnil
, create new contract using code as deployment code. Else call contract at given address with the given input as parametersCalculate gas used by the evm operation
If
Tx
applied successfullyExecute EVM
Tx
postprocessing hooks. If hooks return error, revert the wholeTx
Refund gas according to Ethereum gas accounting rules
Update block bloom filter value using the logs generated from the tx
Emit SDK events for the transaction fields and tx logs
Transactions
This section defines the sdk.Msg
concrete types that result in the state transitions defined on the previous section.
MsgEthereumTx
MsgEthereumTx
An EVM state transition can be achieved by using the MsgEthereumTx
. This message encapsulates an Ethereum transaction data (TxData
) as a sdk.Msg
. It contains the necessary transaction data fields. Note, that the MsgEthereumTx
implements both the sdk.Msg
and sdk.Tx
interfaces. Normally, SDK messages only implement the former, while the latter is a group of messages bundled together.
This message field validation is expected to fail if:
From
field is defined and the address is invalidTxData
stateless validation fails
The transaction execution is expected to fail if:
Any of the custom
AnteHandler
Ethereum decorators checks fail:Minimum gas amount requirements for transaction
Tx sender account doesn't exist or hasn't enough balance for fees
Account sequence doesn't match the transaction
Data.AccountNonce
Message signature verification fails
EVM contract creation (i.e
evm.Create
) fails, orevm.Call
fails
Conversion
The MsgEthreumTx
can be converted to the go-ethereum Transaction
and Message
types in order to create and call evm contracts.
Signing
In order for the signature verification to be valid, the TxData
must contain the v | r | s
values from the Signer
. Sign calculates a secp256k1 ECDSA signature and signs the transaction. It takes a keyring signer and the chainID to sign an Ethereum transaction according to EIP155 standard. This method mutates the transaction as it populates the V, R, S fields of the Transaction's Signature. The function will fail if the sender address is not defined for the msg or if the sender is not registered on the keyring.
TxData
The MsgEthereumTx
supports the 3 valid Ethereum transaction data types from go-ethereum: LegacyTx
, AccessListTx
and DynamicFeeTx
. These types are defined as protobuf messages and packed into a proto.Any
interface type in the MsgEthereumTx
field.
LegacyTx
: EIP-155 transaction typeDynamicFeeTx
: EIP-1559 transaction type. Enabled by London hard fork blockAccessListTx
: EIP-2930 transaction type. Enabled by Berlin hard fork block
LegacyTx
LegacyTx
The transaction data of regular Ethereum transactions.
This message field validation is expected to fail if:
GasPrice
is invalid (nil
, negative or out of int256 bound)Fee
(gasprice * gaslimit) is invalidAmount
is invalid (negative or out of int256 bound)To
address is invalid (non valid ethereum hex address)
DynamicFeeTx
DynamicFeeTx
The transaction data of EIP-1559 dynamic fee transactions.
This message field validation is expected to fail if:
GasTipCap
is invalid (nil
, negative or overflows int256)GasFeeCap
is invalid (nil
, negative or overflows int256)GasFeeCap
is less thanGasTipCap
Fee
(gas price * gas limit) is invalid (overflows int256)Amount
is invalid (negative or overflows int256)To
address is invalid (non-valid ethereum hex address)ChainID
isnil
AccessListTx
AccessListTx
The transaction data of EIP-2930 access list transactions.
This message field validation is expected to fail if:
GasPrice
is invalid (nil
, negative or overflows int256)Fee
(gas price * gas limit) is invalid (overflows int256)Amount
is invalid (negative or overflows int256)To
address is invalid (non-valid ethereum hex address)ChainID
isnil
ABCI
The Application Blockchain Interface (ABCI) allows the application to interact with the Tendermint Consensus engine. The application maintains several ABCI connections with Tendermint. The most relevant for the x/evm
is the Consensus connection at Commit. This connection is responsible for block execution and calls the functions InitChain
(containing InitGenesis
), BeginBlock
, DeliverTx
, EndBlock
, Commit
. InitChain
is only called the first time a new blockchain is started and DeliverTx
is called for each transaction in the block.
InitGenesis
InitGenesis
initializes the EVM module genesis state by setting the GenesisState
fields to the store. In particular, it sets the parameters and genesis accounts (state and code).
ExportGenesis
The ExportGenesis
ABCI function exports the genesis state of the EVM module. In particular, it retrieves all the accounts with their bytecode, balance and storage, the transaction logs, and the EVM parameters and chain configuration.
BeginBlock
The EVM module BeginBlock
logic is executed prior to handling the state transitions from the transactions. The main objective of this function is to:
Set the context for the current block so that the block header, store, gas meter, etc. are available to the
Keeper
once one of theStateDB
functions are called during EVM state transitions.Set the EIP155
ChainID
number (obtained from the full chain-id), in case it hasn't been set before duringInitChain
EndBlock
The EVM module EndBlock
logic occurs after executing all the state transitions from the transactions. The main objective of this function is to:
Emit Block bloom events
This is due for web3 compatibility as the Ethereum headers contain this type as a field. The JSON-RPC service uses this event query to construct an Ethereum header from a Tendermint header.
The block bloom filter value is obtained from the transient store and then emitted
Hooks
The x/evm
module implements an EvmHooks
interface that extend and customize the Tx
processing logic externally.
This supports EVM contracts to call native cosmos modules by
defining a log signature and emitting the specific log from the smart contract,
recognizing those logs in the native tx processing code, and
converting them to native module calls.
To do this, the interface includes a PostTxProcessing
hook that registers custom Tx
hooks in the EvmKeeper
. These Tx
hooks are processed after the EVM state transition is finalized and doesn't fail. Note that there are no default hooks implemented in the EVM module.
PostTxProcessing
PostTxProcessing
PostTxProcessing
is only called after an EVM transaction finished successfully and delegates the call to underlying hooks. If no hook has been registered, this function returns with a nil
error.
It's executed in the same cache context as the EVM transaction, if it returns an error, the whole EVM transaction is reverted, if the hook implementor doesn't want to revert the tx, they can always return nil
instead.
The error returned by the hooks is translated to a VM error failed to process native logs
, the detailed error message is stored in the return value. The message is sent to native modules asynchronously, there's no way for the caller to catch and recover the error.
Use Case: Call Native ERC20 Module on Neura
Here is an example taken from the Neura erc20 module that shows how the EVMHooks
supports a contract calling a native module to convert ERC-20 Tokens into Cosmos native Coins. Following the steps from above.
You can define and emit a Transfer
log signature in the smart contract like this:
The application will register a BankSendHook
to the EvmKeeper
. It recognizes the ethereum tx Log
and converts it to a call to the bank module's SendCoinsFromAccountToAccount
method:
Lastly, register the hook in app.go
:
Events
The x/evm
module emits the Cosmos SDK events after a state execution. The EVM module emits events of the relevant transaction fields, as well as the transaction logs (ethereum events).
MsgEthereumTx
Type | Attribute Key | Attribute Value |
---|---|---|
ethereum_tx |
|
|
ethereum_tx |
|
|
ethereum_tx |
|
|
ethereum_tx |
|
|
ethereum_tx |
|
|
ethereum_tx |
|
|
ethereum_tx |
|
|
tx_log |
|
|
message |
|
|
message |
|
|
message |
|
|
Additionally, the EVM module emits an event during EndBlock
for the filter query block bloom.
ABCI
Type | Attribute Key | Attribute Value |
---|---|---|
block_bloom |
|
|
Parameters
The evm module contains the following parameters:
Params
Key | Type | Default Value |
---|---|---|
| string |
|
| bool |
|
| bool |
|
| []int | TBD |
| ChainConfig | See ChainConfig |
EVM denom
The evm denomination parameter defines the token denomination used on the EVM state transitions and gas consumption for EVM messages.
For example, on Ethereum, the evm_denom
would be ETH
. In the case of Neura, the default denomination is the atto ankr. In terms of precision, ANKR
and ETH
share the same value, i.e. 1 ANKR = 10^18 atto ankr
and 1 ETH = 10^18 wei
.
NOTE: SDK applications that want to import the EVM module as a dependency will need to set their own
evm_denom
(i.e not"atankr"
).
Enable Create
The enable create parameter toggles state transitions that use the vm.Create
function. When the parameter is disabled, it will prevent all contract creation functionality.
Enable Transfer
The enable transfer toggles state transitions that use the vm.Call
function. When the parameter is disabled, it will prevent transfers between accounts and executing a smart contract call.
Extra EIPs
The extra EIPs parameter defines the set of Ethereum Improvement Proposals (EIPs) that can be activated on the Ethereum VM Config
that apply custom jump tables.
NOTE: some of these EIPs are already enabled by the chain configuration, depending on the hard fork number.
The supported EIPS to activate:
Chain Config
The ChainConfig
is a protobuf wrapper type that contains the same fields as the go-ethereum ChainConfig
parameters, but using *sdk.Int
types instead of *big.Int
.
By default, all block configuration fields but ConstantinopleBlock
, are enabled at genesis (height 0).
ChainConfig Defaults
Name | Default Value |
---|---|
HomesteadBlock | 0 |
DAOForkBlock | 0 |
DAOForkSupport |
|
EIP150Block | 0 |
EIP150Hash |
|
EIP155Block | 0 |
EIP158Block | 0 |
ByzantiumBlock | 0 |
ConstantinopleBlock | 0 |
PetersburgBlock | 0 |
IstanbulBlock | 0 |
MuirGlacierBlock | 0 |
BerlinBlock | 0 |
LondonBlock | 0 |
ArrowGlacierBlock | 0 |
GrayGlacierBlock | 0 |
MergeNetsplitBlock | 0 |
ShanghaiBlock | 0 |
CancunBlock. | 0 |
Client
A user can query and interact with the evm
module using the CLI, JSON-RPC, gRPC, or REST.
CLI
Find below a list of neurad
commands added with the x/evm
module. You can obtain the full list by using the neurad -h
command.
Queries
The query
commands allow users to query evm
state.
code
Allows users to query the smart contract code at a given address.
storage
Allows users to query storage for an account with a given key and height.
Transactions
The tx
commands allow users to interact with the evm
module.
raw
Allows users to build cosmos transactions from raw ethereum transaction.
gRPC
Queries
Verb | Method | Description |
---|---|---|
|
| Get an Ethereum account |
|
| Get an Ethereum account's Cosmos Address |
|
| Get an Ethereum account's from a validator consensus Address |
|
| Get the balance of a the EVM denomination for a single EthAccount. |
|
| Get the balance of all coins for a single account |
|
| Get the balance of all coins for a single account |
|
| Get the parameters of x/evm module |
|
| Implements the eth_call rpc api |
|
| Implements the eth_estimateGas rpc api |
|
| Implements the debug_traceTransaction rpc api |
|
| Implements the debug_traceBlockByNumber and debug_traceBlockByHash rpc api |
|
| Get an Ethereum account |
|
| Get an Ethereum account's Cosmos Address |
|
| Get an Ethereum account's from a validator consensus Address |
|
| Get the balance of a the EVM denomination for a single EthAccount. |
|
| Get the balance of all coins for a single account |
|
| Get the balance of all coins for a single account |
|
| Get the parameters of x/evm module |
|
| Implements the eth_call rpc api |
|
| Implements the eth_estimateGas rpc api |
|
| Implements the debug_traceTransaction rpc api |
|
| Implements the debug_traceBlockByNumber and debug_traceBlockByHash rpc api |
Transactions
Verb | Method | Description |
---|---|---|
|
| Submit an Ethereum transactions |
|
| Submit an Ethereum transactions |
Last updated