Skip to content

Commit

Permalink
vm: support dict in script builder
Browse files Browse the repository at this point in the history
  • Loading branch information
ixje committed Mar 27, 2023
1 parent d7e2c02 commit 142b2f8
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
11 changes: 11 additions & 0 deletions neo3/vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,17 @@ def emit_push(self, value) -> ScriptBuilder:
self.emit_push(v)
self.emit(OpCode.APPEND)
return self
elif isinstance(value, dict):
for k, v in value.items():
# This restriction exists on the VM side where keys to a 'Map' may only be of 'PrimitiveType'
if not isinstance(k, (int, str, bool)):
raise ValueError(
f"Unsupported key type {type(k)}. Supported types by the VM are bool, int and str"
)
self.emit_push(v)
self.emit_push(k)
self.emit_push(len(value))
self.emit(OpCode.PACKMAP)
else:
raise ValueError(f"Unsupported value type {type(value)}")

Expand Down
17 changes: 17 additions & 0 deletions tests/test_vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,23 @@ def test_emit_push_bytes(self):
# sb.emit_push(data)
# self.assertIn("Value is too long", str(context.exception))

def test_emit_push_dict(self):
data = {"a": 123, "b": 456}

sb = vm.ScriptBuilder()
sb.emit_push(data)
expected = "007b0c016101c8010c016212be"
self.assertEqual(expected, sb.to_array().hex())

# test invalid key type
sb = vm.ScriptBuilder()
with self.assertRaises(ValueError) as context:
sb.emit_push({1.0: "abc"})
self.assertEqual(
"Unsupported key type <class 'float'>. Supported types by the VM are bool, int and str",
str(context.exception),
)

def test_emit_push_unsupported(self):
class Unsupported:
pass
Expand Down

0 comments on commit 142b2f8

Please sign in to comment.