Skip to content

Commit

Permalink
refactor code
Browse files Browse the repository at this point in the history
  • Loading branch information
dreamer-zq committed Jul 1, 2024
1 parent 1dfd634 commit 042f58b
Show file tree
Hide file tree
Showing 4 changed files with 174 additions and 165 deletions.
1 change: 1 addition & 0 deletions modules/token/depinject.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ func init() {
)
}

// ProvideKeyTable returns the key table for the Token module
func ProvideKeyTable() types.KeyTable {
return v1.ParamKeyTable() //nolint:staticcheck
}
Expand Down
164 changes: 1 addition & 163 deletions modules/token/keeper/depinject_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
package keeper_test

import (
"context"
"fmt"
"math/big"
"time"

runtimev1alpha1 "cosmossdk.io/api/cosmos/app/runtime/v1alpha1"
Expand All @@ -30,8 +27,6 @@ import (
"cosmossdk.io/core/appconfig"
"google.golang.org/protobuf/types/known/durationpb"

cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
vestingtypes "github.com/cosmos/cosmos-sdk/x/auth/vesting/types"
"github.com/cosmos/cosmos-sdk/x/authz"
Expand All @@ -50,15 +45,9 @@ import (
slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types"
stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types"
upgradetypes "github.com/cosmos/cosmos-sdk/x/upgrade/types"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"

tokenmodule "mods.irisnet.org/api/irismod/token/module/v1"
_ "mods.irisnet.org/modules/token"
"mods.irisnet.org/modules/token/contracts"
tokentypes "mods.irisnet.org/modules/token/types"
)

Expand Down Expand Up @@ -265,155 +254,4 @@ var (
},
},
})
)

var (
_ tokentypes.EVMKeeper = (*evm)(nil)
_ tokentypes.ICS20Keeper = (*transferKeeper)(nil)
)


// ProvideEVMKeeper returns an instance of tokentypes.EVMKeeper.
//
// No parameters.
// Returns a tokentypes.EVMKeeper.
func ProvideEVMKeeper() tokentypes.EVMKeeper {
return &evm{
erc20s: make(map[common.Address]*erc20),
}
}

// ProvideICS20Keeper returns an instance of tokentypes.ICS20Keeper.
//
// No parameters.
// Returns a tokentypes.ICS20Keeper.
func ProvideICS20Keeper() tokentypes.ICS20Keeper {
return &transferKeeper{}
}

type evm struct {
erc20s map[common.Address]*erc20
}

// ApplyMessage implements types.EVMKeeper.
func (e *evm) ApplyMessage(ctx sdk.Context, msg core.Message, tracer vm.EVMLogger, commit bool) (*tokentypes.Result, error) {
isCreate := msg.To() == nil
if isCreate {
contractAddr := crypto.CreateAddress(msg.From(), msg.Nonce())

data := msg.Data()[len(contracts.TokenProxyContract.Bin):]
args, err := contracts.TokenProxyContract.ABI.Constructor.Inputs.Unpack(data)
if err != nil {
return nil, err
}

data = args[1].([]byte)
data = data[4:]
args, err = contracts.ERC20TokenContract.ABI.Methods[contracts.MethodInitialize].Inputs.Unpack(data)
if err != nil {
return nil, err
}

name, _ := args[0].(string)
symbol, _ := args[1].(string)
scale, _ := args[2].(uint8)
e.erc20s[contractAddr] = &erc20{
address: contractAddr,
scale: scale,
name: name,
symbol: symbol,
balance: make(map[common.Address]*big.Int),
}
return &tokentypes.Result{
Hash: contractAddr.Hex(),
}, nil
}

erc20Contract, ok := e.erc20s[*msg.To()]
if !ok {
return nil, fmt.Errorf("erc20 contract not found")
}
return e.dispatch(erc20Contract, msg.Data())
}

// ChainID implements types.EVMKeeper.
func (e *evm) ChainID() *big.Int {
return big.NewInt(16688)
}

// EstimateGas implements types.EVMKeeper.
func (e *evm) EstimateGas(ctx context.Context, req *tokentypes.EthCallRequest) (uint64, error) {
return 3000000, nil
}

// SupportedKey implements types.EVMKeeper.
func (e *evm) SupportedKey(pubKey cryptotypes.PubKey) bool {
return true
}

func (e *evm) dispatch(contract *erc20, data []byte) (*tokentypes.Result, error) {
method, err := contracts.ERC20TokenContract.ABI.MethodById(data[0:4])
if err != nil {
return nil, err
}

ret, err := contract.call(method, data[4:])
if err != nil {
return nil, err
}
return &tokentypes.Result{
Hash: contract.address.Hex(),
Ret: ret,
}, nil
}

type erc20 struct {
address common.Address
scale uint8
name, symbol string

balance map[common.Address]*big.Int
}

func (erc20 erc20) call(method *abi.Method, data []byte) ([]byte, error) {
args, err := method.Inputs.Unpack(data)
if err != nil {
return nil, err
}

switch method.Name {
case "name":
return method.Outputs.Pack(erc20.name)
case "symbol":
return method.Outputs.Pack(erc20.symbol)
case "decimals":
return method.Outputs.Pack(erc20.scale)
case "balanceOf":
balance, ok := erc20.balance[args[0].(common.Address)]
if !ok {
return method.Outputs.Pack(big.NewInt(0))
}
return method.Outputs.Pack(balance)
case "mint":
to := args[0].(common.Address)
balance, ok := erc20.balance[args[0].(common.Address)]
if !ok {
balance = big.NewInt(0)
}
erc20.balance[to] = new(big.Int).Add(balance, args[1].(*big.Int))
return nil, nil
case "burn":
from := args[0].(common.Address)
erc20.balance[from] = new(big.Int).Sub(erc20.balance[from], args[1].(*big.Int))
return nil, nil
default:
return nil, fmt.Errorf("unknown method %s", method.Name)
}
}

