Skip to content

Commit

Permalink
Merge pull request #134 from multiversx/code-metadata-value-from-dict
Browse files Browse the repository at this point in the history
Code Metadata Value from dictionary
  • Loading branch information
popenta authored Nov 1, 2024
2 parents a0c581e + d5094e9 commit fb3d420
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 4 deletions.
12 changes: 11 additions & 1 deletion multiversx_sdk/abi/code_metadata_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,18 @@ def set_payload(self, value: Any):
self.value = CodeMetadata.new_from_bytes(value).serialize()
elif isinstance(value, CodeMetadata):
self.value = value.serialize()
elif isinstance(value, dict):
self.value = self._extract_value_from_dict(value)
else:
raise ValueError(f"cannot set payload for code metadata (should be either a CodeMetadata or bytes, but got: {type(value)})")
raise ValueError(f"cannot set payload for code metadata (should be either a CodeMetadata, bytes or dict, but got: {type(value)})")

def _extract_value_from_dict(self, value: dict[str, str]) -> bytes:
hex_value = value.get("hex", None)

if not hex_value:
raise ValueError("cannot get value from dictionary: missing 'hex' key")

return bytes.fromhex(hex_value)

def get_payload(self) -> Any:
return self.value
Expand Down
11 changes: 9 additions & 2 deletions multiversx_sdk/abi/code_metadata_value_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,16 @@ def test_set_payload_and_get_payload():
value.set_payload(CodeMetadata(upgradeable=True, readable=True, payable=True, payable_by_contract=True))
assert value.get_payload() == bytes([0x05, 0x06])

# From dictionary
value = CodeMetadataValue()
value.set_payload({
"hex": "0500"
})
assert value.get_payload() == bytes([0x05, 0x00])

# With errors
with pytest.raises(ValueError, match=re.escape("cannot set payload for code metadata (should be either a CodeMetadata or bytes, but got: <class 'dict'>)")):
CodeMetadataValue().set_payload({})
with pytest.raises(ValueError, match=re.escape("cannot set payload for code metadata (should be either a CodeMetadata, bytes or dict, but got: <class 'int'>)")):
CodeMetadataValue().set_payload(5)

with pytest.raises(ValueError, match="code metadata buffer has length 4, expected 2"):
CodeMetadataValue().set_payload(bytes([0, 1, 2, 3]))
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ allow-direct-references = true

[project]
name = "multiversx-sdk"
version = "0.16.2"
version = "0.16.3"
authors = [
{ name="MultiversX" },
]
Expand Down

0 comments on commit fb3d420

Please sign in to comment.