Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(evm): Tx to create FunToken mapping from ERC20, contract embeds, and ERC20 queries. #1950

Merged
merged 19 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [#1936](https://github.com/NibiruChain/nibiru/pull/1936) - feat(evm): EVM fungible token protobufs and encoding tests
- [#1947](https://github.com/NibiruChain/nibiru/pull/1947) - fix(evm): fix FunToken state marshalling
- [#1949](https://github.com/NibiruChain/nibiru/pull/1949) - feat(evm): add fungible token mapping queries
- [#1950](https://github.com/NibiruChain/nibiru/pull/1950) - feat(evm): Tx to create FunToken mapping from ERC20, contract embeds, and ERC20 queries.

#### Dapp modules: perp, spot, oracle, etc

Expand Down
6 changes: 3 additions & 3 deletions app/server/config/server_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,8 @@ const (
// DefaultMaxTxGasWanted is the default gas wanted for each eth tx returned in ante handler in check tx mode
DefaultMaxTxGasWanted = 0

// DefaultGasCap is the default cap on gas that can be used in eth_call/estimateGas
DefaultGasCap uint64 = 25000000
// DefaultEthCallGasLimit is the default cap on gas that can be used in eth_call/estimateGas
DefaultEthCallGasLimit uint64 = 25_000_000

// DefaultFilterCap is the default cap for total number of filters that can be created
DefaultFilterCap int32 = 200
Expand Down Expand Up @@ -246,7 +246,7 @@ func DefaultJSONRPCConfig() *JSONRPCConfig {
API: GetDefaultAPINamespaces(),
Address: DefaultJSONRPCAddress,
WsAddress: DefaultJSONRPCWsAddress,
GasCap: DefaultGasCap,
GasCap: DefaultEthCallGasLimit,
EVMTimeout: DefaultEVMTimeout,
TxFeeCap: DefaultTxFeeCap,
FilterCap: DefaultFilterCap,
Expand Down
4 changes: 2 additions & 2 deletions app/server/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -185,8 +185,8 @@ which accepts a path for the resulting pprof file.
cmd.Flags().StringSlice(JSONRPCAPI, config.GetDefaultAPINamespaces(), "Defines a list of JSON-RPC namespaces that should be enabled")
cmd.Flags().String(JSONRPCAddress, config.DefaultJSONRPCAddress, "the JSON-RPC server address to listen on")
cmd.Flags().String(JSONWsAddress, config.DefaultJSONRPCWsAddress, "the JSON-RPC WS server address to listen on")
cmd.Flags().Uint64(JSONRPCGasCap, config.DefaultGasCap, "Sets a cap on gas that can be used in eth_call/estimateGas unit is unibi (0=infinite)") //nolint:lll
cmd.Flags().Float64(JSONRPCTxFeeCap, config.DefaultTxFeeCap, "Sets a cap on transaction fee that can be sent via the RPC APIs (1 = default 1 nibi)") //nolint:lll
cmd.Flags().Uint64(JSONRPCGasCap, config.DefaultEthCallGasLimit, "Sets a cap on gas that can be used in eth_call/estimateGas unit is unibi (0=infinite)") //nolint:lll
cmd.Flags().Float64(JSONRPCTxFeeCap, config.DefaultTxFeeCap, "Sets a cap on transaction fee that can be sent via the RPC APIs (1 = default 1 nibi)") //nolint:lll
Unique-Divine marked this conversation as resolved.
Show resolved Hide resolved
cmd.Flags().Int32(JSONRPCFilterCap, config.DefaultFilterCap, "Sets the global cap for total number of filters that can be created")
cmd.Flags().Duration(JSONRPCEVMTimeout, config.DefaultEVMTimeout, "Sets a timeout used for eth_call (0=infinite)")
cmd.Flags().Duration(JSONRPCHTTPTimeout, config.DefaultHTTPTimeout, "Sets a read/write timeout for json-rpc http server (0=infinite)")
Expand Down
6 changes: 4 additions & 2 deletions eth/rpc/rpcapi/eth_api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (

nibirucommon "github.com/NibiruChain/nibiru/x/common"
"github.com/NibiruChain/nibiru/x/common/denoms"
"github.com/NibiruChain/nibiru/x/evm/embeds"
"github.com/NibiruChain/nibiru/x/evm/evmtest"

"github.com/stretchr/testify/suite"
Expand All @@ -42,7 +43,7 @@ type TestSuite struct {
fundedAccEthAddr gethcommon.Address
fundedAccNibiAddr sdk.AccAddress

contractData evmtest.CompiledEvmContract
contractData embeds.CompiledEvmContract
}

func TestSuite_RunAll(t *testing.T) {
Expand All @@ -63,7 +64,8 @@ func (s *TestSuite) SetupSuite() {
s.network = network
s.ethClient = network.Validators[0].JSONRPCClient

s.contractData = evmtest.SmartContract_FunToken.Load(s.T())
s.contractData, err = embeds.SmartContract_FunToken.Load()
s.Require().NoError(err)

testAccPrivateKey, _ := crypto.GenerateKey()
s.fundedAccPrivateKey = testAccPrivateKey
Expand Down
27 changes: 27 additions & 0 deletions proto/eth/evm/v1/tx.proto
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ service Msg {
// UpdateParams defined a governance operation for updating the x/evm module parameters.
// The authority is hard-coded to the Cosmos SDK x/gov module account
rpc UpdateParams(MsgUpdateParams) returns (MsgUpdateParamsResponse);

// CreateFunToken: Create a "FunToken" mapping. Either the ERC20 contract
// address can be given to create the mapping to a bank coin, or the
// denomination for a bank coin can be given to create the mapping to an ERC20.
rpc CreateFunToken(MsgCreateFunToken) returns (MsgCreateFunTokenResponse);
}

// MsgEthereumTx encapsulates an Ethereum transaction as an SDK message.
Expand Down Expand Up @@ -176,3 +181,25 @@ message MsgUpdateParams {
// MsgUpdateParamsResponse defines the response structure for executing a
// MsgUpdateParams message.
message MsgUpdateParamsResponse {}

// MsgCreateFunToken: Arguments to create a "FunToken" mapping. Either the ERC20
// contract address can be given to create the mapping to a bank coin, or the
// denomination for a bank coin can be given to create the mapping to an ERC20.
message MsgCreateFunToken {
// Hexadecimal address of the ERC20 token to which the `FunToken` maps
string from_erc20 = 1 [
(gogoproto.customtype) = "github.com/NibiruChain/nibiru/eth.HexAddr",
(gogoproto.nullable) = false
];

// Coin denomination in the Bank Module.
string from_bank_denom = 2;

// Sender: Address for the signer of the transaction.
string sender = 3;
}

message MsgCreateFunTokenResponse {
// Fungible token mapping corresponding to ERC20 tokens.
eth.evm.v1.FunToken funtoken_mapping = 1 [(gogoproto.nullable) = false];
}
14 changes: 11 additions & 3 deletions x/common/testutil/cli/network.go
Original file line number Diff line number Diff line change
Expand Up @@ -649,10 +649,18 @@ func (n *Network) Cleanup() {
}
}

for _, v := range n.Validators {
_ = v.tmNode.Stop()
}

// TODO: Is there a cleaner way to do this with a synchronous check?
// https://github.com/NibiruChain/nibiru/issues/1955

Comment on lines +656 to +658
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider addressing the TODO comment.

The TODO comment suggests there might be a better way to handle the cleanup process. Addressing this could improve the robustness of the cleanup function.

Would you like assistance in addressing this TODO comment?

// Give a brief pause for things to finish closing in other processes.
// Hopefully this helps with the address-in-use errors. 100ms chosen
// randomly.
time.Sleep(100 * time.Millisecond)
// Hopefully this helps with the address-in-use errors.
// Timeout of 100ms chosen randomly.
// Timeout of 500ms chosen because 100ms was not enough. | 2024-07-02
time.Sleep(500 * time.Millisecond)

if n.Config.CleanupDir {
_ = os.RemoveAll(n.BaseDir)
Expand Down
22 changes: 19 additions & 3 deletions x/evm/const.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package evm

import (
"github.com/NibiruChain/collections"
"github.com/ethereum/go-ethereum/common"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
gethcommon "github.com/ethereum/go-ethereum/common"
)

const (
Expand Down Expand Up @@ -49,12 +50,12 @@ const (
var KeyPrefixBzAccState = KeyPrefixAccState.Prefix()

// PrefixAccStateEthAddr returns a prefix to iterate over a given account storage.
func PrefixAccStateEthAddr(address common.Address) []byte {
func PrefixAccStateEthAddr(address gethcommon.Address) []byte {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add test coverage for PrefixAccStateEthAddr.

The function PrefixAccStateEthAddr is not covered by tests. Ensure that test cases are added to cover this function.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 53-53: x/evm/const.go#L53
Added line #L53 was not covered by tests

return append(KeyPrefixBzAccState, address.Bytes()...)
}

// StateKey defines the full key under which an account state is stored.
func StateKey(address common.Address, key []byte) []byte {
func StateKey(address gethcommon.Address, key []byte) []byte {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add test coverage for StateKey.

The function StateKey is not covered by tests. Ensure that test cases are added to cover this function.

Do you want me to generate the unit testing code or open a GitHub issue to track this task?

Tools
GitHub Check: codecov/patch

[warning] 58-58: x/evm/const.go#L58
Added line #L58 was not covered by tests

return append(PrefixAccStateEthAddr(address), key...)
}

Expand All @@ -71,3 +72,18 @@ const (
// CallTypeSmart call type is used in case of smart contract methods calls
CallTypeSmart
)

// ModuleAddressEVM: Module account address as a `gethcommon.Address`.
func ModuleAddressEVM() gethcommon.Address {
if evmModuleAddr == zeroAddr {
evmModuleAddr = gethcommon.BytesToAddress(
authtypes.NewModuleAddress(ModuleName).Bytes(),
)
}
return evmModuleAddr
}
Unique-Divine marked this conversation as resolved.
Show resolved Hide resolved

var (
zeroAddr gethcommon.Address
evmModuleAddr gethcommon.Address
)
4 changes: 4 additions & 0 deletions x/evm/deps.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package evm
import (
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
bank "github.com/cosmos/cosmos-sdk/x/bank/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
gethcore "github.com/ethereum/go-ethereum/core"
gethcoretypes "github.com/ethereum/go-ethereum/core/types"
Expand All @@ -29,6 +30,9 @@ type BankKeeper interface {
SendCoinsFromModuleToAccount(ctx sdk.Context, senderModule string, recipientAddr sdk.AccAddress, amt sdk.Coins) error
MintCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error
BurnCoins(ctx sdk.Context, moduleName string, amt sdk.Coins) error

GetDenomMetaData(ctx sdk.Context, denom string) (metadata bank.Metadata, isFound bool)
SetDenomMetaData(ctx sdk.Context, denomMetaData bank.Metadata)
}

// StakingKeeper returns the historical headers kept in store.
Expand Down
76 changes: 76 additions & 0 deletions x/evm/embeds/ERC20Minter.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// SPDX-License-Identifier: MIT

pragma solidity 0.8.19;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

/**
* @dev {ERC20} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
*
* The contract owner is set automatically in the constructor as the
* deployer due to "Ownable".
*
* The Context contract is inherited indirectly through "ERC20" and "Ownable".
*
* The account that deploys the contract will be able to mint and burn tokens.
*/
contract ERC20Minter is ERC20, ERC20Burnable, Ownable {
uint8 private _decimals;

/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE` to the
* account that deploys the contract and customizes tokens decimals
*
* See {ERC20-constructor}.
*/
constructor(string memory name, string memory symbol, uint8 decimals_)
ERC20(name, symbol) {
_setupDecimals(decimals_);
}

/**
* @dev Sets `_decimals` as `decimals_ once at Deployment'
*/
function _setupDecimals(uint8 decimals_) private {
_decimals = decimals_;
}

/**
* @dev Overrides the `decimals()` method with custom `_decimals`
*/
function decimals() public view virtual override returns (uint8) {
return _decimals;
}

/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) public virtual onlyOwner {
_mint(to, amount);
}

/**
* @dev Destroys `amount` new tokens for `to`.
*
* See {ERC20-_burn}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function burnCoins(address from, uint256 amount) public virtual onlyOwner {
_burn(from, amount);
}
Comment on lines +72 to +74
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Clarify the requirements for burnCoins.

The burnCoins function's requirements comment mentions MINTER_ROLE, but the function uses onlyOwner. Clarify or correct the comment.

/**
 * @dev Destroys `amount` tokens from `from`.
 *
 * See {ERC20-_burn}.
 *
 * Requirements:
 *
 * - the caller must be the owner.
 */
function burnCoins(address from, uint256 amount) public virtual onlyOwner {
    _burn(from, amount);
}


}
Loading
Loading