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

Activate EVM test #54

Merged
merged 8 commits into from
Dec 12, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
250 changes: 240 additions & 10 deletions integration_test/integration_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ package integrationtest

import (
"context"
"encoding/hex"
"encoding/json"
"fmt"
"math/big"
"os"
"path/filepath"
"testing"
Expand All @@ -14,6 +16,13 @@ import (
txtypes "github.com/cosmos/cosmos-sdk/types/tx"
stakingtype "github.com/cosmos/cosmos-sdk/x/staking/types"

// evmtypes "github.com/evmos/ethermint/x/evm/types"

abibind "github.com/ethereum/go-ethereum/accounts/abi/bind"
ethcommon "github.com/ethereum/go-ethereum/common"
ethcrypto "github.com/ethereum/go-ethereum/crypto"
web3 "github.com/ethereum/go-ethereum/ethclient"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
)
Expand Down Expand Up @@ -42,6 +51,7 @@ func (i *WASMIntegrationTestSuite) SetupSuite() {

i.UserWallet1, i.UserWallet2, i.ValidatorWallet1 = walletSetup()
}

func (i *WASMIntegrationTestSuite) SetupTest() {
i.UserWallet1, i.UserWallet2, i.ValidatorWallet1 = walletSetup()

Expand All @@ -50,9 +60,7 @@ func (i *WASMIntegrationTestSuite) SetupTest() {
i.ValidatorWallet1.RefreshSequence()
}

func (i *WASMIntegrationTestSuite) TearDownTest() {
//
}
func (i *WASMIntegrationTestSuite) TearDownTest() {}

func (u *WASMIntegrationTestSuite) TearDownSuite() {
desc.CloseConnection()
Expand Down Expand Up @@ -83,7 +91,7 @@ func (t *WASMIntegrationTestSuite) Test01_SimpleDelegation() {
Amount: feeAmt.Ceil().RoundInt(),
}

txhash, err := t.UserWallet1.SendTx(ChainID, delegationMsg, fee, xplaGeneralGasLimit)
txhash, err := t.UserWallet1.SendTx(ChainID, delegationMsg, fee, xplaGeneralGasLimit, false)
assert.NoError(t.T(), err)
assert.NotNil(t.T(), txhash)

Expand Down Expand Up @@ -117,7 +125,7 @@ func (t *WASMIntegrationTestSuite) Test01_SimpleDelegation() {
}

func (t *WASMIntegrationTestSuite) Test02_StoreCode() {
contractBytes, err := os.ReadFile(filepath.Join(".", "misc", "dezswap_token.wasm"))
contractBytes, err := os.ReadFile(filepath.Join(".", "misc", "token.wasm"))
if err != nil {
panic(err)
}
Expand All @@ -134,7 +142,7 @@ func (t *WASMIntegrationTestSuite) Test02_StoreCode() {
Amount: feeAmt.Ceil().RoundInt(),
}

txhash, err := t.UserWallet1.SendTx(ChainID, storeMsg, fee, xplaCodeGasLimit)
txhash, err := t.UserWallet1.SendTx(ChainID, storeMsg, fee, xplaCodeGasLimit, false)

assert.NoError(t.T(), err)
assert.NotNil(t.T(), txhash)
Expand Down Expand Up @@ -183,7 +191,7 @@ func (t *WASMIntegrationTestSuite) Test03_InstantiateContract() {
Amount: feeAmt.Ceil().RoundInt(),
}

txhash, err := t.UserWallet2.SendTx(ChainID, instantiateMsg, fee, xplaGeneralGasLimit)
txhash, err := t.UserWallet2.SendTx(ChainID, instantiateMsg, fee, xplaGeneralGasLimit, false)
assert.NoError(t.T(), err)
assert.NotNil(t.T(), txhash)

Expand Down Expand Up @@ -256,7 +264,7 @@ func (t *WASMIntegrationTestSuite) Test04_ContractExecution() {
Amount: feeAmt.Ceil().RoundInt(),
}

txhash, err := t.UserWallet2.SendTx(ChainID, contractExecMsg, fee, xplaGeneralGasLimit)
txhash, err := t.UserWallet2.SendTx(ChainID, contractExecMsg, fee, xplaGeneralGasLimit, false)
assert.NoError(t.T(), err)
assert.NotNil(t.T(), txhash)

Expand Down Expand Up @@ -290,13 +298,199 @@ func (t *WASMIntegrationTestSuite) Test04_ContractExecution() {
assert.Equal(t.T(), "50000000", amtResp.Balance)
}

// Test strategy
// 1. Check balance
// 2. Contract upload & initiate
// 3. Contract execute
// 4. Contract execute by Cosmos SDK Tx -> available from ethermint v0.20

func TestEVMContractAndTx(t *testing.T) {
if testing.Short() {
t.Skip("skipping test in short mode.")
}

if os.Getenv("GITHUB_BASE_REF") != "hypercube" {
t.Skip("EVM is only available on hypercube!")
}

testSuite := &EVMIntegrationTestSuite{}
suite.Run(t, testSuite)
}

type EVMIntegrationTestSuite struct {
suite.Suite

UserWallet1 *WalletInfo
UserWallet2 *WalletInfo
EthClient *web3.Client

Coinbase string
TokenAddress ethcommon.Address

UserWallet1 *EVMWalletInfo
UserWallet2 *EVMWalletInfo
ValidatorWallet1 *EVMWalletInfo
}

func (t *EVMIntegrationTestSuite) SetupSuite() {
desc = NewServiceDesc("127.0.0.1", 9090, 10, true)

var err error
t.EthClient, err = web3.Dial("http://localhost:8545")
if err != nil {
panic(err)
}

t.UserWallet1, t.UserWallet2, t.ValidatorWallet1 = evmWalletSetup()
}

func (t *EVMIntegrationTestSuite) TearDownSuite() {
desc.CloseConnection()
t.EthClient.Close()
}

func (t *EVMIntegrationTestSuite) SetupTest() {
t.UserWallet1.GetNonce(t.EthClient)
t.UserWallet2.GetNonce(t.EthClient)
t.ValidatorWallet1.GetNonce(t.EthClient)

t.UserWallet1.CosmosWalletInfo.RefreshSequence()
t.UserWallet2.CosmosWalletInfo.RefreshSequence()
t.ValidatorWallet1.CosmosWalletInfo.RefreshSequence()
}

func (i *EVMIntegrationTestSuite) TeardownTest() {}

func (t *EVMIntegrationTestSuite) Test01_CheckBalance() {
resp, err := t.EthClient.BalanceAt(context.Background(), t.UserWallet1.EthAddress, nil)

assert.NoError(t.T(), err)

expectedInt := new(big.Int)
expectedInt, _ = expectedInt.SetString("99000000000000000000", 10)
assert.GreaterOrEqual(t.T(), 1, resp.Cmp(expectedInt))

expectedInt, _ = expectedInt.SetString("100000000000000000000", 10)
assert.LessOrEqual(t.T(), -1, resp.Cmp(expectedInt))
}

func (t *EVMIntegrationTestSuite) Test02_DeployTokenContract() {
// Prepare parameters
networkId, err := t.EthClient.NetworkID(context.Background())
assert.NoError(t.T(), err)

ethPrivkey, _ := ethcrypto.ToECDSA(t.UserWallet1.CosmosWalletInfo.PrivKey.Bytes())
auth, err := abibind.NewKeyedTransactorWithChainID(ethPrivkey, networkId)
assert.NoError(t.T(), err)

auth.GasLimit = uint64(1300000)
auth.GasPrice, _ = new(big.Int).SetString(xplaGasPrice, 10)

strbin, err := os.ReadFile(filepath.Join(".", "misc", "token.sol.bin"))
assert.NoError(t.T(), err)

binbyte, _ := hex.DecodeString(string(strbin))

parsedAbi, err := TokenInterfaceMetaData.GetAbi()
assert.NoError(t.T(), err)
assert.NotNil(t.T(), parsedAbi)

// Actual deploy
address, tx, _, err := abibind.DeployContract(auth, *parsedAbi, binbyte, t.EthClient, "Example Token", "XPLAERC")
assert.NoError(t.T(), err)
fmt.Println("Tx hash: ", tx.Hash().String())

time.Sleep(time.Second * 7)

fmt.Println("Token address: ", address.String())
t.TokenAddress = address
}

func (t *EVMIntegrationTestSuite) Test03_ExecuteTokenContractAndQueryOnEvmJsonRpc() {
// Prepare parameters
networkId, err := t.EthClient.NetworkID(context.Background())
assert.NoError(t.T(), err)

store, err := NewTokenInterface(t.TokenAddress, t.EthClient)
assert.NoError(t.T(), err)

// 10^18
multiplier, _ := new(big.Int).SetString("1000000000000000000", 10)
amt := new(big.Int).Mul(big.NewInt(10), multiplier)

ethPrivkey, _ := ethcrypto.ToECDSA(t.UserWallet1.CosmosWalletInfo.PrivKey.Bytes())
auth, err := abibind.NewKeyedTransactorWithChainID(ethPrivkey, networkId)
assert.NoError(t.T(), err)

auth.GasLimit = uint64(300000)
auth.GasPrice, _ = new(big.Int).SetString(xplaGasPrice, 10)

// try to transfer
tx, err := store.Transfer(auth, t.UserWallet2.EthAddress, amt)
assert.NoError(t.T(), err)
fmt.Println("Sent as ", tx.Hash().String())

time.Sleep(time.Second * 7)

// query & assert
callOpt := &abibind.CallOpts{}
resp, err := store.BalanceOf(callOpt, t.UserWallet2.EthAddress)
assert.NoError(t.T(), err)

assert.Equal(t.T(), amt, resp)
}

// Wrote and tried to test triggering EVM by MsgEthereumTx
// But there is a collision between tx msg caching <> ethermint antehandler
// MsgEthereumTx.From kept left <> ethermint antehandler checks and passes only MsgEthereumTx.From is empty
// It resolves from ethermint v0.20
JoowonYun marked this conversation as resolved.
Show resolved Hide resolved
// Before that, EVM can only be triggered by 8545

// func (t *EVMIntegrationTestSuite) Test04_ExecuteTokenContractAndQueryOnCosmos() {
// store, err := NewTokenInterface(t.TokenAddress, t.EthClient)
// assert.NoError(t.T(), err)

// networkId, err := t.EthClient.NetworkID(context.Background())
// assert.NoError(t.T(), err)

// multiplier, _ := new(big.Int).SetString("1000000000000000000", 10)
// amt := new(big.Int).Mul(big.NewInt(10), multiplier)

// ethPrivkey, _ := ethcrypto.ToECDSA(t.UserWallet1.CosmosWalletInfo.PrivKey.Bytes())
// auth, err := abibind.NewKeyedTransactorWithChainID(ethPrivkey, networkId)
// assert.NoError(t.T(), err)

// auth.NoSend = true
// auth.GasLimit = uint64(xplaGeneralGasLimit)
// auth.GasPrice, _ = new(big.Int).SetString(xplaGasPrice, 10)

// unsentTx, err := store.Transfer(auth, t.UserWallet2.EthAddress, amt)
// assert.NoError(t.T(), err)

// msg := &evmtypes.MsgEthereumTx{}
// err = msg.FromEthereumTx(unsentTx)
// assert.NoError(t.T(), err)

// feeAmt := sdktypes.NewDec(xplaGeneralGasLimit).Mul(sdktypes.MustNewDecFromStr(xplaGasPrice))
// fee := sdktypes.Coin{
// Denom: "axpla",
// Amount: feeAmt.Ceil().RoundInt(),
// }

// txHash, err := t.UserWallet1.CosmosWalletInfo.SendTx(ChainID, msg, fee, xplaGeneralGasLimit, true)
// assert.NoError(t.T(), err)

// err = txCheck(txHash)
// assert.NoError(t.T(), err)

// // check
// callOpt := &abibind.CallOpts{}
// resp, err := store.BalanceOf(callOpt, t.UserWallet2.EthAddress)
// assert.NoError(t.T(), err)

// fmt.Println(resp.String())

// assert.Equal(t.T(), new(big.Int).Add(amt, amt), resp)
// }

func walletSetup() (userWallet1, userWallet2, validatorWallet1 *WalletInfo) {
var err error

Expand Down Expand Up @@ -333,6 +527,42 @@ func walletSetup() (userWallet1, userWallet2, validatorWallet1 *WalletInfo) {
return
}

func evmWalletSetup() (userWallet1, userWallet2, validatorWallet1 *EVMWalletInfo) {
var err error

user1Mnemonics, err := os.ReadFile(filepath.Join(".", "test_keys", "user1.mnemonics"))
if err != nil {
panic(err)
}

userWallet1, err = NewEVMWalletInfo(string(user1Mnemonics))
if err != nil {
panic(err)
}

user2Mnemonics, err := os.ReadFile(filepath.Join(".", "test_keys", "user2.mnemonics"))
if err != nil {
panic(err)
}

userWallet2, err = NewEVMWalletInfo(string(user2Mnemonics))
if err != nil {
panic(err)
}

validator1Mnemonics, err := os.ReadFile(filepath.Join(".", "test_keys", "validator1.mnemonics"))
if err != nil {
panic(err)
}

validatorWallet1, err = NewEVMWalletInfo(string(validator1Mnemonics))
if err != nil {
panic(err)
}

return
}

func txCheck(txHash string) error {
var err error

Expand Down
14 changes: 14 additions & 0 deletions integration_test/misc/token.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v4.0.0/contracts/token/ERC20/ERC20.sol";

contract MyToken is ERC20 {
constructor(string memory name, string memory symbol) ERC20(name, symbol) {
// Mint 100 tokens to msg.sender
// Similar to how
// 1 dollar = 100 cents
// 1 token = 1 * (10 ** decimals)
_mint(msg.sender, 100 * 10**uint(decimals()));
}
}
Loading