Documentation
¶
Overview ¶
Package "evm/evmstate" implements a go-ethereum vm.StateDB for Nibiru's Multi VM stack, implemented as SDB. The SDB manages EVM *and* non-EVM state reachable via the sdk.Context by branching the world state with "CacheMultiStore" snapshots. There are no journal entries.
### Model:
- Each SDB represents one Ethereum transaction's execution scope.
- Snapshot() creates a new world-state branch (cached multistore) and a fresh LocalState layer for EVM-specific metadata (logs, refunds, access list, transient storage).
- RevertToSnapshot(n) restores the exact prior world state by jumping to snapshot n.
- Commit() writes cached branches back toward the root Context; BaseApp later commits the root.
### Notes:
- Nibiru uses IAVL-backed KV stores, not MPT/Verkle; we don't compute Ethereum storage roots.
- Read paths (balances/accounts) consult the active branched Context; no journals are needed.
- This design mirrors database snapshotting: revert == restore snapshot, not "undo logs".
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Copyright (c) 2023-2024 Nibi, Inc.
Index ¶
- Constants
- func IsDeliverTx(ctx sdk.Context) bool
- func IsReCheckTxOnly(ctx sdk.Context) bool
- func IsSimulation(ctx sdk.Context) bool
- func MaybeTruncateEventsForFailedEvmTx(ctx sdk.Context, evmResp *evm.MsgEthereumTxResponse)
- func ParseProposerAddr(ctx sdk.Context, proposerAddress sdk.ConsAddress) sdk.ConsAddress
- func Rules(ctx sdk.Context) gethparams.Rules
- func VerifyFee(txData evm.TxData, baseFeeMicronibi *big.Int, ctx sdk.Context) (effFeeWei *uint256.Int, err error)
- type Account
- type CodeHash
- type ERC20BigInt
- type ERC20Bool
- type ERC20Bytes32
- type ERC20String
- type ERC20Uint8
- type EVMConfig
- type EvmState
- func (state EvmState) CalcBloomFromLogs(ctx sdk.Context, newLogs []*gethcore.Log) (bloom gethcore.Bloom)
- func (state EvmState) GetBlockBloomTransient(ctx sdk.Context) *big.Int
- func (state EvmState) GetContractBytecode(ctx sdk.Context, codeHash []byte) (code []byte)
- func (state EvmState) SetAccCode(ctx sdk.Context, codeHash, code []byte)
- func (state EvmState) SetAccState(ctx sdk.Context, addr gethcommon.Address, stateKey gethcommon.Hash, ...)
- type FunTokenState
- type IKeeper
- type IndexesFunToken
- type Keeper
- func (k *Keeper) ApplyEvmMsg(msg core.Message, evmObj *vm.EVM, commit bool) (evmResp *evm.MsgEthereumTxResponse, err error)
- func (k *Keeper) BK() bankkeeper.Keeper
- func (k Keeper) Balance(goCtx context.Context, req *evm.QueryBalanceRequest) (*evm.QueryBalanceResponse, error)
- func (k Keeper) BaseFee(goCtx context.Context, _ *evm.QueryBaseFeeRequest) (*evm.QueryBaseFeeResponse, error)
- func (k Keeper) BaseFeeMicronibiPerGas(_ sdk.Context) *big.Int
- func (k Keeper) BaseFeeWeiPerGas(_ sdk.Context) *big.Int
- func (k *Keeper) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock)
- func (k Keeper) CallContract(evmObj *vm.EVM, fromAcc gethcommon.Address, contract *gethcommon.Address, ...) (evmResp *evm.MsgEthereumTxResponse, err error)
- func (k Keeper) Code(goCtx context.Context, req *evm.QueryCodeRequest) (*evm.QueryCodeResponse, error)
- func (k *Keeper) ConvertCoinToEvm(goCtx context.Context, msg *evm.MsgConvertCoinToEvm) (resp *evm.MsgConvertCoinToEvmResponse, err error)
- func (k *Keeper) ConvertEvmToCoin(goCtx context.Context, msg *evm.MsgConvertEvmToCoin) (resp *evm.MsgConvertEvmToCoinResponse, err error)
- func (k *Keeper) CreateFunToken(goCtx context.Context, msg *evm.MsgCreateFunToken) (resp *evm.MsgCreateFunTokenResponse, err error)
- func (k *Keeper) DeleteAccount(ctx sdk.Context, addr gethcommon.Address) error
- func (k Keeper) ERC20() erc20Calls
- func (k *Keeper) EVMState() EvmState
- func (k *Keeper) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate
- func (k Keeper) EstimateGas(goCtx context.Context, req *evm.EthCallRequest) (*evm.EstimateGasResponse, error)
- func (k Keeper) EthAccount(goCtx context.Context, req *evm.QueryEthAccountRequest) (*evm.QueryEthAccountResponse, error)
- func (k *Keeper) EthCall(goCtx context.Context, req *evm.EthCallRequest) (*evm.MsgEthereumTxResponse, error)
- func (k Keeper) EthChainID(ctx sdk.Context) *big.Int
- func (k *Keeper) EthereumTx(goCtx context.Context, txMsg *evm.MsgEthereumTx) (evmResp *evm.MsgEthereumTxResponse, err error)
- func (k *Keeper) ExportGenesis(ctx sdk.Context) *evm.GenesisState
- func (k *Keeper) ExportGenesisContractAccount(ctx sdk.Context, contract auth.AccountI) (genAcc evm.GenesisAccount, isOk bool)
- func (k Keeper) FeeForCreateFunToken(ctx sdk.Context) sdk.Coins
- func (k Keeper) FindERC20Metadata(ctx sdk.Context, evmObj *vm.EVM, contract gethcommon.Address, abi *gethabi.ABI) (info *evm.ERC20Metadata, err error)
- func (k *Keeper) ForEachStorage(ctx sdk.Context, addr gethcommon.Address, ...)
- func (k Keeper) FunTokenMapping(goCtx context.Context, req *evm.QueryFunTokenMappingRequest) (*evm.QueryFunTokenMappingResponse, error)
- func (k Keeper) GetAccNonce(ctx sdk.Context, addr gethcommon.Address) uint64
- func (k *Keeper) GetAccount(ctx sdk.Context, addr gethcommon.Address) *Account
- func (k *Keeper) GetCode(ctx sdk.Context, codeHash gethcommon.Hash) []byte
- func (k Keeper) GetCoinbaseAddress(ctx sdk.Context) common.Address
- func (k *Keeper) GetEVMConfig(ctx sdk.Context) EVMConfig
- func (k *Keeper) GetEvmTxEvents(ctx sdk.Context, recipient *gethcommon.Address, txType uint8, msg core.Message, ...) (events TxEvents)
- func (k Keeper) GetHashFn(ctx sdk.Context) vm.GetHashFunc
- func (k Keeper) GetParams(ctx sdk.Context) (params evm.Params)
- func (k *Keeper) GetState(ctx sdk.Context, addr gethcommon.Address, stateKey gethcommon.Hash) gethcommon.Hash
- func (k *Keeper) GetWeiBalance(ctx sdk.Context, addr gethcommon.Address) (balance *uint256.Int)
- func (k *Keeper) ImportGenesisAccount(ctx sdk.Context, account evm.GenesisAccount) (err error)
- func (k *Keeper) InitGenesis(ctx sdk.Context, genState evm.GenesisState) []abci.ValidatorUpdate
- func (k Keeper) Logger(ctx sdk.Context) log.Logger
- func (k *Keeper) NewEVM(ctx sdk.Context, msg core.Message, evmCfg EVMConfig, tracer *tracing.Hooks, ...) (evmObj *vm.EVM)
- func (k *Keeper) NewSDB(ctx sdk.Context, txConfig TxConfig) *SDB
- func (k Keeper) Params(goCtx context.Context, _ *evm.QueryParamsRequest) (*evm.QueryParamsResponse, error)
- func (k *Keeper) RefundGas(sdb *SDB, msgFrom gethcommon.Address, leftoverGas uint64, weiPerGas *big.Int) error
- func (k *Keeper) SendWei(ctx sdk.Context, from gethcommon.Address, to gethcommon.Address, ...) error
- func (k *Keeper) SetAccount(ctx sdk.Context, addr gethcommon.Address, account Account) error
- func (k *Keeper) SetCode(ctx sdk.Context, codeHash, code []byte)
- func (k Keeper) SetParams(ctx sdk.Context, params evm.Params) (err error)
- func (k *Keeper) SetState(ctx sdk.Context, addr gethcommon.Address, stateKey gethcommon.Hash, ...)
- func (k Keeper) Storage(goCtx context.Context, req *evm.QueryStorageRequest) (*evm.QueryStorageResponse, error)
- func (k Keeper) TraceBlock(goCtx context.Context, req *evm.QueryTraceBlockRequest) (*evm.QueryTraceBlockResponse, error)
- func (k Keeper) TraceCall(goCtx context.Context, req *evm.QueryTraceTxRequest) (*evm.QueryTraceTxResponse, error)
- func (k *Keeper) TraceEthTxMsg(ctx sdk.Context, evmCfg EVMConfig, txConfig TxConfig, msg core.Message, ...) (traceResult *json.RawMessage, nextLogIndex uint, err error)
- func (k Keeper) TraceTx(goCtx context.Context, req *evm.QueryTraceTxRequest) (*evm.QueryTraceTxResponse, error)
- func (k *Keeper) TxConfig(ctx sdk.Context, txHash common.Hash) TxConfig
- func (k *Keeper) UpdateParams(goCtx context.Context, req *evm.MsgUpdateParams) (resp *evm.MsgUpdateParamsResponse, err error)
- func (k Keeper) VMConfig(ctx sdk.Context, cfg *EVMConfig, tracer *tracing.Hooks) vm.Config
- func (k Keeper) ValidatorAccount(goCtx context.Context, req *evm.QueryValidatorAccountRequest) (*evm.QueryValidatorAccountResponse, error)
- type LocalState
- type NibiruBankKeeper
- type SDB
- func (s *SDB) AddAddressToAccessList(addr gethcommon.Address)
- func (s *SDB) AddBalance(addr gethcommon.Address, wei *uint256.Int, reason tracing.BalanceChangeReason) (prevWei uint256.Int)
- func (s *SDB) AddLog(ethLog *gethcore.Log)
- func (s *SDB) AddPreimage(_ gethcommon.Hash, _ []byte)
- func (s *SDB) AddRefund(gas uint64)
- func (s *SDB) AddSlotToAccessList(addr gethcommon.Address, slot gethcommon.Hash)
- func (s *SDB) AddressInAccessList(addr gethcommon.Address) bool
- func (s *SDB) Commit()
- func (s *SDB) CreateAccount(addr gethcommon.Address)
- func (s *SDB) CreateContract(addr gethcommon.Address)
- func (s *SDB) Ctx() sdk.Context
- func (s *SDB) Empty(addr gethcommon.Address) bool
- func (s *SDB) Exist(addr gethcommon.Address) bool
- func (s *SDB) Finalise(deleteEmptyObjects bool)
- func (s *SDB) GetBalance(addr gethcommon.Address) *uint256.Int
- func (s *SDB) GetCode(addr gethcommon.Address) []byte
- func (s *SDB) GetCodeHash(addr gethcommon.Address) (codeHash gethcommon.Hash)
- func (s *SDB) GetCodeSize(addr gethcommon.Address) int
- func (s *SDB) GetCommittedState(addr gethcommon.Address, hash gethcommon.Hash) gethcommon.Hash
- func (s *SDB) GetNonce(addr gethcommon.Address) uint64
- func (s *SDB) GetRefund() uint64
- func (s *SDB) GetState(addr gethcommon.Address, slotKey gethcommon.Hash) (stateValue gethcommon.Hash)
- func (s *SDB) GetStorageForOneContract(addr gethcommon.Address) StorageForOneContract
- func (s *SDB) GetStorageRoot(addr gethcommon.Address) (root gethcommon.Hash)
- func (s *SDB) GetTransientState(addr gethcommon.Address, key gethcommon.Hash) (stateVal gethcommon.Hash)
- func (s *SDB) GetTransientStorageForOneContract(addr gethcommon.Address) StorageForOneContract
- func (s *SDB) HasSelfDestructed(addr gethcommon.Address) bool
- func (s *SDB) HasSuicided(addr gethcommon.Address) bool
- func (s *SDB) IsCreatedThisTx(addr gethcommon.Address) bool
- func (sdb SDB) IsDeliverTx() bool
- func (sdb SDB) IsReCheckTxOnly() bool
- func (s *SDB) Keeper() *Keeper
- func (s *SDB) Logs() (allLogs []*gethcore.Log)
- func (s *SDB) LogsJson() (jsonBz []byte)
- func (s *SDB) PointCache() *utils.PointCache
- func (s *SDB) Prepare(_ gethparams.Rules, sender, coinbase gethcommon.Address, ...)
- func (s *SDB) RevertToSnapshot(revid int)
- func (s *SDB) RootCtx() sdk.Context
- func (s *SDB) SelfDestruct(addr gethcommon.Address) (prevWei uint256.Int)
- func (s *SDB) SelfDestruct6780(addr gethcommon.Address) (prevWei uint256.Int, isSelfDestructed bool)
- func (s *SDB) SetCode(addr gethcommon.Address, code []byte)
- func (s *SDB) SetCtx(ctx sdk.Context)
- func (s *SDB) SetNonce(addr gethcommon.Address, nonce uint64)
- func (s *SDB) SetState(addr gethcommon.Address, key, value gethcommon.Hash) (prevValue gethcommon.Hash)
- func (s *SDB) SetTransientState(addr gethcommon.Address, key, value gethcommon.Hash)
- func (s *SDB) SlotInAccessList(addr gethcommon.Address, slot gethcommon.Hash) (addrPresent bool, slotPresent bool)
- func (s *SDB) Snapshot() int
- func (s *SDB) SnapshotRevertIdx() int
- func (s *SDB) SubBalance(addr gethcommon.Address, wei *uint256.Int, reason tracing.BalanceChangeReason) (prevWei uint256.Int)
- func (s *SDB) SubRefund(gas uint64)
- func (s SDB) TxCfg() TxConfig
- func (s *SDB) Witness() *stateless.Witness
- type SnapshotAccChange
- type StorageForOneContract
- type TxConfig
- type TxEvents
Constants ¶
const DefaultGethTraceTimeout = 5 * time.Second
Re-export of the default tracer timeout from go-ethereum. See "geth/eth/tracers/api.go".
const ( // Erc20GasLimitDeploy only used internally when deploying ERC20Minter. Erc20GasLimitDeploy uint64 = 2_500_000 )
Variables ¶
This section is empty.
Functions ¶
func IsDeliverTx ¶
IsDeliverTx checks if we're in DeliverTx, NOT in CheckTx, ReCheckTx, or simulation
func IsReCheckTxOnly ¶
IsReCheckTxOnly is true only in ABCI Recheck (sdk.Context.IsReCheckTx). New CheckTx has sdk.Context.IsCheckTx && !sdk.Context.IsReCheckTx; Recheck has both flags set because the SDK sets checkTx=true whenever recheckTx=true.
func IsSimulation ¶
IsSimulation checks if the context is a simulation context.
func MaybeTruncateEventsForFailedEvmTx ¶
func MaybeTruncateEventsForFailedEvmTx( ctx sdk.Context, evmResp *evm.MsgEthereumTxResponse, )
MaybeTruncateEventsForFailedEvmTx truncates the current tx event stream to an ante-computed mark when the EVM response indicates VM-level failure.
This is part of the mitigation for leaked non-EVM module/precompile events on failed EVM transactions: https://github.com/NibiruChain/nibiru/issues/2542
func ParseProposerAddr ¶
func ParseProposerAddr( ctx sdk.Context, proposerAddress sdk.ConsAddress, ) sdk.ConsAddress
ParseProposerAddr returns current block proposer's address when provided proposer address is empty.
func VerifyFee ¶
func VerifyFee( txData evm.TxData, baseFeeMicronibi *big.Int, ctx sdk.Context, ) (effFeeWei *uint256.Int, err error)
VerifyFee is used to return the fee, or token payment, for the given transaction data in [sdk.Coin]s. It checks that the gas limit and uses the "effective fee" from the evm.TxData.
- For evm.DynamicFeeTx, the effective gas price is the minimum of (baseFee + tipCap) and the gas fee cap (feeCap).
- For evm.LegacyTx and evm.AccessListTx, the effective gas price is the max of the gas price and baseFee.
Transactions where the baseFee exceeds the feeCap are priced out under EIP-1559 and will not pass validation.
Args:
- txData: Tx data related to gas, effectie gas, nonce, and chain ID implemented by every Ethereum tx type.
- baseFeeMicronibi:EIP1559 base fee in units of micronibi ("unibi").
- isCheckTx: Comes from `[sdk.Context].isCheckTx()`
Types ¶
type Account ¶
type Account struct {
// BalanceNwei is "NIBI wei", or attoNIBI, balance from the x/bank module
// state. It has the same relationship with NIBI
// that wei has with ETH on Ethereum.
// Therefore, 10^{18} nwei := 1 NIBI. Equivalently, one micronibi (unibi) is
// 10^{12} nwei.
BalanceNwei *uint256.Int
// Nonce is the number of transactions sent from this account or, for contract accounts, the number of contract-creations made by this account
Nonce uint64
// CodeHash is the hash of the contract code for this account, or nil if it's not a contract account
CodeHash []byte
}
Account represents an Ethereum account according to the Auth and Bank module state.
func (*Account) IsContract ¶
IsContract returns if the account contains contract code.
type ERC20BigInt ¶
ERC20BigInt: Unpacking type for "uint256" from Solidity.
type ERC20Bytes32 ¶
type ERC20Bytes32 struct{ Value [32]byte }
type ERC20String ¶
type ERC20String struct{ Value string }
type ERC20Uint8 ¶
type ERC20Uint8 struct{ Value uint8 }
ERC20Uint8: Unpacking type for "uint8" from Solidity. This is only used in the "ERC20.decimals" function.
type EVMConfig ¶
type EVMConfig struct {
Params evm.Params
ChainConfig *gethparams.ChainConfig
// BlockCoinbase: In Ethereum, the coinbase (or "benficiary") is the address that
// proposed the current block. It corresponds to the [COINBASE op code]
// (the "block.coinbase" stack output).
//
// [COINBASE op code]: https://ethereum.org/en/developers/docs/evm/opcodes/
BlockCoinbase gethcommon.Address
// BaseFeeWei is the EVM base fee in units of wei per gas. The term "base
// fee" comes from EIP-1559.
BaseFeeWei *big.Int
}
EVMConfig encapsulates parameters needed to create an instance of the EVM ("go-ethereum/core/vm.EVM").
type EvmState ¶
type EvmState struct {
ModuleParams collections.Item[evm.Params]
// ContractBytecode: Map from (byte)code hash -> contract bytecode
ContractBytecode collections.Map[CodeHash, []byte]
// AccState: Map from eth address (account) and hash of a state key -> smart
// contract state. Each contract essentially has its own key-value store.
//
// - primary key (PK): (EthAddr+EthHash). The contract address and hash for
// a piece of state in that contract forms the primary key.
// - value (V): State value bytes.
AccState collections.Map[
collections.Pair[gethcommon.Address, gethcommon.Hash],
[]byte,
]
// BlockLogSize: EVM tx log size for the block (transient).
BlockLogSize collections.ItemTransient[uint64]
// BlockTxIndex: EVM tx index for the block (transient).
BlockTxIndex collections.ItemTransient[uint64]
// BlockBloom: Bloom filters.
BlockBloom collections.ItemTransient[[]byte]
NetWeiBlockDelta collections.Item[sdkmath.Int]
// WasmPlugins is a derived index from evm.Params.WasmPlugins for fast lookup
// by EVM execution paths. Mutate it only via SetParams.
WasmPlugins collections.Map[string, sdk.AccAddress]
}
EvmState isolates the key-value stores (collections) for the x/evm module.
func NewEvmState ¶
func (EvmState) CalcBloomFromLogs ¶
func (EvmState) GetBlockBloomTransient ¶
GetBlockBloomTransient returns bloom bytes for the current block height
func (EvmState) GetContractBytecode ¶
func (EvmState) SetAccCode ¶
func (EvmState) SetAccState ¶
func (state EvmState) SetAccState( ctx sdk.Context, addr gethcommon.Address, stateKey gethcommon.Hash, stateValue []byte, )
SetState updates contract storage and deletes if the value is empty.
type FunTokenState ¶
type FunTokenState struct {
collections.IndexedMap[[]byte, evm.FunToken, IndexesFunToken]
}
FunTokenState isolates the key-value stores (collections) for fungible token mappings. This struct is written as an extension of the default indexed map to add utility functions.
func NewFunTokenState ¶
func NewFunTokenState( cdc sdkcodec.BinaryCodec, storeKey storetypes.StoreKey, ) FunTokenState
func (FunTokenState) SafeInsert ¶
func (fun FunTokenState) SafeInsert( ctx sdk.Context, erc20 gethcommon.Address, bankDenom string, isMadeFromCoin bool, ) error
Insert adds an evm.FunToken to state with defensive validation. Errors if the given inputs would result in a corrupted evm.FunToken.
type IKeeper ¶
type IKeeper interface {
// GetAccount: Ethereum account getter for a [statedb.Account].
GetAccount(ctx sdk.Context, addr gethcommon.Address) *Account
GetState(ctx sdk.Context, addr gethcommon.Address, key gethcommon.Hash) gethcommon.Hash
GetCode(ctx sdk.Context, codeHash gethcommon.Hash) []byte
// GetAccNonce returns the sequence number of an account, returns 0 if the
// account does not exist.
GetAccNonce(ctx sdk.Context, addr gethcommon.Address) uint64
BK() bankkeeper.Keeper
// ForEachStorage: Iterator over contract storage.
ForEachStorage(
ctx sdk.Context, addr gethcommon.Address,
stopIter func(key, value gethcommon.Hash) bool,
)
SetAccount(ctx sdk.Context, addr gethcommon.Address, account Account) error
SetState(ctx sdk.Context, addr gethcommon.Address, key gethcommon.Hash, value []byte)
// SetCode: Setter for smart contract bytecode. Delete if code is empty.
SetCode(ctx sdk.Context, codeHash []byte, code []byte)
// DeleteAccount handles contract's suicide call, clearing the balance,
// contract bytecode, contract state, and its native account.
DeleteAccount(ctx sdk.Context, addr gethcommon.Address) error
}
Keeper provide underlying storage of StateDB
type IndexesFunToken ¶
type IndexesFunToken struct {
// ERC20Addr (MultiIndex): Index FunToken by ERC-20 contract address.
// - indexing key (IK): ERC-20 addr
// - primary key (PK): FunToken ID
// - value (V): FunToken value
ERC20Addr collections.MultiIndex[gethcommon.Address, []byte, evm.FunToken]
// BankDenom (MultiIndex): Index FunToken by coin denomination
// - indexing key (IK): Coin denom
// - primary key (PK): FunToken ID
// - value (V): FunToken value
BankDenom collections.MultiIndex[string, []byte, evm.FunToken]
}
IndexesFunToken: Abstraction for indexing over the FunToken store.
func (IndexesFunToken) IndexerList ¶
func (idxs IndexesFunToken) IndexerList() []collections.Indexer[[]byte, evm.FunToken]
type Keeper ¶
type Keeper struct {
// EvmState isolates the key-value stores (collections) for the x/evm module.
EvmState EvmState
// FunTokens isolates the key-value stores (collections) for fungible token
// mappings.
FunTokens FunTokenState
Bank *NibiruBankKeeper
SudoKeeper evm.SudoKeeper
// contains filtered or unexported fields
}
func NewKeeper ¶
func NewKeeper( cdc codec.BinaryCodec, storeKey, transientKey storetypes.StoreKey, authority sdk.AccAddress, accKeeper evm.AccountKeeper, bankKeeper *NibiruBankKeeper, stakingKeeper evm.StakingKeeper, sudoKeeper evm.SudoKeeper, tracer string, ) Keeper
NewKeeper is a constructor for an x/evm Keeper. This function is necessary because the Keeper struct has private fields.
func (*Keeper) ApplyEvmMsg ¶
func (k *Keeper) ApplyEvmMsg( msg core.Message, evmObj *vm.EVM, commit bool, ) (evmResp *evm.MsgEthereumTxResponse, err error)
ApplyEvmMsg computes the new state by applying the given message against the existing state. If the message fails, the VM execution error with the reason will be returned to the client and the transaction won't be committed to the store.
## Reverted state
The snapshot and rollback are supported by the `statedb.StateDB`.
## Different Callers
It's called in three scenarios: 1. `ApplyTransaction`, in the transaction processing flow. 2. `EthCall/EthEstimateGas` grpc query handler. 3. Called by other native modules directly.
## Prechecks and Preprocessing
All relevant state transition prechecks for the MsgEthereumTx are performed on the AnteHandler, prior to running the transaction against the state. The prechecks run are the following:
1. the nonce of the message caller is correct 2. caller has enough balance to cover transaction fee(gaslimit * gasprice) 3. the amount of gas required is available in the block 4. the purchased gas is enough to cover intrinsic usage 5. there is no overflow when calculating intrinsic gas 6. caller has enough balance to cover asset transfer for **topmost** call
The preprocessing steps performed by the AnteHandler are:
1. set up the initial access list
## Tracer parameter
It should be a `vm.Tracer` object or nil, if pass `nil`, it'll create a default one based on keeper options.
## Commit parameter
If commit is true, the `StateDB` will be committed, otherwise discarded.
## fullRefundLeftoverGas parameter
For internal calls like funtokens, user does not specify gas limit explicitly. In this case we don't apply any caps for refund and refund 100%
func (*Keeper) BK ¶
func (k *Keeper) BK() bankkeeper.Keeper
func (Keeper) Balance ¶
func (k Keeper) Balance( goCtx context.Context, req *evm.QueryBalanceRequest, ) (*evm.QueryBalanceResponse, error)
Balance implements the gRPC query "/eth.evm.v1.Query/Balance".
The response field "balance_wei" preserves the legacy behavior: it always reports the native EVM NIBI balance in wei. When request field "token" is non-empty, Balance also populates the nullable Bank and ERC20 token balance sections when those representations exist.
Parameters:
- goCtx: The context.Context object representing the request context.
- req: The QueryBalanceRequest object containing the Ethereum hex address or nibi-prefixed Bech32 address.
Returns:
- A pointer to the QueryBalanceResponse object containing the balance.
- An error if the balance retrieval process encounters any issues.
func (Keeper) BaseFee ¶
func (k Keeper) BaseFee( goCtx context.Context, _ *evm.QueryBaseFeeRequest, ) (*evm.QueryBaseFeeResponse, error)
BaseFee implements the Query/BaseFee gRPC method
func (Keeper) BaseFeeMicronibiPerGas ¶
BaseFeeMicronibiPerGas returns the gas base fee in units of the EVM denom. Note that this function is currently constant/stateless.
func (Keeper) BaseFeeWeiPerGas ¶
BaseFeeWeiPerGas is the same as BaseFeeMicronibiPerGas, except its in units of wei per gas.
func (*Keeper) BeginBlock ¶
func (k *Keeper) BeginBlock(ctx sdk.Context, _ abci.RequestBeginBlock)
BeginBlock hook for the EVM module.
func (Keeper) CallContract ¶
func (k Keeper) CallContract( evmObj *vm.EVM, fromAcc gethcommon.Address, contract *gethcommon.Address, contractInput []byte, gasLimit uint64, commit bool, weiValue *big.Int, ) (evmResp *evm.MsgEthereumTxResponse, err error)
CallContract invokes a smart contract with the given [contractInput] or deploys a new contract.
Parameters:
- ctx: The SDK context for the transaction.
- evmObj: EVM instance carrying the current StateDB and interpreter.
- fromAcc: The Ethereum address of the account initiating the contract call.
- contract: Pointer to the Ethereum address of the contract. Nil if new contract is deployed.
- contractInput: Hexadecimal-encoded bytes used as input data to the call.
- gasLimit: Maximum gas available for execution.
- commit: Boolean for whether to commit the vm.StateDB. This functions handles both contract method calls and simulations, depending on the `commit` parameter.
- weiValue: wei value to transfer with the call. Giving `nil` means 0.
Returns:
- evmResp: Execution result containing gas usage, return data, logs, and VM Errors.
- err: Error with
func (Keeper) Code ¶
func (k Keeper) Code( goCtx context.Context, req *evm.QueryCodeRequest, ) (*evm.QueryCodeResponse, error)
Code: Implements the gRPC query for "/eth.evm.v1.Query/Code". Code retrieves the smart contract bytecode associated with a given Ethereum address.
Parameters:
- goCtx: The context.Context object representing the request context.
- req: Request with the Ethereum address of the smart contract bytecode.
Returns:
- Response containing the smart contract bytecode.
- An error if the code retrieval process encounters any issues.
func (*Keeper) ConvertCoinToEvm ¶
func (k *Keeper) ConvertCoinToEvm( goCtx context.Context, msg *evm.MsgConvertCoinToEvm, ) (resp *evm.MsgConvertCoinToEvmResponse, err error)
ConvertCoinToEvm Sends a coin with a valid "FunToken" mapping to the given recipient address ("to_eth_addr") in the corresponding ERC20 representation.
In Nibiru v2.7.0, one special case was added to this function to handle wrapped NIBI (WNIBI) conversions. How this works is, if the Bank Coin given is NIBI, then WNIBI is treated as the fungible token mapping for the NIBI tokens. This can only happen if WNIBI contract is well-defined (non-empty bytecode at the contract address).
If WNIBI is not well-defined, this function falls back to using the "FunToken" mapping if one is present. That cannot happen on mainnet (Eth Chain ID 6900), however it can for local networks and testnets, so we mention it here for completeness.
func (*Keeper) ConvertEvmToCoin ¶
func (k *Keeper) ConvertEvmToCoin( goCtx context.Context, msg *evm.MsgConvertEvmToCoin, ) (resp *evm.MsgConvertEvmToCoinResponse, err error)
ConvertEvmToCoin Sends an ERC20 token with a valid "FunToken" mapping to the given recipient address as a bank coin.
func (*Keeper) CreateFunToken ¶
func (k *Keeper) CreateFunToken( goCtx context.Context, msg *evm.MsgCreateFunToken, ) (resp *evm.MsgCreateFunTokenResponse, err error)
CreateFunToken is a gRPC transaction message for creating fungible token ("FunToken") a mapping between a bank coin and ERC20 token.
If the mapping is generated from an ERC20, this tx creates a bank coin to go with it, and if the mapping's generated from a coin, the EVM module deploys an ERC20 contract that for which it will be the owner.
## Mapping an ERC20 Token a Newly Generated Bank Coin
When an ERC20 token is used to create a FunToken mapping and corresponding Bank Coin, it must produce valid "bank.Metadata"
Constraints:
- The first argument of DenomUnits is required and the official base unit onchain, meaning the denom must be equivalent to bank.Metadata.Base.
- Coin `bank.Metadata.Display` must be a denom of one of the `bank.Metadata.DenomUnits`. It is taken by Cosmos-SDK clients like wallets to be "bank.DenomUnit" client takes the exponent from to display wallet balances.
Decimals for an ERC20 are synonymous to "bank.DenomUnit.Exponent" in what they mean for external clients like wallets.
func (*Keeper) DeleteAccount ¶
DeleteAccount handles contract's suicide call, clearing the balance, contract bytecode, contract state, and its native account. Implements the `statedb.Keeper` interface. Only called by `StateDB.Commit()`.
func (Keeper) ERC20 ¶
func (k Keeper) ERC20() erc20Calls
ERC20 returns a mutable reference to the keeper with an ERC20 contract ABI and Go functions corresponding to contract calls in the ERC20 standard like "mint" and "transfer" in the ERC20 standard.
func (*Keeper) EndBlock ¶
func (k *Keeper) EndBlock(ctx sdk.Context, _ abci.RequestEndBlock) []abci.ValidatorUpdate
EndBlock also retrieves the bloom filter value from the transient store and commits it to the
func (Keeper) EstimateGas ¶
func (k Keeper) EstimateGas( goCtx context.Context, req *evm.EthCallRequest, ) (*evm.EstimateGasResponse, error)
EstimateGas: Implements the gRPC query for "/eth.evm.v1.Query/EstimateGas". This estimates the lowest possible gas limit that allows a transaction to run successfully with the provided context options. This can be called with the "eth_estimateGas" JSON-RPC method.
When [EstimateGas] is called from the JSON-RPC client, we need to reset the gas meter before simulating the transaction (tx) to have an accurate gas estimate txs using EVM extensions.
Parameters:
- goCtx: The context.Context object representing the request context.
- req: The EthCallRequest object containing the transaction parameters.
Returns:
- A response containing the estimated gas cost.
- An error if the gas estimation process encounters any issues.
func (Keeper) EthAccount ¶
func (k Keeper) EthAccount( goCtx context.Context, req *evm.QueryEthAccountRequest, ) (*evm.QueryEthAccountResponse, error)
EthAccount: Implements the gRPC query for "/eth.evm.v1.Query/EthAccount". EthAccount retrieves the account and balance details for an account with the given address.
Parameters:
- goCtx: The context.Context object representing the request context.
- req: Request containing the address in either Ethereum hexadecimal or Bech32 format.
func (*Keeper) EthCall ¶
func (k *Keeper) EthCall( goCtx context.Context, req *evm.EthCallRequest, ) (*evm.MsgEthereumTxResponse, error)
EthCall: Implements the gRPC query for "/eth.evm.v1.Query/EthCall". EthCall performs a smart contract call using the eth_call JSON-RPC method.
An "eth_call" is a method from the Ethereum JSON-RPC specification that allows one to call a smart contract function without execution a transaction on the blockchain. This is useful for simulating transactions and for reading data from the chain using responses from smart contract calls.
Parameters:
- goCtx: Request context with information about the current block that serves as the main access point to the blockchain state.
- req: "eth_call" parameters to interact with a smart contract.
Returns:
- A pointer to the MsgEthereumTxResponse object containing the result of the eth_call.
- An error if the eth_call process encounters any issues.
func (*Keeper) EthereumTx ¶
func (k *Keeper) EthereumTx( goCtx context.Context, txMsg *evm.MsgEthereumTx, ) (evmResp *evm.MsgEthereumTxResponse, err error)
func (*Keeper) ExportGenesis ¶
func (k *Keeper) ExportGenesis(ctx sdk.Context) *evm.GenesisState
ExportGenesis exports genesis state of the EVM module
func (*Keeper) ExportGenesisContractAccount ¶
func (Keeper) FeeForCreateFunToken ¶
func (Keeper) FindERC20Metadata ¶
func (k Keeper) FindERC20Metadata( ctx sdk.Context, evmObj *vm.EVM, contract gethcommon.Address, abi *gethabi.ABI, ) (info *evm.ERC20Metadata, err error)
FindERC20Metadata retrieves the metadata of an ERC20 token.
Parameters:
- ctx: The SDK context for the transaction.
- contract: The Ethereum address of the ERC20 contract.
Returns:
- info: ERC20Metadata containing name, symbol, and decimals.
- err: An error if metadata retrieval fails.
func (*Keeper) ForEachStorage ¶
func (k *Keeper) ForEachStorage( ctx sdk.Context, addr gethcommon.Address, stopIter func(key, value gethcommon.Hash) (keepGoing bool), )
ForEachStorage: Iterator over contract storage. Implements the `statedb.Keeper` interface.
func (Keeper) FunTokenMapping ¶
func (k Keeper) FunTokenMapping( goCtx context.Context, req *evm.QueryFunTokenMappingRequest, ) (*evm.QueryFunTokenMappingResponse, error)
func (Keeper) GetAccNonce ¶
GetAccNonce returns the sequence number of an account, returns 0 if the account does not exist.
func (*Keeper) GetAccount ¶
GetAccount: Ethereum account getter for an evmstate.Account. Implements the `statedb.Keeper` interface. Returns nil if the account does not exist or has the wrong type.
func (*Keeper) GetCode ¶
GetCode: Loads smart contract bytecode associated with the given code hash. Implements the `statedb.Keeper` interface.
func (Keeper) GetCoinbaseAddress ¶
GetCoinbaseAddress returns the block proposer's validator operator address. In Ethereum, the coinbase (or "benficiary") is the address that proposed the current block. It corresponds to the COINBASE op code.
func (*Keeper) GetEvmTxEvents ¶
func (k *Keeper) GetEvmTxEvents( ctx sdk.Context, recipient *gethcommon.Address, txType uint8, msg core.Message, evmResp *evm.MsgEthereumTxResponse, ) (events TxEvents)
GetEvmTxEvents emits all types of EVM events applicable to a particular execution case
func (Keeper) GetHashFn ¶
func (k Keeper) GetHashFn(ctx sdk.Context) vm.GetHashFunc
GetHashFn implements vm.GetHashFunc for the vm.EVM object. It handles 3 cases:
- The requested height matches the current height from context (and thus same epoch number)
- The requested height is from a previous height from the same chain epoch
- The requested height is from a height greater than the latest one
func (*Keeper) GetState ¶
func (k *Keeper) GetState( ctx sdk.Context, addr gethcommon.Address, stateKey gethcommon.Hash, ) gethcommon.Hash
GetState: Implements `statedb.Keeper` interface: Loads smart contract state.
func (*Keeper) GetWeiBalance ¶
GetWeiBalance: Used in the EVM Ante Handler, "github.com/NibiruChain/nibiru/v2/evm/evmante": Load account's balance of gas tokens for EVM execution in EVM denom units.
func (*Keeper) ImportGenesisAccount ¶
func (*Keeper) InitGenesis ¶
func (k *Keeper) InitGenesis( ctx sdk.Context, genState evm.GenesisState, ) []abci.ValidatorUpdate
InitGenesis initializes genesis state based on exported genesis
func (*Keeper) NewEVM ¶
func (k *Keeper) NewEVM( ctx sdk.Context, msg core.Message, evmCfg EVMConfig, tracer *tracing.Hooks, stateDB vm.StateDB, ) (evmObj *vm.EVM)
NewEVM generates a go-ethereum VM.
Args:
- ctx: Consensus and KV store info for the current block.
- msg: Ethereum message sent to a contract
- cfg: Encapsulates params required to construct an EVM.
- tracer: Collects execution traces for EVM transaction logging.
- stateDB: Holds the EVM state.
func (Keeper) Params ¶
func (k Keeper) Params( goCtx context.Context, _ *evm.QueryParamsRequest, ) (*evm.QueryParamsResponse, error)
Params: Implements the gRPC query for "/eth.evm.v1.Query/Params". Params retrieves the EVM module parameters.
Parameters:
- goCtx: The context.Context object representing the request context.
- req: The QueryParamsRequest object (unused).
Returns:
- A pointer to the QueryParamsResponse object containing the EVM module parameters.
- An error if the parameter retrieval process encounters any issues.
func (*Keeper) RefundGas ¶
func (k *Keeper) RefundGas( sdb *SDB, msgFrom gethcommon.Address, leftoverGas uint64, weiPerGas *big.Int, ) error
RefundGas transfers the leftover gas to the sender of the message.
func (*Keeper) SendWei ¶
func (k *Keeper) SendWei( ctx sdk.Context, from gethcommon.Address, to gethcommon.Address, amtWei *uint256.Int, ) error
func (*Keeper) SetAccount ¶
SetAccount: Updates nonce, balance, and codeHash. Implements the `statedb.Keeper` interface. Only called by `StateDB.Commit()`.
func (*Keeper) SetCode ¶
SetCode: Setter for smart contract bytecode. Delete if code is empty. Implements the `statedb.Keeper` interface. Only called by `StateDB.Commit()`. ------------------------------------------------------ codeChange codeChange: [JournalChange] for an update to an account's code (smart contract bytecode). The previous code and hash for the code are stored to enable reversion.
func (*Keeper) SetState ¶
func (k *Keeper) SetState( ctx sdk.Context, addr gethcommon.Address, stateKey gethcommon.Hash, stateValue []byte, )
SetState: Update contract storage, delete if value is empty. Implements the `statedb.Keeper` interface. Only called by `StateDB.Commit()`.
func (Keeper) Storage ¶
func (k Keeper) Storage( goCtx context.Context, req *evm.QueryStorageRequest, ) (*evm.QueryStorageResponse, error)
Storage: Implements the gRPC query for "/eth.evm.v1.Query/Storage". Storage retrieves the storage value for a given Ethereum address and key.
Parameters:
- goCtx: The context.Context object representing the request context.
- req: The QueryStorageRequest object containing the Ethereum address and key.
Returns:
- A pointer to the QueryStorageResponse object containing the storage value.
- An error if the storage retrieval process encounters any issues.
func (Keeper) TraceBlock ¶
func (k Keeper) TraceBlock( goCtx context.Context, req *evm.QueryTraceBlockRequest, ) (*evm.QueryTraceBlockResponse, error)
TraceBlock: Implements the gRPC query for "/eth.evm.v1.Query/TraceBlock". Configures a Nibiru EVM tracer that is used to "trace" and analyze the execution of transactions within a given block. Block information is read from the context (goCtx). [TraceBlock] is responsible iterates over each Eth transaction message and calls [TraceEthTxMsg] on it.
func (Keeper) TraceCall ¶
func (k Keeper) TraceCall( goCtx context.Context, req *evm.QueryTraceTxRequest, ) (*evm.QueryTraceTxResponse, error)
TraceCall configures a new tracer according to the provided configuration, and executes the given message in the provided environment. The return value will be tracer dependent.
func (*Keeper) TraceEthTxMsg ¶
func (k *Keeper) TraceEthTxMsg( ctx sdk.Context, evmCfg EVMConfig, txConfig TxConfig, msg core.Message, traceConfig *evm.TraceConfig, tracerJSONConfig json.RawMessage, ) (traceResult *json.RawMessage, nextLogIndex uint, err error)
TraceEthTxMsg do trace on one transaction, it returns a tuple: (traceResult, nextLogIndex, error).
func (Keeper) TraceTx ¶
func (k Keeper) TraceTx( goCtx context.Context, req *evm.QueryTraceTxRequest, ) (*evm.QueryTraceTxResponse, error)
TraceTx configures a new tracer according to the provided configuration, and executes the given message in the provided environment. The return value will be tracer dependent.
func (*Keeper) UpdateParams ¶
func (k *Keeper) UpdateParams( goCtx context.Context, req *evm.MsgUpdateParams, ) (resp *evm.MsgUpdateParamsResponse, err error)
func (Keeper) VMConfig ¶
VMConfig creates an EVM configuration from the debug setting and the extra EIPs enabled on the module parameters. The config generated uses the default JumpTable from the EVM.
func (Keeper) ValidatorAccount ¶
func (k Keeper) ValidatorAccount( goCtx context.Context, req *evm.QueryValidatorAccountRequest, ) (*evm.QueryValidatorAccountResponse, error)
ValidatorAccount: Implements the gRPC query for "/eth.evm.v1.Query/ValidatorAccount". ValidatorAccount retrieves the account details for a given validator consensus address.
Parameters:
- goCtx: The context.Context object representing the request context.
- req: Request containing the validator consensus address.
Returns:
- Response containing the account details.
- An error if the account retrieval process encounters any issues.
type LocalState ¶
type LocalState struct {
// AccountChangeMap tracks account lifecycle changes (CREATE/DELETE flags)
AccountChangeMap map[gethcommon.Address]SnapshotAccChange
// ContractStorage provides transient storage for EIP-1153 compliance
ContractStorage transientStorage
// contains filtered or unexported fields
}
LocalState represents the local state changes for a single EVM transaction snapshot. It serves as the backbone of the StateDB's snapshot and revert functionality, optimizing performance by minimizing direct access to the underlying storage for uncommitted mutations.
The LocalState is used in a hierarchical manner:
- Each SDB instance has a current `localState` for active changes
- Historical states are stored in `savedStates []*LocalState` for snapshots
- When a snapshot is taken, the current localState is saved and a new one is created
- When reverting, the current localState is discarded and a previous one is restored
This design enables efficient state management for EVM operations like:
- Nested contract calls with snapshot/revert semantics
- Gas refund tracking across transaction execution
- Access list management for EIP-2930 transactions
- Transient storage (EIP-1153) for contract-to-contract communication
- Account lifecycle tracking (creation/deletion)
func NewLocalState ¶
func NewLocalState() *LocalState
type NibiruBankKeeper ¶
type NibiruBankKeeper struct {
bankkeeper.BaseKeeper
}
type SDB ¶
type SDB struct {
// contains filtered or unexported fields
}
SDB is the Nibiru EVM implementation of the EVM interpreter's vm.StateDB. It manages all state changes and snapshotting within the context of an Ethereum transaction.
The SDB manages EVM *and* non-EVM state reachable via the sdk.Context by branching the world state with "CacheMultiStore" snapshots. There are no journal entries.
### Model:
- Each SDB represents one Ethereum transaction's execution scope.
- Snapshot() creates a new world-state branch (cached multistore) and a fresh LocalState layer for EVM-specific metadata (logs, refunds, access list, transient storage).
- RevertToSnapshot(n) restores the exact prior world state by jumping to snapshot n.
- Commit() writes cached branches back toward the root Context; BaseApp later commits the root.
### Notes:
- Nibiru uses IAVL-backed KV stores, not MPT/Verkle; we don't compute Ethereum storage roots.
- Read paths (balances/accounts) consult the active branched Context; no journals are needed.
- This design mirrors database snapshotting: revert == restore snapshot, not "undo logs".
func SDBFromEVM ¶
func (*SDB) AddAddressToAccessList ¶
func (s *SDB) AddAddressToAccessList(addr gethcommon.Address)
AddAddressToAccessList adds the given address to the access list. This operation is safe to perform even if the ccess list fork is not active yet. This function implements the vm.StateDB interface.
func (*SDB) AddBalance ¶
func (s *SDB) AddBalance( addr gethcommon.Address, wei *uint256.Int, reason tracing.BalanceChangeReason, ) (prevWei uint256.Int)
AddBalance adds amount to the account associated with addr. It is used to add funds to the destination account of a transfer.
func (*SDB) AddLog ¶
AddLog adds to the EVM's event log for the current transaction. [AddLog] uses the TxConfig to populate the tx hash, block hash, tx index, and event log index.
func (*SDB) AddPreimage ¶
func (s *SDB) AddPreimage(_ gethcommon.Hash, _ []byte)
AddPreimage records a SHA3 preimage seen by the VM. AddPreimage performs a no-op since the EnablePreimageRecording flag is disabled on the vm.Config during state transitions. No store trie preimages are written to the database.
func (*SDB) AddSlotToAccessList ¶
func (s *SDB) AddSlotToAccessList(addr gethcommon.Address, slot gethcommon.Hash)
AddSlotToAccessList adds the given (address, slot)-tuple to the access list. This operation is safe to perform even if the ccess list fork is not active yet. This function implements the vm.StateDB interface.
func (*SDB) AddressInAccessList ¶
func (s *SDB) AddressInAccessList(addr gethcommon.Address) bool
AddressInAccessList returns true if the given address is in the access list.
func (*SDB) Commit ¶
func (s *SDB) Commit()
Commit writes the dirty journal state changes to the EVM Keeper. The StateDB object cannot be reused after [Commit] has completed. A new object needs to be created from the EVM.
cacheCtxSyncNeeded: If one of the Nibiru-Specific Precompiled Contracts was called, a [JournalChange] of type [PrecompileSnapshotBeforeRun] gets added and we branch off a cache of the commit context (s.evmTxCtx).
func (*SDB) CreateAccount ¶
func (s *SDB) CreateAccount(addr gethcommon.Address)
CreateAccount is called during the EVM CREATE operation. The situation might arise that a contract does the following:
1. sends funds to sha(account ++ (nonce + 1)) 2. tx_create(sha(account ++ nonce)) (note that this gets the address of 1)
Carrying over the balance ensures that Ether doesn't disappear.
func (*SDB) CreateContract ¶
func (s *SDB) CreateContract(addr gethcommon.Address)
CreateContract is used whenever a contract is created. This may be preceded by CreateAccount, but that is not required if it already existed in the state due to funds sent beforehand. This operation sets the 'newContract'-flag, which is required in order to correctly handle EIP-6780 'delete-in-same-transaction' logic.
func (*SDB) Empty ¶
func (s *SDB) Empty(addr gethcommon.Address) bool
Empty returns whether the state object is either non-existent or empty according to the EIP161 specification (balance = nonce = code = 0)
func (*SDB) Exist ¶
func (s *SDB) Exist(addr gethcommon.Address) bool
Exist reports whether the given account address exists in the state. Notably this also returns true for suicided accounts.
func (*SDB) Finalise ¶
"Finalise" prepares state objects at the end of a transaction execution.
In Ethereum/Geth, this typically moves dirty storage to a pending layer, flushes prefetchers, and finalizes flags like newContract.
Behavior: This matches Ethereum behavior (e.g., EIP-161 and EIP-6780 compatibility).
- If the account is non-empty, it clears the `newContract` flag.
- If the account is empty and deleteEmptyObjects is true, it removes it from live state.
In Nibiru, SDB.Finalise can be a a no-op because:
- The Cosmos SDK state machine executes each transaction atomically.
- All writes happen against a cached multistore (`s.cacheCtx`) that gets committed during `StateDB.Commit`.
This function implements the vm.StateDB interface.
func (*SDB) GetBalance ¶
func (s *SDB) GetBalance(addr gethcommon.Address) *uint256.Int
GetBalance retrieves the balance from the given address or 0 if object not found This function implements the vm.StateDB interface.
func (*SDB) GetCode ¶
func (s *SDB) GetCode(addr gethcommon.Address) []byte
GetCode returns the code of account, nil if not exists.
func (*SDB) GetCodeHash ¶
func (s *SDB) GetCodeHash(addr gethcommon.Address) (codeHash gethcommon.Hash)
GetCodeHash returns the code hash of account.
func (*SDB) GetCodeSize ¶
func (s *SDB) GetCodeSize(addr gethcommon.Address) int
GetCodeSize returns the code size of account.
func (*SDB) GetCommittedState ¶
func (s *SDB) GetCommittedState(addr gethcommon.Address, hash gethcommon.Hash) gethcommon.Hash
GetCommittedState retrieves a value from the given account's committed storage trie.
func (*SDB) GetNonce ¶
func (s *SDB) GetNonce(addr gethcommon.Address) uint64
GetNonce returns the nonce of account, 0 if not exists. This function implements the vm.StateDB interface.
func (*SDB) GetState ¶
func (s *SDB) GetState( addr gethcommon.Address, slotKey gethcommon.Hash, ) (stateValue gethcommon.Hash)
GetState retrieves a value from the given account's storage trie.
func (*SDB) GetStorageForOneContract ¶
func (s *SDB) GetStorageForOneContract( addr gethcommon.Address, ) StorageForOneContract
func (*SDB) GetStorageRoot ¶
func (s *SDB) GetStorageRoot(addr gethcommon.Address) (root gethcommon.Hash)
GetStorageRoot returns an empty state hash. This is done because a storage root make sense to implement for Nibiru, as it does not use Merkle Patricia Tries. This function implements the vm.StateDB interface.
func (*SDB) GetTransientState ¶
func (s *SDB) GetTransientState( addr gethcommon.Address, key gethcommon.Hash, ) (stateVal gethcommon.Hash)
GetTransientState gets transient storage (gethcommon.Hash) for a given account.
func (*SDB) GetTransientStorageForOneContract ¶
func (s *SDB) GetTransientStorageForOneContract( addr gethcommon.Address, ) StorageForOneContract
func (*SDB) HasSelfDestructed ¶
func (s *SDB) HasSelfDestructed(addr gethcommon.Address) bool
HasSelfDestructed returns true if the most recent account change status says that the contract is deleted.
func (*SDB) HasSuicided ¶
func (s *SDB) HasSuicided(addr gethcommon.Address) bool
HasSuicided returns if the contract is suicided in current transaction.
func (*SDB) IsCreatedThisTx ¶
func (s *SDB) IsCreatedThisTx(addr gethcommon.Address) bool
IsCreatedThisTx returns true if the given account was created within the execution scope of the current SDB. An SDB corresponds to one EVM transaction.
func (SDB) IsDeliverTx ¶
func (SDB) IsReCheckTxOnly ¶
IsReCheckTxOnly reports whether the active context is ABCI Recheck only. See IsReCheckTxOnly.
func (*SDB) PointCache ¶
func (s *SDB) PointCache() *utils.PointCache
PointCache returns the point cache used by verkle tree. SDB.PointCache is unused on Nibiru (no Verkle); return nil. This function implements the vm.StateDB interface.
func (*SDB) Prepare ¶
func (s *SDB) Prepare( _ gethparams.Rules, sender, coinbase gethcommon.Address, dest *gethcommon.Address, precompiles []gethcommon.Address, txAccesses gethcore.AccessList, )
Prepare handles the preparatory steps for executing a state transition with. This method must be invoked before state transition.
Berlin fork: - Add sender to access list (2929) - Add destination to access list (2929) - Add precompiles to access list (2929) - Add the contents of the optional tx access list (2930)
EIPs Included: - Reset access list (Berlin) - Add coinbase to access list (EIP-3651) | Shanghai - Reset transient storage (EIP-1153)
func (*SDB) RevertToSnapshot ¶
RevertToSnapshot reverts all state changes made since the given revision.
func (*SDB) RootCtx ¶
RootCtx returns the root context captured when the SDB was constructed. It is the base (anchor) context, and subsequent snapshots branch from it. Only the root context is ultimately committed by the baseapp.
Only in SDB.Commit does the SDB write changes from all of the branched contexts, ultimately updating the root ctx to have the changes made to the current branched ctx (SDB.Ctx).
func (*SDB) SelfDestruct ¶
func (s *SDB) SelfDestruct(addr gethcommon.Address) (prevWei uint256.Int)
SelfDestruct marks the given account as suicided. This clears the account balance.
When the SELFDESTRUCT is called, it does so with a "beneficiary", and the EVM interpreter adds the the equivalent balance from the self destructing account to the beneficiary, preserving the supply of ether.
The account's state object is still available until the state is committed, getStateObject will return a non-nil account after [SelfDestruct].
func (*SDB) SelfDestruct6780 ¶
func (s *SDB) SelfDestruct6780( addr gethcommon.Address, ) (prevWei uint256.Int, isSelfDestructed bool)
SelfDestruct6780 calls SDB.SelfDestruct only if the account corresponding to the given "addr" was created this block.
SelfDestruct6780 is post-EIP6780 selfdestruct, which means that it's a send-all-to-beneficiary, unless the contract was created in this same transaction, in which case it will be destructed. This method returns the prior balance, along with a boolean which is true if and only if the object was indeed destructed.
func (*SDB) SetCode ¶
func (s *SDB) SetCode(addr gethcommon.Address, code []byte)
SetCode sets the code of account. This function implements the vm.StateDB interface.
func (*SDB) SetNonce ¶
func (s *SDB) SetNonce(addr gethcommon.Address, nonce uint64)
SetNonce sets the nonce of account. The nonce is a counter of the number of transactions sent from an account.
func (*SDB) SetState ¶
func (s *SDB) SetState( addr gethcommon.Address, key, value gethcommon.Hash, ) (prevValue gethcommon.Hash)
SetState sets the contract state.
func (*SDB) SetTransientState ¶
func (s *SDB) SetTransientState( addr gethcommon.Address, key, value gethcommon.Hash, )
SetTransientState sets transient storage for a given account. It adds the change to the journal so that it can be rolled back to its previous value if there is a revert.
func (*SDB) SlotInAccessList ¶
func (s *SDB) SlotInAccessList( addr gethcommon.Address, slot gethcommon.Hash, ) (addrPresent bool, slotPresent bool)
SlotInAccessList returns true if the given (address, slot)-tuple is in the access list. Checks if a slot for some account is present in the access list, returning separate flags for the presence of the account and the slot respectively.
func (*SDB) SnapshotRevertIdx ¶
SnapshotRevertIdx returns the current snapshot revert index. The original snapshot has revert index 0, and each subsequent snapshot afterward increments this value by 1.
func (*SDB) SubBalance ¶
func (s *SDB) SubBalance( addr gethcommon.Address, wei *uint256.Int, reason tracing.BalanceChangeReason, ) (prevWei uint256.Int)
SubBalance subtracts amount from the account associated with addr. It is used to remove funds from the origin account of a transfer.
func (*SDB) SubRefund ¶
SubRefund removes gas from the refund counter. This method will panic if the refund counter goes below zero
func (*SDB) Witness ¶
Witness returns nil.
Rationale: In Geth v1.14+, a stateless.Witness encompasses the state required to apply a set of transactions and derive a post state/receipt root.
On Ethereum, this can be used to record trie (Merkle Patricia) accesses (storage and account), generate proofs for stateless clients, snap sync, or zkEVMs, and later reconstruct state from those proofs. In other words, [Witness] is part of an effort toward stateless execution.
NOTE: Nibiru does not use a Merkle Patricia Trie. Instead it uses IAVL over KVStore. That means there's no notion of Ethereum-style witnesses unless we simulate that separately.
Thus, this function is optional to implement unless we build:
- zkEVM compatibility
- Stateless Ethereum clients
- Custom light client proofs that require a witness
type SnapshotAccChange ¶
type SnapshotAccChange byte
SnapshotAccChange tracks changes in an account. Changes include:
- an account marked for deletion (suicided).
- an account created during the current EVM tx.
var ( SNAPSHOT_ACC_STATUS_CREATE SnapshotAccChange = 0x01 // SNAPSHOT_ACC_STATUS_DELETE ("deleted") is an EIP-6780 flag indicating // whether the object is eligible for self-destruct according to EIP-6780. // The flag could be set either when the contract is just created within the // current transaction, or when the object was previously existent and is // being deployed as a contract within the current transaction. SNAPSHOT_ACC_STATUS_DELETE SnapshotAccChange = 0x02 )
type StorageForOneContract ¶
type StorageForOneContract map[gethcommon.Hash]gethcommon.Hash
StorageForOneContract represents an in-memory cache of contract storage. In the EVM, contract storage is the mapping from slot key -> slot value, where both are 32-byte arrays of type gethcommon.Hash.
This concept comes from the Ethereum Yellow Paper §4.1: Each account maintains a mapping from 256-bit words to 256-bit words, called "storage".
func (StorageForOneContract) Copy ¶
func (s StorageForOneContract) Copy() StorageForOneContract
func (StorageForOneContract) SortedKeys ¶
func (s StorageForOneContract) SortedKeys() []gethcommon.Hash
SortedKeys sort the keys for deterministic iteration
func (StorageForOneContract) String ¶
func (s StorageForOneContract) String() (str string)
type TxConfig ¶
type TxConfig struct {
BlockHash gethcommon.Hash // hash of current block
TxHash gethcommon.Hash // hash of current tx
TxIndex uint // the index of current transaction
LogIndex uint // the index of next log within current block
}
TxConfig encapsulates the readonly information of current tx for `StateDB`.
func NewEmptyTxConfig ¶
func NewEmptyTxConfig(blockHash gethcommon.Hash) TxConfig
NewEmptyTxConfig construct an empty TxConfig, used in context where there's no transaction, e.g. `eth_call`/`eth_estimateGas`.
type TxEvents ¶
type TxEvents struct {
EventEthereumTx evm.EventEthereumTx // Typed event: eth.evm.v1.EventEthereumTx
EventMessage sdk.Event // Untyped event: "message", used for tendermint subscription
EventContractDeployed *evm.EventContractDeployed
EventContractExecuted *evm.EventContractExecuted
EventTransfer *evm.EventTransfer
}
TxEvents represents ABCI events that are emitted an Ethereum tx. Nil fields repesent intentional omission
Source Files
¶
- call_contract.go
- doc.go
- erc20.go
- evm_state.go
- funtoken_from_coin.go
- funtoken_from_erc20.go
- funtoken_state.go
- gas_fees.go
- genesis.go
- grpc_query.go
- hooks.go
- keeper.go
- msg_convert_coin_to_evm.go
- msg_convert_evm_to_coin.go
- msg_server.go
- sdb_access_list.go
- sdb_config.go
- sdb_debug.go
- sdb_ext_keeper.go
- sdb_interfaces.go
- sdb_state_object.go
- sdb_statedb.go
- vm_config.go