Skip to content

Commit 31e02b9

Browse files
committed
Added ToSnakeCase for discriminators
1 parent 2a702c9 commit 31e02b9

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

pkg/solana/chainwriter/helpers.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"errors"
99
"fmt"
1010
"reflect"
11+
"regexp"
1112
"strings"
1213
"testing"
1314

@@ -204,12 +205,18 @@ func InitializeDataAccount(
204205
}
205206

206207
func GetDiscriminator(instruction string) [8]byte {
207-
fullHash := sha256.Sum256([]byte("global:" + instruction))
208+
fullHash := sha256.Sum256([]byte("global:" + ToSnakeCase(instruction)))
208209
var discriminator [8]byte
209210
copy(discriminator[:], fullHash[:8])
210211
return discriminator
211212
}
212213

214+
func ToSnakeCase(s string) string {
215+
s = regexp.MustCompile(`([a-z0-9])([A-Z])`).ReplaceAllString(s, "${1}_${2}")
216+
s = regexp.MustCompile(`([A-Z]+)([A-Z][a-z])`).ReplaceAllString(s, "${1}_${2}")
217+
return strings.ToLower(s)
218+
}
219+
213220
func GetRandomPubKey(t *testing.T) solana.PublicKey {
214221
privKey, err := solana.NewRandomPrivateKey()
215222
require.NoError(t, err)
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
package chainwriter_test
2+
3+
import (
4+
"testing"
5+
6+
"github.com/smartcontractkit/chainlink-solana/pkg/solana/chainwriter"
7+
)
8+
9+
func TestToSnakeCase(t *testing.T) {
10+
testCases := []struct {
11+
input string
12+
expected string
13+
}{
14+
{"testCamelCase", "test_camel_case"},
15+
{"oneword", "oneword"},
16+
{"", ""},
17+
{"testCamelCaseWithCAPS", "test_camel_case_with_caps"},
18+
{"testCamelCaseWithCAPSAndNumbers123", "test_camel_case_with_caps_and_numbers123"},
19+
}
20+
21+
for _, tc := range testCases {
22+
t.Run(tc.input, func(t *testing.T) {
23+
actual := chainwriter.ToSnakeCase(tc.input)
24+
if actual != tc.expected {
25+
t.Errorf("expected %s, got %s", tc.expected, actual)
26+
}
27+
})
28+
}
29+
}

0 commit comments

Comments
 (0)