From d0702c2cf974b45963704ec0e31717d1daba939b Mon Sep 17 00:00:00 2001 From: Roman Khimov Date: Fri, 19 Aug 2022 10:36:44 +0300 Subject: [PATCH] unwrap: provide ArrayOfUint160 It's a popular type as well. --- pkg/rpcclient/unwrap/unwrap.go | 22 ++++++++++++++++++++++ pkg/rpcclient/unwrap/unwrap_test.go | 17 +++++++++++++++++ 2 files changed, 39 insertions(+) diff --git a/pkg/rpcclient/unwrap/unwrap.go b/pkg/rpcclient/unwrap/unwrap.go index fd1d27a90..0e91a3d01 100644 --- a/pkg/rpcclient/unwrap/unwrap.go +++ b/pkg/rpcclient/unwrap/unwrap.go @@ -195,6 +195,28 @@ func ArrayOfBytes(r *result.Invoke, err error) ([][]byte, error) { return res, nil } +// ArrayOfUint160 checks the result for correct state (HALT) and then extracts a +// slice of util.Uint160 from the returned stack item. +func ArrayOfUint160(r *result.Invoke, err error) ([]util.Uint160, error) { + a, err := Array(r, err) + if err != nil { + return nil, err + } + res := make([]util.Uint160, len(a)) + for i := range a { + b, err := a[i].TryBytes() + if err != nil { + return nil, fmt.Errorf("element %d is not a byte string: %w", i, err) + } + u, err := util.Uint160DecodeBytesBE(b) + if err != nil { + return nil, fmt.Errorf("element %d is not a uint160: %w", i, err) + } + res[i] = u + } + return res, nil +} + // ArrayOfPublicKeys checks the result for correct state (HALT) and then // extracts a slice of public keys from the returned stack item. func ArrayOfPublicKeys(r *result.Invoke, err error) (keys.PublicKeys, error) { diff --git a/pkg/rpcclient/unwrap/unwrap_test.go b/pkg/rpcclient/unwrap/unwrap_test.go index 2f895a07e..29606da5c 100644 --- a/pkg/rpcclient/unwrap/unwrap_test.go +++ b/pkg/rpcclient/unwrap/unwrap_test.go @@ -231,6 +231,23 @@ func TestArrayOfBytes(t *testing.T) { require.Equal(t, []byte("some"), a[0]) } +func TestArrayOfUint160(t *testing.T) { + _, err := ArrayOfUint160(&result.Invoke{State: "HALT", Stack: []stackitem.Item{stackitem.Make(42)}}, nil) + require.Error(t, err) + + _, err = ArrayOfUint160(&result.Invoke{State: "HALT", Stack: []stackitem.Item{stackitem.Make([]stackitem.Item{stackitem.Make([]stackitem.Item{})})}}, nil) + require.Error(t, err) + + _, err = ArrayOfUint160(&result.Invoke{State: "HALT", Stack: []stackitem.Item{stackitem.Make([]stackitem.Item{stackitem.Make([]byte("some"))})}}, nil) + require.Error(t, err) + + u160 := util.Uint160{1, 2, 3} + uints, err := ArrayOfUint160(&result.Invoke{State: "HALT", Stack: []stackitem.Item{stackitem.Make([]stackitem.Item{stackitem.Make(u160.BytesBE())})}}, nil) + require.NoError(t, err) + require.Equal(t, 1, len(uints)) + require.Equal(t, u160, uints[0]) +} + func TestArrayOfPublicKeys(t *testing.T) { _, err := ArrayOfPublicKeys(&result.Invoke{State: "HALT", Stack: []stackitem.Item{stackitem.Make(42)}}, nil) require.Error(t, err)