Skip to content

Commit

Permalink
ethcoder: helper EventTopicHash function
Browse files Browse the repository at this point in the history
  • Loading branch information
pkieltyka committed Apr 25, 2024
1 parent d996860 commit 25d008f
Show file tree
Hide file tree
Showing 2 changed files with 71 additions and 0 deletions.
47 changes: 47 additions & 0 deletions ethcoder/events.go
Original file line number Diff line number Diff line change
@@ -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
}
24 changes: 24 additions & 0 deletions ethcoder/events_test.go
Original file line number Diff line number Diff line change
@@ -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())
}
}

0 comments on commit 25d008f

Please sign in to comment.