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(ibc): utils for erc20 middleware #1081

Merged
merged 7 commits into from
Nov 15, 2022
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -59,6 +59,7 @@ Ref: https://keepachangelog.com/en/1.0.0/
- (docs) [\#980](https://github.com/evmos/evmos/pull/980) Fix documentation links to cosmos-sdk docs.
- (cmd) [\#974](https://github.com/evmos/evmos/pull/974) Add `prune` command.
- (cmd) [\#1027](https://github.com/evmos/evmos/pull/1027) Apply Google CLI Syntax for required and optional args.
- (ibc) [\#1081](https://github.com/evmos/evmos/pull/1081) Added utils functions for ibc denoms.

## [v9.1.0] - 2022-10-25

Expand Down
10 changes: 7 additions & 3 deletions ibc/testing/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (

ethermint "github.com/evmos/ethermint/types"
evmosapp "github.com/evmos/evmos/v10/app"
evmos "github.com/evmos/evmos/v10/types"
)

var DefaultTestingAppInit func() (ibcgotesting.TestingApp, map[string]json.RawMessage) = evmosapp.SetupTestingApp
Expand Down Expand Up @@ -63,19 +64,22 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs
}

// set validators and delegations
stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations)
stakingParams := stakingtypes.DefaultParams()
// set bond demon to be aevmos
stakingParams.BondDenom = evmos.BaseDenom
stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations)
genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis)

totalSupply := sdk.NewCoins()
for _, b := range balances {
// add genesis acc tokens and delegated tokens to total supply
totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(sdk.DefaultBondDenom, bondAmt))...)
totalSupply = totalSupply.Add(b.Coins.Add(sdk.NewCoin(evmos.BaseDenom, bondAmt))...)
}

// add bonded amount to bonded pool module account
balances = append(balances, banktypes.Balance{
Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(),
Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)},
Coins: sdk.Coins{sdk.NewCoin(evmos.BaseDenom, bondAmt)},
})

// update total supply
Expand Down
3 changes: 2 additions & 1 deletion ibc/testing/chain.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/evmos/ethermint/crypto/ethsecp256k1"
ethermint "github.com/evmos/ethermint/types"
evmtypes "github.com/evmos/ethermint/x/evm/types"
evmos "github.com/evmos/evmos/v10/types"
)

// ChainIDPrefix defines the default chain ID prefix for Evmos test chains
Expand Down Expand Up @@ -67,7 +68,7 @@ func NewTestChain(t *testing.T, coord *ibcgotesting.Coordinator, chainID string)

balance := banktypes.Balance{
Address: acc.GetAddress().String(),
Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, amount)),
Coins: sdk.NewCoins(sdk.NewCoin(evmos.BaseDenom, amount)),
}

app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, chainID, balance)
Expand Down
59 changes: 58 additions & 1 deletion ibc/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ func GetTransferSenderRecipient(packet channeltypes.Packet) (
return sender, recipient, data.Sender, data.Receiver, nil
}

