Skip to content

Commit

Permalink
sdk: add Atoi function for ChainID
Browse files Browse the repository at this point in the history
  • Loading branch information
johnsaigle committed Jan 23, 2025
1 parent dd283a7 commit dc21be2
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
17 changes: 17 additions & 0 deletions sdk/vaa/structs.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"fmt"
"io"
"math/big"
"slices"
"strconv"
"strings"
"time"

Expand Down Expand Up @@ -262,6 +264,21 @@ func (c ChainID) String() string {
}
}

// Atoi converts from a string representation of an integer into a valid ChainID.
func Atoi(s string) (chainId ChainID, err error) {
u16, err := strconv.ParseUint(s, 0, 16)
if err != nil {
return
}
if !slices.Contains(GetAllNetworkIDs(), ChainID(u16)) {
err = fmt.Errorf("value %s is not a valid chainId", s)
return
}
chainId = ChainID(u16)
return
}

// ChainIDFromString converts from a chain's full name (e.g. "solana") to its corresponding ChainID.
func ChainIDFromString(s string) (ChainID, error) {
s = strings.ToLower(s)

Expand Down
74 changes: 74 additions & 0 deletions sdk/vaa/structs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1111,3 +1111,77 @@ func TestUnmarshalBody(t *testing.T) {
})
}
}

func TestAtoi(t *testing.T) {

happy := []struct {
name string
input string
expected ChainID
}{
{
name: "simple int 1",
input: "1",
expected: ChainIDSolana,
},
{
name: "simple int 2",
input: "3104",
expected: ChainIDWormchain,
},
{
name: "zero is unset",
input: "0",
expected: ChainIDUnset,
},
{
name: "hex is fine",
input: "0x10",
expected: ChainIDMoonbeam,
},
}
for _, tt := range happy {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

actual, err := Atoi(tt.input)
require.Equal(t, tt.expected, actual)
require.NoError(t, err)
})
}

sad := []struct {
name string
input string
}{
{
name: "negative value",
input: "-1",
},
{
name: "NaN",
input: "garbage",
},
{
name: "overflow",
input: "65536",
},
{
name: "not a real chain",
input: "12345",
},
{
name: "empty string",
input: "",
},
}
for _, tt := range sad {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()

actual, err := Atoi(tt.input)
require.Equal(t, ChainIDUnset, actual)
require.Error(t, err)
})
}
}

0 comments on commit dc21be2

Please sign in to comment.