type transferKeeper struct{}

// HasTrace implements types.ICS20Keeper.
func (t *transferKeeper) HasTrace(ctx sdk.Context, denom string) bool {
return true
}
)
4 changes: 2 additions & 2 deletions modules/token/keeper/keeper_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,8 @@ func (suite *KeeperTestSuite) SetupTest() {
depInjectOptions := simapp.DepinjectOptions{
Config: AppConfig,
Providers: []interface{}{
ProvideEVMKeeper(),
ProvideICS20Keeper(),
keeper.ProvideMockEVM(),
keeper.ProvideMockICS20(),
},
Consumers: []interface{}{&suite.keeper},
}
Expand Down
170 changes: 170 additions & 0 deletions modules/token/keeper/mock.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
package keeper

import (
"context"
"fmt"
"math/big"

cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/ethereum/go-ethereum/accounts/abi"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core"
"github.com/ethereum/go-ethereum/core/vm"
"github.com/ethereum/go-ethereum/crypto"

"mods.irisnet.org/modules/token/contracts"
tokentypes "mods.irisnet.org/modules/token/types"
)


var (
_ tokentypes.EVMKeeper = (*mockEVM)(nil)
_ tokentypes.ICS20Keeper = (*mockICS20)(nil)
)


// ProvideMockEVM returns an instance of tokentypes.EVMKeeper.
//
// No parameters.
// Returns a tokentypes.EVMKeeper.
func ProvideMockEVM() tokentypes.EVMKeeper {
return &mockEVM{
erc20s: make(map[common.Address]*erc20),
}
}

// ProvideMockICS20 returns an instance of tokentypes.ICS20Keeper.
//
// No parameters.
// Returns a tokentypes.ICS20Keeper.
func ProvideMockICS20() tokentypes.ICS20Keeper {
return &mockICS20{}
}

type mockEVM struct {
erc20s map[common.Address]*erc20
}

// ApplyMessage implements types.EVMKeeper.
func (e *mockEVM) ApplyMessage(ctx sdk.Context, msg core.Message, tracer vm.EVMLogger, commit bool) (*tokentypes.Result, error) {
isCreate := msg.To() == nil
if isCreate {
contractAddr := crypto.CreateAddress(msg.From(), msg.Nonce())

data := msg.Data()[len(contracts.TokenProxyContract.Bin):]
args, err := contracts.TokenProxyContract.ABI.Constructor.Inputs.Unpack(data)
if err != nil {
return nil, err
}

data = args[1].([]byte)
data = data[4:]
args, err = contracts.ERC20TokenContract.ABI.Methods[contracts.MethodInitialize].Inputs.Unpack(data)
if err != nil {
return nil, err
}

name, _ := args[0].(string)
symbol, _ := args[1].(string)
scale, _ := args[2].(uint8)
e.erc20s[contractAddr] = &erc20{
address: contractAddr,
scale: scale,
name: name,
symbol: symbol,
balance: make(map[common.Address]*big.Int),
}
return &tokentypes.Result{
Hash: contractAddr.Hex(),
}, nil
}

erc20Contract, ok := e.erc20s[*msg.To()]
if !ok {
return nil, fmt.Errorf("erc20 contract not found")
}
return e.dispatch(erc20Contract, msg.Data())
}

// ChainID implements types.EVMKeeper.
func (e *mockEVM) ChainID() *big.Int {
return big.NewInt(16688)
}

// EstimateGas implements types.EVMKeeper.
func (e *mockEVM) EstimateGas(ctx context.Context, req *tokentypes.EthCallRequest) (uint64, error) {
return 3000000, nil
}

// SupportedKey implements types.EVMKeeper.
func (e *mockEVM) SupportedKey(pubKey cryptotypes.PubKey) bool {
return true
}

func (e *mockEVM) dispatch(contract *erc20, data []byte) (*tokentypes.Result, error) {
method, err := contracts.ERC20TokenContract.ABI.MethodById(data[0:4])
if err != nil {
return nil, err
}

ret, err := contract.call(method, data[4:])
if err != nil {
return nil, err
}
return &tokentypes.Result{
Hash: contract.address.Hex(),
Ret: ret,
}, nil
}

type erc20 struct {
address common.Address
scale uint8
name, symbol string

balance map[common.Address]*big.Int
}

func (erc20 erc20) call(method *abi.Method, data []byte) ([]byte, error) {
args, err := method.Inputs.Unpack(data)
if err != nil {
return nil, err
}

switch method.Name {
case "name":
return method.Outputs.Pack(erc20.name)
case "symbol":
return method.Outputs.Pack(erc20.symbol)
case "decimals":
return method.Outputs.Pack(erc20.scale)
case "balanceOf":
balance, ok := erc20.balance[args[0].(common.Address)]
if !ok {
return method.Outputs.Pack(big.NewInt(0))
}
return method.Outputs.Pack(balance)
case "mint":
to := args[0].(common.Address)
balance, ok := erc20.balance[args[0].(common.Address)]
if !ok {
balance = big.NewInt(0)
}
erc20.balance[to] = new(big.Int).Add(balance, args[1].(*big.Int))
return nil, nil
case "burn":
from := args[0].(common.Address)
erc20.balance[from] = new(big.Int).Sub(erc20.balance[from], args[1].(*big.Int))
return nil, nil
default:
return nil, fmt.Errorf("unknown method %s", method.Name)
}
}

type mockICS20 struct{}

// HasTrace implements types.ICS20Keeper.
func (t *mockICS20) HasTrace(ctx sdk.Context, denom string) bool {
return true
}

0 comments on commit 042f58b

Please sign in to comment.