// GetTransferAmount returns the amount from an ICS20 FungibleTokenPacketData.
// GetTransferAmount returns the amount from an ICS20 FungibleTokenPacketData as a string.
func GetTransferAmount(packet channeltypes.Packet) (string, error) {
// unmarshal packet data to obtain the sender and recipient
var data transfertypes.FungibleTokenPacketData
Expand All @@ -63,3 +63,60 @@ func GetTransferAmount(packet channeltypes.Packet) (string, error) {

return data.Amount, nil
}

// GetReceivedCoin returns the transferred coin from an ICS20 FungibleTokenPacketData
// as seen from the destination chain.
// If the receiving chain is the source chain of the tokens, it removes the prefix
// path added by source (i.e sender) chain to the denom. Otherwise, it adds the
// prefix path from the destination chain to the denom.
func GetReceivedCoin(srcPort, srcChannel, dstPort, dstChannel, rawDenom, rawAmt string) sdk.Coin {
// NOTE: Denom and amount are already validated
amount, _ := sdk.NewIntFromString(rawAmt)

if transfertypes.ReceiverChainIsSource(srcPort, srcChannel, rawDenom) {
// remove prefix added by sender chain
voucherPrefix := transfertypes.GetDenomPrefix(srcPort, srcChannel)
unprefixedDenom := rawDenom[len(voucherPrefix):]

// coin denomination used in sending from the escrow address
denom := unprefixedDenom

// The denomination used to send the coins is either the native denom or the hash of the path
// if the denomination is not native.
denomTrace := transfertypes.ParseDenomTrace(unprefixedDenom)
if denomTrace.Path != "" {
denom = denomTrace.IBCDenom()
}

return sdk.Coin{
Denom: denom,
Amount: amount,
}
}

// since SendPacket did not prefix the denomination, we must prefix denomination here
sourcePrefix := transfertypes.GetDenomPrefix(dstPort, dstChannel)
// NOTE: sourcePrefix contains the trailing "/"
prefixedDenom := sourcePrefix + rawDenom

// construct the denomination trace from the full raw denomination
denomTrace := transfertypes.ParseDenomTrace(prefixedDenom)
voucherDenom := denomTrace.IBCDenom()

return sdk.Coin{
Denom: voucherDenom,
Amount: amount,
}
}

// GetSentCoin returns the sent coin from an ICS20 FungibleTokenPacketData.
func GetSentCoin(rawDenom, rawAmt string) sdk.Coin {
// NOTE: Denom and amount are already validated
amount, _ := sdk.NewIntFromString(rawAmt)
trace := transfertypes.ParseDenomTrace(rawDenom)

return sdk.Coin{
Denom: trace.IBCDenom(),
Amount: amount,
}
}
131 changes: 131 additions & 0 deletions ibc/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -226,3 +226,134 @@ func TestGetTransferAmount(t *testing.T) {
}
}
}

var (
uosmoDenomtrace = transfertypes.DenomTrace{
Path: "transfer/channel-0",
BaseDenom: "uosmo",
}
uosmoIbcdenom = uosmoDenomtrace.IBCDenom()

uatomDenomtrace = transfertypes.DenomTrace{
Path: "transfer/channel-1",
BaseDenom: "uatom",
}
uatomIbcdenom = uatomDenomtrace.IBCDenom()

aevmosDenomtrace = transfertypes.DenomTrace{
Path: "transfer/channel-0",
BaseDenom: "aevmos",
}
aevmosIbcdenom = aevmosDenomtrace.IBCDenom()

uatomOsmoDenomtrace = transfertypes.DenomTrace{
Path: "transfer/channel-0/transfer/channel-1",
BaseDenom: "uatom",
}
uatomOsmoIbcdenom = uatomOsmoDenomtrace.IBCDenom()
)

func TestGetReceivedCoin(t *testing.T) {

testCases := []struct {
name string
srcPort string
srcChannel string
dstPort string
dstChannel string
rawDenom string
rawAmount string
expCoin sdk.Coin
}{
{
"transfer unwrapped coin to destination which is not its source",
"transfer",
"channel-0",
"transfer",
"channel-0",
"uosmo",
"10",
sdk.Coin{Denom: uosmoIbcdenom, Amount: sdk.NewInt(10)},
},
{
"transfer ibc wrapped coin to destination which is its source",
"transfer",
"channel-0",
"transfer",
"channel-0",
"transfer/channel-0/aevmos",
"10",
sdk.Coin{Denom: "aevmos", Amount: sdk.NewInt(10)},
},
{
"transfer 2x ibc wrapped coin to destination which is its source",
"transfer",
"channel-0",
"transfer",
"channel-2",
"transfer/channel-0/transfer/channel-1/uatom",
"10",
sdk.Coin{Denom: uatomIbcdenom, Amount: sdk.NewInt(10)},
},
{
"transfer ibc wrapped coin to destination which is not its source",
"transfer",
"channel-0",
"transfer",
"channel-0",
"transfer/channel-1/uatom",
"10",
sdk.Coin{Denom: uatomOsmoIbcdenom, Amount: sdk.NewInt(10)},
},
}

for _, tc := range testCases {
coin := GetReceivedCoin(tc.srcPort, tc.srcChannel, tc.dstPort, tc.dstChannel, tc.rawDenom, tc.rawAmount)
require.Equal(t, tc.expCoin, coin)
}
}

