Skip to content

Commit

Permalink
Added ToSnakeCase for discriminators
Browse files Browse the repository at this point in the history
  • Loading branch information
silaslenihan committed Feb 13, 2025
1 parent 2a702c9 commit 31e02b9
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
9 changes: 8 additions & 1 deletion pkg/solana/chainwriter/helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"reflect"
"regexp"
"strings"
"testing"

Expand Down Expand Up @@ -204,12 +205,18 @@ func InitializeDataAccount(
}

func GetDiscriminator(instruction string) [8]byte {
fullHash := sha256.Sum256([]byte("global:" + instruction))
fullHash := sha256.Sum256([]byte("global:" + ToSnakeCase(instruction)))
var discriminator [8]byte
copy(discriminator[:], fullHash[:8])
return discriminator
}

func ToSnakeCase(s string) string {
s = regexp.MustCompile(`([a-z0-9])([A-Z])`).ReplaceAllString(s, "${1}_${2}")
s = regexp.MustCompile(`([A-Z]+)([A-Z][a-z])`).ReplaceAllString(s, "${1}_${2}")
return strings.ToLower(s)
}

func GetRandomPubKey(t *testing.T) solana.PublicKey {
privKey, err := solana.NewRandomPrivateKey()
require.NoError(t, err)
Expand Down
29 changes: 29 additions & 0 deletions pkg/solana/chainwriter/helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package chainwriter_test

import (
"testing"

"github.com/smartcontractkit/chainlink-solana/pkg/solana/chainwriter"
)

func TestToSnakeCase(t *testing.T) {
testCases := []struct {
input string
expected string
}{
{"testCamelCase", "test_camel_case"},
{"oneword", "oneword"},
{"", ""},
{"testCamelCaseWithCAPS", "test_camel_case_with_caps"},
{"testCamelCaseWithCAPSAndNumbers123", "test_camel_case_with_caps_and_numbers123"},
}

for _, tc := range testCases {
t.Run(tc.input, func(t *testing.T) {
actual := chainwriter.ToSnakeCase(tc.input)
if actual != tc.expected {
t.Errorf("expected %s, got %s", tc.expected, actual)
}
})
}
}

0 comments on commit 31e02b9

Please sign in to comment.