Skip to content

Commit

Permalink
refactor(evm): funtoken tests (#2001)
Browse files Browse the repository at this point in the history
* create funtoken_from_coin_test.go

* refactor FunTokenFromCoinSuite

* create funtoken_from_erc20_test.go

* refactor DeployContract

* refactor MsgCreateFunToken ValidateBasic()

* add test case for TestCreateFunTokenFromERC20

* refactor TestERC20Calls

* move TestSendFunTokenToEvm

* refactor CreateFunTokenFromERC20

* add TestSendFromEvmToCosmos

* remove ApplyEvmMsgWithEmptyTxConfig

* Update CHANGELOG.md
  • Loading branch information
k-yang authored Aug 14, 2024
1 parent fdcda38 commit dbf26bb
Show file tree
Hide file tree
Showing 22 changed files with 615 additions and 611 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- [#1996](https://github.com/NibiruChain/nibiru/pull/1996) - perf(evm-keeper-precompile): implement sorted map for `k.precompiles` to remove dead code
- [#1997](https://github.com/NibiruChain/nibiru/pull/1997) - refactor(evm): Remove unnecessary params: "enable_call", "enable_create".
- [#2000](https://github.com/NibiruChain/nibiru/pull/2000) - refactor(evm): simplify ERC-20 keeper methods
- [#2001](https://github.com/NibiruChain/nibiru/pull/2001) - refactor(evm): simplify FunToken methods and tests

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

Expand Down
2 changes: 1 addition & 1 deletion eth/rpc/backend/call_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (b *Backend) Resend(args evm.JsonTxArgs, gasPrice *hexutil.Big, gasLimit *h

signer := gethcore.LatestSigner(cfg)

matchTx := args.ToTransaction().AsTransaction()
matchTx := args.ToMsgEthTx().AsTransaction()

// Before replacing the old transaction, ensure the _new_ transaction fee is reasonable.
price := matchTx.GasPrice()
Expand Down
2 changes: 1 addition & 1 deletion eth/rpc/backend/sign_tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func (b *Backend) SendTransaction(args evm.JsonTxArgs) (common.Hash, error) {
// the corresponding chainID validation, we need to sign the transaction before calling it

// Sign transaction
msg := args.ToTransaction()
msg := args.ToMsgEthTx()
if err := msg.Sign(signer, b.clientCtx.Keyring); err != nil {
b.logger.Debug("failed to sign tx", "error", err.Error())
return common.Hash{}, err
Expand Down
4 changes: 2 additions & 2 deletions eth/rpc/backend/sign_tx_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ func (s *BackendSuite) TestSendTransaction() {
queryClient := s.backend.queryClient.QueryClient.(*mocks.EVMQueryClient)
RegisterParamsWithoutHeader(queryClient, 1)
ethSigner := gethcore.LatestSigner(s.backend.ChainConfig())
msg := callArgsDefault.ToTransaction()
msg := callArgsDefault.ToMsgEthTx()
err := msg.Sign(ethSigner, s.backend.clientCtx.Keyring)
s.Require().NoError(err)
tc.expHash = msg.AsTransaction().Hash()
Expand Down Expand Up @@ -263,7 +263,7 @@ func broadcastTx(
RegisterBaseFee(queryClient, baseFee)
RegisterParamsWithoutHeader(queryClient, 1)
ethSigner := gethcore.LatestSigner(s.backend.ChainConfig())
msg := callArgsDefault.ToTransaction()
msg := callArgsDefault.ToMsgEthTx()
err = msg.Sign(ethSigner, s.backend.clientCtx.Keyring)
s.Require().NoError(err)
tx, _ := msg.BuildTx(s.backend.clientCtx.TxConfig.NewTxBuilder(), evm.DefaultEVMDenom)
Expand Down
2 changes: 1 addition & 1 deletion eth/rpc/rpcapi/eth_api.go
Original file line number Diff line number Diff line change
Expand Up @@ -471,7 +471,7 @@ func (e *EthAPI) FillTransaction(
}

// Assemble the transaction and obtain rlp
tx := args.ToTransaction().AsTransaction()
tx := args.ToMsgEthTx().AsTransaction()

data, err := tx.MarshalBinary()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion x/evm/evmmodule/genesis_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func (s *Suite) TestExportInitGenesis() {
amountToSendC := big.NewInt(228)

// Create ERC-20 contract
deployResp, err := evmtest.DeployContract(&deps, erc20Contract, s.T())
deployResp, err := evmtest.DeployContract(&deps, erc20Contract)
s.Require().NoError(err)
erc20Addr := deployResp.ContractAddr
totalSupply, err := deps.EvmKeeper.ERC20().LoadERC20BigInt(
Expand Down
51 changes: 27 additions & 24 deletions x/evm/evmtest/tx.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,38 +141,41 @@ type DeployContractResult struct {
func DeployContract(
deps *TestDeps,
contract embeds.CompiledEvmContract,
t *testing.T,
args ...any,
) (result DeployContractResult, err error) {
) (result *DeployContractResult, err error) {
// Use contract args
packedArgs, err := contract.ABI.Pack("", args...)
if err != nil {
err = errors.Wrap(err, "failed to pack ABI args")
return
return nil, errors.Wrap(err, "failed to pack contract args")
}
bytecodeForCall := append(contract.Bytecode, packedArgs...)

nonce := deps.StateDB().GetNonce(deps.Sender.EthAddr)
jsonTxArgs := evm.JsonTxArgs{
Nonce: (*hexutil.Uint64)(&nonce),
Input: (*hexutil.Bytes)(&bytecodeForCall),
From: &deps.Sender.EthAddr,
msgEthTx, err := GenerateAndSignEthTxMsg(
evm.JsonTxArgs{
Nonce: (*hexutil.Uint64)(&nonce),
Input: (*hexutil.Bytes)(&bytecodeForCall),
From: &deps.Sender.EthAddr,
}, deps,
)
if err != nil {
return nil, errors.Wrap(err, "failed to generate and sign eth tx msg")
}
ethTxMsg, err := GenerateAndSignEthTxMsg(jsonTxArgs, deps)
require.NoError(t, err)

resp, err := deps.App.EvmKeeper.EthereumTx(sdk.WrapSDKContext(deps.Ctx), ethTxMsg)
require.NoError(t, err)
require.Empty(t, resp.VmError)

contractAddress := crypto.CreateAddress(deps.Sender.EthAddr, nonce)
resp, err := deps.App.EvmKeeper.EthereumTx(sdk.WrapSDKContext(deps.Ctx), msgEthTx)
if err != nil {
return nil, errors.Wrap(err, "failed to execute ethereum tx")
}
if resp.VmError != "" {
return nil, fmt.Errorf("vm error: %s", resp.VmError)
}

return DeployContractResult{
return &DeployContractResult{
TxResp: resp,
EthTxMsg: ethTxMsg,
EthTxMsg: msgEthTx,
ContractData: contract,
Nonce: nonce,
ContractAddr: contractAddress,
ContractAddr: crypto.CreateAddress(deps.Sender.EthAddr, nonce),
}, nil
}

Expand All @@ -181,7 +184,7 @@ func DeployAndExecuteERC20Transfer(
deps *TestDeps, t *testing.T,
) (*evm.MsgEthereumTx, []*evm.MsgEthereumTx) {
// TX 1: Deploy ERC-20 contract
deployResp, err := DeployContract(deps, embeds.SmartContract_TestERC20, t)
deployResp, err := DeployContract(deps, embeds.SmartContract_TestERC20)
require.NoError(t, err)
contractData := deployResp.ContractData
nonce := deployResp.Nonce
Expand Down Expand Up @@ -217,9 +220,9 @@ func DeployAndExecuteERC20Transfer(

// GenerateAndSignEthTxMsg estimates gas, sets gas limit and sings the tx
func GenerateAndSignEthTxMsg(
txArgs evm.JsonTxArgs, deps *TestDeps,
jsonTxArgs evm.JsonTxArgs, deps *TestDeps,
) (*evm.MsgEthereumTx, error) {
estimateArgs, err := json.Marshal(&txArgs)
estimateArgs, err := json.Marshal(&jsonTxArgs)
if err != nil {
return nil, err
}
Expand All @@ -235,11 +238,11 @@ func GenerateAndSignEthTxMsg(
if err != nil {
return nil, err
}
txArgs.Gas = (*hexutil.Uint64)(&res.Gas)
jsonTxArgs.Gas = (*hexutil.Uint64)(&res.Gas)

msgEthereumTx := txArgs.ToTransaction()
msgEthTx := jsonTxArgs.ToMsgEthTx()
gethSigner := gethcore.LatestSignerForChainID(deps.App.EvmKeeper.EthChainID(deps.Ctx))
return msgEthereumTx, msgEthereumTx.Sign(gethSigner, deps.Sender.KeyringSigner)
return msgEthTx, msgEthTx.Sign(gethSigner, deps.Sender.KeyringSigner)
}

func TransferWei(
Expand Down
4 changes: 2 additions & 2 deletions x/evm/json_tx_args.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ func (args *JsonTxArgs) String() string {
args.AccessList)
}

// ToTransaction converts the arguments to an ethereum transaction.
// ToMsgEthTx converts the arguments to an ethereum transaction.
// This assumes that setTxDefaults has been called.
func (args *JsonTxArgs) ToTransaction() *MsgEthereumTx {
func (args *JsonTxArgs) ToMsgEthTx() *MsgEthereumTx {
var (
chainID, value, gasPrice, maxFeePerGas, maxPriorityFeePerGas sdkmath.Int
gas, nonce uint64
Expand Down
2 changes: 1 addition & 1 deletion x/evm/json_tx_args_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (suite *TxDataTestSuite) TestConvertTxArgsEthTx() {
},
}
for _, tc := range testCases {
res := tc.txArgs.ToTransaction()
res := tc.txArgs.ToMsgEthTx()
suite.Require().NotNil(res)
}
}
Expand Down
21 changes: 9 additions & 12 deletions x/evm/keeper/erc20.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"math/big"

"cosmossdk.io/errors"
sdk "github.com/cosmos/cosmos-sdk/types"
gethabi "github.com/ethereum/go-ethereum/accounts/abi"
gethcommon "github.com/ethereum/go-ethereum/common"
Expand Down Expand Up @@ -137,8 +138,7 @@ func (k Keeper) CallContract(
) (evmResp *evm.MsgEthereumTxResponse, err error) {
contractInput, err := abi.Pack(methodName, args...)
if err != nil {
err = fmt.Errorf("failed to pack ABI args: %w", err)
return
return nil, fmt.Errorf("failed to pack ABI args: %w", err)
}
return k.CallContractWithInput(ctx, fromAcc, contract, commit, contractInput)
}
Expand Down Expand Up @@ -176,7 +176,7 @@ func (k Keeper) CallContractWithInput(
commit, gasLimit, &fromAcc, contract, contractInput, k, ctx,
)
if err != nil {
return evmResp, err
return nil, err
}

unusedBigInt := big.NewInt(0)
Expand All @@ -201,19 +201,19 @@ func (k Keeper) CallContractWithInput(
k.EthChainID(ctx),
)
if err != nil {
return evmResp, fmt.Errorf("failed to load evm config: %s", err)
return nil, errors.Wrapf(err, "failed to load evm config")
}

txConfig := statedb.NewEmptyTxConfig(gethcommon.BytesToHash(ctx.HeaderHash()))
evmResp, err = k.ApplyEvmMsg(
ctx, evmMsg, evm.NewNoOpTracer(), commit, evmCfg, txConfig,
)
if err != nil {
return evmResp, err
return nil, errors.Wrapf(err, "failed to apply EVM message")
}

if evmResp.Failed() {
return evmResp, fmt.Errorf("%w: EVM error: %s", err, evmResp.VmError)
return nil, errors.Wrapf(err, "EVM execution failed: %s", evmResp.VmError)
}

return evmResp, err
Expand Down Expand Up @@ -249,8 +249,7 @@ func computeCommitGasLimit(
Data: (*hexutil.Bytes)(&contractInput),
})
if err != nil {
err = fmt.Errorf("failed compute gas limit to marshal tx args: %w", err)
return
return gasLimit, fmt.Errorf("failed compute gas limit to marshal tx args: %w", err)
}

gasRes, err := k.EstimateGasForEvmCallType(
Expand All @@ -262,12 +261,10 @@ func computeCommitGasLimit(
evm.CallTypeSmart,
)
if err != nil {
err = fmt.Errorf("failed to compute gas limit: %w", err)
return
return gasLimit, fmt.Errorf("failed to compute gas limit: %w", err)
}

newGasLimit = gasRes.Gas
return newGasLimit, nil
return gasRes.Gas, nil
}

func (k Keeper) LoadERC20Name(
Expand Down
Loading

0 comments on commit dbf26bb

Please sign in to comment.