github.com/fibonacci-chain/fbc@v0.0.0-20231124064014-c7636198c1e9/x/evm/client/cli/utils_test.go (about)

     1  package cli
     2  
     3  import (
     4  	"testing"
     5  
     6  	"github.com/stretchr/testify/require"
     7  
     8  	sdk "github.com/fibonacci-chain/fbc/libs/cosmos-sdk/types"
     9  
    10  	"github.com/ethereum/go-ethereum/common"
    11  )
    12  
    13  func TestAddressFormats(t *testing.T) {
    14  	testCases := []struct {
    15  		name        string
    16  		addrString  string
    17  		expectedHex string
    18  		expectErr   bool
    19  	}{
    20  		{"Cosmos Address", "cosmos18wvvwfmq77a6d8tza4h5sfuy2yj3jj88yqg82a", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
    21  		{"hex without 0x", "3B98C72760F7BBA69D62ED6F48278451251948E7", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
    22  		{"hex with mixed casing", "3b98C72760f7BBA69D62ED6F48278451251948e7", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
    23  		{"hex with 0x", "0x3B98C72760F7BBA69D62ED6F48278451251948E7", "0x3B98c72760f7BBa69D62ED6f48278451251948e7", false},
    24  		{"invalid hex ethereum address", "0x3B98C72760F7BBA69D62ED6F48278451251948E", "", true},
    25  		{"invalid Cosmos address", "cosmos18wvvwfmq77a6d8tza4h5sfuy2yj3jj88", "", true},
    26  		{"empty string", "", "", true},
    27  	}
    28  
    29  	for _, tc := range testCases {
    30  		tc := tc
    31  		t.Run(tc.name, func(t *testing.T) {
    32  			hex, err := accountToHex(tc.addrString)
    33  			require.Equal(t, tc.expectErr, err != nil, err)
    34  
    35  			if !tc.expectErr {
    36  				require.Equal(t, hex, tc.expectedHex)
    37  			}
    38  		})
    39  	}
    40  }
    41  
    42  func TestCosmosToEthereumTypes(t *testing.T) {
    43  	hexString := "0x3B98D72760f7bbA69d62Ed6F48278451251948E7"
    44  	cosmosAddr, err := sdk.AccAddressFromHex(hexString[2:])
    45  	require.NoError(t, err)
    46  
    47  	cosmosFormatted := cosmosAddr.String()
    48  
    49  	// Test decoding a cosmos formatted address
    50  	decodedHex, err := accountToHex(cosmosFormatted)
    51  	require.NoError(t, err)
    52  	require.Equal(t, hexString, decodedHex)
    53  
    54  	// Test converting cosmos address with eth address from hex
    55  	hexEth := common.HexToAddress(hexString)
    56  	convertedEth := common.BytesToAddress(cosmosAddr.Bytes())
    57  	require.Equal(t, hexEth, convertedEth)
    58  
    59  	// Test decoding eth hex output against hex string
    60  	ethDecoded, err := accountToHex(hexEth.Hex())
    61  	require.NoError(t, err)
    62  	require.Equal(t, hexString, ethDecoded)
    63  }