func TestGetSentCoin(t *testing.T) {
testCases := []struct {
name string
rawDenom string
rawAmount string
expCoin sdk.Coin
}{
{
"get unwrapped aevmos coin",
"aevmos",
"10",
sdk.Coin{Denom: "aevmos", Amount: sdk.NewInt(10)},
},
{
"get ibc wrapped aevmos coin",
"transfer/channel-0/aevmos",
"10",
sdk.Coin{Denom: aevmosIbcdenom, Amount: sdk.NewInt(10)},
},
{
"get ibc wrapped uosmo coin",
"transfer/channel-0/uosmo",
"10",
sdk.Coin{Denom: uosmoIbcdenom, Amount: sdk.NewInt(10)},
},
{
"get ibc wrapped uatom coin",
"transfer/channel-1/uatom",
"10",
sdk.Coin{Denom: uatomIbcdenom, Amount: sdk.NewInt(10)},
},
{
"get 2x ibc wrapped uatom coin",
"transfer/channel-0/transfer/channel-1/uatom",
"10",
sdk.Coin{Denom: uatomOsmoIbcdenom, Amount: sdk.NewInt(10)},
},
}

for _, tc := range testCases {
coin := GetSentCoin(tc.rawDenom, tc.rawAmount)
require.Equal(t, tc.expCoin, coin)
}
}
8 changes: 8 additions & 0 deletions types/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ const (
MainnetChainID = "evmos_9001"
// TestnetChainID defines the Evmos EIP155 chain ID for testnet
TestnetChainID = "evmos_9000"
// BaseDenom defines the Evmos mainnet denomination
BaseDenom = "aevmos"
)

// IsMainnet returns true if the chain-id has the Evmos mainnet EIP155 chain prefix.
Expand Down Expand Up @@ -80,3 +82,9 @@ func GetEvmosAddressFromBech32(address string) (sdk.AccAddress, error) {

return sdk.AccAddress(addressBz), nil
}

// Include the possibility to use an ERC-20 contract address as coin Denom
// Otherwise Coin Denom validation will fail in some cases (e.g.: transfer ERC-20 tokens through IBC)
func EvmosCoinDenomRegex() string {
return `^0x[a-fA-F0-9]{40}$|^[a-zA-Z][a-zA-Z0-9/:._-]{2,127}`
}
67 changes: 67 additions & 0 deletions types/utils_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package types

import (
"fmt"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -127,3 +128,69 @@ func TestGetEvmosAddressFromBech32(t *testing.T) {
}
}
}

func TestEvmosCoinDenom(t *testing.T) {
sdk.SetCoinDenomRegex(EvmosCoinDenomRegex)
testCases := []struct {
name string
denom string
expError bool
}{
{
"valid denom - native coin",
"aevmos",
false,
},
{
"valid denom - ibc coin",
"ibc/7B2A4F6E798182988D77B6B884919AF617A73503FDAC27C916CD7A69A69013CF",
false,
},
{
"valid denom - ethereum address (ERC-20 contract)",
"0x52908400098527886e0f7030069857D2E4169EE7",
false,
},
{
"invalid denom - only one character",
"a",
true,
},
{
"invalid denom - too large (> 127 chars)",
"ibc/7B2A4F6E798182988D77B6B884919AF617A73503FDAC27C916CD7A69A69013CF7B2A4F6E798182988D77B6B884919AF617A73503FDAC27C916CD7A69A69013CF",
true,
},
{
"invalid denom - starts with 0 but not followed by 'x'",
"0a52908400098527886E0F7030069857D2E4169EE7",
true,
},
{
"invalid denom - hex address but 19 bytes long",
"0x52908400098527886E0F7030069857D2E4169E",
true,
},
{
"invalid denom - hex address but 21 bytes long",
"0x52908400098527886e0f7030069857D2E4169EE738",
true,
},
{
"invalid denom - invalid hex, has a 'g'",
"0x52908400098527886e0f7030069857D2E4169gE7",
true,
},
}

for _, tc := range testCases {
t.Run(fmt.Sprintf("Case %s", tc.name), func(t *testing.T) {
err := sdk.ValidateDenom(tc.denom)
if tc.expError {
require.Error(t, err, tc.name)
} else {
require.NoError(t, err, tc.name)
}
})
}
}