Skip to content

Commit

Permalink
rpcclient: adjust unwrapContract helper
Browse files Browse the repository at this point in the history
There may be no such contract, then Null stackitem is expected on stack.

Signed-off-by: Anna Shaleva <[email protected]>
  • Loading branch information
AnnaShaleva committed Jul 28, 2023
1 parent 081f9d3 commit e57967b
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
9 changes: 8 additions & 1 deletion pkg/rpcclient/management/management.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,23 @@ func (c *ContractReader) GetContract(hash util.Uint160) (*state.Contract, error)
return unwrapContract(c.invoker.Call(Hash, "getContract", hash))
}

// GetContractByID allows to get contract data from its ID.
// GetContractByID allows to get contract data from its ID. In case of missing
// contract it returns nil state.Contract and nil error.
func (c *ContractReader) GetContractByID(id int32) (*state.Contract, error) {
return unwrapContract(c.invoker.Call(Hash, "getContractById", id))
}

// unwrapContract tries to retrieve state.Contract from the provided result.Invoke.
// If the resulting stack contains stackitem.Null, then nil state and nil error
// will be returned.
func unwrapContract(r *result.Invoke, err error) (*state.Contract, error) {
itm, err := unwrap.Item(r, err)
if err != nil {
return nil, err
}
if itm.Equals(stackitem.Null{}) {
return nil, nil
}
res := new(state.Contract)
err = res.FromStackItem(itm)
if err != nil {
Expand Down
13 changes: 12 additions & 1 deletion pkg/rpcclient/management/management_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,17 @@ func TestReader(t *testing.T) {
require.NoError(t, err)
require.False(t, hm)

ta.res = &result.Invoke{
State: "HALT",
Stack: []stackitem.Item{
stackitem.Null{},
},
}

cs, err := man.GetContract(util.Uint160{1, 2, 3})
require.NoError(t, err)
require.Nil(t, cs)

ta.res = &result.Invoke{
State: "HALT",
Stack: []stackitem.Item{
Expand Down Expand Up @@ -127,7 +138,7 @@ func TestReader(t *testing.T) {
}),
},
}
cs, err := man.GetContract(util.Uint160{1, 2, 3})
cs, err = man.GetContract(util.Uint160{1, 2, 3})
require.NoError(t, err)
require.Equal(t, int32(1), cs.ID)
require.Equal(t, uint16(0), cs.UpdateCounter)
Expand Down

0 comments on commit e57967b

Please sign in to comment.