Skip to content

Commit

Permalink
refactor: general code style cleanups on precompile and statedb journ…
Browse files Browse the repository at this point in the history
…al (#2100)

* statedb: add cacheing for multistore before precompile runs

* messy, working first version that allows for precompile reversion

* wip!: Save checkpoint.
1. Created NibiruBankKeeper with safety around NIBI transfers inside of
   EthereumTx.
2. The "PrecompileCalled" JournalChange now has a propery implementation
   and a strong test case to show that reverting the precompile calls
   works as intended.
3. Remove unneeded functions created for testing with low-level struct
   fields.

* chore: changelog

* finalize bank keeper changes

* revert to previous commit 7f904a0

* fix strange ignored file issue

* remove new bank keeper

* chore: comments from self-review

* refactor: clean up test code

* refactor: clean up parse fund args

* refactor: clean up common precompile functions

* refactor: clean up precompile onrunstart

* refactor: clean up precompile onrunstart

* refactor: clean up oracle precompile

* fix: import

* Delete .gitignore

* Update CHANGELOG.md

* refactor: replace interface{} with any

* refactor: add ABI() precompile fn

* refactor: replace assertNotReadonlyTx

---------

Co-authored-by: Unique-Divine <realuniquedivine@gmail.com>
  • Loading branch information
k-yang and Unique-Divine authored Oct 31, 2024
1 parent 7b7beb7 commit 0afb08f
Show file tree
Hide file tree
Showing 37 changed files with 230 additions and 284 deletions.
7 changes: 4 additions & 3 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ committed as expected, fixes the `StateDB.Commit` to follow its guidelines more
closely, and solves for a critical state inconsistency producible from the
FunToken.sol precompiled contract. It also aligns the precompiles to use
consistent setup and dynamic gas calculations, addressing the following tickets.
- https://github.com/NibiruChain/nibiru/issues/2083
- https://github.com/code-423n4/2024-10-nibiru-zenith/issues/43
- https://github.com/code-423n4/2024-10-nibiru-zenith/issues/47
- <https://github.com/NibiruChain/nibiru/issues/2083>
- <https://github.com/code-423n4/2024-10-nibiru-zenith/issues/43>
- <https://github.com/code-423n4/2024-10-nibiru-zenith/issues/47>
- [#2088](https://github.com/NibiruChain/nibiru/pull/2088) - refactor(evm): remove outdated comment and improper error message text
- [#2089](https://github.com/NibiruChain/nibiru/pull/2089) - better handling of gas consumption within erc20 contract execution
- [#2091](https://github.com/NibiruChain/nibiru/pull/2091) - feat(evm): add fun token creation fee validation
Expand Down Expand Up @@ -163,6 +163,7 @@ about the expected resulting balance for the transfer recipient.
- [#2060](https://github.com/NibiruChain/nibiru/pull/2060) - fix(evm-precompiles): add assertNumArgs validation
- [#2056](https://github.com/NibiruChain/nibiru/pull/2056) - feat(evm): add oracle precompile
- [#2065](https://github.com/NibiruChain/nibiru/pull/2065) - refactor(evm)!: Refactor out dead code from the evm.Params
- [#2100](https://github.com/NibiruChain/nibiru/pull/2100) - refactor: cleanup statedb and precompile sections

### State Machine Breaking (Other)

Expand Down
2 changes: 1 addition & 1 deletion app/server/config/server_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,7 @@ type TLSConfig struct {

// AppConfig helps to override default appConfig template and configs.
// return "", nil if no custom configuration is required for the application.
func AppConfig(denom string) (string, interface{}) {
func AppConfig(denom string) (string, any) {
// Optionally allow the chain developer to overwrite the SDK's default
// server config.
customAppConfig := DefaultConfig()
Expand Down
2 changes: 1 addition & 1 deletion cmd/nibid/cmd/base64.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func GetBuildWasmMsg() *cobra.Command {
Value string `json:"value,omitempty"`
}

js, err := json.Marshal(map[string]interface{}{
js, err := json.Marshal(map[string]any{
"stargate": stargateMessage{
TypeURL: anyMsg.TypeUrl,
Value: base64.StdEncoding.EncodeToString(anyMsg.Value),
Expand Down
8 changes: 4 additions & 4 deletions cmd/nibid/cmd/decode_base64.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ import (
// from the provided JSON data.
// - err error: An error object, which is nil if the operation is successful.
func YieldStargateMsgs(jsonBz []byte) (sgMsgs []wasmvm.StargateMsg, err error) {
var data interface{}
var data any
if err := json.Unmarshal(jsonBz, &data); err != nil {
return sgMsgs, err
}
Expand All @@ -50,7 +50,7 @@ func YieldStargateMsgs(jsonBz []byte) (sgMsgs []wasmvm.StargateMsg, err error) {
// encoded base 64 string.
func parseStargateMsgs(jsonData any, msgs *[]wasmvm.StargateMsg) {
switch v := jsonData.(type) {
case map[string]interface{}:
case map[string]any:
if typeURL, ok := v["type_url"].(string); ok {
if value, ok := v["value"].(string); ok {
*msgs = append(*msgs, wasmvm.StargateMsg{
Expand All @@ -62,7 +62,7 @@ func parseStargateMsgs(jsonData any, msgs *[]wasmvm.StargateMsg) {
for _, value := range v {
parseStargateMsgs(value, msgs)
}
case []interface{}:
case []any:
for _, value := range v {
parseStargateMsgs(value, msgs)
}
Expand Down Expand Up @@ -93,7 +93,7 @@ func DecodeBase64StargateMsgs(
) (newSgMsgs []StargateMsgDecoded, err error) {
codec := clientCtx.Codec

var data interface{}
var data any
if err := json.Unmarshal(jsonBz, &data); err != nil {
return newSgMsgs, fmt.Errorf(
"failed to decode stargate msgs due to invalid JSON: %w", err)
Expand Down
10 changes: 5 additions & 5 deletions eth/eip712/eip712_legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func LegacyWrapTxToTypedData(
data []byte,
feeDelegation *FeeDelegationOptions,
) (apitypes.TypedData, error) {
txData := make(map[string]interface{})
txData := make(map[string]any)

if err := json.Unmarshal(data, &txData); err != nil {
return apitypes.TypedData{}, errorsmod.Wrap(errortypes.ErrJSONUnmarshal, "failed to JSON unmarshal data")
Expand All @@ -58,7 +58,7 @@ func LegacyWrapTxToTypedData(
}

if feeDelegation != nil {
feeInfo, ok := txData["fee"].(map[string]interface{})
feeInfo, ok := txData["fee"].(map[string]any)
if !ok {
return apitypes.TypedData{}, errorsmod.Wrap(errortypes.ErrInvalidType, "cannot parse fee from tx data")
}
Expand Down Expand Up @@ -139,7 +139,7 @@ func extractMsgTypes(cdc codectypes.AnyUnpacker, msgTypeName string, msg sdk.Msg
return rootTypes, nil
}

func walkFields(cdc codectypes.AnyUnpacker, typeMap apitypes.Types, rootType string, in interface{}) (err error) {
func walkFields(cdc codectypes.AnyUnpacker, typeMap apitypes.Types, rootType string, in any) (err error) {
defer doRecover(&err)

t := reflect.TypeOf(in)
Expand All @@ -161,8 +161,8 @@ func walkFields(cdc codectypes.AnyUnpacker, typeMap apitypes.Types, rootType str
}

type CosmosAnyWrapper struct {
Type string `json:"type"`
Value interface{} `json:"value"`
Type string `json:"type"`
Value any `json:"value"`
}

// legacyTraverseFields: Recursively inspects the fields of a given
Expand Down
4 changes: 2 additions & 2 deletions eth/eip712/encoding_legacy.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ import (
)

type aminoMessage struct {
Type string `json:"type"`
Value interface{} `json:"value"`
Type string `json:"type"`
Value any `json:"value"`
}

// LegacyGetEIP712BytesForMsg returns the EIP-712 object bytes for the given SignDoc bytes by decoding the bytes into
Expand Down
4 changes: 2 additions & 2 deletions eth/eip712/message.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
type eip712MessagePayload struct {
payload gjson.Result
numPayloadMsgs int
message map[string]interface{}
message map[string]any
}

const (
Expand All @@ -34,7 +34,7 @@ func createEIP712MessagePayload(data []byte) (eip712MessagePayload, error) {
return eip712MessagePayload{}, errorsmod.Wrap(err, "failed to flatten payload JSON messages")
}

message, ok := payload.Value().(map[string]interface{})
message, ok := payload.Value().(map[string]any)
if !ok {
return eip712MessagePayload{}, errorsmod.Wrap(errortypes.ErrInvalidType, "failed to parse JSON as map")
}
Expand Down
8 changes: 4 additions & 4 deletions eth/rpc/backend/blocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func (b *Backend) BlockNumber() (hexutil.Uint64, error) {
// GetBlockByNumber returns the JSON-RPC compatible Ethereum block identified by
// block number. Depending on fullTx it either returns the full transaction
// objects or if false only the hashes of the transactions.
func (b *Backend) GetBlockByNumber(blockNum rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
func (b *Backend) GetBlockByNumber(blockNum rpc.BlockNumber, fullTx bool) (map[string]any, error) {
resBlock, err := b.TendermintBlockByNumber(blockNum)
if err != nil {
return nil, nil
Expand Down Expand Up @@ -85,7 +85,7 @@ func (b *Backend) GetBlockByNumber(blockNum rpc.BlockNumber, fullTx bool) (map[s

// GetBlockByHash returns the JSON-RPC compatible Ethereum block identified by
// hash.
func (b *Backend) GetBlockByHash(hash gethcommon.Hash, fullTx bool) (map[string]interface{}, error) {
func (b *Backend) GetBlockByHash(hash gethcommon.Hash, fullTx bool) (map[string]any, error) {
resBlock, err := b.TendermintBlockByHash(hash)
if err != nil {
return nil, err
Expand Down Expand Up @@ -348,8 +348,8 @@ func (b *Backend) RPCBlockFromTendermintBlock(
resBlock *tmrpctypes.ResultBlock,
blockRes *tmrpctypes.ResultBlockResults,
fullTx bool,
) (map[string]interface{}, error) {
ethRPCTxs := []interface{}{}
) (map[string]any, error) {
ethRPCTxs := []any{}
block := resBlock.Block

baseFeeWei, err := b.BaseFeeWei(blockRes)
Expand Down
4 changes: 2 additions & 2 deletions eth/rpc/backend/node_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (b *Backend) Accounts() ([]gethcommon.Address, error) {
// - highestBlock: block number of the highest block header this node has received from peers
// - pulledStates: number of state entries processed until now
// - knownStates: number of known state entries that still need to be pulled
func (b *Backend) Syncing() (interface{}, error) {
func (b *Backend) Syncing() (any, error) {
status, err := b.clientCtx.Client.Status(b.ctx)
if err != nil {
return false, err
Expand All @@ -49,7 +49,7 @@ func (b *Backend) Syncing() (interface{}, error) {
return false, nil
}

return map[string]interface{}{
return map[string]any{
"startingBlock": hexutil.Uint64(status.SyncInfo.EarliestBlockHeight),
"currentBlock": hexutil.Uint64(status.SyncInfo.LatestBlockHeight),
// "highestBlock": nil, // NA
Expand Down
8 changes: 4 additions & 4 deletions eth/rpc/backend/tracing.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ import (

// TraceTransaction returns the structured logs created during the execution of EVM
// and returns them as a JSON object.
func (b *Backend) TraceTransaction(hash gethcommon.Hash, config *evm.TraceConfig) (interface{}, error) {
func (b *Backend) TraceTransaction(hash gethcommon.Hash, config *evm.TraceConfig) (any, error) {
// Get transaction by hash
transaction, err := b.GetTxByEthHash(hash)
if err != nil {
Expand Down Expand Up @@ -124,7 +124,7 @@ func (b *Backend) TraceTransaction(hash gethcommon.Hash, config *evm.TraceConfig

// Response format is unknown due to custom tracer config param
// More information can be found here https://geth.ethereum.org/docs/dapp/tracing-filtered
var decodedResult interface{}
var decodedResult any
err = json.Unmarshal(traceResult.Data, &decodedResult)
if err != nil {
return nil, err
Expand Down Expand Up @@ -219,7 +219,7 @@ func (b *Backend) TraceCall(
txArgs evm.JsonTxArgs,
contextBlock rpc.BlockNumber,
config *evm.TraceConfig,
) (interface{}, error) {
) (any, error) {
blk, err := b.TendermintBlockByNumber(contextBlock)
if err != nil {
b.logger.Debug("block not found", "contextBlock", contextBlock)
Expand Down Expand Up @@ -253,7 +253,7 @@ func (b *Backend) TraceCall(
if err != nil {
return nil, err
}
var decodedResult interface{}
var decodedResult any
err = json.Unmarshal(traceResult.Data, &decodedResult)
if err != nil {
return nil, err
Expand Down
2 changes: 1 addition & 1 deletion eth/rpc/backend/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ func (b *Backend) getAccountNonce(accAddr common.Address, pending bool, height i
// See eth_feeHistory method for more details of the return format.
func (b *Backend) retrieveEVMTxFeesFromBlock(
tendermintBlock *tmrpctypes.ResultBlock,
ethBlock *map[string]interface{},
ethBlock *map[string]any,
rewardPercentiles []float64,
tendermintBlockResult *tmrpctypes.ResultBlockResults,
targetOneFeeHistory *rpc.OneFeeHistory,
Expand Down
6 changes: 3 additions & 3 deletions eth/rpc/rpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,17 +114,17 @@ func BlockMaxGasFromConsensusParams(
// transactions.
func FormatBlock(
header tmtypes.Header, size int, gasLimit int64,
gasUsed *big.Int, transactions []interface{}, bloom gethcore.Bloom,
gasUsed *big.Int, transactions []any, bloom gethcore.Bloom,
validatorAddr gethcommon.Address, baseFee *big.Int,
) map[string]interface{} {
) map[string]any {
var transactionsRoot gethcommon.Hash
if len(transactions) == 0 {
transactionsRoot = gethcore.EmptyRootHash
} else {
transactionsRoot = gethcommon.BytesToHash(header.DataHash)
}

result := map[string]interface{}{
result := map[string]any{
"number": hexutil.Uint64(header.Height),
"hash": hexutil.Bytes(header.Hash()),
"parentHash": gethcommon.BytesToHash(header.LastBlockID.Hash.Bytes()),
Expand Down
4 changes: 2 additions & 2 deletions eth/rpc/rpcapi/debugapi/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ func NewImplDebugAPI(

// TraceTransaction returns the structured logs created during the execution of EVM
// and returns them as a JSON object.
func (a *DebugAPI) TraceTransaction(hash common.Hash, config *evm.TraceConfig) (interface{}, error) {
func (a *DebugAPI) TraceTransaction(hash common.Hash, config *evm.TraceConfig) (any, error) {
a.logger.Debug("debug_traceTransaction", "hash", hash)
return a.backend.TraceTransaction(hash, config)
}
Expand Down Expand Up @@ -115,7 +115,7 @@ func (a *DebugAPI) TraceCall(
args evm.JsonTxArgs,
blockNrOrHash rpc.BlockNumberOrHash,
config *evm.TraceConfig,
) (interface{}, error) {
) (any, error) {
a.logger.Debug("debug_traceCall", args.String(), "block number or hash", blockNrOrHash)

// Get Tendermint Block
Expand Down
20 changes: 10 additions & 10 deletions eth/rpc/rpcapi/eth_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ type IEthAPI interface {
//
// Retrieves information from a particular block in the blockchain.
BlockNumber() (hexutil.Uint64, error)
GetBlockByNumber(ethBlockNum rpc.BlockNumber, fullTx bool) (map[string]interface{}, error)
GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error)
GetBlockByNumber(ethBlockNum rpc.BlockNumber, fullTx bool) (map[string]any, error)
GetBlockByHash(hash common.Hash, fullTx bool) (map[string]any, error)
GetBlockTransactionCountByHash(hash common.Hash) *hexutil.Uint
GetBlockTransactionCountByNumber(blockNum rpc.BlockNumber) *hexutil.Uint

Expand Down Expand Up @@ -97,15 +97,15 @@ type IEthAPI interface {
// and replaced by a canonical block instead.
GetUncleByBlockHashAndIndex(
hash common.Hash, idx hexutil.Uint,
) map[string]interface{}
) map[string]any
GetUncleByBlockNumberAndIndex(
number, idx hexutil.Uint,
) map[string]interface{}
) map[string]any
GetUncleCountByBlockHash(hash common.Hash) hexutil.Uint
GetUncleCountByBlockNumber(blockNum rpc.BlockNumber) hexutil.Uint

// Other
Syncing() (interface{}, error)
Syncing() (any, error)
GetTransactionLogs(txHash common.Hash) ([]*gethcore.Log, error)
FillTransaction(
args evm.JsonTxArgs,
Expand Down Expand Up @@ -144,13 +144,13 @@ func (e *EthAPI) BlockNumber() (hexutil.Uint64, error) {
}

// GetBlockByNumber returns the block identified by number.
func (e *EthAPI) GetBlockByNumber(ethBlockNum rpc.BlockNumber, fullTx bool) (map[string]interface{}, error) {
func (e *EthAPI) GetBlockByNumber(ethBlockNum rpc.BlockNumber, fullTx bool) (map[string]any, error) {
e.logger.Debug("eth_getBlockByNumber", "number", ethBlockNum, "full", fullTx)
return e.backend.GetBlockByNumber(ethBlockNum, fullTx)
}

// GetBlockByHash returns the block identified by hash.
func (e *EthAPI) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]interface{}, error) {
func (e *EthAPI) GetBlockByHash(hash common.Hash, fullTx bool) (map[string]any, error) {
e.logger.Debug("eth_getBlockByHash", "hash", hash.Hex(), "full", fullTx)
return e.backend.GetBlockByHash(hash, fullTx)
}
Expand Down Expand Up @@ -359,15 +359,15 @@ func (e *EthAPI) ChainId() (*hexutil.Big, error) { //nolint
// Always returns nil.
func (e *EthAPI) GetUncleByBlockHashAndIndex(
_ common.Hash, _ hexutil.Uint,
) map[string]interface{} {
) map[string]any {
return nil
}

// GetUncleByBlockNumberAndIndex returns the uncle identified by number and
// index. Always returns nil.
func (e *EthAPI) GetUncleByBlockNumberAndIndex(
_, _ hexutil.Uint,
) map[string]interface{} {
) map[string]any {
return nil
}

Expand Down Expand Up @@ -396,7 +396,7 @@ func (e *EthAPI) GetUncleCountByBlockNumber(_ rpc.BlockNumber) hexutil.Uint {
// - highestBlock: block number of the highest block header this node has received from peers
// - pulledStates: number of state entries processed until now
// - knownStates: number of known state entries that still need to be pulled
func (e *EthAPI) Syncing() (interface{}, error) {
func (e *EthAPI) Syncing() (any, error) {
e.logger.Debug("eth_syncing")
return e.backend.Syncing()
}
Expand Down
2 changes: 1 addition & 1 deletion eth/rpc/rpcapi/eth_filters_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -621,7 +621,7 @@ func (api *FiltersAPI) GetFilterLogs(ctx context.Context, id gethrpc.ID) ([]*get
//
// This function implements the "eth_getFilterChanges" JSON-RPC service method.
// https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_getfilterchanges
func (api *FiltersAPI) GetFilterChanges(id gethrpc.ID) (interface{}, error) {
func (api *FiltersAPI) GetFilterChanges(id gethrpc.ID) (any, error) {
api.logger.Debug("eth_getFilterChanges")
api.filtersMu.Lock()
defer api.filtersMu.Unlock()
Expand Down
Loading

0 comments on commit 0afb08f

Please sign in to comment.