rpcclient: adjust unwrapContract helper

There may be no such contract, then Null stackitem is expected on stack.

Signed-off-by: Anna Shaleva <shaleva.ann@nspcc.ru>
This commit is contained in:
Anna Shaleva 2023-07-27 16:28:19 +03:00
parent 081f9d3ac5
commit e57967b11c
2 changed files with 20 additions and 2 deletions

View file

@ -105,16 +105,23 @@ func (c *ContractReader) GetContract(hash util.Uint160) (*state.Contract, error)
return unwrapContract(c.invoker.Call(Hash, "getContract", hash)) 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) { func (c *ContractReader) GetContractByID(id int32) (*state.Contract, error) {
return unwrapContract(c.invoker.Call(Hash, "getContractById", id)) 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) { func unwrapContract(r *result.Invoke, err error) (*state.Contract, error) {
itm, err := unwrap.Item(r, err) itm, err := unwrap.Item(r, err)
if err != nil { if err != nil {
return nil, err return nil, err
} }
if itm.Equals(stackitem.Null{}) {
return nil, nil
}
res := new(state.Contract) res := new(state.Contract)
err = res.FromStackItem(itm) err = res.FromStackItem(itm)
if err != nil { if err != nil {

View file

@ -100,6 +100,17 @@ func TestReader(t *testing.T) {
require.NoError(t, err) require.NoError(t, err)
require.False(t, hm) 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{ ta.res = &result.Invoke{
State: "HALT", State: "HALT",
Stack: []stackitem.Item{ Stack: []stackitem.Item{
@ -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.NoError(t, err)
require.Equal(t, int32(1), cs.ID) require.Equal(t, int32(1), cs.ID)
require.Equal(t, uint16(0), cs.UpdateCounter) require.Equal(t, uint16(0), cs.UpdateCounter)