diff --git a/ethcoder/events.go b/ethcoder/events.go new file mode 100644 index 00000000..80082ff5 --- /dev/null +++ b/ethcoder/events.go @@ -0,0 +1,47 @@ +package ethcoder + +import ( + "fmt" + "strings" + + "github.com/0xsequence/ethkit" +) + +// EventTopicHash returns the keccak256 hash of the event signature +// +// e.g. "Transfer(address indexed from, address indexed to, uint256 value)" +// will return 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef +func EventTopicHash(event string) (ethkit.Hash, error) { + eventSig := parseEventSignature(event) + if eventSig == "" { + return ethkit.Hash{}, fmt.Errorf("ethcoder: event format is invalid, expecting Method(arg1,arg2,..)") + } + return Keccak256Hash([]byte(eventSig)), nil +} + +func parseEventSignature(event string) string { + if !strings.Contains(event, "(") || !strings.Contains(event, ")") { + return "" + } + p := strings.Split(event, "(") + if len(p) != 2 { + return "" + } + method := p[0] + + args := strings.TrimSuffix(p[1], ")") + if args == "" { + return fmt.Sprintf("%s()", method) + } + + typs := []string{} + p = strings.Split(args, ",") + for _, a := range p { + typ := strings.Split(strings.TrimSpace(a), " ")[0] + typs = append(typs, typ) + } + + x := fmt.Sprintf("%s(%s)", method, strings.Join(typs, ",")) + fmt.Println(x) + return x +} diff --git a/ethcoder/events_test.go b/ethcoder/events_test.go new file mode 100644 index 00000000..10cda709 --- /dev/null +++ b/ethcoder/events_test.go @@ -0,0 +1,24 @@ +package ethcoder_test + +import ( + "testing" + + "github.com/0xsequence/ethkit/ethcoder" + "github.com/stretchr/testify/require" +) + +func TestEventTopicHash(t *testing.T) { + in := []struct { + event string + }{ + {"Transfer(address indexed from, address indexed to, uint256 value)"}, + {"Transfer(address from, address indexed to, uint256 value)"}, + {"Transfer(address, address , uint256 )"}, + } + + for _, x := range in { + topicHash, err := ethcoder.EventTopicHash(x.event) + require.NoError(t, err) + require.Equal(t, "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef", topicHash.String()) + } +}