From 2ddf8a6506a124b124abe80bf4a0165525b575f7 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 19 Jun 2023 13:29:43 -0300 Subject: [PATCH 01/17] #864ewhbru - Have a separate branch for testing the releases before merging it into the master branch --- .circleci/config.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.circleci/config.yml b/.circleci/config.yml index 10737f217..db165873a 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -186,7 +186,7 @@ workflows: only: /.*/ branches: only: - - development + - staging - master - publish-docs: context: aws @@ -197,5 +197,5 @@ workflows: only: /.*/ branches: only: - - development + - staging - master \ No newline at end of file From 7995540b335e8fb96ac6dad48384ce109a1867e4 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 8 May 2023 17:41:14 -0300 Subject: [PATCH 02/17] #864ejf5fm - Add all smart contract related files paths and fix file indexes in sequence point on debug file --- boa3/internal/analyser/moduleanalyser.py | 3 + boa3/internal/compiler/compiler.py | 2 +- .../compiler/filegenerator/__init__.py | 0 .../{ => filegenerator}/filegenerator.py | 334 ++++++++++++------ .../compiler/filegenerator/importdata.py | 34 ++ boa3/internal/model/debuginstruction.py | 2 +- boa3/internal/model/method.py | 1 + boa3/internal/model/type/classes/classtype.py | 14 +- ...=> GenerationWithUserModuleNameImports.py} | 4 +- boa3_test/tests/boa_test.py | 4 +- .../compiler_tests/test_file_generation.py | 79 ++++- docs/ContractExamplesTest.md | 2 +- 12 files changed, 358 insertions(+), 121 deletions(-) create mode 100644 boa3/internal/compiler/filegenerator/__init__.py rename boa3/internal/compiler/{ => filegenerator}/filegenerator.py (66%) create mode 100644 boa3/internal/compiler/filegenerator/importdata.py rename boa3_test/test_sc/generation_test/{GenerationWithUserModuleImportsDupNames.py => GenerationWithUserModuleNameImports.py} (66%) diff --git a/boa3/internal/analyser/moduleanalyser.py b/boa3/internal/analyser/moduleanalyser.py index a92f443e0..b35f5c81a 100644 --- a/boa3/internal/analyser/moduleanalyser.py +++ b/boa3/internal/analyser/moduleanalyser.py @@ -781,6 +781,9 @@ def visit_FunctionDef(self, function: ast.FunctionDef): external_name=external_function_name, is_init=is_class_constructor) + # debug information + method.file_origin = self.filename.replace(os.path.sep, constants.PATH_SEPARATOR) + if function.name in Builtin.internal_methods: internal_method = Builtin.internal_methods[function.name] if not internal_method.is_valid_deploy_method(method): diff --git a/boa3/internal/compiler/compiler.py b/boa3/internal/compiler/compiler.py index e9d4c8f88..5fce48739 100644 --- a/boa3/internal/compiler/compiler.py +++ b/boa3/internal/compiler/compiler.py @@ -5,7 +5,7 @@ from boa3.internal.analyser.analyser import Analyser from boa3.internal.compiler.codegenerator.codegenerator import CodeGenerator from boa3.internal.compiler.compileroutput import CompilerOutput -from boa3.internal.compiler.filegenerator import FileGenerator +from boa3.internal.compiler.filegenerator.filegenerator import FileGenerator from boa3.internal.exception.NotLoadedException import NotLoadedException diff --git a/boa3/internal/compiler/filegenerator/__init__.py b/boa3/internal/compiler/filegenerator/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/boa3/internal/compiler/filegenerator.py b/boa3/internal/compiler/filegenerator/filegenerator.py similarity index 66% rename from boa3/internal/compiler/filegenerator.py rename to boa3/internal/compiler/filegenerator/filegenerator.py index 54993cb35..0b07f8dab 100644 --- a/boa3/internal/compiler/filegenerator.py +++ b/boa3/internal/compiler/filegenerator/filegenerator.py @@ -1,15 +1,19 @@ import json import logging +import os.path from typing import Any, Dict, List, Optional, Tuple from boa3.internal import constants from boa3.internal.analyser.analyser import Analyser from boa3.internal.compiler.compileroutput import CompilerOutput +from boa3.internal.compiler.filegenerator.importdata import ImportData from boa3.internal.model.event import Event from boa3.internal.model.imports.importsymbol import BuiltinImport, Import +from boa3.internal.model.imports.package import Package from boa3.internal.model.method import Method from boa3.internal.model.symbol import ISymbol from boa3.internal.model.type.classes.classtype import ClassType +from boa3.internal.model.type.classes.userclass import UserClass from boa3.internal.model.type.itype import IType from boa3.internal.model.variable import Variable from boa3.internal.neo import to_hex_str @@ -38,6 +42,9 @@ def __init__(self, compiler_result: CompilerOutput, analyser: Analyser, entry_fi self._all_methods: Dict[str, Method] = None self._all_static_vars: Dict[str, Variable] = None + self._inner_methods = None + self._inner_events = None + @property def _public_methods(self) -> Dict[str, Method]: """ @@ -54,9 +61,7 @@ def _static_variables(self) -> Dict[str, Variable]: :return: a dictionary that maps each global variable with its identifier """ - if self._all_static_vars is not None: - return self._all_static_vars - else: + if self._all_static_vars is None: variables: Dict[Tuple[str, str], Variable] = {} imported_symbols: Dict[str, Import] = {} @@ -95,7 +100,7 @@ def _static_variables(self) -> Dict[str, Variable]: self._all_static_vars = {var_id: var for (unique_id, var_id), var in variables.items()} - return self._all_static_vars + return self._all_static_vars @property def _methods(self) -> Dict[str, Method]: @@ -104,51 +109,74 @@ def _methods(self) -> Dict[str, Method]: :return: a dictionary that maps each method with its identifier """ - from boa3.internal.model.builtin.method import IBuiltinMethod - return {name: method for name, method in self._symbols.items() - if ((isinstance(method, Method) and method.defined_by_entry) - or (isinstance(method, IBuiltinMethod) and method.is_public) - )} + if self._inner_methods is None: + from boa3.internal.model.builtin.method import IBuiltinMethod + all_entry_file_methods = {} + for name, symbol in self._symbols.items(): + if isinstance(symbol, Method) and symbol.defined_by_entry: + all_entry_file_methods[name] = symbol + elif isinstance(symbol, IBuiltinMethod) and symbol.is_public: + all_entry_file_methods[name] = symbol + elif isinstance(symbol, UserClass): + for class_method_name, class_method in symbol.methods.items(): + if class_method.defined_by_entry: + all_entry_file_methods[f'{symbol.identifier}.{class_method_name}'] = class_method + + self._inner_methods = all_entry_file_methods + return self._inner_methods @property def _methods_with_imports(self) -> Dict[Tuple[str, str], Method]: - if self._all_methods is not None: - return self._all_methods + if self._all_methods is None: + from boa3.internal.model.builtin.decorator.builtindecorator import IBuiltinCallable - from boa3.internal.model.builtin.decorator.builtindecorator import IBuiltinCallable + methods: Dict[Tuple[str, str], Method] = {} + imported_symbols: Dict[str, Import] = {symbol.origin: symbol for symbol in self._all_imports} - methods: Dict[Tuple[str, str], Method] = {} - imported_symbols: Dict[str, Import] = {} + for name, symbol in self._symbols.items(): + if isinstance(symbol, Method) and not isinstance(symbol, IBuiltinCallable): + if symbol.defined_by_entry: + methods[(self._entry_file, name)] = symbol + elif isinstance(symbol, UserClass): + for class_method_name, class_method in symbol.methods.items(): + if class_method.defined_by_entry and class_method.is_compiled: + methods[(self._entry_file, f'{symbol.identifier}.{class_method_name}')] = class_method + + elif isinstance(symbol, Import) and symbol.origin not in imported_symbols: + imported_symbols[symbol.origin] = symbol - for name, symbol in self._symbols.items(): - if symbol.defined_by_entry and isinstance(symbol, Method) and not isinstance(symbol, IBuiltinCallable): - methods[(self._entry_file, name)] = symbol - elif isinstance(symbol, Import): - imported_symbols[symbol.origin] = symbol + imported_to_map, imports_unique_ids = self._get_imports_unique_ids(imported_symbols, + True, + list(methods.values()) + ) - imported_to_map, imports_unique_ids = self._get_imports_unique_ids(imported_symbols, - True, - list(methods.values()) - ) + if imports_unique_ids[-1] != self._entry_file: + # update entry file to be a unique name + unique_id = imports_unique_ids[-1] + methods = {(unique_id, method_name): method for (module_id, method_name), method in methods.items()} + + # include all user created methods in the list, even the methods that aren't imported in the entry file + for index in range(len(imported_to_map)): + module_full_path, module_import = list(imported_to_map.items())[index] + module_id = imports_unique_ids[index] - if imports_unique_ids[-1] != self._entry_file: - # update entry file to be a unique name - unique_id = imports_unique_ids[-1] - methods = {(unique_id, method_name): method for (module_id, method_name), method in methods.items()} + for name, symbol in module_import.all_symbols.items(): + if (isinstance(symbol, Method) + and not isinstance(symbol, IBuiltinCallable) + and symbol not in [method for method in methods.values()]): + if symbol.file_origin is None and module_import.origin_file in self._files: + symbol.file_origin = module_import.origin_file - # include all user created methods in the list, even the methods that aren't imported in the entry file - for index in range(len(imported_to_map)): - module_full_path, module_import = list(imported_to_map.items())[index] - module_id = imports_unique_ids[index] + methods[(module_id, name)] = symbol + elif isinstance(symbol, UserClass): + for class_method_name, class_method in symbol.methods.items(): + if class_method.file_origin is None and module_import.origin_file in self._files: + class_method.file_origin = module_import.origin_file - for name, symbol in module_import.all_symbols.items(): - if (isinstance(symbol, Method) - and not isinstance(symbol, IBuiltinCallable) - and symbol not in [method for method in methods.values()]): - methods[(module_id, name)] = symbol + methods[(module_id, f'{symbol.identifier}.{class_method_name}')] = class_method - self._all_methods = methods - return methods + self._all_methods = methods + return self._all_methods @property def _events(self) -> Dict[str, Event]: @@ -157,36 +185,62 @@ def _events(self) -> Dict[str, Event]: :return: a dictionary that maps each event with its identifier """ - events = set() - for imported in self._all_imports: - events.update([event for event in imported.all_symbols.values() if isinstance(event, Event)]) - events.update([event for event in self._symbols.values() if isinstance(event, Event)]) + if self._inner_events is None: + events = set() + for imported in self._all_imports: + events.update([event for event in imported.all_symbols.values() if isinstance(event, Event)]) + events.update([event for event in self._symbols.values() if isinstance(event, Event)]) - return {event.name: event for event in events} + self._inner_events = {event.name: event for event in events} + return self._inner_events @property def _all_imports(self) -> List[Import]: - if self.__all_imports is not None: - return self.__all_imports + if self.__all_imports is None: + all_imports = [imported for imported in self._symbols.values() + if (isinstance(imported, (Import, Package)) + and not isinstance(imported, BuiltinImport))] + only_imports = [] + imported_files = [] + + index = 0 + while index < len(all_imports): + imported = all_imports[index] + index += 1 + + if isinstance(imported, Package) and isinstance(imported.origin, Import): + all_imports.append(imported.origin) + file_origin = imported.origin.origin + + for symbol in imported.symbols.values(): + if isinstance(symbol, Method) and symbol.is_compiled and symbol.file_origin is None: + symbol.file_origin = file_origin + if isinstance(symbol, UserClass): + for class_symbol in symbol.symbols.values(): + if isinstance(class_symbol, Method) and class_symbol.file_origin is None: + class_symbol.file_origin = file_origin + + if isinstance(imported, Import): + if imported.origin not in imported_files: + only_imports.append(imported) + imported_files.append(imported.origin) + else: + # import already included + continue + + inner_symbols = imported.all_symbols if hasattr(imported, 'all_symbols') else imported.symbols + for inner in inner_symbols.values(): + if (isinstance(inner, (Import, Package)) + and not isinstance(inner, BuiltinImport) + and inner not in all_imports): + all_imports.append(inner) + + self.__all_imports = list(reversed(only_imports)) # first positions are the most inner imports + # using for instead a generator to keep the result determined + for import_ in imported_files: + if os.path.isfile(import_) and import_ not in self._files: + self._files.append(import_) - all_imports = [imported for imported in self._symbols.values() - if (isinstance(imported, Import) - and not isinstance(imported, BuiltinImport))] - index = 0 - while index < len(all_imports): - imported = all_imports[index] - for inner in imported.all_symbols.values(): - if (isinstance(inner, Import) - and not isinstance(inner, BuiltinImport) - and inner not in all_imports): - all_imports.append(inner) - index += 1 - - self.__all_imports = list(reversed(all_imports)) # first positions are the most inner imports - # using for instead a generator to keep the result determined - for import_ in all_imports: - if import_.origin not in self._files: - self._files.append(import_.origin) return self.__all_imports # region NEF @@ -282,10 +336,10 @@ def _get_abi_methods(self) -> List[Dict[str, Any]]: :return: a dictionary with the abi methods """ - methods = [] - for method_id, method in self._public_methods.items(): - methods.append(self._construct_abi_method(method_id, method)) - return methods + return [ + self._construct_abi_method(method_id, method) + for method_id, method in self._public_methods.items() + ] def _construct_abi_method(self, method_id: str, method: Method) -> Dict[str, Any]: from boa3.internal.compiler.codegenerator.vmcodemapping import VMCodeMapping @@ -441,6 +495,7 @@ def _get_debug_info(self) -> Dict[str, Any]: """ return { "hash": self._nef_hash, + "entrypoint": self._entry_file_full_path, "documents": self._files, "static-variables": self._get_debug_static_variables(), "methods": self._get_debug_methods(), @@ -453,16 +508,36 @@ def _get_debug_methods(self) -> List[Dict[str, Any]]: :return: a dictionary with the methods' debug information """ - return [ - self._get_method_debug_info(module_id, method_id, method) - for (module_id, method_id), method in self._methods_with_imports.items() - if method.is_compiled - ] + method_ids = [] + debug_methods = [] + + for (module_id, method_id), method in self._methods_with_imports.items(): + dbg_method = self._get_method_debug_info(module_id, method_id, method) + dbg_id = dbg_method['id'] + if method.is_compiled and dbg_id not in method_ids: + method_ids.append(dbg_id) + debug_methods.append(dbg_method) + + return debug_methods def _get_method_debug_info(self, module_id: str, method_id: str, method: Method) -> Dict[str, Any]: from boa3.internal.compiler.codegenerator.vmcodemapping import VMCodeMapping from boa3.internal.neo.vm.type.AbiType import AbiType from boa3.internal.model.type.itype import IType + + sequence_points = [] + for instruction in method.debug_map(): + vm_code_map = VMCodeMapping.instance() + start_address = vm_code_map.get_start_address(instruction.code) + end_address = vm_code_map.get_end_address(instruction.code) + if start_address >= method.start_address and end_address <= method.end_address: + sequence_points.append( + '{0}[{1}]{2}:{3}-{4}:{5}'.format(start_address, + self._get_method_origin_index(method), + instruction.start_line, instruction.start_col, + instruction.end_line, instruction.end_col) + ) + return { "id": str(id(method)), "name": '{0},{1}'.format(module_id, method_id), @@ -475,16 +550,13 @@ def _get_method_debug_info(self, module_id: str, method_id: str, method: Method) '{0},{1}'.format(name, var.type.abi_type if isinstance(var.type, IType) else AbiType.Any) for name, var in method.locals.items() ], - "sequence-points": [ - '{0}[{1}]{2}:{3}-{4}:{5}'.format(VMCodeMapping.instance().get_start_address(instruction.code), - self._get_method_origin_index(method), - instruction.start_line, instruction.start_col, - instruction.end_line, instruction.end_col) - for instruction in method.debug_map() - ] + "sequence-points": sequence_points } def _get_method_origin_index(self, method: Method) -> int: + if method.file_origin in self._files: + return self._files.index(method.file_origin) + imported_files: List[Import] = [imported for imported in self._symbols.values() if (isinstance(imported, Import) and not isinstance(imported, BuiltinImport) @@ -508,15 +580,23 @@ def _get_debug_events(self) -> List[Dict[str, Any]]: :return: a dictionary with the event's debug information """ - return [ - { - "id": str(id(event)), + event_ids = [] + debug_events = [] + + for event_id, event in self._events.items(): + dbg_id = str(id(event)) + dbg_event = { + "id": dbg_id, "name": ',{0}'.format(event_id), # TODO: include module name "params": [ '{0},{1}'.format(name, var.type.abi_type) for name, var in event.args.items() ] - } for event_id, event in self._events.items() - ] + } + if dbg_id not in event_ids: + event_ids.append(dbg_id) + debug_events.append(dbg_event) + + return debug_events def _get_debug_static_variables(self) -> List[str]: """ @@ -548,10 +628,10 @@ def _get_debug_static_variables(self) -> List[str]: # endregion def _get_static_var_unique_name(self, variable_id) -> str: - imported_symbols: Dict[str, Import] = {} + imported_symbols: Dict[str, Import] = {symbol.origin: symbol for symbol in self._all_imports} for name, symbol in self._symbols.items(): - if isinstance(symbol, Import): + if isinstance(symbol, Import) and symbol.origin not in imported_symbols: imported_symbols[symbol.origin] = symbol imported_to_map, imports_unique_ids = self._get_imports_unique_ids(imported_symbols, @@ -587,14 +667,12 @@ def _get_static_var_slot_index(self, variable_id) -> Optional[int]: def _get_imports_unique_ids(self, imported_symbols: Dict[str, Import], importing_methods: bool, - inner_imported_symbols: List[ISymbol] = None) -> Tuple[Dict[str, Import], List[str]]: + inner_imported_symbols: List[ISymbol] = None) -> Tuple[Dict[str, ImportData], List[str]]: if not isinstance(imported_symbols, dict): return {}, [] if not isinstance(inner_imported_symbols, list): inner_imported_symbols = [] - from boa3.internal.model.builtin.builtincallable import IBuiltinCallable - # must map all imports, including inner imports index = 0 while index < len(imported_symbols): @@ -605,22 +683,7 @@ def _get_imports_unique_ids(self, imported_symbols: Dict[str, Import], index += 1 # map the modules that have user modules not imported by the entry file - imported_to_map: Dict[str, Import] = {} - for name, imported in imported_symbols.items(): - if isinstance(imported, BuiltinImport): - need_to_map = False - else: - need_to_map = any(not importing_methods # is importing variables or is a method but not builtin - or (((isinstance(symbol, Method) and not isinstance(symbol, IBuiltinCallable)) - or (isinstance(symbol, ClassType) and len(symbol.symbols) > 0) - ) - and symbol not in inner_imported_symbols) - for name, symbol in imported.all_symbols.items()) - if need_to_map: - filtered_name = name.replace('.py', '').replace('/__init__', '') - imported_to_map[filtered_name] = imported_symbols[name] - if name not in self._files: - self._files.append(name) + imported_to_map: Dict[str, ImportData] = self._get_imports_to_map(imported_symbols, importing_methods) # change the full path names to unique small names imports_paths = list(imported_to_map) @@ -657,3 +720,64 @@ def _get_imports_unique_ids(self, imported_symbols: Dict[str, Import], imports_unique_ids.append(short_name) return imported_to_map, imports_unique_ids + + def _get_imports_to_map(self, imported_symbols: Dict[str, Import], + importing_methods: bool) -> Dict[str, ImportData]: + + imported_to_map: Dict[str, ImportData] = {} + inner_packages: List[Tuple[str, Package]] = [] + + for name, imported in imported_symbols.items(): + need_to_map = False + filtered_name = name.replace('.py', '').replace('/__init__', '') + + if not isinstance(imported, BuiltinImport): + for _, symbol in imported.all_symbols.items(): + if isinstance(symbol, Package): + inner_packages.append((filtered_name, symbol)) + + elif self._need_to_map_symbol(symbol, importing_methods): + need_to_map = True + + if need_to_map: + if os.path.isfile(name): + origin_file = name + else: + origin_file = None + + imported_to_map[filtered_name] = ImportData(imported_symbols[name], filtered_name, origin_file) + if isinstance(origin_file, str) and origin_file not in self._files: + self._files.append(origin_file) + + while len(inner_packages) > 0: + origin, package = inner_packages.pop(0) + package_origin = f'{origin}/{package.raw_identifier}' + for child in package.inner_packages.values(): + inner_packages.append((package_origin, child)) + + if isinstance(package.origin, Import): + need_to_map = self._need_to_map_symbol(package.origin, False) + origin_file = package.origin.origin + + if not os.path.isfile(origin_file): + origin_file = None + + if isinstance(origin_file, str) and origin_file not in self._files: + self._files.append(origin_file) + else: + origin_file = None + need_to_map = True + + if need_to_map: + imported_to_map[package_origin] = ImportData(package, package_origin, origin_file) + + return imported_to_map + + def _need_to_map_symbol(self, symbol: ISymbol, importing_methods: bool) -> bool: + from boa3.internal.model.builtin.builtincallable import IBuiltinCallable + + return (not importing_methods # is importing variables or is a method but not builtin + or (((isinstance(symbol, Method) and not isinstance(symbol, IBuiltinCallable)) + or (isinstance(symbol, ClassType) and len(symbol.symbols) > 0) + )) + ) diff --git a/boa3/internal/compiler/filegenerator/importdata.py b/boa3/internal/compiler/filegenerator/importdata.py new file mode 100644 index 000000000..bcab14f08 --- /dev/null +++ b/boa3/internal/compiler/filegenerator/importdata.py @@ -0,0 +1,34 @@ +from typing import Dict + +from boa3.internal.model.symbol import ISymbol + + +class ImportData: + def __init__(self, import_symbol: ISymbol, origin_id: str, origin_file: str = None): + self._imported_symbol = import_symbol + self._origin_id = origin_id + self._origin_file = origin_file + + @property + def origin(self) -> str: + if self._origin_id is not None: + return self._origin_id + + if hasattr(self._imported_symbol, 'origin'): + return self._imported_symbol.origin + + return None + + @property + def origin_file(self) -> str: + return self._origin_file + + @property + def all_symbols(self) -> Dict[str, ISymbol]: + if hasattr(self._imported_symbol, 'all_symbols'): + return self._imported_symbol.all_symbols + + if hasattr(self._imported_symbol, 'symbols'): + return self._imported_symbol.symbols + + return {} diff --git a/boa3/internal/model/debuginstruction.py b/boa3/internal/model/debuginstruction.py index db79a8ea8..48650b2d9 100644 --- a/boa3/internal/model/debuginstruction.py +++ b/boa3/internal/model/debuginstruction.py @@ -26,5 +26,5 @@ def __str__(self) -> str: @classmethod def build(cls, ast_node: ast.AST, bytecode: VMCode) -> DebugInstruction: end_line: int = ast_node.end_lineno if hasattr(ast_node, 'end_lineno') else ast_node.lineno - end_col: int = ast_node.end_col_offset if hasattr(ast_node, 'end_lineno') else ast_node.col_offset + end_col: int = ast_node.end_col_offset + 1 if hasattr(ast_node, 'end_lineno') else ast_node.col_offset return cls(bytecode, ast_node.lineno, ast_node.col_offset, end_line, end_col) diff --git a/boa3/internal/model/method.py b/boa3/internal/model/method.py index 901b9488d..043bc46e1 100644 --- a/boa3/internal/model/method.py +++ b/boa3/internal/model/method.py @@ -43,6 +43,7 @@ def __init__(self, args: Dict[str, Variable] = None, self._debug_map: List[DebugInstruction] = [] self.origin_class: Optional[ClassType] = None + self.file_origin: Optional[str] = None @property def shadowing_name(self) -> str: diff --git a/boa3/internal/model/type/classes/classtype.py b/boa3/internal/model/type/classes/classtype.py index b126808ef..1af82e8ab 100644 --- a/boa3/internal/model/type/classes/classtype.py +++ b/boa3/internal/model/type/classes/classtype.py @@ -118,6 +118,16 @@ def instance_methods(self): instance_funcs.update(base.instance_methods) return instance_funcs + @property + def methods(self): + """ + :rtype: Dict[str, boa3.internal.model.method.Method] + """ + methods = self.static_methods.copy() + methods.update(self.class_methods) + methods.update(self.instance_methods) + return methods + @abstractmethod def constructor_method(self): """ @@ -130,9 +140,7 @@ def constructor_method(self): @property def symbols(self) -> Dict[str, ISymbol]: s = {} - s.update(self.static_methods) - s.update(self.class_methods) - s.update(self.instance_methods) + s.update(self.methods) s.update(self.variables) s.update(self.properties) return s diff --git a/boa3_test/test_sc/generation_test/GenerationWithUserModuleImportsDupNames.py b/boa3_test/test_sc/generation_test/GenerationWithUserModuleNameImports.py similarity index 66% rename from boa3_test/test_sc/generation_test/GenerationWithUserModuleImportsDupNames.py rename to boa3_test/test_sc/generation_test/GenerationWithUserModuleNameImports.py index 1682d9218..58e41eec6 100644 --- a/boa3_test/test_sc/generation_test/GenerationWithUserModuleImportsDupNames.py +++ b/boa3_test/test_sc/generation_test/GenerationWithUserModuleNameImports.py @@ -3,9 +3,9 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.runtime import Notification from boa3.builtin.type import UInt160 -from boa3_test.test_sc.interop_test.runtime.GetNotifications import with_param +from boa3_test.test_sc.interop_test.runtime import GetNotifications @public def main(args: list, key: UInt160) -> List[Notification]: - return with_param(args, key) + return GetNotifications.with_param(args, key) diff --git a/boa3_test/tests/boa_test.py b/boa3_test/tests/boa_test.py index 09bc65564..6fcfde640 100644 --- a/boa3_test/tests/boa_test.py +++ b/boa3_test/tests/boa_test.py @@ -65,7 +65,7 @@ def get_compiler_analyser(self, compiler: Compiler) -> Analyser: return compiler._analyser def get_all_imported_methods(self, compiler: Compiler) -> Dict[str, Method]: - from boa3.internal.compiler.filegenerator import FileGenerator + from boa3.internal.compiler.filegenerator.filegenerator import FileGenerator generator = FileGenerator(compiler.result, compiler._analyser, compiler._entry_smart_contract) return {constants.VARIABLE_NAME_SEPARATOR.join(name): value for name, value in generator._methods_with_imports.items()} @@ -173,6 +173,8 @@ def get_contract_path(self, *args: str) -> str: path = '{0}/{1}'.format(dir_folder, contract_name) if not os.path.isfile(path): raise FileNotFoundError(path) + else: + path = os.path.abspath(path).replace(os.path.sep, constants.PATH_SEPARATOR) return path def get_deploy_file_paths_without_compiling(self, contract_path: str) -> Tuple[str, str]: diff --git a/boa3_test/tests/compiler_tests/test_file_generation.py b/boa3_test/tests/compiler_tests/test_file_generation.py index f49ec6954..c2462ee94 100644 --- a/boa3_test/tests/compiler_tests/test_file_generation.py +++ b/boa3_test/tests/compiler_tests/test_file_generation.py @@ -400,7 +400,8 @@ def test_generate_nefdbgnfo_file(self): debug_info = self.get_debug_info(nef_output) self.assertTrue(os.path.exists(expected_debug_info_output)) - self.assertNotIn('entrypoint', debug_info) + self.assertIn('entrypoint', debug_info) + self.assertEqual(path, debug_info['entrypoint']) self.assertIn('methods', debug_info) self.assertGreater(len(debug_info['methods']), 0) @@ -452,7 +453,8 @@ def test_generate_nefdbgnfo_file_with_event(self): debug_info = self.get_debug_info(nef_output) self.assertTrue(os.path.exists(expected_debug_info_output)) - self.assertNotIn('entrypoint', debug_info) + self.assertIn('entrypoint', debug_info) + self.assertEqual(path, debug_info['entrypoint']) self.assertIn('events', debug_info) self.assertGreater(len(debug_info['events']), 0) @@ -494,7 +496,8 @@ def test_generate_nefdbgnfo_file_with_static_variables(self): debug_info = self.get_debug_info(nef_output) self.assertTrue(os.path.exists(expected_debug_info_output)) - self.assertNotIn('entrypoint', debug_info) + self.assertIn('entrypoint', debug_info) + self.assertEqual(path, debug_info['entrypoint']) self.assertIn('static-variables', debug_info) self.assertGreater(len(debug_info['static-variables']), 0) @@ -516,9 +519,9 @@ def test_generate_nefdbgnfo_file_with_static_variables(self): def test_generate_nefdbgnfo_file_with_user_module_import(self): from boa3.internal.model.type.itype import IType - path = self.get_contract_path('GenerationWithUserModuleImportsDupNames.py') + path = self.get_contract_path('GenerationWithUserModuleImports.py') nef_output, _ = self.get_deploy_file_paths(path) - expected_nef_output = nef_output.replace('.nef', '.nefdbgnfo') + expected_debug_output = nef_output.replace('.nef', '.nefdbgnfo') compiler = Compiler() with LOCK: @@ -532,8 +535,70 @@ def test_generate_nefdbgnfo_file_with_user_module_import(self): debug_info = self.get_debug_info(nef_output) - self.assertTrue(os.path.exists(expected_nef_output)) - self.assertNotIn('entrypoint', debug_info) + self.assertTrue(os.path.exists(expected_debug_output)) + self.assertIn('entrypoint', debug_info) + self.assertEqual(debug_info['entrypoint'], path) + self.assertIn('methods', debug_info) + self.assertGreater(len(debug_info['methods']), 0) + + for debug_method in debug_info['methods']: + self.assertIn('name', debug_method) + name_without_parsing = debug_method['name'] + parsed_name = name_without_parsing.split(constants.VARIABLE_NAME_SEPARATOR) + self.assertEqual(2, len(parsed_name)) + self.assertIn(name_without_parsing, methods) + actual_method = methods[name_without_parsing] + + # validate id + self.assertIn('id', debug_method) + self.assertEqual(str(id(actual_method)), debug_method['id']) + + # validate parameters + self.assertIn('params', debug_method) + self.assertEqual(len(actual_method.args), len(debug_method['params'])) + for var in debug_method['params']: + self.assertEqual(2, len(var.split(constants.VARIABLE_NAME_SEPARATOR))) + param_id, param_type = var.split(constants.VARIABLE_NAME_SEPARATOR) + self.assertIn(param_id, actual_method.args) + self.assertEqual(param_type, actual_method.args[param_id].type.abi_type) + + # validate local variables + self.assertIn('variables', debug_method) + self.assertEqual(len(actual_method.locals), len(debug_method['variables'])) + for var in debug_method['variables']: + self.assertEqual(2, len(var.split(constants.VARIABLE_NAME_SEPARATOR))) + var_id, var_type = var.split(constants.VARIABLE_NAME_SEPARATOR) + self.assertIn(var_id, actual_method.locals) + local_type = actual_method.locals[var_id].type + self.assertEqual(local_type.abi_type if isinstance(local_type, IType) else AbiType.Any, var_type) + + def test_generate_nefdbgnfo_file_with_user_module_name_import(self): + from boa3.internal.model.type.itype import IType + path = self.get_contract_path('test_sc/import_test', 'ImportModuleWithoutInit.py') + imported_path = self.get_contract_path('test_sc/import_test/sample_package/package', 'another_module.py') + nef_output, _ = self.get_deploy_file_paths(path) + expected_debug_output = nef_output.replace('.nef', '.nefdbgnfo') + + compiler = Compiler() + with LOCK: + compiler.compile_and_save(path, nef_output, debug=True) + + methods: Dict[str, Method] = { + name: method + for name, method in self.get_all_imported_methods(compiler).items() + if isinstance(method, Method) + } + + debug_info = self.get_debug_info(nef_output) + + self.assertTrue(os.path.exists(expected_debug_output)) + self.assertIn('entrypoint', debug_info) + self.assertEqual(debug_info['entrypoint'], path) + + self.assertIn('documents', debug_info) + self.assertGreater(len(debug_info['documents']), 1) + self.assertIn(imported_path, debug_info['documents']) + self.assertIn('methods', debug_info) self.assertGreater(len(debug_info['methods']), 0) diff --git a/docs/ContractExamplesTest.md b/docs/ContractExamplesTest.md index a7fe90db1..3ea165bb6 100644 --- a/docs/ContractExamplesTest.md +++ b/docs/ContractExamplesTest.md @@ -543,7 +543,7 @@ #### Import - GenerationWithUserModuleImports.py, -- GenerationWithUserModuleImportsDupNames.py, +- GenerationWithUserModuleNameImports.py, - ImportUserModuleWithNotImportedSymbols.py, - ImportUserModuleWithNotImportedVariables.py From 1ce46242a3d9028c69fe40b107dffbf23d92ae1d Mon Sep 17 00:00:00 2001 From: Erik van den Brink Date: Mon, 22 May 2023 14:52:11 +0200 Subject: [PATCH 03/17] #864emdffj - Fix import error due to incorrect path --- boa3/internal/analyser/importanalyser.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/boa3/internal/analyser/importanalyser.py b/boa3/internal/analyser/importanalyser.py index ce867472b..06a4c0e0b 100644 --- a/boa3/internal/analyser/importanalyser.py +++ b/boa3/internal/analyser/importanalyser.py @@ -53,8 +53,8 @@ def __init__(self, import_target: str, root_folder: str, return importer_file_dir = os.path.dirname(importer_file) - sys.path.append(self.root_folder) - sys.path.append(importer_file_dir) + sys.path.insert(0, self.root_folder) + sys.path.insert(1, importer_file_dir) try: import_spec = importlib.util.find_spec(import_target) module_origin: str = import_spec.origin From 4d17f1e202b1000c72f2f10c0cc02a42c0ca89fa Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 22 May 2023 15:25:04 -0300 Subject: [PATCH 04/17] #861mucfzd - fix incorrect code generated for statics --- .../compiler/codegenerator/codegenerator.py | 80 +++++++++++-------- 1 file changed, 48 insertions(+), 32 deletions(-) diff --git a/boa3/internal/compiler/codegenerator/codegenerator.py b/boa3/internal/compiler/codegenerator/codegenerator.py index 1bb38b98a..f3e99d3c0 100644 --- a/boa3/internal/compiler/codegenerator/codegenerator.py +++ b/boa3/internal/compiler/codegenerator/codegenerator.py @@ -297,7 +297,7 @@ def _module_variables(self, modified_variable: bool) -> List[str]: module_global_ids = [] result_global_vars = [] for var_id, var in self.symbol_table.items(): - if isinstance(var, Variable) and var.is_reassigned == modified_variable: + if isinstance(var, Variable) and var.is_reassigned == modified_variable and var not in result_global_vars: module_global_variables.append((var_id, var)) module_global_ids.append(var_id) result_global_vars.append(var) @@ -399,41 +399,57 @@ def get_symbol(self, identifier: str, scope: Optional[ISymbol] = None, is_intern if isinstance(self.additional_symbols, dict): cur_symbol_table.update(self.additional_symbols) + found_id = None + found_symbol = None if len(self._scope_stack) > 0: for symbol_scope in self._scope_stack: if identifier in symbol_scope: - return identifier, symbol_scope[identifier] + found_id, found_symbol = identifier, symbol_scope[identifier] + break - if scope is not None and hasattr(scope, 'symbols') and isinstance(scope.symbols, dict): - if identifier in scope.symbols and isinstance(scope.symbols[identifier], ISymbol): - return identifier, scope.symbols[identifier] - else: - if self._current_method is not None and identifier in self._current_method.symbols: - return identifier, self._current_method.symbols[identifier] - elif identifier in cur_symbol_table: - return identifier, cur_symbol_table[identifier] - - # the symbol may be a built in. If not, returns None - symbol = Builtin.get_symbol(identifier) - if symbol is not None: - return identifier, symbol - - if not isinstance(identifier, str): - return identifier, symbol - split = identifier.split(constants.ATTRIBUTE_NAME_SEPARATOR) - if len(split) > 1: - attribute, symbol_id = constants.ATTRIBUTE_NAME_SEPARATOR.join(split[:-1]), split[-1] - another_attr_id, attr = self.get_symbol(attribute, is_internal=is_internal) - if hasattr(attr, 'symbols') and symbol_id in attr.symbols: - return symbol_id, attr.symbols[symbol_id] - elif isinstance(attr, Package) and symbol_id in attr.inner_packages: - return symbol_id, attr.inner_packages[symbol_id] - - if is_internal: - from boa3.internal.model import imports - found_symbol = imports.builtin.get_internal_symbol(identifier) - if isinstance(found_symbol, ISymbol): - return identifier, found_symbol + if found_id is None: + if scope is not None and hasattr(scope, 'symbols') and isinstance(scope.symbols, dict): + if identifier in scope.symbols and isinstance(scope.symbols[identifier], ISymbol): + found_id, found_symbol = identifier, scope.symbols[identifier] + else: + if self._current_method is not None and identifier in self._current_method.symbols: + found_id, found_symbol = identifier, self._current_method.symbols[identifier] + elif identifier in cur_symbol_table: + found_id, found_symbol = identifier, cur_symbol_table[identifier] + else: + # the symbol may be a built-in. If not, returns None + symbol = Builtin.get_symbol(identifier) + if symbol is not None: + found_id, found_symbol = identifier, symbol + + elif not isinstance(identifier, str): + found_id, found_symbol = identifier, symbol + + else: + split = identifier.split(constants.ATTRIBUTE_NAME_SEPARATOR) + if len(split) > 1: + attribute, symbol_id = constants.ATTRIBUTE_NAME_SEPARATOR.join(split[:-1]), split[-1] + another_attr_id, attr = self.get_symbol(attribute, is_internal=is_internal) + if hasattr(attr, 'symbols') and symbol_id in attr.symbols: + found_id, found_symbol = symbol_id, attr.symbols[symbol_id] + elif isinstance(attr, Package) and symbol_id in attr.inner_packages: + found_id, found_symbol = symbol_id, attr.inner_packages[symbol_id] + + if found_id is None and is_internal: + from boa3.internal.model import imports + found_symbol = imports.builtin.get_internal_symbol(identifier) + if isinstance(found_symbol, ISymbol): + found_id = identifier + + if found_id is not None: + if isinstance(found_symbol, Variable) and not found_symbol.is_reassigned and found_id not in self._statics: + # verifies if it's a static variable with a unique name + for static_id, static_var in self._static_vars: + if found_symbol == static_var: + found_id = static_id + break + + return found_id, found_symbol return identifier, Type.none def initialize_static_fields(self) -> bool: From c07752b3c78ce197707e8b129eb13ebd98f416ac Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 23 May 2023 12:32:34 -0300 Subject: [PATCH 05/17] #861murnz7 - storage.find FindOptions are ignored and generates incorrect code --- boa3/internal/compiler/codegenerator/codegenerator.py | 3 +++ boa3/internal/model/builtin/interop/interop.py | 8 +++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/boa3/internal/compiler/codegenerator/codegenerator.py b/boa3/internal/compiler/codegenerator/codegenerator.py index f3e99d3c0..b1b541bba 100644 --- a/boa3/internal/compiler/codegenerator/codegenerator.py +++ b/boa3/internal/compiler/codegenerator/codegenerator.py @@ -419,6 +419,9 @@ def get_symbol(self, identifier: str, scope: Optional[ISymbol] = None, is_intern else: # the symbol may be a built-in. If not, returns None symbol = Builtin.get_symbol(identifier) + if symbol is None: + symbol = Interop.get_symbol(identifier) + if symbol is not None: found_id, found_symbol = identifier, symbol diff --git a/boa3/internal/model/builtin/interop/interop.py b/boa3/internal/model/builtin/interop/interop.py index 8ded6e403..fa1c74b79 100644 --- a/boa3/internal/model/builtin/interop/interop.py +++ b/boa3/internal/model/builtin/interop/interop.py @@ -1,5 +1,5 @@ from enum import Enum -from typing import Dict, List +from typing import Dict, List, Optional from boa3.internal.model.builtin.interop.blockchain import * from boa3.internal.model.builtin.interop.contract import * @@ -38,6 +38,12 @@ class InteropPackage(str, Enum): class Interop: + @classmethod + def get_symbol(cls, symbol_id: str) -> Optional[IdentifiedSymbol]: + for pkg_symbols in cls._interop_symbols.values(): + for method in pkg_symbols: + if method.identifier == symbol_id: + return method @classmethod def interop_symbols(cls, package: str = None) -> List[IdentifiedSymbol]: From 024de78054333bb24d191ba8d1769a7696ec3d07 Mon Sep 17 00:00:00 2001 From: luc10921 Date: Tue, 23 May 2023 14:58:22 -0300 Subject: [PATCH 06/17] CU-861murv23 - unresolved reference 'Iterator' --- boa3/builtin/compile_time/__init__.py | 9 +++++++ boa3/builtin/contract/__init__.py | 9 +++++++ boa3/builtin/interop/blockchain/__init__.py | 16 +++++++++++++ boa3/builtin/interop/blockchain/block.py | 4 ++++ boa3/builtin/interop/blockchain/signer.py | 9 +++++++ .../builtin/interop/blockchain/transaction.py | 4 ++++ boa3/builtin/interop/contract/__init__.py | 18 ++++++++++++++ boa3/builtin/interop/contract/contract.py | 4 ++++ .../interop/contract/contractmanifest.py | 12 ++++++++++ boa3/builtin/interop/crypto/__init__.py | 13 ++++++++++ boa3/builtin/interop/iterator/__init__.py | 5 ++++ boa3/builtin/interop/json/__init__.py | 6 +++++ boa3/builtin/interop/policy/__init__.py | 8 +++++++ boa3/builtin/interop/role/__init__.py | 6 +++++ boa3/builtin/interop/runtime/__init__.py | 24 +++++++++++++++++++ boa3/builtin/interop/runtime/notification.py | 3 +++ boa3/builtin/interop/stdlib/__init__.py | 16 +++++++++++++ boa3/builtin/interop/storage/__init__.py | 13 ++++++++++ .../builtin/interop/storage/storagecontext.py | 2 ++ boa3/builtin/interop/storage/storagemap.py | 2 ++ boa3/builtin/nativecontract/__init__.py | 21 ++++++++++++++++ .../nativecontract/contractmanagement.py | 6 +++++ boa3/builtin/nativecontract/cryptolib.py | 5 ++++ boa3/builtin/nativecontract/gas.py | 5 ++++ boa3/builtin/nativecontract/ledger.py | 5 ++++ boa3/builtin/nativecontract/neo.py | 5 ++++ boa3/builtin/nativecontract/oracle.py | 5 ++++ boa3/builtin/nativecontract/policy.py | 5 ++++ boa3/builtin/nativecontract/rolemanagement.py | 6 +++++ boa3/builtin/nativecontract/stdlib.py | 5 ++++ boa3/builtin/type/__init__.py | 14 +++++++++++ .../internal/model/builtin/interop/interop.py | 7 +++++- .../model/builtin/native/nativecontract.py | 7 ++---- 33 files changed, 273 insertions(+), 6 deletions(-) diff --git a/boa3/builtin/compile_time/__init__.py b/boa3/builtin/compile_time/__init__.py index 72bc99558..3f9b8206a 100644 --- a/boa3/builtin/compile_time/__init__.py +++ b/boa3/builtin/compile_time/__init__.py @@ -1,3 +1,12 @@ +__all__ = [ + 'CreateNewEvent', + 'public', + 'metadata', + 'contract', + 'display_name', + 'NeoMetadata', +] + from typing import List, Dict, Any, Union, Optional, Tuple from boa3.builtin.type import ByteString, Event diff --git a/boa3/builtin/contract/__init__.py b/boa3/builtin/contract/__init__.py index c795e0063..215810b88 100644 --- a/boa3/builtin/contract/__init__.py +++ b/boa3/builtin/contract/__init__.py @@ -1,3 +1,12 @@ +__all__ = [ + 'Nep5TransferEvent', + 'Nep11TransferEvent', + 'Nep17TransferEvent', + 'abort', + 'NeoAccountState', + 'to_script_hash', +] + from typing import Union, Any from boa3.builtin.compile_time import CreateNewEvent diff --git a/boa3/builtin/interop/blockchain/__init__.py b/boa3/builtin/interop/blockchain/__init__.py index d5c501964..47dc0af35 100644 --- a/boa3/builtin/interop/blockchain/__init__.py +++ b/boa3/builtin/interop/blockchain/__init__.py @@ -1,3 +1,19 @@ +__all__ = [ + 'Block', + 'Signer', + 'Transaction', + 'VMState', + 'get_contract', + 'get_block', + 'get_transaction', + 'get_transaction_from_block', + 'get_transaction_height', + 'get_transaction_signers', + 'get_transaction_vm_state', + 'current_hash', + 'current_index', +] + from typing import List, Union from boa3.builtin.interop.blockchain.block import Block diff --git a/boa3/builtin/interop/blockchain/block.py b/boa3/builtin/interop/blockchain/block.py index f4a93a796..aa5880a07 100644 --- a/boa3/builtin/interop/blockchain/block.py +++ b/boa3/builtin/interop/blockchain/block.py @@ -1,3 +1,7 @@ +__all__ = [ + 'Block' +] + from boa3.builtin.type import UInt160, UInt256 diff --git a/boa3/builtin/interop/blockchain/signer.py b/boa3/builtin/interop/blockchain/signer.py index 938fe4847..fad37fee3 100644 --- a/boa3/builtin/interop/blockchain/signer.py +++ b/boa3/builtin/interop/blockchain/signer.py @@ -1,3 +1,12 @@ +__all__ = [ + "Signer", + "WitnessRule", + "WitnessCondition", + "WitnessConditionType", + "WitnessRuleAction", + "WitnessScope", +] + from typing import List from boa3.builtin.type import UInt160 diff --git a/boa3/builtin/interop/blockchain/transaction.py b/boa3/builtin/interop/blockchain/transaction.py index 865694f6d..c9eaf16bd 100644 --- a/boa3/builtin/interop/blockchain/transaction.py +++ b/boa3/builtin/interop/blockchain/transaction.py @@ -1,3 +1,7 @@ +__all__ = [ + 'Transaction', +] + from boa3.builtin.type import UInt160, UInt256 diff --git a/boa3/builtin/interop/contract/__init__.py b/boa3/builtin/interop/contract/__init__.py index 1a3ed13ac..daf82a857 100644 --- a/boa3/builtin/interop/contract/__init__.py +++ b/boa3/builtin/interop/contract/__init__.py @@ -1,7 +1,25 @@ +__all__ = [ + 'CallFlags', + 'Contract', + 'ContractManifest', + 'call_contract', + 'create_contract', + 'update_contract', + 'destroy_contract', + 'get_minimum_deployment_fee', + 'get_call_flags', + 'create_standard_account', + 'create_multisig_account', + 'NEO', + 'GAS', +] + + from typing import Any, List, Sequence from boa3.builtin.interop.contract.callflagstype import CallFlags from boa3.builtin.interop.contract.contract import Contract +from boa3.builtin.interop.contract.contractmanifest import ContractManifest from boa3.builtin.type import ECPoint, UInt160 diff --git a/boa3/builtin/interop/contract/contract.py b/boa3/builtin/interop/contract/contract.py index 35570a513..4775d88b2 100644 --- a/boa3/builtin/interop/contract/contract.py +++ b/boa3/builtin/interop/contract/contract.py @@ -1,3 +1,7 @@ +__all__ = [ + 'Contract', +] + from boa3.builtin.interop.contract.contractmanifest import ContractManifest from boa3.builtin.type import UInt160 diff --git a/boa3/builtin/interop/contract/contractmanifest.py b/boa3/builtin/interop/contract/contractmanifest.py index fb4bbcfad..514b351df 100644 --- a/boa3/builtin/interop/contract/contractmanifest.py +++ b/boa3/builtin/interop/contract/contractmanifest.py @@ -1,3 +1,15 @@ +__all__ = [ + 'ContractManifest', + 'ContractPermission', + 'ContractPermissionDescriptor', + 'ContractGroup', + 'ContractAbi', + 'ContractMethodDescriptor', + 'ContractEventDescriptor', + 'ContractParameterDefinition', + 'ContractParameterType', +] + from typing import List, Optional from boa3.builtin.type import ECPoint, UInt160 diff --git a/boa3/builtin/interop/crypto/__init__.py b/boa3/builtin/interop/crypto/__init__.py index 2c06c9042..28a50cba1 100644 --- a/boa3/builtin/interop/crypto/__init__.py +++ b/boa3/builtin/interop/crypto/__init__.py @@ -1,3 +1,16 @@ +__all__ = [ + 'NamedCurve', + 'sha256', + 'ripemd160', + 'hash160', + 'hash256', + 'check_sig', + 'check_multisig', + 'verify_with_ecdsa', + 'murmur32', +] + + from typing import Any, List from boa3.builtin.interop.crypto.namedcurve import NamedCurve diff --git a/boa3/builtin/interop/iterator/__init__.py b/boa3/builtin/interop/iterator/__init__.py index 97e1c122a..cdecd2216 100644 --- a/boa3/builtin/interop/iterator/__init__.py +++ b/boa3/builtin/interop/iterator/__init__.py @@ -1,5 +1,10 @@ from __future__ import annotations +__all__ = [ + 'Iterator', +] + + from typing import Any diff --git a/boa3/builtin/interop/json/__init__.py b/boa3/builtin/interop/json/__init__.py index 4941bb785..6fe41e252 100644 --- a/boa3/builtin/interop/json/__init__.py +++ b/boa3/builtin/interop/json/__init__.py @@ -1,3 +1,9 @@ +__all__ = [ + 'json_serialize', + 'json_deserialize', +] + + from typing import Any diff --git a/boa3/builtin/interop/policy/__init__.py b/boa3/builtin/interop/policy/__init__.py index 08bfc750a..f246b6207 100644 --- a/boa3/builtin/interop/policy/__init__.py +++ b/boa3/builtin/interop/policy/__init__.py @@ -1,3 +1,11 @@ +__all__ = [ + 'get_exec_fee_factor', + 'get_fee_per_byte', + 'get_storage_price', + 'is_blocked', +] + + from boa3.builtin.type import UInt160 diff --git a/boa3/builtin/interop/role/__init__.py b/boa3/builtin/interop/role/__init__.py index 999dee236..a4bfa7262 100644 --- a/boa3/builtin/interop/role/__init__.py +++ b/boa3/builtin/interop/role/__init__.py @@ -1,3 +1,9 @@ +__all__ = [ + 'Role', + 'get_designated_by_role', +] + + from boa3.builtin.interop.role.roletype import Role from boa3.builtin.type import ECPoint diff --git a/boa3/builtin/interop/runtime/__init__.py b/boa3/builtin/interop/runtime/__init__.py index d033981a9..f0c7eea11 100644 --- a/boa3/builtin/interop/runtime/__init__.py +++ b/boa3/builtin/interop/runtime/__init__.py @@ -1,3 +1,27 @@ +__all__ = [ + 'Notification', + 'TriggerType', + 'check_witness', + 'notify', + 'log', + 'get_trigger', + 'get_notifications', + 'get_network', + 'burn_gas', + 'get_random', + 'load_script', + 'address_version', + 'executing_script_hash', + 'calling_script_hash', + 'time', + 'gas_left', + 'platform', + 'invocation_counter', + 'entry_script_hash', + 'script_container', +] + + from typing import Any, List, Union, Sequence from boa3.builtin.interop.contract.callflagstype import CallFlags diff --git a/boa3/builtin/interop/runtime/notification.py b/boa3/builtin/interop/runtime/notification.py index 8fa2fead7..4da4aaded 100644 --- a/boa3/builtin/interop/runtime/notification.py +++ b/boa3/builtin/interop/runtime/notification.py @@ -1,3 +1,6 @@ +__all__ = ['Notification'] + + from boa3.builtin.type import UInt160 diff --git a/boa3/builtin/interop/stdlib/__init__.py b/boa3/builtin/interop/stdlib/__init__.py index e10cd8c8a..ed358f431 100644 --- a/boa3/builtin/interop/stdlib/__init__.py +++ b/boa3/builtin/interop/stdlib/__init__.py @@ -1,3 +1,19 @@ +__all__ = [ + 'base58_encode', + 'base58_decode', + 'base58_check_encode', + 'base58_check_decode', + 'base64_encode', + 'base64_decode', + 'serialize', + 'deserialize', + 'atoi', + 'itoa', + 'memory_search', + 'memory_compare', +] + + from typing import Any from boa3.builtin.type import ByteString diff --git a/boa3/builtin/interop/storage/__init__.py b/boa3/builtin/interop/storage/__init__.py index 1e9453ebe..ccf6d8bb4 100644 --- a/boa3/builtin/interop/storage/__init__.py +++ b/boa3/builtin/interop/storage/__init__.py @@ -1,3 +1,16 @@ +__all__ = [ + 'FindOptions', + 'StorageContext', + 'StorageMap', + 'get', + 'get_context', + 'get_read_only_context', + 'put', + 'delete', + 'find', +] + + from typing import Union from boa3.builtin.interop.iterator import Iterator diff --git a/boa3/builtin/interop/storage/storagecontext.py b/boa3/builtin/interop/storage/storagecontext.py index 53a85bff6..5814d5e49 100644 --- a/boa3/builtin/interop/storage/storagecontext.py +++ b/boa3/builtin/interop/storage/storagecontext.py @@ -1,5 +1,7 @@ from __future__ import annotations +__all__ = ['StorageContext'] + from boa3.builtin.interop.storage.storagemap import StorageMap from boa3.builtin.type import ByteString diff --git a/boa3/builtin/interop/storage/storagemap.py b/boa3/builtin/interop/storage/storagemap.py index 4ffaaebf7..be548f2c0 100644 --- a/boa3/builtin/interop/storage/storagemap.py +++ b/boa3/builtin/interop/storage/storagemap.py @@ -1,3 +1,5 @@ +__all__ = ['StorageMap'] + from typing import Union from boa3.builtin.type import ByteString diff --git a/boa3/builtin/nativecontract/__init__.py b/boa3/builtin/nativecontract/__init__.py index e69de29bb..6175927e9 100644 --- a/boa3/builtin/nativecontract/__init__.py +++ b/boa3/builtin/nativecontract/__init__.py @@ -0,0 +1,21 @@ +__all__ = [ + 'ContractManagement', + 'CryptoLib', + 'GAS', + 'Ledger', + 'NEO', + 'Oracle', + 'Policy', + 'RoleManagement', + 'StdLib', +] + +from boa3.builtin.nativecontract.contractmanagement import ContractManagement +from boa3.builtin.nativecontract.cryptolib import CryptoLib +from boa3.builtin.nativecontract.gas import GAS +from boa3.builtin.nativecontract.ledger import Ledger +from boa3.builtin.nativecontract.neo import NEO +from boa3.builtin.nativecontract.oracle import Oracle +from boa3.builtin.nativecontract.policy import Policy +from boa3.builtin.nativecontract.rolemanagement import RoleManagement +from boa3.builtin.nativecontract.stdlib import StdLib diff --git a/boa3/builtin/nativecontract/contractmanagement.py b/boa3/builtin/nativecontract/contractmanagement.py index a14882bd9..f6e554ff4 100644 --- a/boa3/builtin/nativecontract/contractmanagement.py +++ b/boa3/builtin/nativecontract/contractmanagement.py @@ -1,3 +1,9 @@ +__all__ = [ + 'ContractManagement', + 'Contract', +] + + from typing import Any from boa3.builtin.interop.contract import Contract diff --git a/boa3/builtin/nativecontract/cryptolib.py b/boa3/builtin/nativecontract/cryptolib.py index 44b5bd991..e0d9fd519 100644 --- a/boa3/builtin/nativecontract/cryptolib.py +++ b/boa3/builtin/nativecontract/cryptolib.py @@ -1,3 +1,8 @@ +__all__ = [ + 'CryptoLib', + 'NamedCurve', +] + from typing import Any from boa3.builtin.interop.crypto import NamedCurve diff --git a/boa3/builtin/nativecontract/gas.py b/boa3/builtin/nativecontract/gas.py index 0c8f1797c..f4fffce5f 100644 --- a/boa3/builtin/nativecontract/gas.py +++ b/boa3/builtin/nativecontract/gas.py @@ -1,3 +1,8 @@ +__all__ = [ + 'GAS', +] + + from typing import Any from boa3.builtin.type import UInt160 diff --git a/boa3/builtin/nativecontract/ledger.py b/boa3/builtin/nativecontract/ledger.py index 32375621a..0ec692979 100644 --- a/boa3/builtin/nativecontract/ledger.py +++ b/boa3/builtin/nativecontract/ledger.py @@ -1,3 +1,8 @@ +__all__ = [ + 'Ledger', +] + + from typing import List, Union from boa3.builtin.interop.blockchain import Block, Signer, Transaction, VMState diff --git a/boa3/builtin/nativecontract/neo.py b/boa3/builtin/nativecontract/neo.py index 2c3d3b9a4..6604ed663 100644 --- a/boa3/builtin/nativecontract/neo.py +++ b/boa3/builtin/nativecontract/neo.py @@ -1,3 +1,8 @@ +__all__ = [ + 'NEO', +] + + from typing import Any, List, Tuple from boa3.builtin.contract import NeoAccountState diff --git a/boa3/builtin/nativecontract/oracle.py b/boa3/builtin/nativecontract/oracle.py index 4fc9e3400..8922b4eb6 100644 --- a/boa3/builtin/nativecontract/oracle.py +++ b/boa3/builtin/nativecontract/oracle.py @@ -1,3 +1,8 @@ +__all__ = [ + 'Oracle', +] + + from typing import Union, Any from boa3.builtin.type import UInt160 diff --git a/boa3/builtin/nativecontract/policy.py b/boa3/builtin/nativecontract/policy.py index 1ca449d7e..88198d95b 100644 --- a/boa3/builtin/nativecontract/policy.py +++ b/boa3/builtin/nativecontract/policy.py @@ -1,3 +1,8 @@ +__all__ = [ + 'Policy', +] + + from boa3.builtin.type import UInt160 diff --git a/boa3/builtin/nativecontract/rolemanagement.py b/boa3/builtin/nativecontract/rolemanagement.py index 62d278f46..f0be0046c 100644 --- a/boa3/builtin/nativecontract/rolemanagement.py +++ b/boa3/builtin/nativecontract/rolemanagement.py @@ -1,3 +1,9 @@ +__all__ = [ + 'RoleManagement', + 'Role', +] + + from boa3.builtin.interop.role.roletype import Role from boa3.builtin.type import ECPoint, UInt160 diff --git a/boa3/builtin/nativecontract/stdlib.py b/boa3/builtin/nativecontract/stdlib.py index 4986a4f81..9583e5fc4 100644 --- a/boa3/builtin/nativecontract/stdlib.py +++ b/boa3/builtin/nativecontract/stdlib.py @@ -1,3 +1,8 @@ +__all__ = [ + 'StdLib', +] + + from typing import Any from boa3.builtin.type import ByteString, UInt160 diff --git a/boa3/builtin/type/__init__.py b/boa3/builtin/type/__init__.py index e115b53e2..abc23191f 100644 --- a/boa3/builtin/type/__init__.py +++ b/boa3/builtin/type/__init__.py @@ -1,5 +1,19 @@ from __future__ import annotations +__all__ = [ + 'Event', + 'UInt160', + 'UInt256', + 'ECPoint', + 'ByteString', + 'Address', + 'BlockHash', + 'PublicKey', + 'ScriptHash', + 'ScriptHashLittleEndian', + 'TransactionId', +] + from typing import Sequence, Union diff --git a/boa3/internal/model/builtin/interop/interop.py b/boa3/internal/model/builtin/interop/interop.py index fa1c74b79..a18b4b297 100644 --- a/boa3/internal/model/builtin/interop/interop.py +++ b/boa3/internal/model/builtin/interop/interop.py @@ -336,9 +336,14 @@ def interop_events(cls) -> List[Event]: ] ) + RoleTypeModule = Package(identifier=RoleType.identifier.lower(), + types=[RoleType] + ) + RolePackage = Package(identifier=InteropPackage.Role, types=[RoleType], - methods=[GetDesignatedByRole] + methods=[GetDesignatedByRole], + packages=[RoleTypeModule] ) RuntimePackage = Package(identifier=InteropPackage.Runtime, diff --git a/boa3/internal/model/builtin/native/nativecontract.py b/boa3/internal/model/builtin/native/nativecontract.py index 94947e8d6..7a891a312 100644 --- a/boa3/internal/model/builtin/native/nativecontract.py +++ b/boa3/internal/model/builtin/native/nativecontract.py @@ -24,8 +24,7 @@ class NativeContract: ContractManagementModule = Package(identifier=ContractManagement.identifier.lower(), types=[ContractManagement, - Interop.ContractType, - Builtin.UInt160]) + Interop.ContractType]) CryptoLibModule = Package(identifier=CryptoLib.identifier.lower(), types=[CryptoLib, @@ -36,9 +35,7 @@ class NativeContract: ) LedgerModule = Package(identifier=Ledger.identifier.lower(), - types=[Ledger, - Interop.BlockType, - Interop.TransactionType] + types=[Ledger] ) NeoModule = Package(identifier=NEO.identifier.lower(), From 9791b2194ac4ab13461f313f25e1b47d2b1634c4 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 23 May 2023 14:54:39 -0300 Subject: [PATCH 07/17] #861mua6h8 - fix fail to compile contract due to metadata --- boa3/internal/analyser/moduleanalyser.py | 26 +++++++++++++++++++----- 1 file changed, 21 insertions(+), 5 deletions(-) diff --git a/boa3/internal/analyser/moduleanalyser.py b/boa3/internal/analyser/moduleanalyser.py index b35f5c81a..b767b4440 100644 --- a/boa3/internal/analyser/moduleanalyser.py +++ b/boa3/internal/analyser/moduleanalyser.py @@ -366,23 +366,39 @@ def _read_metadata_object(self, function: ast.FunctionDef): else: function.returns = None function.decorator_list = [] + + imports: List[ast.AST] = [] + other_instructions: List[ast.AST] = [] + for node in self._tree.body: + if node == function: + # metadata function must be right after all the imports, so it executes correctly + continue + + if isinstance(node, (ast.ImportFrom, ast.Import)): + imports.append(node) + else: + other_instructions.append(node) + module: ast.Module = ast.parse('') - module.body = [node for node in self._tree.body - if isinstance(node, (ast.ImportFrom, ast.Import))] - module.body.append(function) + module.body = imports + [function] + other_instructions ast.copy_location(module, function) + namespace = {} try: # executes the function code = compile(module, filename='', mode='exec') - namespace = {} exec(code, namespace) - obj: Any = namespace[function.name]() except ModuleNotFoundError: # will fail if any imports can't be executed # in this case, the error is already logged return + except BaseException as inner_exception: + # reordering the module tree may raise unexpected exceptions + # ignore if it has generated the metadata function + if function.name not in namespace: + raise inner_exception + obj: Any = namespace[function.name]() node: ast.AST = function.body[-1] if len(function.body) > 0 else function # return must be a NeoMetadata object if not isinstance(obj, NeoMetadata): From d1d6cbcdfaafec34149aa4bc949f67bef8504953 Mon Sep 17 00:00:00 2001 From: luc10921 Date: Wed, 24 May 2023 14:50:29 -0300 Subject: [PATCH 08/17] CU-861mtqhdq - false error on missing NEP-11 transfer event --- boa3/internal/analyser/analyser.py | 3 ++ .../supportedstandard/standardanalyser.py | 27 +++--------- ...aInfoSupportedStandardsEventFromPackage.py | 43 +++++++++++++++++++ .../metadata_test/aux_package/__init__.py | 0 .../aux_package/internal_package/__init__.py | 17 ++++++++ .../tests/compiler_tests/test_metadata.py | 26 +++++++++++ 6 files changed, 95 insertions(+), 21 deletions(-) create mode 100644 boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsEventFromPackage.py create mode 100644 boa3_test/test_sc/metadata_test/aux_package/__init__.py create mode 100644 boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py diff --git a/boa3/internal/analyser/analyser.py b/boa3/internal/analyser/analyser.py index f6de32213..043c16112 100644 --- a/boa3/internal/analyser/analyser.py +++ b/boa3/internal/analyser/analyser.py @@ -226,3 +226,6 @@ def update_symbol_table_with_imports(self): self.symbol_table[file_path] = import_symbol self._included_imported_files = True + + def get_imports(self) -> List[Analyser]: + return list(self._imported_files.values()) diff --git a/boa3/internal/analyser/supportedstandard/standardanalyser.py b/boa3/internal/analyser/supportedstandard/standardanalyser.py index d771906e4..9f00ff747 100644 --- a/boa3/internal/analyser/supportedstandard/standardanalyser.py +++ b/boa3/internal/analyser/supportedstandard/standardanalyser.py @@ -5,7 +5,6 @@ from boa3.internal.analyser.astanalyser import IAstAnalyser from boa3.internal.exception import CompilerError from boa3.internal.model.event import Event -from boa3.internal.model.imports import importsymbol from boa3.internal.model.method import Method from boa3.internal.model.symbol import ISymbol @@ -33,6 +32,7 @@ def __init__(self, analyser, symbol_table: Dict[str, ISymbol], log: bool = False standards = [] self.standards: List[str] = standards + self._analyser = analyser self._filter_standards_names() self._validate_standards() self._check_other_implemented_standards() @@ -88,8 +88,9 @@ def _validate_standards(self): # validate standard's events events = [symbol for symbol in self.symbols.values() if isinstance(symbol, Event)] # imported events should be included in the validation - for imported in self._get_all_imports(): - events.extend([event for event in imported.all_symbols.values() if isinstance(event, Event)]) + for import_ in self._analyser.get_imports(): + events.extend([event for event in import_.symbol_table.values() + if isinstance(event, Event) and event not in events]) for standard_event in current_standard.events: is_implemented = False @@ -122,22 +123,6 @@ def _validate_standards(self): CompilerError.MissingStandardDefinition(standard, method_id, optional_method) ) - def _get_all_imports(self) -> List[importsymbol.Import]: - all_imports = [imported for imported in self.symbols.values() - if (isinstance(imported, importsymbol.Import) - and not isinstance(imported, importsymbol.BuiltinImport))] - index = 0 - while index < len(all_imports): - imported = all_imports[index] - for inner in imported.all_symbols.values(): - if (isinstance(inner, importsymbol.Import) - and not isinstance(inner, importsymbol.BuiltinImport) - and inner not in all_imports): - all_imports.append(inner) - index += 1 - - return all_imports - def _check_other_implemented_standards(self): other_standards = supportedstandard.neo_standards.copy() # verify only standards that were not mentioned @@ -147,8 +132,8 @@ def _check_other_implemented_standards(self): # gets a list of all events events = [symbol for symbol in self.symbols.copy().values() if isinstance(symbol, Event)] - for imported in self._get_all_imports(): - events.extend([event for event in imported.all_symbols.values() if isinstance(event, Event)]) + for import_ in self._analyser.get_imports(): + events.extend([event for event in import_.symbol_table.values() if isinstance(event, Event)]) # verify if the methods and events that were implemented corresponds to a standard for standard in other_standards: diff --git a/boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsEventFromPackage.py b/boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsEventFromPackage.py new file mode 100644 index 000000000..68bdde804 --- /dev/null +++ b/boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsEventFromPackage.py @@ -0,0 +1,43 @@ +from typing import Any + +from boa3.builtin.compile_time import NeoMetadata, metadata, public +from boa3.builtin.type import UInt160 +from boa3_test.test_sc.metadata_test.aux_package import internal_package + + +@public +def Main() -> int: + return 5 + + +@metadata +def standards_manifest() -> NeoMetadata: + meta = NeoMetadata() + meta.supported_standards = ['NEP-17'] + return meta + + +@public(safe=True) +def symbol() -> str: + pass + + +@public(safe=True) +def decimals() -> int: + pass + + +@public(name='totalSupply', safe=True) +def total_supply() -> int: + pass + + +@public(name='balanceOf', safe=True) +def balance_of(account: UInt160) -> int: + pass + + +@public +def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) -> bool: + internal_package.method_called(from_address, to_address, amount) + return True diff --git a/boa3_test/test_sc/metadata_test/aux_package/__init__.py b/boa3_test/test_sc/metadata_test/aux_package/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py b/boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py new file mode 100644 index 000000000..cd496243d --- /dev/null +++ b/boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py @@ -0,0 +1,17 @@ +from boa3.builtin.compile_time import CreateNewEvent + +from typing import Union +from boa3.builtin.type import UInt160 + +on_transfer = CreateNewEvent( + [ + ('from_addr', Union[UInt160, None]), + ('to_addr', Union[UInt160, None]), + ('amount', int), + ], + 'Transfer' +) + + +def method_called(token_owner: Union[UInt160, None], to: Union[UInt160, None], amount: int): + on_transfer(token_owner, to, amount) diff --git a/boa3_test/tests/compiler_tests/test_metadata.py b/boa3_test/tests/compiler_tests/test_metadata.py index 3f31b1d98..850601cc3 100644 --- a/boa3_test/tests/compiler_tests/test_metadata.py +++ b/boa3_test/tests/compiler_tests/test_metadata.py @@ -190,6 +190,32 @@ def test_metadata_info_supported_standards(self): self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) self.assertEqual(manifest_struct, invoke.result[4]) + def test_metadata_info_supported_standards_from_package(self): + path = self.get_contract_path('MetadataInfoSupportedStandardsEventFromPackage.py') + output, manifest = self.compile_and_save(path) + + self.assertIn('supportedstandards', manifest) + self.assertIsInstance(manifest['supportedstandards'], list) + self.assertGreater(len(manifest['supportedstandards']), 0) + self.assertIn('NEP-17', manifest['supportedstandards']) + + nef, manifest = self.get_bytes_output(path) + path, _ = self.get_deploy_file_paths(path) + get_contract_path, _ = self.get_deploy_file_paths('test_sc/native_test/contractmanagement', 'GetContract.py') + + runner = NeoTestRunner(runner_id=self.method_name()) + # verify using NeoManifestStruct + contract = runner.deploy_contract(path) + runner.update_contracts(export_checkpoint=True) + call_hash = contract.script_hash + + invoke = runner.call_contract(get_contract_path, 'main', call_hash) + manifest_struct = NeoManifestStruct.from_json(manifest) + + runner.execute() + self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) + self.assertEqual(manifest_struct, invoke.result[4]) + def test_metadata_info_supported_standards_with_imported_event(self): path = self.get_contract_path('MetadataInfoSupportedStandardsImportedEvent.py') output, manifest = self.get_output(path) From dfa723ab5711081dbff5b9a2e6fb128ae00cc2ff Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 29 May 2023 17:44:30 -0300 Subject: [PATCH 09/17] #861mv8zhx - No code generated for onNEP11Payment and onNEP17Payment function --- .../internal/compiler/codegenerator/codegeneratorvisitor.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/boa3/internal/compiler/codegenerator/codegeneratorvisitor.py b/boa3/internal/compiler/codegenerator/codegeneratorvisitor.py index 316fc45f9..8ff6f93d7 100644 --- a/boa3/internal/compiler/codegenerator/codegeneratorvisitor.py +++ b/boa3/internal/compiler/codegenerator/codegeneratorvisitor.py @@ -345,10 +345,16 @@ def visit_Return(self, ret: ast.Return) -> GeneratorData: """ if self.generator.stack_size > 0: self.generator.clear_stack(True) + if self.current_method.return_type is not Type.none: result = self.visit_to_generate(ret.value) if result.type is Type.none and not self.generator.is_none_inserted(): self.generator.convert_literal(None) + elif ret.value is not None: + self.visit_to_generate(ret.value) + if self.generator.stack_size > 0: + self.generator.remove_stack_top_item() + self.generator.insert_return() return self.build_data(ret) From cfc8d851c7bb799d7dfc25e70ff058576995f1a9 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 30 May 2023 17:58:47 -0300 Subject: [PATCH 10/17] #864ek123w - Move ByteString methods outside the class --- boa3/builtin/type/__init__.py | 109 +---------- boa3/builtin/type/helper.py | 38 ++++ boa3/internal/analyser/analyser.py | 4 +- boa3/internal/analyser/constructanalyser.py | 31 +-- boa3/internal/analyser/typeanalyser.py | 22 ++- boa3/internal/model/builtin/builtin.py | 34 ++-- .../builtin/classmethod/tobytesmethod.py | 25 +-- .../builtin/method/toscripthashmethod.py | 8 +- .../collection/mapping/mutable/dicttype.py | 3 +- .../collection/sequence/mutable/listtype.py | 6 + .../sequence/mutable/mutablesequencetype.py | 1 + .../type/collection/sequence/sequencetype.py | 12 ++ .../model/type/primitive/bytestringtype.py | 14 -- .../model/type/primitive/bytestype.py | 13 -- boa3/internal/model/type/primitive/inttype.py | 6 - boa3/internal/model/type/primitive/strtype.py | 3 +- boa3_test/examples/amm.py | 41 ++-- .../auxiliary_contracts/update_contract.py | 6 +- boa3_test/examples/htlc.py | 38 ++-- boa3_test/examples/ico.py | 16 +- boa3_test/examples/nep11_non_divisible.py | 32 ++-- boa3_test/examples/nep17.py | 10 +- boa3_test/examples/nep5.py | 8 +- boa3_test/examples/update_contract.py | 6 +- boa3_test/examples/wrapped_gas.py | 16 +- boa3_test/examples/wrapped_neo.py | 16 +- .../ConcatBytesVariablesAndConstants.py | 7 +- .../built_in_methods_test/IntToBytes.py | 3 +- .../IntToBytesAsParameter.py | 3 +- .../IntToBytesWithBuiltin.py | 4 - .../built_in_methods_test/IntZeroToBytes.py | 4 +- ...Type.py => ScriptHashBuiltinWrongUsage.py} | 0 .../built_in_methods_test/ScriptHashInt.py | 3 +- .../ScriptHashIntBuiltinCall.py | 4 - .../ScriptHashMismatchedType.py | 5 +- .../built_in_methods_test/ScriptHashStr.py | 5 +- .../ScriptHashStrBuiltinCall.py | 4 - .../ScriptHashTooFewParameters.py | 5 +- .../ScriptHashTooManyParameters.py | 5 +- .../ScriptHashVariable.py | 3 +- .../ScriptHashVariableBuiltinCall.py | 4 - .../built_in_methods_test/StrToBytes.py | 3 +- .../StrToBytesWithBuiltin.py | 4 - .../ToBytesMismatchedType.py | 5 +- .../test_sc/bytes_test/BytearrayToInt.py | 3 +- .../bytes_test/BytearrayToIntWithBuiltin.py | 4 - .../BytearrayToIntWithBytesBuiltin.py | 4 - boa3_test/test_sc/bytes_test/BytesToBool.py | 3 +- .../bytes_test/BytesToBoolWithBuiltin.py | 4 - .../BytesToBoolWithBuiltinHardCodedFalse.py | 6 - .../BytesToBoolWithBuiltinHardCodedTrue.py | 6 - .../BytesToBoolWithBuiltinMismatchedTypes.py | 2 - boa3_test/test_sc/bytes_test/BytesToInt.py | 3 +- .../bytes_test/BytesToIntWithBuiltin.py | 4 - .../BytesToIntWithBuiltinMismatchedTypes.py | 2 - .../BytesToIntWithBytearrayBuiltin.py | 2 - boa3_test/test_sc/bytes_test/BytesToStr.py | 3 +- .../bytes_test/BytesToStrWithBuiltin.py | 4 - .../BytesToStrWithBuiltinMismatchedTypes.py | 2 - .../test_sc/function_test/FunctionAsArg.py | 5 +- ...ManifestTypeHintFromUInt160ToScriptHash.py | 3 +- ...HintFromUInt160ToScriptHashLittleEndian.py | 3 +- ...lseIsInstanceConditionWithUnionVariable.py | 7 +- boa3_test/test_sc/if_test/IfWithInnerFor.py | 3 +- boa3_test/test_sc/if_test/IfWithInnerWhile.py | 3 +- .../interop_test/contract/CallFlagsUsage.py | 3 +- .../interop_test/contract/NewContract.py | 3 +- .../storage/ImportInteropStorage.py | 3 +- .../interop_test/storage/ImportStorage.py | 3 +- .../interop_test/storage/StorageAsReadOnly.py | 5 +- .../interop_test/storage/StorageGetAndPut1.py | 3 +- .../interop_test/storage/StorageGetAndPut2.py | 3 +- .../bytestring/ByteStringToBool.py | 2 - .../bytestring/ByteStringToBoolWithBuiltin.py | 7 - .../bytestring/ByteStringToBytes.py | 2 - .../ByteStringToBytesWithBuiltin.py | 7 - .../bytestring/ByteStringToInt.py | 2 - .../bytestring/ByteStringToIntWithBuiltin.py | 7 - .../bytestring/ByteStringToStr.py | 2 - .../bytestring/ByteStringToStrWithBuiltin.py | 7 - .../typing_test/CastPersistedInScope.py | 3 +- .../compiler_tests/test_builtin_method.py | 120 ++---------- boa3_test/tests/compiler_tests/test_bytes.py | 134 +------------ .../tests/compiler_tests/test_neo_types.py | 178 ++---------------- docs/ContractExamplesTest.md | 6 +- 85 files changed, 355 insertions(+), 810 deletions(-) create mode 100644 boa3/builtin/type/helper.py rename boa3_test/test_sc/built_in_methods_test/{ScriptHashBuiltinMismatchedType.py => ScriptHashBuiltinWrongUsage.py} (100%) delete mode 100644 boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedFalse.py delete mode 100644 boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedTrue.py delete mode 100644 boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinMismatchedTypes.py delete mode 100644 boa3_test/test_sc/bytes_test/BytesToIntWithBuiltinMismatchedTypes.py delete mode 100644 boa3_test/test_sc/bytes_test/BytesToIntWithBytearrayBuiltin.py delete mode 100644 boa3_test/test_sc/bytes_test/BytesToStrWithBuiltinMismatchedTypes.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBoolWithBuiltin.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytesWithBuiltin.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToIntWithBuiltin.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStrWithBuiltin.py diff --git a/boa3/builtin/type/__init__.py b/boa3/builtin/type/__init__.py index abc23191f..efbf3adf8 100644 --- a/boa3/builtin/type/__init__.py +++ b/boa3/builtin/type/__init__.py @@ -14,7 +14,7 @@ 'TransactionId', ] -from typing import Sequence, Union +from typing import Union class Event: @@ -63,109 +63,10 @@ def to_script_hash(self) -> bytes: pass -class ByteString: - """ - An type annotation for values that can be str or bytes. Same as Union[str, bytes] - """ - - def to_bytes(self) -> bytes: - """ - Converts an ByteString value to an array of bytes - """ - pass - - def to_str(self) -> str: - """ - Converts an ByteString value to a string. - """ - pass - - def to_int(self) -> int: - """ - Return the integer represented by this ByteString. - """ - pass - - def to_bool(self) -> bool: - """ - Return the boolean represented by this ByteString. - """ - pass - - def isdigit(self) -> bool: - """ - Return True if the ByteString is a digit string, False otherwise. - - A ByteString is a digit string if all characters in the ByteString are digits and there - is at least one character in the ByteString. - """ - pass - - def join(self, __iterable: Sequence[ByteString]) -> ByteString: - """ - S.join(__iterable: Sequence[ByteString]) -> ByteString - - Concatenate any number of ByteStrings. - - The ByteString whose method is called is inserted in between each given ByteString. - The result is returned as a new ByteString. - """ - pass - - def lower(self) -> ByteString: - """ - S.lower() -> ByteString - - Return a copy of the ByteString converted to lowercase. - """ - pass - - def startswith(self, prefix: ByteString, start: int = 0, end: int = -1) -> bool: - """ - S.startswith(prefix: ByteString, start: int, end: int) -> bool - - Return True if S starts with the specified prefix, False otherwise. - With optional start, test S beginning at that position. - With optional end, stop comparing S at that position. - prefix can also be a tuple of strings to try. - """ - pass - - def strip(self, __chars: ByteString) -> ByteString: - """ - S.strip(__chars: ByteString) -> ByteString - - Return a copy of the ByteString with leading and trailing whitespace remove. - - If chars is given and not None, remove characters in chars instead. - """ - pass - - def upper(self) -> ByteString: - """ - S.upper() -> ByteString - - Return a copy of the ByteString converted to uppercase. - """ - pass - - def __add__(self, *args, **kwargs): # real signature unknown - """ - Return self+value. - """ - pass - - def __mul__(self, *args, **kwargs): # real signature unknown - """ - Return self*value. - """ - pass - - def __rmul__(self, *args, **kwargs): # real signature unknown - """ - Return value*self. - """ - pass +ByteString = Union[str, bytes] +""" +An type annotation for values that can be str or bytes. Same as Union[str, bytes] +""" class Address(str): diff --git a/boa3/builtin/type/helper.py b/boa3/builtin/type/helper.py new file mode 100644 index 000000000..d4b5dbfbc --- /dev/null +++ b/boa3/builtin/type/helper.py @@ -0,0 +1,38 @@ +__all__ = [ + 'to_bool', + 'to_bytes', + 'to_int', + 'to_str', +] + +from typing import Union + +from boa3.builtin.type import ByteString + + +def to_bytes(value: Union[ByteString, int]) -> bytes: + """ + Converts a str or integer value to an array of bytes + """ + pass + + +def to_str(value: bytes) -> str: + """ + Converts a bytes value to a string. + """ + pass + + +def to_int(value: bytes) -> int: + """ + Converts a bytes value to the integer it represents. + """ + pass + + +def to_bool(value: bytes) -> bool: + """ + Return a bytes value to the boolean it represents. + """ + pass diff --git a/boa3/internal/analyser/analyser.py b/boa3/internal/analyser/analyser.py index 043c16112..2e3b64294 100644 --- a/boa3/internal/analyser/analyser.py +++ b/boa3/internal/analyser/analyser.py @@ -82,6 +82,8 @@ def analyse(path: str, log: bool = False, # fill symbol table if not analyser.__analyse_modules(imported_files, import_stack): return analyser + analyser.__pre_execute() + # check if standards are correctly implemented if not analyser.__check_standards(): return analyser @@ -173,7 +175,7 @@ def __pre_execute(self): """ Pre executes the instructions of the ast for optimization """ - self.ast_tree = ConstructAnalyser(self.ast_tree, log=self._log).tree + self.ast_tree = ConstructAnalyser(self.ast_tree, self.symbol_table, log=self._log).tree def __pos_execute(self): """ diff --git a/boa3/internal/analyser/constructanalyser.py b/boa3/internal/analyser/constructanalyser.py index 111995912..db01da2f5 100644 --- a/boa3/internal/analyser/constructanalyser.py +++ b/boa3/internal/analyser/constructanalyser.py @@ -1,7 +1,9 @@ import ast +from typing import Dict from boa3.internal.analyser.astanalyser import IAstAnalyser from boa3.internal.model import set_internal_call +from boa3.internal.model.symbol import ISymbol class ConstructAnalyser(IAstAnalyser, ast.NodeTransformer): @@ -12,8 +14,9 @@ class ConstructAnalyser(IAstAnalyser, ast.NodeTransformer): These methods are used to walk through the Python abstract syntax tree. """ - def __init__(self, ast_tree: ast.AST, log: bool = False): + def __init__(self, ast_tree: ast.AST, symbol_table: Dict[str, ISymbol], log: bool = False): super().__init__(ast_tree, log=log) + self.symbols = symbol_table.copy() self.visit(self._tree) @property @@ -31,9 +34,15 @@ def visit_Call(self, call: ast.Call) -> ast.AST: :param call: the python ast function call node """ - if isinstance(call.func, ast.Attribute): - from boa3.internal.model.builtin.builtin import Builtin - if call.func.attr == Builtin.ScriptHashMethod_.identifier: + if isinstance(call.func, ast.Name): + from boa3.internal.model.builtin.method import ScriptHashMethod + to_script_hash = None + for symbol_id, symbol in self.symbols.items(): + if isinstance(symbol, ScriptHashMethod) and call.func.id == symbol_id: + to_script_hash = symbol + break + + if to_script_hash is not None: from boa3.internal.constants import SYS_VERSION_INFO from boa3.internal.model.type.type import Type types = { @@ -45,16 +54,12 @@ def visit_Call(self, call: ast.Call) -> ast.AST: if SYS_VERSION_INFO >= (3, 8) else (ast.Num, ast.Str, ast.Bytes)) - if isinstance(call.func.value, literal) and len(call.args) == 0: - value = ast.literal_eval(call.func.value) - if not isinstance(value, tuple(types.values())): - return call - elif (isinstance(call.func.value, ast.Name) # checks if is the name of a type - and call.func.value.id in types # and if the arguments is from the same type - and len(call.args) == 1 - and isinstance(call.args[0], literal)): + if len(call.args) != 1: + return call + + if isinstance(call.args[0], literal): value = ast.literal_eval(call.args[0]) - if not isinstance(value, (types[call.func.value.id],)): + if not isinstance(value, tuple(types.values())): return call else: return call diff --git a/boa3/internal/analyser/typeanalyser.py b/boa3/internal/analyser/typeanalyser.py index 4edcc11a7..25ecde4f2 100644 --- a/boa3/internal/analyser/typeanalyser.py +++ b/boa3/internal/analyser/typeanalyser.py @@ -1146,7 +1146,7 @@ def visit_Call(self, call: ast.Call): callable_method_id = constants.INIT_METHOD_ID if not isinstance(callable_target, Callable): - # the symbol doesn't exists or is not a function + # the symbol doesn't exist or is not a function # if it is None, the error was already logged if callable_id is not None: if callable_method_id is not None: @@ -1615,6 +1615,10 @@ def visit_Attribute(self, attribute: ast.Attribute) -> Union[str, Attribute]: symbol = self.get_symbol(value) if symbol is None: return '{0}.{1}'.format(value, attribute.attr) + value_type = self.get_type(symbol) + else: + value_type = self.get_type(value) + if isinstance(value, ISymbol): symbol = value @@ -1687,6 +1691,22 @@ def visit_Attribute(self, attribute: ast.Attribute) -> Union[str, Attribute]: attr_value = symbol if not isinstance(symbol, PythonClass) else attribute.value else: attr_value = attribute.value + if not isinstance(symbol, Import): + if hasattr(attr_type, 'symbols'): + is_valid_symbol_in_attribute = attribute.attr in attr_type.symbols + else: + is_valid_symbol_in_attribute = attr_symbol in self.symbols.values() + attr_id = value_type.identifier + else: + is_valid_symbol_in_attribute = attribute.attr in symbol.symbols + attr_id = attr_type + + if not is_internal and not is_valid_symbol_in_attribute: + self._log_error( + CompilerError.UnresolvedReference( + attribute.lineno, attribute.col_offset, + symbol_id='{0}.{1}'.format(attr_id, attribute.attr) + )) if isinstance(attr_symbol, Property): if isinstance(attribute.ctx, ast.Load): diff --git a/boa3/internal/model/builtin/builtin.py b/boa3/internal/model/builtin/builtin.py index 8d21b0d29..667dae6d7 100644 --- a/boa3/internal/model/builtin/builtin.py +++ b/boa3/internal/model/builtin/builtin.py @@ -27,6 +27,7 @@ class BoaPackage(str, Enum): Contract = 'contract' Interop = 'interop' Type = 'type' + TypeHelper = 'helper' VM = 'vm' CompileTime = 'compile_time' @@ -241,6 +242,26 @@ def builtin_events(cls) -> List[EventSymbol]: return lst + _builtin_type_package_symbols = [ByteString, + ECPoint, + UInt160, + UInt256, + Event, + Address, + BlockHash, + PublicKey, + ScriptHashType_, + ScriptHashLittleEndian, + TransactionId, + Package(identifier=BoaPackage.TypeHelper, + methods=[ConvertToBool, + ConvertToBytes, + ConvertToInt, + ConvertToStr, + ] + ) + ] + _boa_symbols: Dict[BoaPackage, List[IdentifiedSymbol]] = { BoaPackage.Contract: [Abort, NeoAccountState, @@ -250,18 +271,7 @@ def builtin_events(cls) -> List[EventSymbol]: ScriptHashMethod_ ], BoaPackage.Interop: Interop.package_symbols, - BoaPackage.Type: [ByteString, - ECPoint, - UInt160, - UInt256, - Event, - Address, - BlockHash, - PublicKey, - ScriptHashType_, - ScriptHashLittleEndian, - TransactionId, - ], + BoaPackage.Type: _builtin_type_package_symbols, BoaPackage.VM: [Opcode ], BoaPackage.CompileTime: [ContractInterface, diff --git a/boa3/internal/model/builtin/classmethod/tobytesmethod.py b/boa3/internal/model/builtin/classmethod/tobytesmethod.py index 3e5d97baa..0305bd909 100644 --- a/boa3/internal/model/builtin/classmethod/tobytesmethod.py +++ b/boa3/internal/model/builtin/classmethod/tobytesmethod.py @@ -17,9 +17,6 @@ class ToBytesMethod(IBuiltinMethod, ABC): def __init__(self, self_type: IType): identifier = 'to_bytes' - if isinstance(self_type, IdentifiedSymbol): - identifier = '-{0}_{1}'.format(self_type.identifier, identifier) - args: Dict[str, Variable] = {'self': Variable(self_type)} from boa3.internal.model.type.type import Type super().__init__(identifier, args, return_type=Type.bytes) @@ -33,6 +30,12 @@ def validate_parameters(self, *params: IExpression) -> bool: return False return isinstance(params[0], IExpression) and isinstance(params[0].type, BytesType) + @property + def identifier(self) -> str: + if isinstance(self._arg_self.type, IdentifiedSymbol): + return '-{0}_{1}'.format(self._arg_self.type.identifier, self._identifier) + return self._identifier + @property def _opcode(self) -> List[Tuple[Opcode, bytes]]: from boa3.internal.model.type.type import Type @@ -40,6 +43,14 @@ def _opcode(self) -> List[Tuple[Opcode, bytes]]: (Opcode.CONVERT, Type.bytes.stack_item) ] + def build(self, value: Any) -> IBuiltinMethod: + if isinstance(value, IntType): + return IntToBytesMethod(value) + elif isinstance(value, (StrType, ByteStringType)): + return StrToBytesMethod(value) + # if it is not a valid type, show mismatched type with int + return IntToBytesMethod() + def push_self_first(self) -> bool: return self.has_self_argument @@ -56,14 +67,6 @@ class _ConvertToBytesMethod(ToBytesMethod): def __init__(self): super().__init__(None) - def build(self, value: Any) -> IBuiltinMethod: - if isinstance(value, IntType): - return IntToBytesMethod(value) - elif isinstance(value, (StrType, ByteStringType)): - return StrToBytesMethod(value) - # if it is not a valid type, show mismatched type with int - return IntToBytesMethod() - ToBytes = _ConvertToBytesMethod() diff --git a/boa3/internal/model/builtin/method/toscripthashmethod.py b/boa3/internal/model/builtin/method/toscripthashmethod.py index ff9de5e6d..76ed5045f 100644 --- a/boa3/internal/model/builtin/method/toscripthashmethod.py +++ b/boa3/internal/model/builtin/method/toscripthashmethod.py @@ -19,14 +19,14 @@ def __init__(self, data_type: IType = None): data_type = Type.any identifier = 'to_script_hash' - args: Dict[str, Variable] = {'self': Variable(data_type)} + args: Dict[str, Variable] = {'value': Variable(data_type)} from boa3.internal.model.type.collection.sequence.uint160type import UInt160Type super().__init__(identifier, args, return_type=UInt160Type.build()) @property def identifier(self) -> str: from boa3.internal.model.type.type import Type - self_type = self.args['self'].type + self_type = self.args['value'].type if self_type is Type.any: return self._identifier return '-{0}_from_{1}'.format(self._identifier, self_type._identifier) @@ -40,7 +40,7 @@ def validate_parameters(self, *params: IExpression) -> bool: @property def is_supported(self) -> bool: - return self.args['self'].type is not Type.any + return self.args['value'].type is not Type.any @property def _opcode(self) -> List[Tuple[Opcode, bytes]]: @@ -108,7 +108,7 @@ def _body(self) -> Optional[str]: return None def build(self, value: Any) -> IBuiltinMethod: - if 'self' in self.args and self.args['self'].type is not Type.any: + if 'value' in self.args and self.args['value'].type is not Type.any: return self from boa3.internal.model.type.collection.sequence.ecpointtype import ECPointType diff --git a/boa3/internal/model/type/collection/mapping/mutable/dicttype.py b/boa3/internal/model/type/collection/mapping/mutable/dicttype.py index d7911d135..b72475a7d 100644 --- a/boa3/internal/model/type/collection/mapping/mutable/dicttype.py +++ b/boa3/internal/model/type/collection/mapping/mutable/dicttype.py @@ -28,7 +28,8 @@ def _init_class_symbols(self): from boa3.internal.model.builtin.builtin import Builtin - instance_methods = [Builtin.DictKeys, + instance_methods = [Builtin.Copy, + Builtin.DictKeys, Builtin.DictValues, Builtin.DictPop, Builtin.DictPopDefault, diff --git a/boa3/internal/model/type/collection/sequence/mutable/listtype.py b/boa3/internal/model/type/collection/sequence/mutable/listtype.py index 7922b4466..ca5a18c01 100644 --- a/boa3/internal/model/type/collection/sequence/mutable/listtype.py +++ b/boa3/internal/model/type/collection/sequence/mutable/listtype.py @@ -27,6 +27,12 @@ def _init_class_symbols(self): from boa3.internal.model.builtin.builtin import Builtin + instance_methods = [Builtin.Copy + ] + + for instance_method in instance_methods: + self._instance_methods[instance_method.raw_identifier] = instance_method.build(self) + self._instance_methods[constants.INIT_METHOD_ID] = Builtin.ListGeneric @property diff --git a/boa3/internal/model/type/collection/sequence/mutable/mutablesequencetype.py b/boa3/internal/model/type/collection/sequence/mutable/mutablesequencetype.py index 493442c4f..be931e6d3 100644 --- a/boa3/internal/model/type/collection/sequence/mutable/mutablesequencetype.py +++ b/boa3/internal/model/type/collection/sequence/mutable/mutablesequencetype.py @@ -22,6 +22,7 @@ def _init_class_symbols(self): Builtin.SequenceClear, Builtin.SequenceInsert, Builtin.SequenceExtend, + Builtin.SequencePop, Builtin.SequenceReverse, Builtin.SequenceRemove, ] diff --git a/boa3/internal/model/type/collection/sequence/sequencetype.py b/boa3/internal/model/type/collection/sequence/sequencetype.py index 70cdfeba6..94155f50e 100644 --- a/boa3/internal/model/type/collection/sequence/sequencetype.py +++ b/boa3/internal/model/type/collection/sequence/sequencetype.py @@ -34,3 +34,15 @@ def abi_type(self) -> AbiType: @property def stack_item(self) -> StackItemType: return StackItemType.Array + + def _init_class_symbols(self): + super()._init_class_symbols() + + from boa3.internal.model.builtin.builtin import Builtin + + instance_methods = [Builtin.CountSequenceGeneric, + Builtin.SequenceIndex, + ] + + for instance_method in instance_methods: + self._instance_methods[instance_method.raw_identifier] = instance_method.build([self, self.value_type]) diff --git a/boa3/internal/model/type/primitive/bytestringtype.py b/boa3/internal/model/type/primitive/bytestringtype.py index ea82fdf11..608051250 100644 --- a/boa3/internal/model/type/primitive/bytestringtype.py +++ b/boa3/internal/model/type/primitive/bytestringtype.py @@ -21,20 +21,6 @@ def _is_type_of(cls, value: Any) -> bool: or Type.bytes.is_type_of(value) or isinstance(value, ByteStringType)) - def _init_class_symbols(self): - super()._init_class_symbols() - - from boa3.internal.model.builtin.builtin import Builtin - - instance_methods = [Builtin.ConvertToBytes, - Builtin.ConvertToBool, - Builtin.ConvertToInt, - Builtin.ConvertToStr, - ] - - for instance_method in instance_methods: - self._instance_methods[instance_method.raw_identifier] = instance_method.build(self) - @classmethod def build(cls, value: Any = None) -> IType: return _ByteString diff --git a/boa3/internal/model/type/primitive/bytestype.py b/boa3/internal/model/type/primitive/bytestype.py index cb06edeb1..6c0311902 100644 --- a/boa3/internal/model/type/primitive/bytestype.py +++ b/boa3/internal/model/type/primitive/bytestype.py @@ -36,16 +36,3 @@ def build_collection(cls, *value_type: IType): @classmethod def _is_type_of(cls, value: Any): return type(value) is bytes or isinstance(value, BytesType) - - def _init_class_symbols(self): - super()._init_class_symbols() - - from boa3.internal.model.builtin.builtin import Builtin - - instance_methods = [Builtin.ConvertToBool, - Builtin.ConvertToInt, - Builtin.ConvertToStr, - ] - - for instance_method in instance_methods: - self._instance_methods[instance_method.raw_identifier] = instance_method.build(self) diff --git a/boa3/internal/model/type/primitive/inttype.py b/boa3/internal/model/type/primitive/inttype.py index 7528f010c..9ebc9a3a2 100644 --- a/boa3/internal/model/type/primitive/inttype.py +++ b/boa3/internal/model/type/primitive/inttype.py @@ -33,12 +33,6 @@ def _init_class_symbols(self): from boa3.internal.model.builtin.builtin import Builtin - instance_methods = [Builtin.ConvertToBytes - ] - - for instance_method in instance_methods: - self._instance_methods[instance_method.raw_identifier] = instance_method.build(self) - self._instance_methods[constants.INIT_METHOD_ID] = Builtin.IntInt @classmethod diff --git a/boa3/internal/model/type/primitive/strtype.py b/boa3/internal/model/type/primitive/strtype.py index d70ff6352..76ae448c4 100644 --- a/boa3/internal/model/type/primitive/strtype.py +++ b/boa3/internal/model/type/primitive/strtype.py @@ -28,8 +28,7 @@ def _init_class_symbols(self): from boa3.internal.model.builtin.builtin import Builtin - instance_methods = [Builtin.ConvertToBytes, - Builtin.StrSplit, + instance_methods = [Builtin.StrSplit, Builtin.BytesStringIndex, ] diff --git a/boa3_test/examples/amm.py b/boa3_test/examples/amm.py index e3bef9778..9829fb67b 100644 --- a/boa3_test/examples/amm.py +++ b/boa3_test/examples/amm.py @@ -7,7 +7,7 @@ from boa3.builtin.interop.contract import call_contract from boa3.builtin.math import sqrt from boa3.builtin.nativecontract.contractmanagement import ContractManagement -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -143,7 +143,7 @@ def total_supply() -> int: :return: the total token supply deployed in the system. """ - return storage.get(SUPPLY_KEY).to_int() + return type_helper.to_int(storage.get(SUPPLY_KEY)) @public(name='balanceOf', safe=True) @@ -157,7 +157,7 @@ def balance_of(account: UInt160) -> int: :type account: UInt160 """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) @public @@ -186,7 +186,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -204,7 +204,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event @@ -277,7 +277,7 @@ def set_address(address_token_a: UInt160, address_token_b: UInt160) -> bool: if not runtime.check_witness(get_owner()): return False - if not storage.get(DEPLOYED).to_bool(): + if not type_helper.to_bool(storage.get(DEPLOYED)): return False if storage.get(TOKEN_A) != b'' or storage.get(TOKEN_B) != b'': @@ -306,7 +306,8 @@ def get_reserves() -> List[int]: :return: a list of 2 ints, the value in the first index is reserve of token_a and the second value is the reserve of token_b """ - return [storage.get(SUPPLY_KEY + TOKEN_A).to_int(), storage.get(SUPPLY_KEY + TOKEN_B).to_int()] + return [type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_A)), + type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_B))] @public @@ -334,8 +335,8 @@ def add_liquidity(amount_token_a_desired: int, amount_token_b_desired: int, amou """ assert runtime.check_witness(user_address), 'failed on check witness' - reserve_token_a = storage.get(SUPPLY_KEY + TOKEN_A).to_int() - reserve_token_b = storage.get(SUPPLY_KEY + TOKEN_B).to_int() + reserve_token_a = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_A)) + reserve_token_b = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_B)) # If there is no liquidity pool, then the values that will be used to mint and create a pool are the desired ones if reserve_token_a == 0 and reserve_token_b == 0: amount_token_a = amount_token_a_desired @@ -391,8 +392,8 @@ def mint(user_address: UInt160) -> int: # reserve_token_a and reserve_token_b are the amount of token_a and token_b tokens that the smart contract has saved in the # storage, it's not the actual amount that is in the balance, because the amount is not updated after transferring # the token_a and token_b tokens, it will be update only after minting - reserve_token_a = storage.get(SUPPLY_KEY + TOKEN_A).to_int() - reserve_token_b = storage.get(SUPPLY_KEY + TOKEN_B).to_int() + reserve_token_a = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_A)) + reserve_token_b = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_B)) # balance_token_a and balance_token_b are the actual amount that are in the balance of this smart contract balance_token_a = call_contract(get_token_a(), 'balanceOf', [runtime.executing_script_hash]) @@ -405,7 +406,7 @@ def mint(user_address: UInt160) -> int: amount_token_a = balance_token_a - reserve_token_a amount_token_b = balance_token_b - reserve_token_b - total_supply = storage.get(SUPPLY_KEY).to_int() + total_supply = type_helper.to_int(storage.get(SUPPLY_KEY)) # if there are no AMM tokens, then the quantity of AMM tokens that will be minted are calculated multiplying # amount_token_a and amount_token_b if total_supply == 0: @@ -419,7 +420,7 @@ def mint(user_address: UInt160) -> int: # updates the total supply of AMM tokens storage.put(SUPPLY_KEY, total_supply + liquidity) # change the amount of liquidity the user has - storage.put(user_address, storage.get(user_address).to_int() + liquidity) + storage.put(user_address, type_helper.to_int(storage.get(user_address)) + liquidity) on_transfer(None, user_address, liquidity) update(balance_token_a, balance_token_b) @@ -510,7 +511,7 @@ def burn(liquidity: int, user_address: UInt160) -> List[int]: amount_token_b: int = 0 if isinstance(balance_token_a, int) and isinstance(balance_token_b, int): - total_supply = storage.get(SUPPLY_KEY).to_int() + total_supply = type_helper.to_int(storage.get(SUPPLY_KEY)) # amount_token_a and amount_token_b are the amount that will be transferred to the user after burning the liquidity amount_token_a = liquidity * balance_token_a // total_supply @@ -575,8 +576,8 @@ def swap(amount_token_a_out: int, amount_token_b_out: int, user_address: UInt160 any token from the user, or if the constant k after the swap ends up being lower than the one at the beginning """ assert amount_token_a_out > 0 or amount_token_b_out > 0 - reserve_token_a = storage.get(SUPPLY_KEY + TOKEN_A).to_int() - reserve_token_b = storage.get(SUPPLY_KEY + TOKEN_B).to_int() + reserve_token_a = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_A)) + reserve_token_b = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_B)) assert amount_token_a_out < reserve_token_a and amount_token_b_out < reserve_token_b token_a = get_token_a() @@ -633,13 +634,13 @@ def swap_tokens(amount_in: int, amount_out_min: int, token_in: UInt160, user_add # Verifies if the user is trying to swap token_a or token_b and set the variables accordingly if token_in == token_a: - reserve_token_in = storage.get(SUPPLY_KEY + TOKEN_A).to_int() - reserve_token_out = storage.get(SUPPLY_KEY + TOKEN_B).to_int() + reserve_token_in = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_A)) + reserve_token_out = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_B)) amount_token_a_in = amount_in amount_token_b_in = 0 else: - reserve_token_in = storage.get(SUPPLY_KEY + TOKEN_B).to_int() - reserve_token_out = storage.get(SUPPLY_KEY + TOKEN_A).to_int() + reserve_token_in = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_B)) + reserve_token_out = type_helper.to_int(storage.get(SUPPLY_KEY + TOKEN_A)) amount_token_a_in = 0 amount_token_b_in = amount_in diff --git a/boa3_test/examples/auxiliary_contracts/update_contract.py b/boa3_test/examples/auxiliary_contracts/update_contract.py index 2d425b466..e383c0287 100644 --- a/boa3_test/examples/auxiliary_contracts/update_contract.py +++ b/boa3_test/examples/auxiliary_contracts/update_contract.py @@ -5,7 +5,7 @@ from boa3.builtin.interop.blockchain import Transaction from boa3.builtin.interop.runtime import check_witness from boa3.builtin.nativecontract.contractmanagement import ContractManagement -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- # TOKEN SETTINGS @@ -76,7 +76,7 @@ def method(account: UInt160): # now there is a verification to this method if check_witness(get_owner()): - storage.put(account, storage.get(account).to_int() + 2 * 10 ** 8) + storage.put(account, type_helper.to_int(storage.get(account)) + 2 * 10 ** 8) on_transfer(None, account, 2 * 10 ** 8) # more omitted code @@ -101,7 +101,7 @@ def balance_of(account: UInt160) -> int: Get the current balance of an address. """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) @public diff --git a/boa3_test/examples/htlc.py b/boa3_test/examples/htlc.py index ac3953ea7..b5c91c2fc 100644 --- a/boa3_test/examples/htlc.py +++ b/boa3_test/examples/htlc.py @@ -6,7 +6,7 @@ from boa3.builtin.interop.blockchain import Transaction from boa3.builtin.interop.contract import GAS as GAS_SCRIPT, call_contract from boa3.builtin.interop.crypto import hash160 -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -108,7 +108,7 @@ def atomic_swap(person_a_address: UInt160, person_a_token: UInt160, person_a_amo # the parameter amount must be greater than 0. If not, this method should throw an exception. assert person_a_amount > 0 and person_b_amount > 0 - if storage.get(NOT_INITIALIZED).to_bool() and verify(): + if type_helper.to_bool(storage.get(NOT_INITIALIZED)) and verify(): storage.put(ADDRESS_PREFIX + PERSON_A, person_a_address) storage.put(TOKEN_PREFIX + PERSON_A, person_a_token) storage.put(AMOUNT_PREFIX + PERSON_A, person_a_amount) @@ -145,13 +145,13 @@ def onNEP17Payment(from_address: UInt160, amount: int, data: Any): if from_address is None and runtime.calling_script_hash == GAS_SCRIPT: return - if not storage.get(NOT_INITIALIZED).to_bool(): + if not type_helper.to_bool(storage.get(NOT_INITIALIZED)): # Used to check if the one who's transferring to this contract is the PERSON_A address = storage.get(ADDRESS_PREFIX + PERSON_A) - # Used to check if PERSON_A already transfer to this smart contract - funded_crypto = storage.get(FUNDED_PREFIX + PERSON_A).to_int() + # Used to check if PERSON_A has already transferred to this smart contract + funded_crypto = type_helper.to_int(storage.get(FUNDED_PREFIX + PERSON_A)) # Used to check if PERSON_A is transferring the correct amount - amount_crypto = storage.get(AMOUNT_PREFIX + PERSON_A).to_int() + amount_crypto = type_helper.to_int(storage.get(AMOUNT_PREFIX + PERSON_A)) # Used to check if PERSON_A is transferring the correct token token_crypto = storage.get(TOKEN_PREFIX + PERSON_A) if (from_address == address and @@ -164,9 +164,9 @@ def onNEP17Payment(from_address: UInt160, amount: int, data: Any): # Used to check if the one who's transferring to this contract is the OTHER_PERSON address = storage.get(ADDRESS_PREFIX + PERSON_B) # Used to check if PERSON_B already transfer to this smart contract - funded_crypto = storage.get(FUNDED_PREFIX + PERSON_B).to_int() + funded_crypto = type_helper.to_int(storage.get(FUNDED_PREFIX + PERSON_B)) # Used to check if PERSON_B is transferring the correct amount - amount_crypto = storage.get(AMOUNT_PREFIX + PERSON_B).to_int() + amount_crypto = type_helper.to_int(storage.get(AMOUNT_PREFIX + PERSON_B)) # Used to check if PERSON_B is transferring the correct token token_crypto = storage.get(TOKEN_PREFIX + PERSON_B) if (from_address == address and @@ -191,17 +191,19 @@ def withdraw(secret: str) -> bool: :rtype: bool """ # Checking if PERSON_A and PERSON_B transferred to this smart contract - funded_person_a = storage.get(FUNDED_PREFIX + PERSON_A).to_int() - funded_person_b = storage.get(FUNDED_PREFIX + PERSON_B).to_int() + funded_person_a = type_helper.to_int(storage.get(FUNDED_PREFIX + PERSON_A)) + funded_person_b = type_helper.to_int(storage.get(FUNDED_PREFIX + PERSON_B)) if verify() and not refund() and hash160(secret) == storage.get(SECRET_HASH) and funded_person_a != 0 and funded_person_b != 0: storage.put(FUNDED_PREFIX + PERSON_A, 0) storage.put(FUNDED_PREFIX + PERSON_B, 0) storage.put(NOT_INITIALIZED, True) storage.put(START_TIME, 0) call_contract(UInt160(storage.get(TOKEN_PREFIX + PERSON_B)), 'transfer', - [runtime.executing_script_hash, storage.get(ADDRESS_PREFIX + PERSON_A), storage.get(AMOUNT_PREFIX + PERSON_B), None]) + [runtime.executing_script_hash, storage.get(ADDRESS_PREFIX + PERSON_A), + type_helper.to_int(storage.get(AMOUNT_PREFIX + PERSON_B)), None]) call_contract(UInt160(storage.get(TOKEN_PREFIX + PERSON_A)), 'transfer', - [runtime.executing_script_hash, storage.get(ADDRESS_PREFIX + PERSON_B), storage.get(AMOUNT_PREFIX + PERSON_A), None]) + [runtime.executing_script_hash, storage.get(ADDRESS_PREFIX + PERSON_B), + type_helper.to_int(storage.get(AMOUNT_PREFIX + PERSON_A)), None]) return True return False @@ -215,18 +217,20 @@ def refund() -> bool: :return: whether enough time has passed and the cryptocurrencies were refunded :rtype: bool """ - if runtime.time > storage.get(START_TIME).to_int() + LOCK_TIME: + if runtime.time > type_helper.to_int(storage.get(START_TIME)) + LOCK_TIME: # Checking if PERSON_A transferred to this smart contract - funded_crypto = storage.get(FUNDED_PREFIX + PERSON_A).to_int() + funded_crypto = type_helper.to_int(storage.get(FUNDED_PREFIX + PERSON_A)) if funded_crypto != 0: call_contract(UInt160(storage.get(TOKEN_PREFIX + PERSON_A)), 'transfer', - [runtime.executing_script_hash, UInt160(storage.get(ADDRESS_PREFIX + PERSON_A)), storage.get(AMOUNT_PREFIX + PERSON_A).to_int(), None]) + [runtime.executing_script_hash, UInt160(storage.get(ADDRESS_PREFIX + PERSON_A)), + type_helper.to_int(storage.get(AMOUNT_PREFIX + PERSON_A)), None]) # Checking if PERSON_B transferred to this smart contract - funded_crypto = storage.get(FUNDED_PREFIX + PERSON_B).to_int() + funded_crypto = type_helper.to_int(storage.get(FUNDED_PREFIX + PERSON_B)) if funded_crypto != 0: call_contract(UInt160(storage.get(TOKEN_PREFIX + PERSON_B)), 'transfer', - [runtime.executing_script_hash, storage.get(ADDRESS_PREFIX + PERSON_B), storage.get(AMOUNT_PREFIX + PERSON_B).to_int(), None]) + [runtime.executing_script_hash, storage.get(ADDRESS_PREFIX + PERSON_B), + type_helper.to_int(storage.get(AMOUNT_PREFIX + PERSON_B)), None]) storage.put(FUNDED_PREFIX + PERSON_A, 0) storage.put(FUNDED_PREFIX + PERSON_B, 0) storage.put(NOT_INITIALIZED, True) diff --git a/boa3_test/examples/ico.py b/boa3_test/examples/ico.py index dbb03367a..6233702ae 100644 --- a/boa3_test/examples/ico.py +++ b/boa3_test/examples/ico.py @@ -8,7 +8,7 @@ from boa3.builtin.nativecontract.contractmanagement import ContractManagement from boa3.builtin.nativecontract.gas import GAS as GAS_TOKEN from boa3.builtin.nativecontract.neo import NEO as NEO_TOKEN -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -96,7 +96,7 @@ def is_valid_address(address: UInt160) -> bool: :return: whether the given address is validated by kyc """ - return storage.get(KYC_WHITELIST_PREFIX + address).to_int() > 0 + return type_helper.to_int(storage.get(KYC_WHITELIST_PREFIX + address)) > 0 @public @@ -222,7 +222,7 @@ def total_supply() -> int: :return: the total token supply deployed in the system. """ - return storage.get(TOKEN_TOTAL_SUPPLY_PREFIX).to_int() + return type_helper.to_int(storage.get(TOKEN_TOTAL_SUPPLY_PREFIX)) @public(name='balanceOf', safe=True) @@ -239,7 +239,7 @@ def balance_of(account: UInt160) -> int: :raise AssertionError: raised if `account` length is not 20. """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) @public @@ -268,7 +268,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -286,7 +286,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event @@ -359,7 +359,7 @@ def allowance(from_address: UInt160, to_address: UInt160) -> int: """ # the parameters from and to should be 20-byte addresses. If not, this method should throw an exception. assert len(from_address) == 20 and len(to_address) == 20 - return storage.get(TRANSFER_ALLOWANCE_PREFIX + from_address + to_address).to_int() + return type_helper.to_int(storage.get(TRANSFER_ALLOWANCE_PREFIX + from_address + to_address)) @public(name='transferFrom') @@ -417,7 +417,7 @@ def transfer_from(originator: UInt160, from_address: UInt160, to_address: UInt16 storage.put(originator, originator_balance - amount) # updates to's balance - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event diff --git a/boa3_test/examples/nep11_non_divisible.py b/boa3_test/examples/nep11_non_divisible.py index 66a3800d2..33050320c 100644 --- a/boa3_test/examples/nep11_non_divisible.py +++ b/boa3_test/examples/nep11_non_divisible.py @@ -15,7 +15,7 @@ from boa3.builtin.interop.stdlib import deserialize, serialize from boa3.builtin.interop.storage import delete, find, get, get_read_only_context, put from boa3.builtin.interop.storage.findoptions import FindOptions -from boa3.builtin.type import ByteString, UInt160 +from boa3.builtin.type import ByteString, UInt160, helper as type_helper # ------------------------------------------- @@ -170,8 +170,8 @@ def totalSupply() -> int: :return: the total token supply deployed in the system. """ - debug(['totalSupply: ', get(SUPPLY_PREFIX).to_int()]) - return get(SUPPLY_PREFIX, get_read_only_context()).to_int() + debug(['totalSupply: ', type_helper.to_int(get(SUPPLY_PREFIX))]) + return type_helper.to_int(get(SUPPLY_PREFIX, get_read_only_context())) @public(safe=True) @@ -187,8 +187,8 @@ def balanceOf(owner: UInt160) -> int: :raise AssertionError: raised if `owner` length is not 20. """ expect(validateAddress(owner), "Not a valid address") - debug(['balanceOf: ', get(mk_balance_key(owner), get_read_only_context()).to_int()]) - return get(mk_balance_key(owner), get_read_only_context()).to_int() + debug(['balanceOf: ', type_helper.to_int(get(mk_balance_key(owner), get_read_only_context()))]) + return type_helper.to_int(get(mk_balance_key(owner), get_read_only_context())) @public(safe=True) @@ -349,7 +349,7 @@ def _deploy(data: Any, upgrade: bool): if upgrade: return - if get(DEPLOYED, get_read_only_context()).to_bool(): + if type_helper.to_bool(get(DEPLOYED, get_read_only_context())): return tx = cast(Transaction, script_container) @@ -574,8 +574,8 @@ def updatePause(status: bool) -> bool: expect(verified, '`account` is not allowed for updatePause') expect(isinstance(status, bool), "status has to be of type bool") put(PAUSED, status) - debug(['updatePause: ', get(PAUSED, get_read_only_context()).to_bool()]) - return get(PAUSED, get_read_only_context()).to_bool() + debug(['updatePause: ', type_helper.to_bool(get(PAUSED, get_read_only_context()))]) + return type_helper.to_bool(get(PAUSED, get_read_only_context())) @public(safe=True) @@ -587,8 +587,8 @@ def isPaused() -> bool: :return: whether the contract is paused """ - debug(['isPaused: ', get(PAUSED).to_bool()]) - if get(PAUSED, get_read_only_context()).to_bool(): + debug(['isPaused: ', type_helper.to_bool(get(PAUSED))]) + if type_helper.to_bool(get(PAUSED, get_read_only_context())): return True return False @@ -689,9 +689,9 @@ def internal_mint(account: UInt160, meta: ByteString, lockedContent: ByteString, """ expect(len(meta) != 0, '`meta` can not be empty') - tokenId = get(TOKEN_COUNT, get_read_only_context()).to_int() + 1 + tokenId = type_helper.to_int(get(TOKEN_COUNT, get_read_only_context())) + 1 put(TOKEN_COUNT, tokenId) - tokenIdBytes = tokenId.to_bytes() + tokenIdBytes = type_helper.to_bytes(tokenId) set_owner_of(tokenIdBytes, account) set_balance(account, 1) @@ -745,14 +745,14 @@ def set_owner_of(tokenId: ByteString, owner: UInt160): def add_to_supply(amount: int): - total = totalSupply() + (amount) + total = totalSupply() + amount debug(['add_to_supply: ', amount]) put(SUPPLY_PREFIX, total) def set_balance(owner: UInt160, amount: int): old = balanceOf(owner) - new = old + (amount) + new = old + amount debug(['set_balance: ', amount]) key = mk_balance_key(owner) @@ -822,7 +822,7 @@ def remove_royalties(tokenId: ByteString): def get_locked_view_counter(tokenId: ByteString) -> int: key = mk_lv_key(tokenId) debug(['get_locked_view_counter: ', key, tokenId]) - return get(key, get_read_only_context()).to_int() + return type_helper.to_int(get(key, get_read_only_context())) def remove_locked_view_counter(tokenId: ByteString): @@ -834,7 +834,7 @@ def remove_locked_view_counter(tokenId: ByteString): def set_locked_view_counter(tokenId: ByteString): key = mk_lv_key(tokenId) debug(['set_locked_view_counter: ', key, tokenId]) - count = get(key, get_read_only_context()).to_int() + 1 + count = type_helper.to_int(get(key, get_read_only_context())) + 1 put(key, count) diff --git a/boa3_test/examples/nep17.py b/boa3_test/examples/nep17.py index 325795958..008021702 100644 --- a/boa3_test/examples/nep17.py +++ b/boa3_test/examples/nep17.py @@ -6,7 +6,7 @@ from boa3.builtin.interop.blockchain import Transaction from boa3.builtin.interop.contract import GAS as GAS_SCRIPT, NEO as NEO_SCRIPT, call_contract from boa3.builtin.nativecontract.contractmanagement import ContractManagement -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -102,7 +102,7 @@ def total_supply() -> int: :return: the total token supply deployed in the system. """ - return storage.get(SUPPLY_KEY).to_int() + return type_helper.to_int(storage.get(SUPPLY_KEY)) @public(name='balanceOf', safe=True) @@ -116,7 +116,7 @@ def balance_of(account: UInt160) -> int: :type account: UInt160 """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) @public @@ -145,7 +145,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -163,7 +163,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event diff --git a/boa3_test/examples/nep5.py b/boa3_test/examples/nep5.py index e898cdc2b..b2b6760c8 100644 --- a/boa3_test/examples/nep5.py +++ b/boa3_test/examples/nep5.py @@ -9,7 +9,7 @@ from boa3.builtin.contract import Nep5TransferEvent from boa3.builtin.interop import runtime, storage from boa3.builtin.interop.blockchain import Transaction -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -142,7 +142,7 @@ def balanceOf(account: bytes) -> int: :raise AssertionError: raised if `account` length is not 20. """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) @public @@ -169,7 +169,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int) -> bool: assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -192,7 +192,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int) -> bool: else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event, and must return true diff --git a/boa3_test/examples/update_contract.py b/boa3_test/examples/update_contract.py index d2790729d..6396cf844 100644 --- a/boa3_test/examples/update_contract.py +++ b/boa3_test/examples/update_contract.py @@ -5,7 +5,7 @@ from boa3.builtin.interop.blockchain import Transaction from boa3.builtin.interop.runtime import check_witness from boa3.builtin.nativecontract.contractmanagement import ContractManagement -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- # TOKEN SETTINGS @@ -78,7 +78,7 @@ def method(account: UInt160): This method is not working as intended and ends up giving tokens to a user whenever he wants. """ # some omitted code - storage.put(account, storage.get(account).to_int() + 2 * 10 ** 8) + storage.put(account, type_helper.to_int(storage.get(account)) + 2 * 10 ** 8) on_transfer(None, account, 2 * 10 ** 8) # more omitted code @@ -103,7 +103,7 @@ def balance_of(account: UInt160) -> int: Get the current balance of an address. """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) def get_owner() -> UInt160: diff --git a/boa3_test/examples/wrapped_gas.py b/boa3_test/examples/wrapped_gas.py index cd1e82993..c49258d53 100644 --- a/boa3_test/examples/wrapped_gas.py +++ b/boa3_test/examples/wrapped_gas.py @@ -6,7 +6,7 @@ from boa3.builtin.interop.contract import GAS as GAS_SCRIPT, call_contract from boa3.builtin.nativecontract.contractmanagement import ContractManagement from boa3.builtin.nativecontract.gas import GAS as GAS_TOKEN -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -108,7 +108,7 @@ def total_supply() -> int: :return: the total token supply deployed in the system. """ - return storage.get(SUPPLY_KEY).to_int() + return type_helper.to_int(storage.get(SUPPLY_KEY)) @public(name='balanceOf', safe=True) @@ -122,7 +122,7 @@ def balance_of(account: UInt160) -> int: :type account: bytes """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) @public @@ -151,7 +151,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -169,7 +169,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event @@ -209,7 +209,7 @@ def transfer_from(spender: UInt160, from_address: UInt160, to_address: UInt160, assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -237,7 +237,7 @@ def transfer_from(spender: UInt160, from_address: UInt160, to_address: UInt160, else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event @@ -286,7 +286,7 @@ def allowance(owner: UInt160, spender: UInt160) -> int: :param spender: the address that can spend zGAS from the owner's account :type spender: UInt160 """ - return storage.get(ALLOWANCE_PREFIX + owner + spender).to_int() + return type_helper.to_int(storage.get(ALLOWANCE_PREFIX + owner + spender)) def post_transfer(from_address: Union[UInt160, None], to_address: Union[UInt160, None], amount: int, data: Any, diff --git a/boa3_test/examples/wrapped_neo.py b/boa3_test/examples/wrapped_neo.py index 9bcee6271..bd3af7ee9 100644 --- a/boa3_test/examples/wrapped_neo.py +++ b/boa3_test/examples/wrapped_neo.py @@ -7,7 +7,7 @@ from boa3.builtin.interop.contract import GAS as GAS_SCRIPT, NEO as NEO_SCRIPT, call_contract from boa3.builtin.nativecontract.contractmanagement import ContractManagement from boa3.builtin.nativecontract.neo import NEO as NEO_TOKEN -from boa3.builtin.type import UInt160 +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -108,7 +108,7 @@ def total_supply() -> int: :return: the total token supply deployed in the system. """ - return storage.get(SUPPLY_KEY).to_int() + return type_helper.to_int(storage.get(SUPPLY_KEY)) @public(name='balanceOf', safe=True) @@ -122,7 +122,7 @@ def balance_of(account: UInt160) -> int: :type account: bytes """ assert len(account) == 20 - return storage.get(account).to_int() + return type_helper.to_int(storage.get(account)) @public @@ -151,7 +151,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -169,7 +169,7 @@ def transfer(from_address: UInt160, to_address: UInt160, amount: int, data: Any) else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event @@ -209,7 +209,7 @@ def transfer_from(spender: UInt160, from_address: UInt160, to_address: UInt160, assert amount >= 0 # The function MUST return false if the from account balance does not have enough tokens to spend. - from_balance = storage.get(from_address).to_int() + from_balance = type_helper.to_int(storage.get(from_address)) if from_balance < amount: return False @@ -237,7 +237,7 @@ def transfer_from(spender: UInt160, from_address: UInt160, to_address: UInt160, else: storage.put(from_address, from_balance - amount) - to_balance = storage.get(to_address).to_int() + to_balance = type_helper.to_int(storage.get(to_address)) storage.put(to_address, to_balance + amount) # if the method succeeds, it must fire the transfer event @@ -286,7 +286,7 @@ def allowance(owner: UInt160, spender: UInt160) -> int: :param spender: the address that can spend zNEO from the owner's account :type spender: UInt160 """ - return storage.get(ALLOWANCE_PREFIX + owner + spender).to_int() + return type_helper.to_int(storage.get(ALLOWANCE_PREFIX + owner + spender)) def post_transfer(from_address: Union[UInt160, None], to_address: Union[UInt160, None], amount: int, data: Any, diff --git a/boa3_test/test_sc/arithmetic_test/ConcatBytesVariablesAndConstants.py b/boa3_test/test_sc/arithmetic_test/ConcatBytesVariablesAndConstants.py index 191e5f20b..8f23f3698 100644 --- a/boa3_test/test_sc/arithmetic_test/ConcatBytesVariablesAndConstants.py +++ b/boa3_test/test_sc/arithmetic_test/ConcatBytesVariablesAndConstants.py @@ -1,5 +1,6 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.runtime import address_version +from boa3.builtin.type.helper import to_bytes VALUE1 = b'value1' @@ -9,17 +10,17 @@ @public def concat1() -> bytes: - current_time = address_version.to_bytes() + b'some_bytes_after' + current_time = to_bytes(address_version) + b'some_bytes_after' return VALUE1 + b' ' + VALUE2 + b' ' + VALUE3 + b' ' + current_time @public def concat2() -> bytes: - current_time = address_version.to_bytes() + b'some_bytes_after' + current_time = to_bytes(address_version) + b'some_bytes_after' return VALUE1 + VALUE2 + VALUE3 + current_time @public def concat3() -> bytes: - current_time = address_version.to_bytes() + b'some_bytes_after' + current_time = to_bytes(address_version) + b'some_bytes_after' return VALUE1 + b'__' + VALUE2 + b'__' + VALUE3 + b'__' + current_time diff --git a/boa3_test/test_sc/built_in_methods_test/IntToBytes.py b/boa3_test/test_sc/built_in_methods_test/IntToBytes.py index 8bc434705..8063a06a5 100644 --- a/boa3_test/test_sc/built_in_methods_test/IntToBytes.py +++ b/boa3_test/test_sc/built_in_methods_test/IntToBytes.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bytes @public def int_to_bytes() -> bytes: - return (123).to_bytes() + return to_bytes(123) diff --git a/boa3_test/test_sc/built_in_methods_test/IntToBytesAsParameter.py b/boa3_test/test_sc/built_in_methods_test/IntToBytesAsParameter.py index 2d3c62ce6..6a03d0b50 100644 --- a/boa3_test/test_sc/built_in_methods_test/IntToBytesAsParameter.py +++ b/boa3_test/test_sc/built_in_methods_test/IntToBytesAsParameter.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop import storage from boa3.builtin.interop.stdlib import serialize +from boa3.builtin.type.helper import to_bytes @public @@ -15,7 +16,7 @@ def return_bytes(value: bytes) -> bytes: class Example: def __init__(self, current_supply: int): - set_value(current_supply.to_bytes(), self) + set_value(to_bytes(current_supply), self) def set_value(token_id: bytes, example_class: Example): diff --git a/boa3_test/test_sc/built_in_methods_test/IntToBytesWithBuiltin.py b/boa3_test/test_sc/built_in_methods_test/IntToBytesWithBuiltin.py index 0a53bc52d..86db6ad4c 100644 --- a/boa3_test/test_sc/built_in_methods_test/IntToBytesWithBuiltin.py +++ b/boa3_test/test_sc/built_in_methods_test/IntToBytesWithBuiltin.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def int_to_bytes() -> bytes: return int.to_bytes(123) diff --git a/boa3_test/test_sc/built_in_methods_test/IntZeroToBytes.py b/boa3_test/test_sc/built_in_methods_test/IntZeroToBytes.py index 2bf4301d9..662dc7a2d 100644 --- a/boa3_test/test_sc/built_in_methods_test/IntZeroToBytes.py +++ b/boa3_test/test_sc/built_in_methods_test/IntZeroToBytes.py @@ -1,7 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bytes @public def int_to_bytes() -> bytes: - - return (0).to_bytes() + return to_bytes(0) diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashBuiltinMismatchedType.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashBuiltinWrongUsage.py similarity index 100% rename from boa3_test/test_sc/built_in_methods_test/ScriptHashBuiltinMismatchedType.py rename to boa3_test/test_sc/built_in_methods_test/ScriptHashBuiltinWrongUsage.py diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashInt.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashInt.py index 56b752725..138e08ed5 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashInt.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashInt.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.contract import to_script_hash @public def Main() -> bytes: - return (123).to_script_hash() + return to_script_hash(123) diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashIntBuiltinCall.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashIntBuiltinCall.py index 869ba30cc..b01875e0c 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashIntBuiltinCall.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashIntBuiltinCall.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def Main() -> bytes: return int.to_script_hash(123) diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashMismatchedType.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashMismatchedType.py index 2adced0b5..e01525a31 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashMismatchedType.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashMismatchedType.py @@ -1,2 +1,5 @@ +from boa3.builtin.contract import to_script_hash + + def Main() -> bytes: - return [1, 2, 3].to_script_hash() + return to_script_hash([1, 2, 3]) diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashStr.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashStr.py index 63ad69467..01d137526 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashStr.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashStr.py @@ -1,11 +1,12 @@ from boa3.builtin.compile_time import public +from boa3.builtin.contract import to_script_hash @public def Main() -> bytes: - return 'NUnLWXALK2G6gYa7RadPLRiQYunZHnncxg '.to_script_hash() + return to_script_hash('NUnLWXALK2G6gYa7RadPLRiQYunZHnncxg ') @public def Main2() -> bytes: - return '123'.to_script_hash() + return to_script_hash('123') diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashStrBuiltinCall.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashStrBuiltinCall.py index 2cf97bfa1..ee0950618 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashStrBuiltinCall.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashStrBuiltinCall.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def Main() -> bytes: return str.to_script_hash('123') diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashTooFewParameters.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashTooFewParameters.py index 38343ad90..ac12b74ca 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashTooFewParameters.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashTooFewParameters.py @@ -1,2 +1,5 @@ +from boa3.builtin.contract import to_script_hash + + def Main() -> bytes: - return int.to_script_hash() + return to_script_hash() diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashTooManyParameters.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashTooManyParameters.py index 308761e4f..851cc892a 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashTooManyParameters.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashTooManyParameters.py @@ -1,2 +1,5 @@ +from boa3.builtin.contract import to_script_hash + + def Main() -> bytes: - return (123).to_script_hash(123) + return to_script_hash(123, 123) diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashVariable.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashVariable.py index 7b2bcbb68..c178b62bf 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashVariable.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashVariable.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.contract import to_script_hash @public def Main(a: bytes) -> bytes: - return a.to_script_hash() + return to_script_hash(a) diff --git a/boa3_test/test_sc/built_in_methods_test/ScriptHashVariableBuiltinCall.py b/boa3_test/test_sc/built_in_methods_test/ScriptHashVariableBuiltinCall.py index afd555a74..6b468bebc 100644 --- a/boa3_test/test_sc/built_in_methods_test/ScriptHashVariableBuiltinCall.py +++ b/boa3_test/test_sc/built_in_methods_test/ScriptHashVariableBuiltinCall.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def Main(a: bytes) -> bytes: return bytes.to_script_hash(a) diff --git a/boa3_test/test_sc/built_in_methods_test/StrToBytes.py b/boa3_test/test_sc/built_in_methods_test/StrToBytes.py index dccabb070..af6ca6b44 100644 --- a/boa3_test/test_sc/built_in_methods_test/StrToBytes.py +++ b/boa3_test/test_sc/built_in_methods_test/StrToBytes.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bytes @public def str_to_bytes() -> bytes: - return '123'.to_bytes() + return to_bytes('123') diff --git a/boa3_test/test_sc/built_in_methods_test/StrToBytesWithBuiltin.py b/boa3_test/test_sc/built_in_methods_test/StrToBytesWithBuiltin.py index 6f4f7f5cf..6c3b07199 100644 --- a/boa3_test/test_sc/built_in_methods_test/StrToBytesWithBuiltin.py +++ b/boa3_test/test_sc/built_in_methods_test/StrToBytesWithBuiltin.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def str_to_bytes() -> bytes: return str.to_bytes('123') diff --git a/boa3_test/test_sc/built_in_methods_test/ToBytesMismatchedType.py b/boa3_test/test_sc/built_in_methods_test/ToBytesMismatchedType.py index d5b902175..64ff2a100 100644 --- a/boa3_test/test_sc/built_in_methods_test/ToBytesMismatchedType.py +++ b/boa3_test/test_sc/built_in_methods_test/ToBytesMismatchedType.py @@ -1,2 +1,5 @@ +from boa3.builtin.type.helper import to_bytes + + def list_to_bytes() -> bytes: - return ['1', '2', '3'].to_bytes() + return to_bytes(['1', '2', '3']) diff --git a/boa3_test/test_sc/bytes_test/BytearrayToInt.py b/boa3_test/test_sc/bytes_test/BytearrayToInt.py index b5bda1815..aa2c48c45 100644 --- a/boa3_test/test_sc/bytes_test/BytearrayToInt.py +++ b/boa3_test/test_sc/bytes_test/BytearrayToInt.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_int @public def bytes_to_int() -> int: - return bytearray(b'\x01\x02').to_int() + return to_int(bytearray(b'\x01\x02')) diff --git a/boa3_test/test_sc/bytes_test/BytearrayToIntWithBuiltin.py b/boa3_test/test_sc/bytes_test/BytearrayToIntWithBuiltin.py index 45c8db802..bc46e490f 100644 --- a/boa3_test/test_sc/bytes_test/BytearrayToIntWithBuiltin.py +++ b/boa3_test/test_sc/bytes_test/BytearrayToIntWithBuiltin.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def bytes_to_int() -> int: return bytearray.to_int(bytearray(b'\x01\x02')) diff --git a/boa3_test/test_sc/bytes_test/BytearrayToIntWithBytesBuiltin.py b/boa3_test/test_sc/bytes_test/BytearrayToIntWithBytesBuiltin.py index bbd3e126a..12f87e5e2 100644 --- a/boa3_test/test_sc/bytes_test/BytearrayToIntWithBytesBuiltin.py +++ b/boa3_test/test_sc/bytes_test/BytearrayToIntWithBytesBuiltin.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def bytes_to_int() -> int: return bytes.to_int(bytearray(b'\x01\x02')) diff --git a/boa3_test/test_sc/bytes_test/BytesToBool.py b/boa3_test/test_sc/bytes_test/BytesToBool.py index 823241404..fce5f2015 100644 --- a/boa3_test/test_sc/bytes_test/BytesToBool.py +++ b/boa3_test/test_sc/bytes_test/BytesToBool.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bool @public def bytes_to_bool(args: bytes) -> bool: - return args.to_bool() + return to_bool(args) diff --git a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltin.py b/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltin.py index 7f38ae203..c7a42476b 100644 --- a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltin.py +++ b/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltin.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def bytes_to_bool(args: bytes) -> bool: return bytes.to_bool(args) diff --git a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedFalse.py b/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedFalse.py deleted file mode 100644 index 4820cf84d..000000000 --- a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedFalse.py +++ /dev/null @@ -1,6 +0,0 @@ -from boa3.builtin.compile_time import public - - -@public -def bytes_to_bool() -> bool: - return bytes.to_bool(b'\x00') diff --git a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedTrue.py b/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedTrue.py deleted file mode 100644 index 1693d335f..000000000 --- a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinHardCodedTrue.py +++ /dev/null @@ -1,6 +0,0 @@ -from boa3.builtin.compile_time import public - - -@public -def bytes_to_bool() -> bool: - return bytes.to_bool(b'\x01') diff --git a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinMismatchedTypes.py b/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinMismatchedTypes.py deleted file mode 100644 index fc9677a4c..000000000 --- a/boa3_test/test_sc/bytes_test/BytesToBoolWithBuiltinMismatchedTypes.py +++ /dev/null @@ -1,2 +0,0 @@ -def bytes_to_bool() -> bool: - return bytes.to_bool('ab') diff --git a/boa3_test/test_sc/bytes_test/BytesToInt.py b/boa3_test/test_sc/bytes_test/BytesToInt.py index 959071989..415fb2e3a 100644 --- a/boa3_test/test_sc/bytes_test/BytesToInt.py +++ b/boa3_test/test_sc/bytes_test/BytesToInt.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_int @public def bytes_to_int() -> int: - return b'\x01\x02'.to_int() + return to_int(b'\x01\x02') diff --git a/boa3_test/test_sc/bytes_test/BytesToIntWithBuiltin.py b/boa3_test/test_sc/bytes_test/BytesToIntWithBuiltin.py index 1d4c4cc0a..0414502d5 100644 --- a/boa3_test/test_sc/bytes_test/BytesToIntWithBuiltin.py +++ b/boa3_test/test_sc/bytes_test/BytesToIntWithBuiltin.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def bytes_to_int() -> int: return bytes.to_int(b'\x01\x02') diff --git a/boa3_test/test_sc/bytes_test/BytesToIntWithBuiltinMismatchedTypes.py b/boa3_test/test_sc/bytes_test/BytesToIntWithBuiltinMismatchedTypes.py deleted file mode 100644 index 2c58ff138..000000000 --- a/boa3_test/test_sc/bytes_test/BytesToIntWithBuiltinMismatchedTypes.py +++ /dev/null @@ -1,2 +0,0 @@ -def bytes_to_int() -> int: - return bytes.to_int('ab') diff --git a/boa3_test/test_sc/bytes_test/BytesToIntWithBytearrayBuiltin.py b/boa3_test/test_sc/bytes_test/BytesToIntWithBytearrayBuiltin.py deleted file mode 100644 index 5ed15f241..000000000 --- a/boa3_test/test_sc/bytes_test/BytesToIntWithBytearrayBuiltin.py +++ /dev/null @@ -1,2 +0,0 @@ -def bytes_to_int() -> int: - return bytearray.to_int(b'\x01\x02') diff --git a/boa3_test/test_sc/bytes_test/BytesToStr.py b/boa3_test/test_sc/bytes_test/BytesToStr.py index 3812cb774..2797adc8c 100644 --- a/boa3_test/test_sc/bytes_test/BytesToStr.py +++ b/boa3_test/test_sc/bytes_test/BytesToStr.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_str @public def bytes_to_str() -> str: - return b'abc'.to_str() + return to_str(b'abc') diff --git a/boa3_test/test_sc/bytes_test/BytesToStrWithBuiltin.py b/boa3_test/test_sc/bytes_test/BytesToStrWithBuiltin.py index a916e90a7..ea6f08263 100644 --- a/boa3_test/test_sc/bytes_test/BytesToStrWithBuiltin.py +++ b/boa3_test/test_sc/bytes_test/BytesToStrWithBuiltin.py @@ -1,6 +1,2 @@ -from boa3.builtin.compile_time import public - - -@public def bytes_to_str() -> str: return bytes.to_str(b'123') diff --git a/boa3_test/test_sc/bytes_test/BytesToStrWithBuiltinMismatchedTypes.py b/boa3_test/test_sc/bytes_test/BytesToStrWithBuiltinMismatchedTypes.py deleted file mode 100644 index 2c7c93b1e..000000000 --- a/boa3_test/test_sc/bytes_test/BytesToStrWithBuiltinMismatchedTypes.py +++ /dev/null @@ -1,2 +0,0 @@ -def bytes_to_str() -> str: - return bytes.to_str(123) diff --git a/boa3_test/test_sc/function_test/FunctionAsArg.py b/boa3_test/test_sc/function_test/FunctionAsArg.py index 811f69711..54959ea04 100644 --- a/boa3_test/test_sc/function_test/FunctionAsArg.py +++ b/boa3_test/test_sc/function_test/FunctionAsArg.py @@ -1,12 +1,13 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bytes, to_int @public def main(value: int) -> int: - var = return_int(value.to_bytes()) + var = return_int(to_bytes(value)) return var def return_int(arg1: bytes) -> int: - return arg1.to_int() + return to_int(arg1) diff --git a/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHash.py b/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHash.py index 596bd2b15..1db1d0b31 100644 --- a/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHash.py +++ b/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHash.py @@ -1,7 +1,8 @@ from boa3.builtin.compile_time import public +from boa3.builtin.contract import to_script_hash from boa3.builtin.type import ScriptHash @public def Main() -> ScriptHash: - return int.to_script_hash(123) + return to_script_hash(123) diff --git a/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHashLittleEndian.py b/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHashLittleEndian.py index 2cb0f5008..8116aeb2f 100644 --- a/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHashLittleEndian.py +++ b/boa3_test/test_sc/generation_test/ManifestTypeHintFromUInt160ToScriptHashLittleEndian.py @@ -1,7 +1,8 @@ from boa3.builtin.compile_time import public +from boa3.builtin.contract import to_script_hash from boa3.builtin.type import ScriptHashLittleEndian @public def Main() -> ScriptHashLittleEndian: - return int.to_script_hash(123) + return to_script_hash(123) diff --git a/boa3_test/test_sc/if_test/IfElseIsInstanceConditionWithUnionVariable.py b/boa3_test/test_sc/if_test/IfElseIsInstanceConditionWithUnionVariable.py index eda28472d..d5e73deee 100644 --- a/boa3_test/test_sc/if_test/IfElseIsInstanceConditionWithUnionVariable.py +++ b/boa3_test/test_sc/if_test/IfElseIsInstanceConditionWithUnionVariable.py @@ -1,11 +1,12 @@ from typing import Union from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bytes @public def example(value: Union[str, int]) -> bytes: - if isinstance(value, int): - return value.to_bytes() + if isinstance(value, str): + return to_bytes(value) else: - return value.to_bytes() + return to_bytes(value) diff --git a/boa3_test/test_sc/if_test/IfWithInnerFor.py b/boa3_test/test_sc/if_test/IfWithInnerFor.py index 59de6bab7..d486e8f45 100644 --- a/boa3_test/test_sc/if_test/IfWithInnerFor.py +++ b/boa3_test/test_sc/if_test/IfWithInnerFor.py @@ -1,4 +1,5 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bytes, to_str @public @@ -12,7 +13,7 @@ def Main(condition: bool) -> str: id_destiny = "" for c in some_string: - if c.to_bytes().to_str() != "|": + if to_str(to_bytes(c)) != "|": id_destiny = id_destiny + c else: if count > 0: diff --git a/boa3_test/test_sc/if_test/IfWithInnerWhile.py b/boa3_test/test_sc/if_test/IfWithInnerWhile.py index e12a3cdf8..3808fd944 100644 --- a/boa3_test/test_sc/if_test/IfWithInnerWhile.py +++ b/boa3_test/test_sc/if_test/IfWithInnerWhile.py @@ -1,4 +1,5 @@ from boa3.builtin.compile_time import public +from boa3.builtin.type.helper import to_bytes, to_str @public @@ -14,7 +15,7 @@ def Main(condition: bool) -> str: while index < len(some_string): c = some_string[index:index + 1] - if c.to_bytes().to_str() != "|": + if to_str(to_bytes(c)) != "|": id_destiny = id_destiny + c else: if count > 0: diff --git a/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py b/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py index b80523edf..fc310a5b4 100644 --- a/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py +++ b/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py @@ -4,6 +4,7 @@ from boa3.builtin.interop.contract import NEO, call_contract from boa3.builtin.interop.runtime import executing_script_hash, notify from boa3.builtin.interop.storage import get, put +from boa3.builtin.type.helper import to_int @public @@ -23,4 +24,4 @@ def put_value(key: str, value: int): @public def get_value(key: str) -> int: - return get(key).to_int() + return to_int(get(key)) diff --git a/boa3_test/test_sc/interop_test/contract/NewContract.py b/boa3_test/test_sc/interop_test/contract/NewContract.py index 8c3976f02..23c8b6faf 100644 --- a/boa3_test/test_sc/interop_test/contract/NewContract.py +++ b/boa3_test/test_sc/interop_test/contract/NewContract.py @@ -3,11 +3,12 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.runtime import notify from boa3.builtin.interop.storage import get, put +from boa3.builtin.type.helper import to_str @public def main() -> str: - return get('storage').to_str() + return to_str(get('storage')) @public diff --git a/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py b/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py index d2e0af6ff..93c2b5c57 100644 --- a/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py +++ b/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py @@ -1,6 +1,7 @@ from boa3.builtin import interop from boa3.builtin.compile_time import public from boa3.builtin.interop.iterator import Iterator +from boa3.builtin.type.helper import to_int @public @@ -10,7 +11,7 @@ def put_value(key: str, value: int): @public def get_value(key: str) -> int: - return interop.storage.get(key).to_int() + return to_int(interop.storage.get(key)) @public diff --git a/boa3_test/test_sc/interop_test/storage/ImportStorage.py b/boa3_test/test_sc/interop_test/storage/ImportStorage.py index b84d0f573..95410443d 100644 --- a/boa3_test/test_sc/interop_test/storage/ImportStorage.py +++ b/boa3_test/test_sc/interop_test/storage/ImportStorage.py @@ -1,6 +1,7 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop import storage from boa3.builtin.interop.iterator import Iterator +from boa3.builtin.type.helper import to_int @public @@ -10,7 +11,7 @@ def put_value(key: str, value: int): @public def get_value(key: str) -> int: - return storage.get(key).to_int() + return to_int(storage.get(key)) @public diff --git a/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py b/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py index d594e1419..2c9eceb8a 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py +++ b/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py @@ -1,5 +1,6 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.storage import get, get_context, put +from boa3.builtin.type.helper import to_str @public @@ -9,7 +10,7 @@ def put_value_in_storage(key: str, value: str): @public def get_value_in_storage(key: str) -> str: - return get(key).to_str() + return to_str(get(key)) @public @@ -19,4 +20,4 @@ def put_value_in_storage_read_only(key: str, value: str): @public def get_value_in_storage_read_only(key: str) -> str: - return get(key, get_context().as_read_only()).to_str() + return to_str(get(key, get_context().as_read_only())) diff --git a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py index 069a87422..c72b2dd0d 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py +++ b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py @@ -1,5 +1,6 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.storage import get, put +from boa3.builtin.type.helper import to_int @public @@ -9,4 +10,4 @@ def put_value(key: str, value: int): @public def get_value(key: str) -> int: - return get(key).to_int() + return to_int(get(key)) diff --git a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py index 1ee7a2ba4..8c7bbd388 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py +++ b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py @@ -1,10 +1,11 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.storage import get, put +from boa3.builtin.type.helper import to_int @public def get_value(key: str) -> int: - return get(key).to_int() + return to_int(get(key)) @public diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py index 8cf3b500d..5d0492dc7 100644 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py +++ b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py @@ -1,7 +1,5 @@ -from boa3.builtin.compile_time import public from boa3.builtin.type import ByteString -@public def to_bool(arg: ByteString) -> bool: return arg.to_bool() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBoolWithBuiltin.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBoolWithBuiltin.py deleted file mode 100644 index b9bdc8f92..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBoolWithBuiltin.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def to_bool(arg: ByteString) -> bool: - return ByteString.to_bool(arg) diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py index e6f103be7..9079c1279 100644 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py +++ b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py @@ -1,7 +1,5 @@ -from boa3.builtin.compile_time import public from boa3.builtin.type import ByteString -@public def to_bytes(arg: ByteString) -> bytes: return arg.to_bytes() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytesWithBuiltin.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytesWithBuiltin.py deleted file mode 100644 index 3350ba9be..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytesWithBuiltin.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def to_bytes(arg: ByteString) -> bytes: - return ByteString.to_bytes(arg) diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py index 12f67afee..66b2a2a72 100644 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py +++ b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py @@ -1,7 +1,5 @@ -from boa3.builtin.compile_time import public from boa3.builtin.type import ByteString -@public def to_int(arg: ByteString) -> int: return arg.to_int() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToIntWithBuiltin.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToIntWithBuiltin.py deleted file mode 100644 index ab830009d..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToIntWithBuiltin.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def to_int(arg: ByteString) -> int: - return ByteString.to_int(arg) diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py index 1077dea34..444360dae 100644 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py +++ b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py @@ -1,7 +1,5 @@ -from boa3.builtin.compile_time import public from boa3.builtin.type import ByteString -@public def to_str(arg: ByteString) -> str: return arg.to_str() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStrWithBuiltin.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStrWithBuiltin.py deleted file mode 100644 index 99ef37a4b..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStrWithBuiltin.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def to_str(arg: ByteString) -> str: - return ByteString.to_str(arg) diff --git a/boa3_test/test_sc/typing_test/CastPersistedInScope.py b/boa3_test/test_sc/typing_test/CastPersistedInScope.py index 401ffaea6..5d2f63703 100644 --- a/boa3_test/test_sc/typing_test/CastPersistedInScope.py +++ b/boa3_test/test_sc/typing_test/CastPersistedInScope.py @@ -3,6 +3,7 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop import runtime from boa3.builtin.type import UInt160 +from boa3.builtin.type.helper import to_str TEST_AMOUNT_1 = 10 TEST_AMOUNT_2 = 2 @@ -25,4 +26,4 @@ def main(from_address: Union[UInt160, None], amount: int, data: Any): def mint(account: UInt160, amount: int): assert amount >= 0 if amount != 0: - runtime.log(account.to_str()) + runtime.log(to_str(account)) diff --git a/boa3_test/tests/compiler_tests/test_builtin_method.py b/boa3_test/tests/compiler_tests/test_builtin_method.py index 26edb6e1c..d921edac6 100644 --- a/boa3_test/tests/compiler_tests/test_builtin_method.py +++ b/boa3_test/tests/compiler_tests/test_builtin_method.py @@ -526,23 +526,8 @@ def test_script_hash_int(self): self.assertEqual(expected_results[x], invokes[x].result) def test_script_hash_int_with_builtin(self): - path, _ = self.get_deploy_file_paths('ScriptHashIntBuiltinCall.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - from boa3.internal.neo import to_script_hash - script_hash = to_script_hash(Integer(123).to_byte_array()) - - invokes.append(runner.call_contract(path, 'Main')) - expected_results.append(script_hash) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('ScriptHashIntBuiltinCall.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_script_hash_str(self): path, _ = self.get_deploy_file_paths('ScriptHashStr.py') @@ -569,24 +554,8 @@ def test_script_hash_str(self): self.assertEqual(expected_results[x], invokes[x].result) def test_script_hash_str_with_builtin(self): - path, _ = self.get_deploy_file_paths('ScriptHashStrBuiltinCall.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - from boa3.internal.neo import to_script_hash - script_hash = to_script_hash(String('123').to_bytes()) - - invokes.append(runner.call_contract(path, 'Main', - expected_result_type=bytes)) - expected_results.append(script_hash) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('ScriptHashStrBuiltinCall.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_script_hash_variable(self): path, _ = self.get_deploy_file_paths('ScriptHashVariable.py') @@ -618,34 +587,8 @@ def test_script_hash_variable(self): self.assertEqual(VMState.FAULT, runner.vm_state, msg=runner.cli_log) def test_script_hash_variable_with_builtin(self): - path, _ = self.get_deploy_file_paths('ScriptHashVariableBuiltinCall.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - from boa3.internal.neo import to_script_hash - from base58 import b58encode - - script_hash = to_script_hash(String('123').to_bytes()) - invokes.append(runner.call_contract(path, 'Main', '123', - expected_result_type=bytes)) - expected_results.append(script_hash) - - value = b58encode('123') - if isinstance(value, int): - value = Integer(value).to_byte_array() - - script_hash = to_script_hash(value) - invokes.append(runner.call_contract(path, 'Main', value, - expected_result_type=bytes)) - expected_results.append(script_hash) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('ScriptHashVariableBuiltinCall.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_script_hash_too_many_parameters(self): path = self.get_contract_path('ScriptHashTooManyParameters.py') @@ -659,9 +602,9 @@ def test_script_hash_mismatched_types(self): path = self.get_contract_path('ScriptHashMismatchedType.py') self.assertCompilerLogs(CompilerError.MismatchedTypes, path) - def test_script_hash_builtin_mismatched_types(self): - path = self.get_contract_path('ScriptHashBuiltinMismatchedType.py') - self.assertCompilerLogs(CompilerError.MismatchedTypes, path) + def test_script_hash_builtin(self): + path = self.get_contract_path('ScriptHashBuiltinWrongUsage.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) # endregion @@ -704,22 +647,8 @@ def test_int_zero_to_bytes(self): self.assertEqual(expected_results[x], invokes[x].result) def test_int_to_bytes_with_builtin(self): - path, _ = self.get_deploy_file_paths('IntToBytesWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - value = Integer(123).to_byte_array() - invokes.append(runner.call_contract(path, 'int_to_bytes', - expected_result_type=bytes)) - expected_results.append(value) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('IntToBytesWithBuiltin.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_int_to_bytes_as_parameter(self): path, _ = self.get_deploy_file_paths('IntToBytesAsParameter.py') @@ -769,33 +698,8 @@ def test_str_to_bytes(self): self.assertEqual(expected_results[x], invokes[x].result) def test_str_to_bytes_with_builtin(self): - value = String('123').to_bytes() - expected_output = ( - Opcode.PUSHDATA1 # str.to_bytes('123') - + Integer(len(value)).to_byte_array(min_length=1) - + value - + Opcode.RET - ) - path = self.get_contract_path('StrToBytesWithBuiltin.py') - output = self.compile(path) - self.assertEqual(expected_output, output) - - path, _ = self.get_deploy_file_paths(path) - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'str_to_bytes', - expected_result_type=bytes)) - expected_results.append(value) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_to_bytes_mismatched_types(self): path = self.get_contract_path('ToBytesMismatchedType.py') diff --git a/boa3_test/tests/compiler_tests/test_bytes.py b/boa3_test/tests/compiler_tests/test_bytes.py index fa7684bf5..77721b856 100644 --- a/boa3_test/tests/compiler_tests/test_bytes.py +++ b/boa3_test/tests/compiler_tests/test_bytes.py @@ -139,28 +139,8 @@ def test_bytes_to_int(self): self.assertEqual(expected_results[x], invokes[x].result) def test_bytes_to_int_with_builtin(self): - path, _ = self.get_deploy_file_paths('BytesToIntWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytes_to_int')) - expected_results.append(513) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_bytes_to_int_mismatched_types(self): - path = self.get_contract_path('BytesToIntWithBuiltinMismatchedTypes.py') - self.assertCompilerLogs(CompilerError.MismatchedTypes, path) - - def test_bytes_to_int_with_byte_array_builtin(self): - path = self.get_contract_path('BytesToIntWithBytearrayBuiltin.py') - self.assertCompilerLogs(CompilerError.MismatchedTypes, path) + path = self.get_contract_path('BytesToIntWithBuiltin.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_bytes_to_bool(self): path, _ = self.get_deploy_file_paths('BytesToBool.py') @@ -185,62 +165,8 @@ def test_bytes_to_bool(self): self.assertEqual(expected_results[x], invokes[x].result) def test_bytes_to_bool_with_builtin(self): - path, _ = self.get_deploy_file_paths('BytesToBoolWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytes_to_bool', b'\x00')) - expected_results.append(False) - - invokes.append(runner.call_contract(path, 'bytes_to_bool', b'\x01')) - expected_results.append(True) - - invokes.append(runner.call_contract(path, 'bytes_to_bool', b'\x02')) - expected_results.append(True) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_bytes_to_bool_with_builtin_hard_coded_false(self): - path, _ = self.get_deploy_file_paths('BytesToBoolWithBuiltinHardCodedFalse.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytes_to_bool')) - expected_results.append(False) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_bytes_to_bool_with_builtin_hard_coded_true(self): - path, _ = self.get_deploy_file_paths('BytesToBoolWithBuiltinHardCodedTrue.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytes_to_bool')) - expected_results.append(True) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_bytes_to_bool_mismatched_types(self): - path = self.get_contract_path('BytesToBoolWithBuiltinMismatchedTypes.py') - self.assertCompilerLogs(CompilerError.MismatchedTypes, path) + path = self.get_contract_path('BytesToBoolWithBuiltin.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_bytes_to_str(self): path, _ = self.get_deploy_file_paths('BytesToStr.py') @@ -259,24 +185,8 @@ def test_bytes_to_str(self): self.assertEqual(expected_results[x], invokes[x].result) def test_bytes_to_str_with_builtin(self): - path, _ = self.get_deploy_file_paths('BytesToStrWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytes_to_str')) - expected_results.append('123') - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_bytes_to_str_mismatched_types(self): - path = self.get_contract_path('BytesToStrWithBuiltinMismatchedTypes.py') - self.assertCompilerLogs(CompilerError.MismatchedTypes, path) + path = self.get_contract_path('BytesToStrWithBuiltin.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_bytes_from_byte_array(self): data = b'\x01\x02\x03' @@ -1103,36 +1013,12 @@ def test_byte_array_to_int(self): self.assertEqual(expected_results[x], invokes[x].result) def test_byte_array_to_int_with_builtin(self): - path, _ = self.get_deploy_file_paths('BytearrayToIntWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytes_to_int')) - expected_results.append(513) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('BytearrayToIntWithBuiltin.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_byte_array_to_int_with_bytes_builtin(self): - path, _ = self.get_deploy_file_paths('BytearrayToIntWithBytesBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytes_to_int')) - expected_results.append(513) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('BytearrayToIntWithBytesBuiltin.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_boa2_byte_array_test(self): path, _ = self.get_deploy_file_paths('BytearrayBoa2Test.py') diff --git a/boa3_test/tests/compiler_tests/test_neo_types.py b/boa3_test/tests/compiler_tests/test_neo_types.py index bc41c506d..3e9072bbc 100644 --- a/boa3_test/tests/compiler_tests/test_neo_types.py +++ b/boa3_test/tests/compiler_tests/test_neo_types.py @@ -462,7 +462,7 @@ def test_ecpoint_script_hash_from_builtin(self): # region ByteString def test_byte_string_manifest_generation(self): - path = self.get_contract_path('bytestring', 'ByteStringToBool.py') + path = self.get_contract_path('bytestring', 'ConcatWithByteString.py') _, expected_manifest_output = self.get_deploy_file_paths(path) output, manifest = self.get_output(path) @@ -479,181 +479,27 @@ def test_byte_string_manifest_generation(self): method = abi['methods'][0] self.assertIn('parameters', method) - self.assertEqual(1, len(method['parameters'])) + self.assertEqual(2, len(method['parameters'])) self.assertIn('type', method['parameters'][0]) self.assertEqual(AbiType.ByteArray, method['parameters'][0]['type']) + self.assertIn('type', method['parameters'][1]) + self.assertEqual(AbiType.ByteArray, method['parameters'][1]['type']) def test_byte_string_to_bool(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToBool.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_bool', b'\x00')) - expected_results.append(False) - invokes.append(runner.call_contract(path, 'to_bool', '\x00')) - expected_results.append(False) - - invokes.append(runner.call_contract(path, 'to_bool', b'\x01')) - expected_results.append(True) - invokes.append(runner.call_contract(path, 'to_bool', '\x01')) - expected_results.append(True) - - invokes.append(runner.call_contract(path, 'to_bool', b'\x02')) - expected_results.append(True) - invokes.append(runner.call_contract(path, 'to_bool', '\x02')) - expected_results.append(True) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_byte_string_to_bool_with_builtin(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToBoolWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_bool', b'\x00')) - expected_results.append(False) - invokes.append(runner.call_contract(path, 'to_bool', '\x00')) - expected_results.append(False) - - invokes.append(runner.call_contract(path, 'to_bool', b'\x01')) - expected_results.append(True) - invokes.append(runner.call_contract(path, 'to_bool', '\x01')) - expected_results.append(True) - - invokes.append(runner.call_contract(path, 'to_bool', b'\x02')) - expected_results.append(True) - invokes.append(runner.call_contract(path, 'to_bool', '\x02')) - expected_results.append(True) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('bytestring', 'ByteStringToBool.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_byte_string_to_int(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToInt.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_int', b'\x01\x02')) - expected_results.append(513) - invokes.append(runner.call_contract(path, 'to_int', '\x01\x02')) - expected_results.append(513) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_byte_string_to_int_with_builtin(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToIntWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_int', b'\x01\x02')) - expected_results.append(513) - invokes.append(runner.call_contract(path, 'to_int', '\x01\x02')) - expected_results.append(513) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('bytestring', 'ByteStringToInt.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_byte_string_to_str(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToStr.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_str', b'abc')) - expected_results.append('abc') - - invokes.append(runner.call_contract(path, 'to_str', b'123')) - expected_results.append('123') - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_byte_string_to_str_with_builtin(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToStrWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_str', b'abc')) - expected_results.append('abc') - - invokes.append(runner.call_contract(path, 'to_str', b'123')) - expected_results.append('123') - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('bytestring', 'ByteStringToStr.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_byte_string_to_bytes(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToBytes.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_bytes', 'abc', - expected_result_type=bytes)) - expected_results.append(b'abc') - - invokes.append(runner.call_contract(path, 'to_bytes', '123', - expected_result_type=bytes)) - expected_results.append(b'123') - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_byte_string_to_bytes_with_builtin(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringToBytesWithBuiltin.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'to_bytes', 'abc', - expected_result_type=bytes)) - expected_results.append(b'abc') - - invokes.append(runner.call_contract(path, 'to_bytes', '123', - expected_result_type=bytes)) - expected_results.append(b'123') - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('bytestring', 'ByteStringToBytes.py') + self.assertCompilerLogs(CompilerError.UnresolvedReference, path) def test_concat_with_bytes(self): path, _ = self.get_deploy_file_paths('bytestring', 'ConcatWithBytes.py') diff --git a/docs/ContractExamplesTest.md b/docs/ContractExamplesTest.md index 3ea165bb6..0083339a8 100644 --- a/docs/ContractExamplesTest.md +++ b/docs/ContractExamplesTest.md @@ -151,10 +151,8 @@ - BytesGetValue.py, - BytesGetValueNegativeIndex.py, - BytesLiteral.py, -- BytesToInt.py, -- BytesToIntWithBuiltin.py, -- BytesToStr.py, -- BytesToStrWithBuiltin.py +- BytesToInt.py, +- BytesToStr.py ### Dict type From 01b01f62ab9aed12762dc266c679b355ad0c9e2d Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 5 Jun 2023 12:12:07 -0300 Subject: [PATCH 11/17] #864ek123w - Code review --- boa3/internal/model/builtin/classmethod/__init__.py | 8 -------- boa3/internal/model/builtin/method/__init__.py | 8 ++++++++ .../model/builtin/{classmethod => method}/toboolmethod.py | 0 .../builtin/{classmethod => method}/tobytesmethod.py | 0 .../model/builtin/{classmethod => method}/tointmethod.py | 0 .../model/builtin/{classmethod => method}/tostrmethod.py | 0 6 files changed, 8 insertions(+), 8 deletions(-) rename boa3/internal/model/builtin/{classmethod => method}/toboolmethod.py (100%) rename boa3/internal/model/builtin/{classmethod => method}/tobytesmethod.py (100%) rename boa3/internal/model/builtin/{classmethod => method}/tointmethod.py (100%) rename boa3/internal/model/builtin/{classmethod => method}/tostrmethod.py (100%) diff --git a/boa3/internal/model/builtin/classmethod/__init__.py b/boa3/internal/model/builtin/classmethod/__init__.py index c5eb7a1a2..923f6b346 100644 --- a/boa3/internal/model/builtin/classmethod/__init__.py +++ b/boa3/internal/model/builtin/classmethod/__init__.py @@ -22,10 +22,6 @@ 'StartsWithMethod', 'StripMethod', 'UpperMethod', - 'ToBoolMethod', - 'ToBytesMethod', - 'ToIntMethod', - 'ToStrMethod', 'UpperMethod', ] @@ -52,8 +48,4 @@ from boa3.internal.model.builtin.classmethod.reversemethod import ReverseMethod from boa3.internal.model.builtin.classmethod.startswithmethod import StartsWithMethod from boa3.internal.model.builtin.classmethod.stripmethod import StripMethod -from boa3.internal.model.builtin.classmethod.toboolmethod import ToBool as ToBoolMethod -from boa3.internal.model.builtin.classmethod.tobytesmethod import ToBytes as ToBytesMethod -from boa3.internal.model.builtin.classmethod.tointmethod import ToInt as ToIntMethod -from boa3.internal.model.builtin.classmethod.tostrmethod import ToStr as ToStrMethod from boa3.internal.model.builtin.classmethod.uppermethod import UpperMethod diff --git a/boa3/internal/model/builtin/method/__init__.py b/boa3/internal/model/builtin/method/__init__.py index d1b1bda62..d6c0d7de8 100644 --- a/boa3/internal/model/builtin/method/__init__.py +++ b/boa3/internal/model/builtin/method/__init__.py @@ -29,6 +29,10 @@ 'StrSplitMethod', 'SumMethod', 'SuperMethod', + 'ToBoolMethod', + 'ToBytesMethod', + 'ToIntMethod', + 'ToStrMethod', ] from boa3.internal.model.builtin.method.absmethod import AbsMethod @@ -60,4 +64,8 @@ from boa3.internal.model.builtin.method.strsplitmethod import StrSplitMethod from boa3.internal.model.builtin.method.summethod import SumMethod from boa3.internal.model.builtin.method.supermethod import SuperMethod +from boa3.internal.model.builtin.method.toboolmethod import ToBool as ToBoolMethod +from boa3.internal.model.builtin.method.tobytesmethod import ToBytes as ToBytesMethod +from boa3.internal.model.builtin.method.tointmethod import ToInt as ToIntMethod from boa3.internal.model.builtin.method.toscripthashmethod import ScriptHashMethod +from boa3.internal.model.builtin.method.tostrmethod import ToStr as ToStrMethod diff --git a/boa3/internal/model/builtin/classmethod/toboolmethod.py b/boa3/internal/model/builtin/method/toboolmethod.py similarity index 100% rename from boa3/internal/model/builtin/classmethod/toboolmethod.py rename to boa3/internal/model/builtin/method/toboolmethod.py diff --git a/boa3/internal/model/builtin/classmethod/tobytesmethod.py b/boa3/internal/model/builtin/method/tobytesmethod.py similarity index 100% rename from boa3/internal/model/builtin/classmethod/tobytesmethod.py rename to boa3/internal/model/builtin/method/tobytesmethod.py diff --git a/boa3/internal/model/builtin/classmethod/tointmethod.py b/boa3/internal/model/builtin/method/tointmethod.py similarity index 100% rename from boa3/internal/model/builtin/classmethod/tointmethod.py rename to boa3/internal/model/builtin/method/tointmethod.py diff --git a/boa3/internal/model/builtin/classmethod/tostrmethod.py b/boa3/internal/model/builtin/method/tostrmethod.py similarity index 100% rename from boa3/internal/model/builtin/classmethod/tostrmethod.py rename to boa3/internal/model/builtin/method/tostrmethod.py From be82206d243ac0f9ad63ebb169dc699955fb87e4 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 5 Jun 2023 15:11:00 -0300 Subject: [PATCH 12/17] #861mv1dju - Remove ByteString class --- boa3/builtin/compile_time/__init__.py | 4 +- boa3/builtin/contract/__init__.py | 4 +- boa3/builtin/interop/crypto/__init__.py | 14 +- boa3/builtin/interop/runtime/__init__.py | 4 +- boa3/builtin/interop/stdlib/__init__.py | 8 +- boa3/builtin/interop/storage/__init__.py | 17 +- .../builtin/interop/storage/storagecontext.py | 5 +- boa3/builtin/interop/storage/storagemap.py | 20 +- boa3/builtin/nativecontract/cryptolib.py | 14 +- boa3/builtin/nativecontract/stdlib.py | 8 +- boa3/builtin/type/__init__.py | 7 - boa3/builtin/type/helper.py | 4 +- boa3/internal/model/builtin/builtin.py | 7 +- .../builtin/classmethod/isdigitmethod.py | 3 +- .../model/builtin/classmethod/joinmethod.py | 3 +- .../model/builtin/classmethod/lowermethod.py | 4 +- .../builtin/classmethod/startswithmethod.py | 3 +- .../model/builtin/classmethod/stripmethod.py | 3 +- .../model/builtin/classmethod/uppermethod.py | 4 +- .../builtin/contract/nep11transferevent.py | 6 +- .../builtin/decorator/contractdecorator.py | 6 +- .../builtin/interop/crypto/murmur32method.py | 6 +- .../builtin/interop/crypto/verifywithecdsa.py | 5 +- .../interop/runtime/loadscriptmethod.py | 3 +- .../interop/stdlib/memorycomparemethod.py | 3 +- .../interop/stdlib/memorysearchmethod.py | 3 +- .../storagecontextcreatemapmethod.py | 4 +- .../interop/storage/storagedeletemethod.py | 4 +- .../interop/storage/storagefindmethod.py | 15 +- .../interop/storage/storagegetmethod.py | 7 +- .../storagemap/storagemapdeletemethod.py | 5 +- .../storage/storagemap/storagemapgetmethod.py | 5 +- .../storage/storagemap/storagemapputmethod.py | 12 +- .../storage/storagemap/storagemaptype.py | 9 +- .../interop/storage/storageputmethod.py | 12 +- .../internal/model/builtin/method/__init__.py | 4 +- .../builtin/method/printbytestringmethod.py | 4 +- .../model/builtin/method/printmethod.py | 3 +- .../builtin/method/strbytestringmethod.py | 6 +- .../model/builtin/method/strmethod.py | 2 +- .../model/builtin/method/toboolmethod.py | 5 +- .../model/builtin/method/tobytesmethod.py | 5 +- .../model/builtin/method/tointmethod.py | 5 +- .../model/builtin/method/tostrmethod.py | 5 +- .../operation/binary/arithmetic/concat.py | 19 +- .../arithmetic/strbytesmultiplication.py | 3 +- .../internal/model/standards/nep11standard.py | 9 +- .../model/type/primitive/bytestringtype.py | 3 +- boa3/internal/model/type/primitive/strtype.py | 2 +- boa3_test/examples/amm.py | 4 +- .../auxiliary_contracts/update_contract.py | 4 +- boa3_test/examples/hello_world.py | 2 +- boa3_test/examples/nep11_non_divisible.py | 134 ++++---- boa3_test/examples/nep17.py | 4 +- boa3_test/examples/nep5.py | 4 +- boa3_test/examples/update_contract.py | 4 +- boa3_test/examples/wrapped_gas.py | 2 +- boa3_test/examples/wrapped_neo.py | 4 +- .../interop_test/contract/CallFlagsUsage.py | 4 +- .../interop_test/contract/NewContract.py | 4 +- .../test_sc/interop_test/crypto/Murmur32.py | 3 +- .../interop_test/crypto/VerifyWithECDsa.py | 6 +- .../crypto/VerifyWithECDsaSecp256r1Str.py | 2 - .../iterator/ImportInteropIterator.py | 2 +- .../interop_test/iterator/ImportIterator.py | 2 +- .../iterator/IteratorImplicitTyping.py | 4 +- .../interop_test/iterator/IteratorNext.py | 4 +- .../interop_test/iterator/IteratorValue.py | 4 +- .../iterator/IteratorValueAccess.py | 4 +- .../runtime/LoadScriptDynamicCall.py | 5 +- .../interop_test/stdlib/MemoryCompare.py | 5 +- .../stdlib/MemoryCompareTooFewArguments.py | 3 +- .../stdlib/MemoryCompareTooManyArguments.py | 3 +- .../interop_test/stdlib/MemorySearch.py | 5 +- .../stdlib/MemorySearchDefault.py | 5 +- .../interop_test/stdlib/MemorySearchStart.py | 5 +- .../stdlib/MemorySearchTooFewArguments.py | 3 +- .../stdlib/MemorySearchTooManyArguments.py | 3 +- .../stdlib/SerializationBoa2Test.py | 8 +- .../storage/ImportInteropStorage.py | 10 +- .../interop_test/storage/ImportStorage.py | 8 +- .../interop_test/storage/StorageAsReadOnly.py | 8 +- .../interop_test/storage/StorageBoa2Test.py | 2 +- .../interop_test/storage/StorageCreateMap.py | 8 +- .../storage/StorageDeleteBytesKey.py | 2 +- .../storage/StorageDeleteStrKey.py | 16 - .../storage/StorageDeleteWithContext.py | 5 +- .../storage/StorageFindBytesPrefix.py | 3 +- .../storage/StorageFindStrPrefix.py | 6 +- .../storage/StorageFindWithContext.py | 5 +- .../storage/StorageFindWithOptions.py | 5 +- .../interop_test/storage/StorageGetAndPut1.py | 4 +- .../interop_test/storage/StorageGetAndPut2.py | 4 +- .../interop_test/storage/StorageGetStrKey.py | 12 - .../storage/StorageGetWithContext.py | 7 +- .../storage/StoragePutStrKeyBytesValue.py | 2 - .../storage/StoragePutStrKeyIntValue.py | 2 - .../storage/StoragePutStrKeyStrValue.py | 2 - ...ssingImplementationNEP11OptionalMethods.py | 6 +- .../test_sc/native_test/cryptolib/Murmur32.py | 3 +- .../native_test/cryptolib/VerifyWithECDsa.py | 6 +- .../cryptolib/VerifyWithECDsaSecp256k1Str.py | 2 - .../cryptolib/VerifyWithECDsaSecp256r1Str.py | 2 - .../native_test/stdlib/MemoryCompare.py | 5 +- .../stdlib/MemoryCompareTooFewArguments.py | 3 +- .../stdlib/MemoryCompareTooManyArguments.py | 3 +- .../native_test/stdlib/MemorySearch.py | 5 +- .../native_test/stdlib/MemorySearchDefault.py | 5 +- .../native_test/stdlib/MemorySearchStart.py | 5 +- .../stdlib/MemorySearchTooFewArguments.py | 3 +- .../stdlib/MemorySearchTooManyArguments.py | 3 +- .../stdlib/SerializationBoa2Test.py | 8 +- .../neo_type_test/IsInstanceIterator.py | 2 +- .../neo_type_test/IsInstanceStorageMap.py | 2 +- .../bytestring/ByteStringMultiplication.py | 7 - .../bytestring/ByteStringToBool.py | 5 - .../bytestring/ByteStringToBytes.py | 5 - .../bytestring/ByteStringToInt.py | 5 - .../bytestring/ByteStringToStr.py | 5 - .../bytestring/ConcatWithByteString.py | 7 - .../bytestring/ConcatWithBytes.py | 7 - .../neo_type_test/bytestring/ConcatWithStr.py | 7 - .../while_test/WhileWithInteropCondition.py | 2 +- .../test_interop/test_contract.py | 16 +- .../test_interop/test_crypto.py | 181 +--------- .../test_interop/test_iterator.py | 30 +- .../test_interop/test_storage.py | 309 ++---------------- .../test_native/test_cryptolib.py | 50 +-- .../tests/compiler_tests/test_neo_types.py | 143 -------- docs/source/tutorials.rst | 2 +- 130 files changed, 374 insertions(+), 1143 deletions(-) delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringMultiplication.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ConcatWithByteString.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ConcatWithBytes.py delete mode 100644 boa3_test/test_sc/neo_type_test/bytestring/ConcatWithStr.py diff --git a/boa3/builtin/compile_time/__init__.py b/boa3/builtin/compile_time/__init__.py index 3f9b8206a..2f30bfda0 100644 --- a/boa3/builtin/compile_time/__init__.py +++ b/boa3/builtin/compile_time/__init__.py @@ -9,7 +9,7 @@ from typing import List, Dict, Any, Union, Optional, Tuple -from boa3.builtin.type import ByteString, Event +from boa3.builtin.type import Event def CreateNewEvent(arguments: List[Tuple[str, type]] = [], event_name: str = '') -> Event: @@ -49,7 +49,7 @@ def metadata(*args): pass -def contract(script_hash: ByteString): +def contract(script_hash: Union[str, bytes]): """ This decorator identifies a class that should be interpreted as an interface to an existing contract. diff --git a/boa3/builtin/contract/__init__.py b/boa3/builtin/contract/__init__.py index 215810b88..cb8a26b24 100644 --- a/boa3/builtin/contract/__init__.py +++ b/boa3/builtin/contract/__init__.py @@ -10,7 +10,7 @@ from typing import Union, Any from boa3.builtin.compile_time import CreateNewEvent -from boa3.builtin.type import ByteString, ECPoint, UInt160, Event +from boa3.builtin.type import ECPoint, UInt160, Event Nep5TransferEvent: Event = CreateNewEvent( [ @@ -32,7 +32,7 @@ ('from', Union[UInt160, None]), ('to', Union[UInt160, None]), ('amount', int), - ('tokenId', ByteString) + ('tokenId', Union[str, bytes]) ], 'Transfer' ) diff --git a/boa3/builtin/interop/crypto/__init__.py b/boa3/builtin/interop/crypto/__init__.py index 28a50cba1..410a7e718 100644 --- a/boa3/builtin/interop/crypto/__init__.py +++ b/boa3/builtin/interop/crypto/__init__.py @@ -14,7 +14,7 @@ from typing import Any, List from boa3.builtin.interop.crypto.namedcurve import NamedCurve -from boa3.builtin.type import ByteString, ECPoint +from boa3.builtin.type import ECPoint def sha256(key: Any) -> bytes: @@ -93,12 +93,12 @@ def check_multisig(pubkeys: List[ECPoint], signatures: List[bytes]) -> bool: pass -def verify_with_ecdsa(message: Any, pubkey: ECPoint, signature: ByteString, curve: NamedCurve) -> bool: +def verify_with_ecdsa(message: bytes, pubkey: ECPoint, signature: bytes, curve: NamedCurve) -> bool: """ - Using the elliptic curve, it checks if the signature of the any item was originally produced by the public key. + Using the elliptic curve, it checks if the signature of the message was originally produced by the public key. :param message: the encrypted message - :type message: Any + :type message: bytes :param pubkey: the public key that might have created the item :type pubkey: ECPoint :param signature: the signature of the item @@ -111,15 +111,15 @@ def verify_with_ecdsa(message: Any, pubkey: ECPoint, signature: ByteString, curv pass -def murmur32(data: ByteString, seed: int) -> ByteString: +def murmur32(data: bytes, seed: int) -> bytes: """ Computes the hash value for the specified byte array using the murmur32 algorithm. :param data: the input to compute the hash code for - :type data: ByteString + :type data: bytes :param seed: the seed of the murmur32 hash function :type seed: int :return: the hash value - :rtype: ByteString + :rtype: bytes """ pass diff --git a/boa3/builtin/interop/runtime/__init__.py b/boa3/builtin/interop/runtime/__init__.py index f0c7eea11..cfabe20b6 100644 --- a/boa3/builtin/interop/runtime/__init__.py +++ b/boa3/builtin/interop/runtime/__init__.py @@ -27,7 +27,7 @@ from boa3.builtin.interop.contract.callflagstype import CallFlags from boa3.builtin.interop.runtime.notification import Notification from boa3.builtin.interop.runtime.triggertype import TriggerType -from boa3.builtin.type import ECPoint, UInt160, ByteString +from boa3.builtin.type import ECPoint, UInt160 def check_witness(hash_or_pubkey: Union[UInt160, ECPoint]) -> bool: @@ -119,7 +119,7 @@ def get_random() -> int: pass -def load_script(script: ByteString, args: Sequence = (), flags: CallFlags = CallFlags.NONE) -> Any: +def load_script(script: bytes, args: Sequence = (), flags: CallFlags = CallFlags.NONE) -> Any: """ Loads a script at runtime. """ diff --git a/boa3/builtin/interop/stdlib/__init__.py b/boa3/builtin/interop/stdlib/__init__.py index ed358f431..46c685c5e 100644 --- a/boa3/builtin/interop/stdlib/__init__.py +++ b/boa3/builtin/interop/stdlib/__init__.py @@ -14,9 +14,7 @@ ] -from typing import Any - -from boa3.builtin.type import ByteString +from typing import Any, Union def base58_encode(key: bytes) -> str: @@ -151,7 +149,7 @@ def itoa(value: int, base: int = 10) -> str: pass -def memory_search(mem: ByteString, value: ByteString, start: int = 0, backward: bool = False) -> int: +def memory_search(mem: Union[bytes, str], value: Union[bytes, str], start: int = 0, backward: bool = False) -> int: """ Searches for a given value in a given memory. @@ -170,7 +168,7 @@ def memory_search(mem: ByteString, value: ByteString, start: int = 0, backward: pass -def memory_compare(mem1: ByteString, mem2: ByteString) -> int: +def memory_compare(mem1: Union[bytes, str], mem2: Union[bytes, str]) -> int: """ Compares a memory with another one. diff --git a/boa3/builtin/interop/storage/__init__.py b/boa3/builtin/interop/storage/__init__.py index ccf6d8bb4..01638a958 100644 --- a/boa3/builtin/interop/storage/__init__.py +++ b/boa3/builtin/interop/storage/__init__.py @@ -17,15 +17,14 @@ from boa3.builtin.interop.storage.findoptions import FindOptions from boa3.builtin.interop.storage.storagecontext import StorageContext from boa3.builtin.interop.storage.storagemap import StorageMap -from boa3.builtin.type import ByteString -def get(key: ByteString, context: StorageContext = None) -> bytes: +def get(key: bytes, context: StorageContext = None) -> bytes: """ Gets a value from the persistent store based on the given key. :param key: value identifier in the store - :type key: str or bytes + :type key: bytes :param context: storage context to be used :type context: StorageContext :return: the value corresponding to given key for current storage context @@ -54,12 +53,12 @@ def get_read_only_context() -> StorageContext: pass -def put(key: ByteString, value: Union[int, ByteString], context: StorageContext = None): +def put(key: bytes, value: Union[int, bytes, str], context: StorageContext = None): """ Inserts a given value in the key-value format into the persistent storage. :param key: the identifier in the store for the new value - :type key: str or bytes + :type key: bytes :param value: value to be stored :type value: int or str or bytes :param context: storage context to be used @@ -68,26 +67,26 @@ def put(key: ByteString, value: Union[int, ByteString], context: StorageContext pass -def delete(key: ByteString, context: StorageContext = None): +def delete(key: bytes, context: StorageContext = None): """ Removes a given key from the persistent storage if exists. :param key: the identifier in the store for the new value - :type key: str or bytes + :type key: bytes :param context: storage context to be used :type context: StorageContext """ pass -def find(prefix: ByteString, +def find(prefix: bytes, context: StorageContext = None, options: FindOptions = FindOptions.NONE) -> Iterator: """ Searches in the storage for keys that start with the given prefix. :param prefix: prefix to find the storage keys - :type prefix: str or bytes + :type prefix: bytes :param context: storage context to be used :type context: StorageContext :param options: the options of the search diff --git a/boa3/builtin/interop/storage/storagecontext.py b/boa3/builtin/interop/storage/storagecontext.py index 5814d5e49..04cf62ae6 100644 --- a/boa3/builtin/interop/storage/storagecontext.py +++ b/boa3/builtin/interop/storage/storagecontext.py @@ -3,7 +3,6 @@ __all__ = ['StorageContext'] from boa3.builtin.interop.storage.storagemap import StorageMap -from boa3.builtin.type import ByteString class StorageContext: @@ -14,12 +13,12 @@ class StorageContext: def __init__(self): pass - def create_map(self, prefix: ByteString) -> StorageMap: + def create_map(self, prefix: bytes) -> StorageMap: """ Creates a storage map with the given prefix. :param prefix: the identifier of the storage map - :type prefix: str or bytes + :type prefix: bytes :return: a map with the key-values in the storage that match with the given prefix :rtype: StorageMap """ diff --git a/boa3/builtin/interop/storage/storagemap.py b/boa3/builtin/interop/storage/storagemap.py index be548f2c0..38a6f944c 100644 --- a/boa3/builtin/interop/storage/storagemap.py +++ b/boa3/builtin/interop/storage/storagemap.py @@ -2,47 +2,45 @@ from typing import Union -from boa3.builtin.type import ByteString - class StorageMap: """ The key-value storage for the specific prefix in the given storage context. """ - def __init__(self, context, prefix: ByteString): - from boa3.builtin.interop.storage.storagecontext import StorageContext + def __init__(self, context, prefix: bytes): + from boa3.builtin.interop.storage import StorageContext self._context: StorageContext - self._prefix: ByteString + self._prefix: bytes - def get(self, key: ByteString) -> bytes: + def get(self, key: bytes) -> bytes: """ Gets a value from the map based on the given key. :param key: value identifier in the store - :type key: str or bytes + :type key: bytes :return: the value corresponding to given key for current storage context :rtype: bytes """ pass - def put(self, key: ByteString, value: Union[int, ByteString]): + def put(self, key: bytes, value: Union[int, bytes, str]): """ Inserts a given value in the key-value format into the map. :param key: the identifier in the store for the new value - :type key: str or bytes + :type key: bytes :param value: value to be stored :type value: int or str or bytes """ pass - def delete(self, key: ByteString): + def delete(self, key: bytes): """ Removes a given key from the map if exists. :param key: the identifier in the store for the new value - :type key: str or bytes + :type key: bytes """ pass diff --git a/boa3/builtin/nativecontract/cryptolib.py b/boa3/builtin/nativecontract/cryptolib.py index e0d9fd519..3a5edf69e 100644 --- a/boa3/builtin/nativecontract/cryptolib.py +++ b/boa3/builtin/nativecontract/cryptolib.py @@ -6,7 +6,7 @@ from typing import Any from boa3.builtin.interop.crypto import NamedCurve -from boa3.builtin.type import ByteString, ECPoint, UInt160 +from boa3.builtin.type import ECPoint, UInt160 class CryptoLib: @@ -17,16 +17,16 @@ class CryptoLib: hash: UInt160 @classmethod - def murmur32(cls, data: ByteString, seed: int) -> ByteString: + def murmur32(cls, data: bytes, seed: int) -> bytes: """ Computes the hash value for the specified byte array using the murmur32 algorithm. :param data: the input to compute the hash code for - :type data: ByteString + :type data: bytes :param seed: the seed of the murmur32 hash function :type seed: int :return: the hash value - :rtype: ByteString + :rtype: bytes """ pass @@ -55,12 +55,12 @@ def ripemd160(cls, key: Any) -> bytes: pass @classmethod - def verify_with_ecdsa(cls, message: Any, pubkey: ECPoint, signature: ByteString, curve: NamedCurve) -> bool: + def verify_with_ecdsa(cls, message: bytes, pubkey: ECPoint, signature: bytes, curve: NamedCurve) -> bool: """ - Using the elliptic curve, it checks if the signature of the any item was originally produced by the public key. + Using the elliptic curve, it checks if the signature of the message was originally produced by the public key. :param message: the encrypted message - :type message: Any + :type message: bytes :param pubkey: the public key that might have created the item :type pubkey: ECPoint :param signature: the signature of the item diff --git a/boa3/builtin/nativecontract/stdlib.py b/boa3/builtin/nativecontract/stdlib.py index 9583e5fc4..baeae0964 100644 --- a/boa3/builtin/nativecontract/stdlib.py +++ b/boa3/builtin/nativecontract/stdlib.py @@ -3,9 +3,9 @@ ] -from typing import Any +from typing import Any, Union -from boa3.builtin.type import ByteString, UInt160 +from boa3.builtin.type import UInt160 class StdLib: @@ -177,7 +177,7 @@ def atoi(cls, value: str, base: int = 10) -> int: pass @classmethod - def memory_compare(cls, mem1: ByteString, mem2: ByteString) -> int: + def memory_compare(cls, mem1: Union[bytes, str], mem2: Union[bytes, str]) -> int: """ Compares a memory with another one. @@ -192,7 +192,7 @@ def memory_compare(cls, mem1: ByteString, mem2: ByteString) -> int: pass @classmethod - def memory_search(cls, mem: ByteString, value: ByteString, start: int = 0, backward: bool = False) -> int: + def memory_search(cls, mem: Union[bytes, str], value: Union[bytes, str], start: int = 0, backward: bool = False) -> int: """ Searches for a given value in a given memory. diff --git a/boa3/builtin/type/__init__.py b/boa3/builtin/type/__init__.py index efbf3adf8..7e17d0da8 100644 --- a/boa3/builtin/type/__init__.py +++ b/boa3/builtin/type/__init__.py @@ -5,7 +5,6 @@ 'UInt160', 'UInt256', 'ECPoint', - 'ByteString', 'Address', 'BlockHash', 'PublicKey', @@ -63,12 +62,6 @@ def to_script_hash(self) -> bytes: pass -ByteString = Union[str, bytes] -""" -An type annotation for values that can be str or bytes. Same as Union[str, bytes] -""" - - class Address(str): """ A class used only to indicate that a parameter or return on the manifest should be treated as an Address. diff --git a/boa3/builtin/type/helper.py b/boa3/builtin/type/helper.py index d4b5dbfbc..33fec9b8b 100644 --- a/boa3/builtin/type/helper.py +++ b/boa3/builtin/type/helper.py @@ -7,10 +7,8 @@ from typing import Union -from boa3.builtin.type import ByteString - -def to_bytes(value: Union[ByteString, int]) -> bytes: +def to_bytes(value: Union[str, int]) -> bytes: """ Converts a str or integer value to an array of bytes """ diff --git a/boa3/internal/model/builtin/builtin.py b/boa3/internal/model/builtin/builtin.py index 667dae6d7..efdd56e5d 100644 --- a/boa3/internal/model/builtin/builtin.py +++ b/boa3/internal/model/builtin/builtin.py @@ -20,7 +20,6 @@ from boa3.internal.model.type.itype import IType from boa3.internal.model.type.math import Math from boa3.internal.model.type.neo import * -from boa3.internal.model.type.primitive.bytestringtype import ByteStringType class BoaPackage(str, Enum): @@ -74,7 +73,7 @@ def get_by_self(cls, symbol_id: str, self_type: IType) -> Optional[Callable]: Range = RangeMethod() Reversed = ReversedMethod() StrBool = StrBoolMethod() - StrByteString = StrByteStringMethod() + StrBytes = StrBytesMethod() StrInt = StrIntMethod() Super = SuperMethod() @@ -173,7 +172,6 @@ def interop_symbols(cls, package: str = None) -> Dict[str, IdentifiedSymbol]: Public = PublicDecorator() # boa builtin type - ByteString = ByteStringType.build() Event = EventType UInt160 = UInt160Type.build() UInt256 = UInt256Type.build() @@ -242,8 +240,7 @@ def builtin_events(cls) -> List[EventSymbol]: return lst - _builtin_type_package_symbols = [ByteString, - ECPoint, + _builtin_type_package_symbols = [ECPoint, UInt160, UInt256, Event, diff --git a/boa3/internal/model/builtin/classmethod/isdigitmethod.py b/boa3/internal/model/builtin/classmethod/isdigitmethod.py index ccc70eaea..e2b900f26 100644 --- a/boa3/internal/model/builtin/classmethod/isdigitmethod.py +++ b/boa3/internal/model/builtin/classmethod/isdigitmethod.py @@ -12,8 +12,7 @@ def __init__(self, self_type: IByteStringType = None): from boa3.internal.model.type.type import Type if not isinstance(self_type, IByteStringType): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType - self_type = ByteStringType.build() + self_type = Type.bytes identifier = 'isdigit' args: Dict[str, Variable] = {'self': Variable(self_type)} diff --git a/boa3/internal/model/builtin/classmethod/joinmethod.py b/boa3/internal/model/builtin/classmethod/joinmethod.py index 759bd6d8b..0b2457767 100644 --- a/boa3/internal/model/builtin/classmethod/joinmethod.py +++ b/boa3/internal/model/builtin/classmethod/joinmethod.py @@ -14,8 +14,7 @@ def __init__(self, self_type: IByteStringType = None, iterable_type: Union[Seque from boa3.internal.model.type.type import Type if not isinstance(self_type, IByteStringType): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType - self_type = ByteStringType.build() + self_type = Type.bytes if not isinstance(iterable_type, (SequenceType, DictType)): iterable_type = Type.sequence.build_collection([self_type]) diff --git a/boa3/internal/model/builtin/classmethod/lowermethod.py b/boa3/internal/model/builtin/classmethod/lowermethod.py index 3e74fffca..66d02238c 100644 --- a/boa3/internal/model/builtin/classmethod/lowermethod.py +++ b/boa3/internal/model/builtin/classmethod/lowermethod.py @@ -10,8 +10,8 @@ class LowerMethod(IBuiltinMethod): def __init__(self, self_type: IByteStringType = None): if not isinstance(self_type, IByteStringType): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType - self_type = ByteStringType.build() + from boa3.internal.model.type.type import Type + self_type = Type.bytes identifier = 'lower' args: Dict[str, Variable] = {'self': Variable(self_type)} diff --git a/boa3/internal/model/builtin/classmethod/startswithmethod.py b/boa3/internal/model/builtin/classmethod/startswithmethod.py index 4f07e7e33..9a69190c5 100644 --- a/boa3/internal/model/builtin/classmethod/startswithmethod.py +++ b/boa3/internal/model/builtin/classmethod/startswithmethod.py @@ -13,8 +13,7 @@ def __init__(self, self_type: IByteStringType = None): from boa3.internal.model.type.type import Type if not isinstance(self_type, IByteStringType): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType - self_type = ByteStringType.build() + self_type = Type.bytes identifier = 'startswith' args: Dict[str, Variable] = { diff --git a/boa3/internal/model/builtin/classmethod/stripmethod.py b/boa3/internal/model/builtin/classmethod/stripmethod.py index 32a373792..fbcb348f2 100644 --- a/boa3/internal/model/builtin/classmethod/stripmethod.py +++ b/boa3/internal/model/builtin/classmethod/stripmethod.py @@ -13,8 +13,7 @@ def __init__(self, self_type: IByteStringType = None): from boa3.internal.model.type.type import Type if not isinstance(self_type, IByteStringType): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType - self_type = ByteStringType.build() + self_type = Type.bytes identifier = 'strip' args: Dict[str, Variable] = { diff --git a/boa3/internal/model/builtin/classmethod/uppermethod.py b/boa3/internal/model/builtin/classmethod/uppermethod.py index f6142001b..9aaf1accb 100644 --- a/boa3/internal/model/builtin/classmethod/uppermethod.py +++ b/boa3/internal/model/builtin/classmethod/uppermethod.py @@ -11,8 +11,8 @@ class UpperMethod(IBuiltinMethod): def __init__(self, self_type: IByteStringType = None): if not isinstance(self_type, IByteStringType): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType - self_type = ByteStringType.build() + from boa3.internal.model.type.type import Type + self_type = Type.bytes identifier = 'upper' args: Dict[str, Variable] = {'self': Variable(self_type)} diff --git a/boa3/internal/model/builtin/contract/nep11transferevent.py b/boa3/internal/model/builtin/contract/nep11transferevent.py index 15088dd23..948e42462 100644 --- a/boa3/internal/model/builtin/contract/nep11transferevent.py +++ b/boa3/internal/model/builtin/contract/nep11transferevent.py @@ -1,7 +1,6 @@ from typing import Dict from boa3.internal.model.builtin.method.builtinevent import IBuiltinEvent -from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.variable import Variable @@ -10,12 +9,15 @@ class Nep11TransferEvent(IBuiltinEvent): def __init__(self): from boa3.internal.model.type.type import Type from boa3.internal.model.type.collection.sequence.uint160type import UInt160Type + identifier = 'Nep11TransferEvent' + type_token_id = Type.union.build([Type.str, Type.bytes]) + args: Dict[str, Variable] = { 'from_addr': Variable(Type.union.build([Type.none, UInt160Type.build()])), 'to_addr': Variable(Type.union.build([Type.none, UInt160Type.build()])), 'amount': Variable(Type.int), - 'tokenId': Variable(ByteStringType.build()), + 'tokenId': Variable(type_token_id), } super().__init__(identifier, args) self.name = 'Transfer' diff --git a/boa3/internal/model/builtin/decorator/contractdecorator.py b/boa3/internal/model/builtin/decorator/contractdecorator.py index b668af34e..dce4cf895 100644 --- a/boa3/internal/model/builtin/decorator/contractdecorator.py +++ b/boa3/internal/model/builtin/decorator/contractdecorator.py @@ -8,10 +8,12 @@ class ContractDecorator(IBuiltinDecorator): def __init__(self): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType + from boa3.internal.model.type.type import Type identifier = 'contract' - args: Dict[str, Variable] = {'script_hash': Variable(ByteStringType.build())} + args: Dict[str, Variable] = {'script_hash': Variable(Type.union.build([Type.bytes, + Type.str + ]))} super().__init__(identifier, args) self.contract_hash = UInt160() diff --git a/boa3/internal/model/builtin/interop/crypto/murmur32method.py b/boa3/internal/model/builtin/interop/crypto/murmur32method.py index fa361f7b4..794a839fa 100644 --- a/boa3/internal/model/builtin/interop/crypto/murmur32method.py +++ b/boa3/internal/model/builtin/interop/crypto/murmur32method.py @@ -7,11 +7,11 @@ class Murmur32Method(CryptoLibMethod): def __init__(self): from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType + identifier = 'murmur32' native_identifier = 'murmur32' args: Dict[str, Variable] = { - 'data': Variable(ByteStringType.build()), + 'data': Variable(Type.bytes), 'seed': Variable(Type.int), } - super().__init__(identifier, native_identifier, args, return_type=ByteStringType.build()) + super().__init__(identifier, native_identifier, args, return_type=Type.bytes) diff --git a/boa3/internal/model/builtin/interop/crypto/verifywithecdsa.py b/boa3/internal/model/builtin/interop/crypto/verifywithecdsa.py index d6584f176..4c074e10a 100644 --- a/boa3/internal/model/builtin/interop/crypto/verifywithecdsa.py +++ b/boa3/internal/model/builtin/interop/crypto/verifywithecdsa.py @@ -9,15 +9,14 @@ class VerifyWithECDsaMethod(CryptoLibMethod): def __init__(self): from boa3.internal.model.type.type import Type from boa3.internal.model.type.collection.sequence.ecpointtype import ECPointType - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.builtin.interop.crypto.namedcurvetype import NamedCurveType identifier = 'verify_with_ecdsa' native_identifier = 'verifyWithECDsa' args: Dict[str, Variable] = { - 'data': Variable(Type.any), + 'data': Variable(Type.bytes), 'pubkey': Variable(ECPointType.build()), - 'signature': Variable(ByteStringType.build()), + 'signature': Variable(Type.bytes), 'curve': Variable(NamedCurveType.build()) } super().__init__(identifier, native_identifier, args, return_type=Type.bool) diff --git a/boa3/internal/model/builtin/interop/runtime/loadscriptmethod.py b/boa3/internal/model/builtin/interop/runtime/loadscriptmethod.py index fe2d9e600..2337f4f8a 100644 --- a/boa3/internal/model/builtin/interop/runtime/loadscriptmethod.py +++ b/boa3/internal/model/builtin/interop/runtime/loadscriptmethod.py @@ -11,7 +11,6 @@ class LoadScriptMethod(InteropMethod): def __init__(self): from boa3.internal.model.builtin.interop.contract.callflagstype import CallFlagsType from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.neo3.contracts import CallFlags identifier = 'load_script' @@ -19,7 +18,7 @@ def __init__(self): call_flags: CallFlagsType = CallFlagsType.build() args: Dict[str, Variable] = { - 'script': Variable(ByteStringType.build()), + 'script': Variable(Type.bytes), 'args': Variable(Type.sequence), 'call_flags': Variable(call_flags) } diff --git a/boa3/internal/model/builtin/interop/stdlib/memorycomparemethod.py b/boa3/internal/model/builtin/interop/stdlib/memorycomparemethod.py index 8ef2268d5..0c1490f2b 100644 --- a/boa3/internal/model/builtin/interop/stdlib/memorycomparemethod.py +++ b/boa3/internal/model/builtin/interop/stdlib/memorycomparemethod.py @@ -8,11 +8,10 @@ class MemoryCompareMethod(StdLibMethod): def __init__(self): from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'memory_compare' syscall = 'memoryCompare' - byte_string_type = ByteStringType.build() + byte_string_type = Type.union.build([Type.bytes, Type.str]) args: Dict[str, Variable] = { 'mem1': Variable(byte_string_type), diff --git a/boa3/internal/model/builtin/interop/stdlib/memorysearchmethod.py b/boa3/internal/model/builtin/interop/stdlib/memorysearchmethod.py index 653047089..76c7979db 100644 --- a/boa3/internal/model/builtin/interop/stdlib/memorysearchmethod.py +++ b/boa3/internal/model/builtin/interop/stdlib/memorysearchmethod.py @@ -10,11 +10,10 @@ class MemorySearchMethod(StdLibMethod): def __init__(self): from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'memory_search' native_identifier = 'memorySearch' - byte_string_type = ByteStringType.build() + byte_string_type = Type.union.build([Type.bytes, Type.str]) args: Dict[str, Variable] = { 'mem': Variable(byte_string_type), diff --git a/boa3/internal/model/builtin/interop/storage/storagecontext/storagecontextcreatemapmethod.py b/boa3/internal/model/builtin/interop/storage/storagecontext/storagecontextcreatemapmethod.py index b1a118218..197f857fc 100644 --- a/boa3/internal/model/builtin/interop/storage/storagecontext/storagecontextcreatemapmethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagecontext/storagecontextcreatemapmethod.py @@ -10,10 +10,10 @@ class StorageContextCreateMapMethod(IBuiltinMethod): def __init__(self): from boa3.internal.model.builtin.interop.storage.storagecontext.storagecontexttype import _StorageContext from boa3.internal.model.builtin.interop.storage.storagemap.storagemaptype import _StorageMap - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType + from boa3.internal.model.type.type import Type identifier = 'create_map' - byte_string_type = ByteStringType.build() + byte_string_type = Type.bytes args: Dict[str, Variable] = {'self': Variable(_StorageContext), 'prefix': Variable(byte_string_type)} diff --git a/boa3/internal/model/builtin/interop/storage/storagedeletemethod.py b/boa3/internal/model/builtin/interop/storage/storagedeletemethod.py index c3336b8ba..039a000db 100644 --- a/boa3/internal/model/builtin/interop/storage/storagedeletemethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagedeletemethod.py @@ -14,14 +14,12 @@ class StorageDeleteMethod(InteropMethod): def __init__(self): from boa3.internal.model.type.type import Type from boa3.internal.model.builtin.interop.storage.storagecontext.storagecontexttype import StorageContextType - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'delete' syscall = 'System.Storage.Delete' context_type = StorageContextType.build() - byte_string_type = ByteStringType.build() - args: Dict[str, Variable] = {'key': Variable(byte_string_type), + args: Dict[str, Variable] = {'key': Variable(Type.bytes), 'context': Variable(context_type)} from boa3.internal.model.builtin.interop.storage.storagegetcontextmethod import StorageGetContextMethod diff --git a/boa3/internal/model/builtin/interop/storage/storagefindmethod.py b/boa3/internal/model/builtin/interop/storage/storagefindmethod.py index 355348058..3b3cdfb1e 100644 --- a/boa3/internal/model/builtin/interop/storage/storagefindmethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagefindmethod.py @@ -21,8 +21,7 @@ def __init__(self, find_options_type: FindOptionsType, prefix_type: IType = None context_type = StorageContextType.build() if prefix_type is None: - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType - prefix_type = ByteStringType.build() + prefix_type = Type.bytes args: Dict[str, Variable] = {'prefix': Variable(prefix_type), 'context': Variable(context_type), @@ -48,6 +47,18 @@ def __init__(self, find_options_type: FindOptionsType, prefix_type: IType = None def identifier(self) -> str: return '-{0}_{1}'.format(self._identifier, self.prefix_arg.type.identifier) + def validate_parameters(self, *params: IExpression) -> bool: + if any(not isinstance(param, IExpression) for param in params): + return False + + args: List[IType] = [arg.type for arg in self.args.values()] + if len(params) > len(args): + return False + if len(params) < len(self.args_without_default): + return False + + return self.prefix_arg.type.is_type_of(params[0].type) + @property def generation_order(self) -> List[int]: """ diff --git a/boa3/internal/model/builtin/interop/storage/storagegetmethod.py b/boa3/internal/model/builtin/interop/storage/storagegetmethod.py index 7957c8d1b..5997ada42 100644 --- a/boa3/internal/model/builtin/interop/storage/storagegetmethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagegetmethod.py @@ -15,14 +15,12 @@ class StorageGetMethod(InteropMethod): def __init__(self): from boa3.internal.model.type.type import Type from boa3.internal.model.builtin.interop.storage.storagecontext.storagecontexttype import StorageContextType - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'get' syscall = 'System.Storage.Get' context_type = StorageContextType.build() - byte_string_type = ByteStringType.build() - args: Dict[str, Variable] = {'key': Variable(byte_string_type), + args: Dict[str, Variable] = {'key': Variable(Type.bytes), 'context': Variable(context_type)} from boa3.internal.model.builtin.interop.storage.storagegetcontextmethod import StorageGetContextMethod @@ -40,10 +38,9 @@ def _opcode(self) -> List[Tuple[Opcode, bytes]]: opcodes.extend([ (Opcode.DUP, b''), (Opcode.ISNULL, b''), - (Opcode.JMPIFNOT, Integer(7).to_byte_array(signed=True, min_length=1)), + (Opcode.JMPIFNOT, Integer(5).to_byte_array(signed=True, min_length=1)), (Opcode.DROP, b''), (Opcode.PUSHDATA1, b'\x00'), - (Opcode.CONVERT, Type.bytes.stack_item), ]) return opcodes diff --git a/boa3/internal/model/builtin/interop/storage/storagemap/storagemapdeletemethod.py b/boa3/internal/model/builtin/interop/storage/storagemap/storagemapdeletemethod.py index 6840e11a3..63ebbc7a1 100644 --- a/boa3/internal/model/builtin/interop/storage/storagemap/storagemapdeletemethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagemap/storagemapdeletemethod.py @@ -10,13 +10,10 @@ class StorageMapDeleteMethod(IBuiltinMethod): def __init__(self): from boa3.internal.model.builtin.interop.storage.storagemap.storagemaptype import _StorageMap from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'delete' - byte_string_type = ByteStringType.build() - args: Dict[str, Variable] = {'self': Variable(_StorageMap), - 'key': Variable(byte_string_type)} + 'key': Variable(Type.bytes)} super().__init__(identifier, args, return_type=Type.none) diff --git a/boa3/internal/model/builtin/interop/storage/storagemap/storagemapgetmethod.py b/boa3/internal/model/builtin/interop/storage/storagemap/storagemapgetmethod.py index a6620ffaa..c3cf8d13e 100644 --- a/boa3/internal/model/builtin/interop/storage/storagemap/storagemapgetmethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagemap/storagemapgetmethod.py @@ -10,13 +10,10 @@ class StorageMapGetMethod(IBuiltinMethod): def __init__(self): from boa3.internal.model.builtin.interop.storage.storagemap.storagemaptype import _StorageMap from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'get' - byte_string_type = ByteStringType.build() - args: Dict[str, Variable] = {'self': Variable(_StorageMap), - 'key': Variable(byte_string_type)} + 'key': Variable(Type.bytes)} super().__init__(identifier, args, return_type=Type.bytes) diff --git a/boa3/internal/model/builtin/interop/storage/storagemap/storagemapputmethod.py b/boa3/internal/model/builtin/interop/storage/storagemap/storagemapputmethod.py index f27867e36..44b91223d 100644 --- a/boa3/internal/model/builtin/interop/storage/storagemap/storagemapputmethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagemap/storagemapputmethod.py @@ -10,16 +10,16 @@ class StorageMapPutMethod(IBuiltinMethod): def __init__(self): from boa3.internal.model.builtin.interop.storage.storagemap.storagemaptype import _StorageMap from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'put' - byte_string_type = ByteStringType.build() + storage_value_type = Type.union.build([Type.bytes, + Type.int, + Type.str, + ]) args: Dict[str, Variable] = {'self': Variable(_StorageMap), - 'key': Variable(byte_string_type), - 'value': Variable(Type.union.build([byte_string_type, - Type.int - ]))} + 'key': Variable(Type.bytes), + 'value': Variable(storage_value_type)} super().__init__(identifier, args, return_type=Type.none) diff --git a/boa3/internal/model/builtin/interop/storage/storagemap/storagemaptype.py b/boa3/internal/model/builtin/interop/storage/storagemap/storagemaptype.py index 0ba458d46..d6f3c681d 100644 --- a/boa3/internal/model/builtin/interop/storage/storagemap/storagemaptype.py +++ b/boa3/internal/model/builtin/interop/storage/storagemap/storagemaptype.py @@ -35,12 +35,11 @@ def class_variables(self) -> Dict[str, Variable]: def _all_variables(self) -> Dict[str, Variable]: from boa3.internal.model.builtin.interop.storage.storagecontext.storagecontexttype import \ _StorageContext as StorageContextType - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType + from boa3.internal.model.type.type import Type - byte_string_type = ByteStringType.build() private_variables = { '_context': Variable(StorageContextType), - '_prefix': Variable(byte_string_type) + '_prefix': Variable(Type.bytes) } variables = super()._all_variables variables.update(private_variables) @@ -102,9 +101,7 @@ def __init__(self, return_type: StorageMapType): identifier = '-StorageMap__init__' args: Dict[str, Variable] = { 'context': Variable(StorageContextType), - 'prefix': Variable(Type.union.build([Type.bytes, - Type.str - ])) + 'prefix': Variable(Type.bytes) } super().__init__(identifier, args, return_type=return_type) diff --git a/boa3/internal/model/builtin/interop/storage/storageputmethod.py b/boa3/internal/model/builtin/interop/storage/storageputmethod.py index d18fa2bf8..abe9e9275 100644 --- a/boa3/internal/model/builtin/interop/storage/storageputmethod.py +++ b/boa3/internal/model/builtin/interop/storage/storageputmethod.py @@ -14,17 +14,17 @@ class StoragePutMethod(InteropMethod): def __init__(self): from boa3.internal.model.type.type import Type from boa3.internal.model.builtin.interop.storage.storagecontext.storagecontexttype import StorageContextType - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType identifier = 'put' syscall = 'System.Storage.Put' context_type = StorageContextType.build() - byte_string_type = ByteStringType.build() + storage_value_type = Type.union.build([Type.bytes, + Type.int, + Type.str, + ]) - args: Dict[str, Variable] = {'key': Variable(byte_string_type), - 'value': Variable(Type.union.build([byte_string_type, - Type.int - ])), + args: Dict[str, Variable] = {'key': Variable(Type.bytes), + 'value': Variable(storage_value_type), 'context': Variable(context_type)} from boa3.internal.model.builtin.interop.storage.storagegetcontextmethod import StorageGetContextMethod diff --git a/boa3/internal/model/builtin/method/__init__.py b/boa3/internal/model/builtin/method/__init__.py index d6c0d7de8..f2fbe0b25 100644 --- a/boa3/internal/model/builtin/method/__init__.py +++ b/boa3/internal/model/builtin/method/__init__.py @@ -24,7 +24,7 @@ 'ReversedMethod', 'ScriptHashMethod', 'StrBoolMethod', - 'StrByteStringMethod', + 'StrBytesMethod', 'StrIntMethod', 'StrSplitMethod', 'SumMethod', @@ -59,7 +59,7 @@ from boa3.internal.model.builtin.method.rangemethod import RangeMethod from boa3.internal.model.builtin.method.reversedmethod import ReversedMethod from boa3.internal.model.builtin.method.strboolmethod import StrBoolMethod -from boa3.internal.model.builtin.method.strbytestringmethod import StrByteStringMethod +from boa3.internal.model.builtin.method.strbytestringmethod import StrBytesMethod from boa3.internal.model.builtin.method.strintmethod import StrIntMethod from boa3.internal.model.builtin.method.strsplitmethod import StrSplitMethod from boa3.internal.model.builtin.method.summethod import SumMethod diff --git a/boa3/internal/model/builtin/method/printbytestringmethod.py b/boa3/internal/model/builtin/method/printbytestringmethod.py index 4df7124e5..ffdeb4af2 100644 --- a/boa3/internal/model/builtin/method/printbytestringmethod.py +++ b/boa3/internal/model/builtin/method/printbytestringmethod.py @@ -6,9 +6,9 @@ class PrintByteStringMethod(PrintMethod): def __init__(self, arg_value: IType): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType + from boa3.internal.model.type.primitive.ibytestringtype import IByteStringType - if not isinstance(arg_value, IType) or not ByteStringType.build().is_type_of(arg_value): + if not isinstance(arg_value, IType) or not isinstance(arg_value, IByteStringType): from boa3.internal.model.type.type import Type arg_value = Type.str diff --git a/boa3/internal/model/builtin/method/printmethod.py b/boa3/internal/model/builtin/method/printmethod.py index 858ed2a75..062c11099 100644 --- a/boa3/internal/model/builtin/method/printmethod.py +++ b/boa3/internal/model/builtin/method/printmethod.py @@ -107,7 +107,6 @@ def build(self, value: Any) -> IBuiltinMethod: from boa3.internal.model.builtin.method.printbytestringmethod import PrintByteStringMethod from boa3.internal.model.type.classes.userclass import UserClass from boa3.internal.model.type.type import Type - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType if Type.bool.is_type_of(value): from boa3.internal.model.builtin.method.printboolmethod import PrintBoolMethod @@ -117,7 +116,7 @@ def build(self, value: Any) -> IBuiltinMethod: from boa3.internal.model.builtin.method.printintmethod import PrintIntMethod return PrintIntMethod() - elif ByteStringType.build().is_type_of(value): + elif Type.str.is_type_of(value) or Type.bytes.is_type_of(value): return PrintByteStringMethod(value) elif isinstance(value, UserClass): diff --git a/boa3/internal/model/builtin/method/strbytestringmethod.py b/boa3/internal/model/builtin/method/strbytestringmethod.py index 30816230b..cc92dd7c4 100644 --- a/boa3/internal/model/builtin/method/strbytestringmethod.py +++ b/boa3/internal/model/builtin/method/strbytestringmethod.py @@ -6,13 +6,13 @@ from boa3.internal.neo.vm.opcode.Opcode import Opcode -class StrByteStringMethod(StrMethod): +class StrBytesMethod(StrMethod): def __init__(self): - from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.type.type import Type + args: Dict[str, Variable] = { - 'object': Variable(ByteStringType.build()), + 'object': Variable(Type.union.build([Type.bytes, Type.str])), } object_default = ast.parse("'{0}'".format(Type.str.default_value)).body[0].value diff --git a/boa3/internal/model/builtin/method/strmethod.py b/boa3/internal/model/builtin/method/strmethod.py index c295933de..0ba1b00ff 100644 --- a/boa3/internal/model/builtin/method/strmethod.py +++ b/boa3/internal/model/builtin/method/strmethod.py @@ -50,4 +50,4 @@ def build(self, value: Any) -> IBuiltinMethod: if Type.int.is_type_of(value[0]): return Builtin.StrInt - return Builtin.StrByteString + return Builtin.StrBytes diff --git a/boa3/internal/model/builtin/method/toboolmethod.py b/boa3/internal/model/builtin/method/toboolmethod.py index 0f29ac4ee..d9b17a28a 100644 --- a/boa3/internal/model/builtin/method/toboolmethod.py +++ b/boa3/internal/model/builtin/method/toboolmethod.py @@ -5,7 +5,6 @@ from boa3.internal.model.expression import IExpression from boa3.internal.model.identifiedsymbol import IdentifiedSymbol from boa3.internal.model.type.itype import IType -from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.type.primitive.bytestype import BytesType from boa3.internal.model.variable import Variable from boa3.internal.neo.vm.opcode.Opcode import Opcode @@ -54,7 +53,7 @@ def __init__(self): super().__init__(None) def build(self, value: Any) -> IBuiltinMethod: - if isinstance(value, (BytesType, ByteStringType)): + if isinstance(value, BytesType): return BytesToBoolMethod(value) # if it is not a valid type, show mismatched type with bytes return BytesToBoolMethod() @@ -65,7 +64,7 @@ def build(self, value: Any) -> IBuiltinMethod: class BytesToBoolMethod(ToBoolMethod): def __init__(self, self_type: IType = None): - if not isinstance(self_type, (BytesType, ByteStringType)): + if not isinstance(self_type, BytesType): from boa3.internal.model.type.type import Type self_type = Type.bytes super().__init__(self_type) diff --git a/boa3/internal/model/builtin/method/tobytesmethod.py b/boa3/internal/model/builtin/method/tobytesmethod.py index 0305bd909..2fe45aa08 100644 --- a/boa3/internal/model/builtin/method/tobytesmethod.py +++ b/boa3/internal/model/builtin/method/tobytesmethod.py @@ -5,7 +5,6 @@ from boa3.internal.model.expression import IExpression from boa3.internal.model.identifiedsymbol import IdentifiedSymbol from boa3.internal.model.type.itype import IType -from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.type.primitive.bytestype import BytesType from boa3.internal.model.type.primitive.inttype import IntType from boa3.internal.model.type.primitive.strtype import StrType @@ -46,7 +45,7 @@ def _opcode(self) -> List[Tuple[Opcode, bytes]]: def build(self, value: Any) -> IBuiltinMethod: if isinstance(value, IntType): return IntToBytesMethod(value) - elif isinstance(value, (StrType, ByteStringType)): + elif isinstance(value, StrType): return StrToBytesMethod(value) # if it is not a valid type, show mismatched type with int return IntToBytesMethod() @@ -122,7 +121,7 @@ def _opcode(self) -> List[Tuple[Opcode, bytes]]: class StrToBytesMethod(ToBytesMethod): def __init__(self, self_type: IType = None): - if not isinstance(self_type, (StrType, ByteStringType)): + if not isinstance(self_type, StrType): from boa3.internal.model.type.type import Type self_type = Type.str super().__init__(self_type) diff --git a/boa3/internal/model/builtin/method/tointmethod.py b/boa3/internal/model/builtin/method/tointmethod.py index 4c2cacaff..cd978e9d1 100644 --- a/boa3/internal/model/builtin/method/tointmethod.py +++ b/boa3/internal/model/builtin/method/tointmethod.py @@ -5,7 +5,6 @@ from boa3.internal.model.expression import IExpression from boa3.internal.model.identifiedsymbol import IdentifiedSymbol from boa3.internal.model.type.itype import IType -from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.type.primitive.bytestype import BytesType from boa3.internal.model.variable import Variable from boa3.internal.neo.vm.opcode.Opcode import Opcode @@ -54,7 +53,7 @@ def __init__(self): super().__init__(None) def build(self, value: Any) -> IBuiltinMethod: - if isinstance(value, (BytesType, ByteStringType)): + if isinstance(value, BytesType): return BytesToIntMethod(value) # if it is not a valid type, show mismatched type with bytes return BytesToIntMethod() @@ -65,7 +64,7 @@ def build(self, value: Any) -> IBuiltinMethod: class BytesToIntMethod(ToIntMethod): def __init__(self, self_type: IType = None): - if not isinstance(self_type, (BytesType, ByteStringType)): + if not isinstance(self_type, BytesType): from boa3.internal.model.type.type import Type self_type = Type.bytes super().__init__(self_type) diff --git a/boa3/internal/model/builtin/method/tostrmethod.py b/boa3/internal/model/builtin/method/tostrmethod.py index 8756b4d3a..b739be031 100644 --- a/boa3/internal/model/builtin/method/tostrmethod.py +++ b/boa3/internal/model/builtin/method/tostrmethod.py @@ -5,7 +5,6 @@ from boa3.internal.model.expression import IExpression from boa3.internal.model.identifiedsymbol import IdentifiedSymbol from boa3.internal.model.type.itype import IType -from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.type.primitive.bytestype import BytesType from boa3.internal.model.variable import Variable from boa3.internal.neo.vm.opcode.Opcode import Opcode @@ -54,7 +53,7 @@ def __init__(self): super().__init__(None) def build(self, value: Any) -> IBuiltinMethod: - if isinstance(value, (BytesType, ByteStringType)): + if isinstance(value, BytesType): return BytesToStrMethod(value) # if it is not a valid type, show mismatched type with bytes return BytesToStrMethod() @@ -65,7 +64,7 @@ def build(self, value: Any) -> IBuiltinMethod: class BytesToStrMethod(ToStrMethod): def __init__(self, self_type: IType = None): - if not isinstance(self_type, (BytesType, ByteStringType)): + if not isinstance(self_type, BytesType): from boa3.internal.model.type.type import Type self_type = Type.bytes super().__init__(self_type) diff --git a/boa3/internal/model/operation/binary/arithmetic/concat.py b/boa3/internal/model/operation/binary/arithmetic/concat.py index 3de5ecc52..4935bdbc5 100644 --- a/boa3/internal/model/operation/binary/arithmetic/concat.py +++ b/boa3/internal/model/operation/binary/arithmetic/concat.py @@ -1,6 +1,5 @@ from typing import List, Optional, Tuple -from boa3.internal.model.builtin.builtin import Builtin from boa3.internal.model.operation.binary.binaryoperation import BinaryOperation from boa3.internal.model.operation.operator import Operator from boa3.internal.model.type.type import IType, Type @@ -16,7 +15,7 @@ class Concat(BinaryOperation): :ivar right: the left operand type. Inherited from :class:`BinaryOperation` :ivar result: the result type of the operation. Inherited from :class:`IOperation` """ - _valid_types: List[IType] = [Type.str, Type.bytes, Builtin.ByteString] + _valid_types: List[IType] = [Type.str, Type.bytes] def __init__(self, left: IType = Type.str, right: IType = None): self.operator: Operator = Operator.Plus @@ -45,21 +44,7 @@ def validate_type(self, *types: IType) -> bool: def _get_result(self, left: IType, right: IType) -> IType: if self.validate_type(left, right): - left_internal = self._get_valid_type(left) - right_internal = self._get_valid_type(right) - - if left_internal.is_type_of(Builtin.ByteString): - # for bytestring + str the result is str and bytestring + bytes is bytes - return right - if right_internal.is_type_of(Builtin.ByteString): - return left - - if right.is_type_of(left): - return right - if left.is_type_of(right): - return left - - return left_internal + return left else: return Type.none diff --git a/boa3/internal/model/operation/binary/arithmetic/strbytesmultiplication.py b/boa3/internal/model/operation/binary/arithmetic/strbytesmultiplication.py index 716fad70b..cabad8834 100644 --- a/boa3/internal/model/operation/binary/arithmetic/strbytesmultiplication.py +++ b/boa3/internal/model/operation/binary/arithmetic/strbytesmultiplication.py @@ -1,6 +1,5 @@ from typing import List, Tuple -from boa3.internal.model.builtin.builtin import Builtin from boa3.internal.model.operation.binary.binaryoperation import BinaryOperation from boa3.internal.model.operation.operator import Operator from boa3.internal.model.type.type import IType, Type @@ -16,7 +15,7 @@ class StrBytesMultiplication(BinaryOperation): :ivar right: the left operand type. Inherited from :class:`BinaryOperation` :ivar result: the result type of the operation. Inherited from :class:`IOperation` """ - _valid_types: List[IType] = [Type.str, Type.bytes, Builtin.ByteString] + _valid_types: List[IType] = [Type.str, Type.bytes] def __init__(self, left: IType = Type.str, right: IType = Type.int): self.operator: Operator = Operator.Mult diff --git a/boa3/internal/model/standards/nep11standard.py b/boa3/internal/model/standards/nep11standard.py index ed516980b..a6c5b74be 100644 --- a/boa3/internal/model/standards/nep11standard.py +++ b/boa3/internal/model/standards/nep11standard.py @@ -3,7 +3,6 @@ from boa3.internal.model.standards.neostandard import INeoStandard from boa3.internal.model.standards.standardmethod import StandardMethod from boa3.internal.model.type.collection.sequence.uint160type import UInt160Type -from boa3.internal.model.type.primitive.bytestringtype import ByteStringType from boa3.internal.model.type.type import Type @@ -11,7 +10,7 @@ class Nep11Standard(INeoStandard): def __init__(self): type_uint160 = UInt160Type.build() type_iterator = IteratorType.build() - type_bytestring = ByteStringType.build() + type_token_id = Type.union.build([Type.str, Type.bytes]) methods = [ StandardMethod('symbol', safe=True, @@ -31,11 +30,11 @@ def __init__(self): return_type=type_iterator), StandardMethod('transfer', args={'to': type_uint160, - 'tokenId': type_bytestring, + 'tokenId': type_token_id, 'data': Type.any}, return_type=Type.bool), StandardMethod('ownerOf', safe=True, - args={'tokenId': type_bytestring}, + args={'tokenId': type_token_id}, return_type=type_uint160), ] @@ -45,7 +44,7 @@ def __init__(self): return_type=type_iterator), StandardMethod('properties', safe=True, args={ - 'tokenId': type_bytestring, + 'tokenId': type_token_id, }, return_type=Type.dict), ] diff --git a/boa3/internal/model/type/primitive/bytestringtype.py b/boa3/internal/model/type/primitive/bytestringtype.py index 608051250..9a131264f 100644 --- a/boa3/internal/model/type/primitive/bytestringtype.py +++ b/boa3/internal/model/type/primitive/bytestringtype.py @@ -18,8 +18,7 @@ def __init__(self): def _is_type_of(cls, value: Any) -> bool: from boa3.internal.model.type.type import Type return (Type.str.is_type_of(value) - or Type.bytes.is_type_of(value) - or isinstance(value, ByteStringType)) + or Type.bytes.is_type_of(value)) @classmethod def build(cls, value: Any = None) -> IType: diff --git a/boa3/internal/model/type/primitive/strtype.py b/boa3/internal/model/type/primitive/strtype.py index 76ae448c4..382ccd442 100644 --- a/boa3/internal/model/type/primitive/strtype.py +++ b/boa3/internal/model/type/primitive/strtype.py @@ -35,7 +35,7 @@ def _init_class_symbols(self): for instance_method in instance_methods: self._instance_methods[instance_method.raw_identifier] = instance_method.build(self) - self._instance_methods[constants.INIT_METHOD_ID] = Builtin.StrByteString + self._instance_methods[constants.INIT_METHOD_ID] = Builtin.StrBytes @classmethod def build(cls, value: Any) -> IType: diff --git a/boa3_test/examples/amm.py b/boa3_test/examples/amm.py index 9829fb67b..7371409f9 100644 --- a/boa3_test/examples/amm.py +++ b/boa3_test/examples/amm.py @@ -243,7 +243,7 @@ def _deploy(data: Any, update: bool): """ if not update: container: Transaction = runtime.script_container - storage.put('owner', container.sender) + storage.put(b'owner', container.sender) storage.put(DEPLOYED, True) @@ -259,7 +259,7 @@ def onNEP17Payment(from_address: UInt160, amount: int, data: Any): def get_owner() -> UInt160: - return UInt160(storage.get('owner')) + return UInt160(storage.get(b'owner')) @public diff --git a/boa3_test/examples/auxiliary_contracts/update_contract.py b/boa3_test/examples/auxiliary_contracts/update_contract.py index e383c0287..92c91e6b6 100644 --- a/boa3_test/examples/auxiliary_contracts/update_contract.py +++ b/boa3_test/examples/auxiliary_contracts/update_contract.py @@ -13,8 +13,8 @@ # The keys used to access the storage -OWNER_KEY = 'owner' -SUPPLY_KEY = 'totalSupply' +OWNER_KEY = b'owner' +SUPPLY_KEY = b'totalSupply' TOKEN_TOTAL_SUPPLY = 10_000_000 * 10 ** 8 # 10m total supply * 10^8 (decimals) diff --git a/boa3_test/examples/hello_world.py b/boa3_test/examples/hello_world.py index 9f9f48ed7..22d9de52b 100644 --- a/boa3_test/examples/hello_world.py +++ b/boa3_test/examples/hello_world.py @@ -4,7 +4,7 @@ @public def Main(): - storage.put('hello', 'world') + storage.put(b'hello', b'world') @metadata diff --git a/boa3_test/examples/nep11_non_divisible.py b/boa3_test/examples/nep11_non_divisible.py index 33050320c..be9e661ac 100644 --- a/boa3_test/examples/nep11_non_divisible.py +++ b/boa3_test/examples/nep11_non_divisible.py @@ -15,7 +15,7 @@ from boa3.builtin.interop.stdlib import deserialize, serialize from boa3.builtin.interop.storage import delete, find, get, get_read_only_context, put from boa3.builtin.interop.storage.findoptions import FindOptions -from boa3.builtin.type import ByteString, UInt160, helper as type_helper +from boa3.builtin.type import UInt160, helper as type_helper # ------------------------------------------- @@ -83,7 +83,7 @@ def gm_manifest() -> NeoMetadata: ('from_addr', Union[UInt160, None]), ('to_addr', Union[UInt160, None]), ('amount', int), - ('tokenId', ByteString) + ('tokenId', bytes) ], 'Transfer' ) @@ -100,7 +100,7 @@ def gm_manifest() -> NeoMetadata: on_unlock = CreateNewEvent( [ - ('tokenId', ByteString), + ('tokenId', bytes), ('counter', int) ], 'UnlockIncremented' @@ -210,7 +210,7 @@ def tokensOf(owner: UInt160) -> Iterator: @public -def transfer(to: UInt160, tokenId: ByteString, data: Any) -> bool: +def transfer(to: UInt160, tokenId: bytes, data: Any) -> bool: """ Transfers the token with id tokenId to address to @@ -228,7 +228,7 @@ def transfer(to: UInt160, tokenId: ByteString, data: Any) -> bool: :param to: the address to transfer to :type to: UInt160 :param tokenId: the token to transfer - :type tokenId: ByteString + :type tokenId: bytes :param data: whatever data is pertinent to the onPayment method :type data: Any :return: whether the transfer was successful @@ -253,7 +253,7 @@ def transfer(to: UInt160, tokenId: ByteString, data: Any) -> bool: return True -def post_transfer(token_owner: Union[UInt160, None], to: Union[UInt160, None], tokenId: ByteString, data: Any): +def post_transfer(token_owner: Union[UInt160, None], to: Union[UInt160, None], tokenId: bytes, data: Any): """ Checks if the one receiving NEP11 tokens is a smart contract and if it's one the onPayment method will be called - internal @@ -261,8 +261,8 @@ def post_transfer(token_owner: Union[UInt160, None], to: Union[UInt160, None], t :type token_owner: UInt160 :param to: the address of the receiver :type to: UInt160 - :param tokenId: the token hash as ByteString - :type tokenId: ByteString + :param tokenId: the token hash as bytes + :type tokenId: bytes :param data: any pertinent data that might validate the transaction :type data: Any """ @@ -275,14 +275,14 @@ def post_transfer(token_owner: Union[UInt160, None], to: Union[UInt160, None], t @public(safe=True) -def ownerOf(tokenId: ByteString) -> UInt160: +def ownerOf(tokenId: bytes) -> UInt160: """ Get the owner of the specified token. The parameter tokenId SHOULD be a valid NFT. If not, this method SHOULD throw an exception. :param tokenId: the token for which to check the ownership - :type tokenId: ByteString + :type tokenId: bytes :return: the owner of the specified token. :raise AssertionError: raised if `tokenId` is not a valid NFT. """ @@ -304,14 +304,14 @@ def tokens() -> Iterator: @public(safe=True) -def properties(tokenId: ByteString) -> Dict[Any, Any]: +def properties(tokenId: bytes) -> Dict[Any, Any]: """ Get the properties of a token. The parameter tokenId SHOULD be a valid NFT. If no metadata is found (invalid tokenId), an exception is thrown. :param tokenId: the token for which to check the properties - :type tokenId: ByteString + :type tokenId: bytes :return: a serialized NVM object containing the properties for the given NFT. :raise AssertionError: raised if `tokenId` is not a valid NFT, or if no metadata available. """ @@ -323,14 +323,14 @@ def properties(tokenId: ByteString) -> Dict[Any, Any]: @public(safe=True) -def propertiesJson(tokenId: ByteString) -> ByteString: +def propertiesJson(tokenId: bytes) -> str: """ Get the properties of a token. The parameter tokenId SHOULD be a valid NFT. If no metadata is found (invalid tokenId), an exception is thrown. :param tokenId: the token for which to check the properties - :type tokenId: ByteString + :type tokenId: bytes :return: a serialized NVM object containing the properties for the given NFT. :raise AssertionError: raised if `tokenId` is not a valid NFT, or if no metadata available. """ @@ -384,7 +384,7 @@ def internal_deploy(owner: UInt160): @public(name='onNEP11Payment') -def on_nep11_payment(from_address: UInt160, amount: int, token_id: ByteString, data: Any): +def on_nep11_payment(from_address: UInt160, amount: int, token_id: bytes, data: Any): """ This contract will not receive another NEP-11 token. @@ -393,7 +393,7 @@ def on_nep11_payment(from_address: UInt160, amount: int, token_id: ByteString, d :param amount: the amount of cryptocurrency that is being sent to the this smart contract :type amount: int :param token_id: the id of the token that is being sent - :type token_id: ByteString + :type token_id: bytes :param data: any pertinent data that might validate the transaction :type data: Any """ @@ -405,12 +405,12 @@ def on_nep11_payment(from_address: UInt160, amount: int, token_id: ByteString, d # ------------------------------------------- @public -def burn(tokenId: ByteString) -> bool: +def burn(tokenId: bytes) -> bool: """ Burn a token. :param tokenId: the token to burn - :type tokenId: ByteString + :type tokenId: bytes :return: whether the burn was successful. :raise AssertionError: raised if the contract is paused. """ @@ -419,18 +419,18 @@ def burn(tokenId: ByteString) -> bool: @public -def mint(account: UInt160, meta: ByteString, lockedContent: ByteString, royalties: ByteString) -> ByteString: +def mint(account: UInt160, meta: str, lockedContent: str, royalties: str) -> bytes: """ Mint new token. :param account: the address of the account that is minting token :type account: UInt160 :param meta: the metadata to use for this token - :type meta: ByteString + :type meta: str :param lockedContent: the lock content to use for this token - :type lockedContent: ByteString + :type lockedContent: str :param royalties: the royalties to use for this token - :type royalties: ByteString + :type royalties: str :return: tokenId of the token minted :raise AssertionError: raised if the contract is paused or if check witness fails. """ @@ -447,13 +447,13 @@ def mint(account: UInt160, meta: ByteString, lockedContent: ByteString, royaltie @public(safe=True) -def getRoyalties(tokenId: ByteString) -> ByteString: +def getRoyalties(tokenId: bytes) -> str: """ Get a token royalties values. :param tokenId: the token to get royalties values - :type tokenId: ByteString - :return: ByteString of addresses and values for this token royalties. + :type tokenId: bytes + :return: str of addresses and values for this token royalties. :raise AssertionError: raised if any `tokenId` is not a valid NFT. """ royalties = get_royalties(tokenId) @@ -462,12 +462,12 @@ def getRoyalties(tokenId: ByteString) -> ByteString: @public(safe=True) -def getLockedContentViewCount(tokenId: ByteString) -> int: +def getLockedContentViewCount(tokenId: bytes) -> int: """ Get lock content view count of a token. :param tokenId: the token to query - :type tokenId: ByteString + :type tokenId: bytes :return: number of times the lock content of this token was accessed. """ debug(['getLockedContentViewCount: ', get_locked_view_counter(tokenId)]) @@ -475,12 +475,12 @@ def getLockedContentViewCount(tokenId: ByteString) -> int: @public -def getLockedContent(tokenId: ByteString) -> ByteString: +def getLockedContent(tokenId: bytes) -> str: """ Get lock content of a token. :param tokenId: the token to query - :type tokenId: ByteString + :type tokenId: bytes :return: the lock content of this token. :raise AssertionError: raised if witness is not owner :emits UnlockIncremented @@ -506,10 +506,6 @@ def getAuthorizedAddress() -> list[UInt160]: this method will be triggered as a VerificationTrigger to verify that the signature is correct. For example, this method needs to be called when withdrawing token from the contract. - :param address: the address of the account that is being authorized - :type address: UInt160 - :param authorized: authorization status of this address - :type authorized: bool :return: whether the transaction signature is correct :raise AssertionError: raised if witness is not verified. """ @@ -622,9 +618,9 @@ def update(script: bytes, manifest: bytes): Upgrade the contract. :param script: the contract script - :type script: ByteString + :type script: bytes :param manifest: the contract manifest - :type manifest: ByteString + :type manifest: bytes :raise AssertionError: raised if witness is not verified """ verified: bool = verify() @@ -646,12 +642,12 @@ def destroy(): debug(['destroy called and done']) -def internal_burn(tokenId: ByteString) -> bool: +def internal_burn(tokenId: bytes) -> bool: """ Burn a token - internal :param tokenId: the token to burn - :type tokenId: ByteString + :type tokenId: bytes :return: whether the burn was successful. :raise AssertionError: raised if `tokenId` is not a valid NFT. """ @@ -672,18 +668,18 @@ def internal_burn(tokenId: ByteString) -> bool: return True -def internal_mint(account: UInt160, meta: ByteString, lockedContent: ByteString, royalties: ByteString) -> ByteString: +def internal_mint(account: UInt160, meta: str, lockedContent: str, royalties: str) -> bytes: """ Mint new token - internal :param account: the address of the account that is minting token :type account: UInt160 :param meta: the metadata to use for this token - :type meta: ByteString + :type meta: str :param lockedContent: the lock content to use for this token - :type lockedContent: ByteString + :type lockedContent: str :param royalties: the royalties to use for this token - :type royalties: ByteString + :type royalties: str :return: tokenId of the token minted :raise AssertionError: raised if meta is empty, or if contract is paused. """ @@ -713,32 +709,32 @@ def internal_mint(account: UInt160, meta: ByteString, lockedContent: ByteString, return tokenIdBytes -def remove_token_account(holder: UInt160, tokenId: ByteString): +def remove_token_account(holder: UInt160, tokenId: bytes): key = mk_account_key(holder) + tokenId debug(['add_token_account: ', key, tokenId]) delete(key) -def add_token_account(holder: UInt160, tokenId: ByteString): +def add_token_account(holder: UInt160, tokenId: bytes): key = mk_account_key(holder) + tokenId debug(['add_token_account: ', key, tokenId]) put(key, tokenId) -def get_owner_of(tokenId: ByteString) -> UInt160: +def get_owner_of(tokenId: bytes) -> UInt160: key = mk_token_key(tokenId) debug(['get_owner_of: ', key, tokenId]) owner = get(key, get_read_only_context()) return UInt160(owner) -def remove_owner_of(tokenId: ByteString): +def remove_owner_of(tokenId: bytes): key = mk_token_key(tokenId) debug(['remove_owner_of: ', key, tokenId]) delete(key) -def set_owner_of(tokenId: ByteString, owner: UInt160): +def set_owner_of(tokenId: bytes, owner: UInt160): key = mk_token_key(tokenId) debug(['set_owner_of: ', key, tokenId]) put(key, owner) @@ -762,76 +758,76 @@ def set_balance(owner: UInt160, amount: int): delete(key) -def get_meta(tokenId: ByteString) -> ByteString: +def get_meta(tokenId: bytes) -> str: key = mk_meta_key(tokenId) debug(['get_meta: ', key, tokenId]) val = get(key, get_read_only_context()) - return val + return type_helper.to_str(val) -def remove_meta(tokenId: ByteString): +def remove_meta(tokenId: bytes): key = mk_meta_key(tokenId) debug(['remove_meta: ', key, tokenId]) delete(key) -def add_meta(tokenId: ByteString, meta: ByteString): +def add_meta(tokenId: bytes, meta: str): key = mk_meta_key(tokenId) debug(['add_meta: ', key, tokenId]) put(key, meta) -def get_locked_content(tokenId: ByteString) -> ByteString: +def get_locked_content(tokenId: bytes) -> str: key = mk_locked_key(tokenId) debug(['get_locked_content: ', key, tokenId]) - val = get(key, get_read_only_context()) + val = type_helper.to_str(get(key, get_read_only_context())) return val -def remove_locked_content(tokenId: ByteString): +def remove_locked_content(tokenId: bytes): key = mk_locked_key(tokenId) debug(['remove_locked_content: ', key, tokenId]) delete(key) -def add_locked_content(tokenId: ByteString, content: ByteString): +def add_locked_content(tokenId: bytes, content: str): key = mk_locked_key(tokenId) debug(['add_locked_content: ', key, tokenId]) put(key, content) -def get_royalties(tokenId: ByteString) -> ByteString: +def get_royalties(tokenId: bytes) -> str: key = mk_royalties_key(tokenId) debug(['get_royalties: ', key, tokenId]) val = get(key, get_read_only_context()) - return val + return type_helper.to_str(val) -def add_royalties(tokenId: ByteString, royalties: str): +def add_royalties(tokenId: bytes, royalties: str): key = mk_royalties_key(tokenId) debug(['add_royalties: ', key, tokenId]) put(key, royalties) -def remove_royalties(tokenId: ByteString): +def remove_royalties(tokenId: bytes): key = mk_royalties_key(tokenId) debug(['remove_royalties: ', key, tokenId]) delete(key) -def get_locked_view_counter(tokenId: ByteString) -> int: +def get_locked_view_counter(tokenId: bytes) -> int: key = mk_lv_key(tokenId) debug(['get_locked_view_counter: ', key, tokenId]) return type_helper.to_int(get(key, get_read_only_context())) -def remove_locked_view_counter(tokenId: ByteString): +def remove_locked_view_counter(tokenId: bytes): key = mk_lv_key(tokenId) debug(['remove_locked_view_counter: ', key, tokenId]) delete(key) -def set_locked_view_counter(tokenId: ByteString): +def set_locked_view_counter(tokenId: bytes): key = mk_lv_key(tokenId) debug(['set_locked_view_counter: ', key, tokenId]) count = type_helper.to_int(get(key, get_read_only_context())) + 1 @@ -856,33 +852,33 @@ def validateAddress(address: UInt160) -> bool: return True -def mk_account_key(address: UInt160) -> ByteString: +def mk_account_key(address: UInt160) -> bytes: return ACCOUNT_PREFIX + address -def mk_balance_key(address: UInt160) -> ByteString: +def mk_balance_key(address: UInt160) -> bytes: return BALANCE_PREFIX + address -def mk_token_key(tokenId: ByteString) -> ByteString: +def mk_token_key(tokenId: bytes) -> bytes: return TOKEN_PREFIX + tokenId -def mk_token_data_key(tokenId: ByteString) -> ByteString: +def mk_token_data_key(tokenId: bytes) -> bytes: return TOKEN_DATA_PREFIX + tokenId -def mk_meta_key(tokenId: ByteString) -> ByteString: +def mk_meta_key(tokenId: bytes) -> bytes: return META_PREFIX + tokenId -def mk_locked_key(tokenId: ByteString) -> ByteString: +def mk_locked_key(tokenId: bytes) -> bytes: return LOCKED_PREFIX + tokenId -def mk_royalties_key(tokenId: ByteString) -> ByteString: +def mk_royalties_key(tokenId: bytes) -> bytes: return ROYALTIES_PREFIX + tokenId -def mk_lv_key(tokenId: ByteString) -> ByteString: +def mk_lv_key(tokenId: bytes) -> bytes: return LOCKED_VIEW_COUNT_PREFIX + tokenId diff --git a/boa3_test/examples/nep17.py b/boa3_test/examples/nep17.py index 008021702..8f3b241d1 100644 --- a/boa3_test/examples/nep17.py +++ b/boa3_test/examples/nep17.py @@ -34,8 +34,8 @@ def manifest_metadata() -> NeoMetadata: # The keys used to access the storage -OWNER_KEY = 'owner' -SUPPLY_KEY = 'totalSupply' +OWNER_KEY = b'owner' +SUPPLY_KEY = b'totalSupply' # Symbol of the Token TOKEN_SYMBOL = 'NEP17' diff --git a/boa3_test/examples/nep5.py b/boa3_test/examples/nep5.py index b2b6760c8..1bb01940e 100644 --- a/boa3_test/examples/nep5.py +++ b/boa3_test/examples/nep5.py @@ -36,8 +36,8 @@ def manifest_metadata() -> NeoMetadata: # ------------------------------------------- # The keys used to access the storage -OWNER_KEY = 'owner' -SUPPLY_KEY = 'totalSupply' +OWNER_KEY = b'owner' +SUPPLY_KEY = b'totalSupply' # Name of the Token TOKEN_NAME = 'NEP5 Standard' diff --git a/boa3_test/examples/update_contract.py b/boa3_test/examples/update_contract.py index 6396cf844..599ab7f1f 100644 --- a/boa3_test/examples/update_contract.py +++ b/boa3_test/examples/update_contract.py @@ -13,8 +13,8 @@ # The keys used to access the storage -OWNER_KEY = 'owner' -SUPPLY_KEY = 'totalSupply' +OWNER_KEY = b'owner' +SUPPLY_KEY = b'totalSupply' TOKEN_TOTAL_SUPPLY = 10_000_000 * 10 ** 8 # 10m total supply * 10^8 (decimals) diff --git a/boa3_test/examples/wrapped_gas.py b/boa3_test/examples/wrapped_gas.py index c49258d53..1fd2e624b 100644 --- a/boa3_test/examples/wrapped_gas.py +++ b/boa3_test/examples/wrapped_gas.py @@ -36,7 +36,7 @@ def manifest_metadata() -> NeoMetadata: # Script hash of the contract owner OWNER = UInt160() -SUPPLY_KEY = 'totalSupply' +SUPPLY_KEY = b'totalSupply' # Symbol of the Token TOKEN_SYMBOL = 'zGAS' diff --git a/boa3_test/examples/wrapped_neo.py b/boa3_test/examples/wrapped_neo.py index bd3af7ee9..07bfa73b4 100644 --- a/boa3_test/examples/wrapped_neo.py +++ b/boa3_test/examples/wrapped_neo.py @@ -35,8 +35,8 @@ def manifest_metadata() -> NeoMetadata: # The keys used to access the storage -OWNER_KEY = 'owner' -SUPPLY_KEY = 'totalSupply' +OWNER_KEY = b'owner' +SUPPLY_KEY = b'totalSupply' # Symbol of the Token TOKEN_SYMBOL = 'zNEO' diff --git a/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py b/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py index fc310a5b4..113969db3 100644 --- a/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py +++ b/boa3_test/test_sc/interop_test/contract/CallFlagsUsage.py @@ -18,10 +18,10 @@ def notify_user(): @public -def put_value(key: str, value: int): +def put_value(key: bytes, value: int): put(key, value) @public -def get_value(key: str) -> int: +def get_value(key: bytes) -> int: return to_int(get(key)) diff --git a/boa3_test/test_sc/interop_test/contract/NewContract.py b/boa3_test/test_sc/interop_test/contract/NewContract.py index 23c8b6faf..3c3c1d175 100644 --- a/boa3_test/test_sc/interop_test/contract/NewContract.py +++ b/boa3_test/test_sc/interop_test/contract/NewContract.py @@ -8,7 +8,7 @@ @public def main() -> str: - return to_str(get('storage')) + return to_str(get(b'storage')) @public @@ -16,4 +16,4 @@ def _deploy(data: Any, update: bool): notify(update) notify(data) if isinstance(data, str): - put('storage', data) + put(b'storage', data) diff --git a/boa3_test/test_sc/interop_test/crypto/Murmur32.py b/boa3_test/test_sc/interop_test/crypto/Murmur32.py index 28c2bddfa..65ca05364 100644 --- a/boa3_test/test_sc/interop_test/crypto/Murmur32.py +++ b/boa3_test/test_sc/interop_test/crypto/Murmur32.py @@ -1,8 +1,7 @@ from boa3.builtin.compile_time import public from boa3.builtin.nativecontract.cryptolib import CryptoLib -from boa3.builtin.type import ByteString @public -def main(data: ByteString, seed: int) -> ByteString: +def main(data: bytes, seed: int) -> bytes: return CryptoLib.murmur32(data, seed) diff --git a/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsa.py b/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsa.py index e31b446cc..3d2a0d1d0 100644 --- a/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsa.py +++ b/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsa.py @@ -1,10 +1,8 @@ -from typing import Any - from boa3.builtin.compile_time import public from boa3.builtin.interop.crypto import NamedCurve, verify_with_ecdsa -from boa3.builtin.type import ByteString, ECPoint +from boa3.builtin.type import ECPoint @public -def Main(message: Any, pubkey: ECPoint, signature: ByteString, curve: NamedCurve) -> bool: +def Main(message: bytes, pubkey: ECPoint, signature: bytes, curve: NamedCurve) -> bool: return verify_with_ecdsa(message, pubkey, signature, curve) diff --git a/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsaSecp256r1Str.py b/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsaSecp256r1Str.py index eabbb7479..1a3fb22b2 100644 --- a/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsaSecp256r1Str.py +++ b/boa3_test/test_sc/interop_test/crypto/VerifyWithECDsaSecp256r1Str.py @@ -1,8 +1,6 @@ -from boa3.builtin.compile_time import public from boa3.builtin.interop.crypto import NamedCurve, verify_with_ecdsa from boa3.builtin.type import ECPoint -@public def Main(): verify_with_ecdsa('unit test', ECPoint(b'0123456789ABCDEFGHIJKLMNOPQRSTUVW'), b'signature', NamedCurve.SECP256R1) diff --git a/boa3_test/test_sc/interop_test/iterator/ImportInteropIterator.py b/boa3_test/test_sc/interop_test/iterator/ImportInteropIterator.py index 6189d3426..90730d713 100644 --- a/boa3_test/test_sc/interop_test/iterator/ImportInteropIterator.py +++ b/boa3_test/test_sc/interop_test/iterator/ImportInteropIterator.py @@ -4,4 +4,4 @@ @public def return_iterator() -> interop.iterator.Iterator: - return interop.storage.find('random_prefix') + return interop.storage.find(b'random_prefix') diff --git a/boa3_test/test_sc/interop_test/iterator/ImportIterator.py b/boa3_test/test_sc/interop_test/iterator/ImportIterator.py index 73714a47e..9120c4feb 100644 --- a/boa3_test/test_sc/interop_test/iterator/ImportIterator.py +++ b/boa3_test/test_sc/interop_test/iterator/ImportIterator.py @@ -5,4 +5,4 @@ @public def return_iterator() -> iterator.Iterator: - return find('random_prefix') + return find(b'random_prefix') diff --git a/boa3_test/test_sc/interop_test/iterator/IteratorImplicitTyping.py b/boa3_test/test_sc/interop_test/iterator/IteratorImplicitTyping.py index b56e7f2d1..9d29a019c 100644 --- a/boa3_test/test_sc/interop_test/iterator/IteratorImplicitTyping.py +++ b/boa3_test/test_sc/interop_test/iterator/IteratorImplicitTyping.py @@ -6,13 +6,13 @@ @public -def store(prefix: str, value: Any): +def store(prefix: bytes, value: Any): serialized_value = StdLib.serialize(value) storage.put(prefix, serialized_value) @public -def search_storage(prefix: str) -> dict: +def search_storage(prefix: bytes) -> dict: data_list = {} data = storage.find(prefix) diff --git a/boa3_test/test_sc/interop_test/iterator/IteratorNext.py b/boa3_test/test_sc/interop_test/iterator/IteratorNext.py index 6c7947cb4..d2f66066f 100644 --- a/boa3_test/test_sc/interop_test/iterator/IteratorNext.py +++ b/boa3_test/test_sc/interop_test/iterator/IteratorNext.py @@ -3,10 +3,10 @@ @public -def has_next(prefix: str) -> bool: +def has_next(prefix: bytes) -> bool: return storage.find(prefix).next() @public -def store_data(key: str, value: int): +def store_data(key: bytes, value: int): storage.put(key, value) diff --git a/boa3_test/test_sc/interop_test/iterator/IteratorValue.py b/boa3_test/test_sc/interop_test/iterator/IteratorValue.py index 1c5b82cc3..fa69da87b 100644 --- a/boa3_test/test_sc/interop_test/iterator/IteratorValue.py +++ b/boa3_test/test_sc/interop_test/iterator/IteratorValue.py @@ -5,7 +5,7 @@ @public -def test_iterator(prefix: str) -> Union[tuple, None]: +def test_iterator(prefix: bytes) -> Union[tuple, None]: it = storage.find(prefix) if it.next(): return it.value @@ -13,5 +13,5 @@ def test_iterator(prefix: str) -> Union[tuple, None]: @public -def store_data(key: str, value: int): +def store_data(key: bytes, value: int): storage.put(key, value) diff --git a/boa3_test/test_sc/interop_test/iterator/IteratorValueAccess.py b/boa3_test/test_sc/interop_test/iterator/IteratorValueAccess.py index 37189fad5..628b2bee9 100644 --- a/boa3_test/test_sc/interop_test/iterator/IteratorValueAccess.py +++ b/boa3_test/test_sc/interop_test/iterator/IteratorValueAccess.py @@ -6,13 +6,13 @@ @public -def store(prefix: str, value: Any): +def store(prefix: bytes, value: Any): serialized_value = StdLib.serialize(value) storage.put(prefix, serialized_value) @public -def search_storage(prefix: str) -> dict: +def search_storage(prefix: bytes) -> dict: data_list = {} data = storage.find(prefix) diff --git a/boa3_test/test_sc/interop_test/runtime/LoadScriptDynamicCall.py b/boa3_test/test_sc/interop_test/runtime/LoadScriptDynamicCall.py index 4b329c1da..1c7ec8ec2 100644 --- a/boa3_test/test_sc/interop_test/runtime/LoadScriptDynamicCall.py +++ b/boa3_test/test_sc/interop_test/runtime/LoadScriptDynamicCall.py @@ -3,17 +3,16 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.contract import CallFlags from boa3.builtin.interop.runtime import load_script -from boa3.builtin.type import ByteString from boa3.builtin.vm import Opcode @public def dynamic_sum_with_flags(a: int, b: int, flags: CallFlags) -> int: - script: ByteString = Opcode.ADD + script: bytes = Opcode.ADD return cast(int, load_script(script, [a, b], flags)) @public def dynamic_sum(a: int, b: int) -> int: - script: ByteString = Opcode.ADD + script: bytes = Opcode.ADD return cast(int, load_script(script, [a, b])) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemoryCompare.py b/boa3_test/test_sc/interop_test/stdlib/MemoryCompare.py index 723fdd30b..2b3b2c59c 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemoryCompare.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemoryCompare.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.interop.stdlib import memory_compare -from boa3.builtin.type import ByteString @public -def main(mem1: ByteString, mem2: ByteString) -> int: +def main(mem1: Union[str, bytes], mem2: Union[str, bytes]) -> int: return memory_compare(mem1, mem2) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooFewArguments.py b/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooFewArguments.py index ad4a18616..a8dbea088 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooFewArguments.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooFewArguments.py @@ -1,6 +1,5 @@ from boa3.builtin.interop.stdlib import memory_compare -from boa3.builtin.type import ByteString -def main(mem1: ByteString) -> int: +def main(mem1: bytes) -> int: return memory_compare(mem1) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooManyArguments.py b/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooManyArguments.py index 4e3a774b8..13891ce26 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooManyArguments.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemoryCompareTooManyArguments.py @@ -1,8 +1,7 @@ from typing import Any from boa3.builtin.interop.stdlib import memory_compare -from boa3.builtin.type import ByteString -def main(mem1: ByteString, mem2: ByteString, arg: Any) -> int: +def main(mem1: bytes, mem2: bytes, arg: Any) -> int: return memory_compare(mem1, mem2, arg) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemorySearch.py b/boa3_test/test_sc/interop_test/stdlib/MemorySearch.py index 49887e3c4..ee960391f 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemorySearch.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemorySearch.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.interop.stdlib import memory_search -from boa3.builtin.type import ByteString @public -def main(mem: ByteString, value: ByteString, start: int, backward: bool) -> int: +def main(mem: Union[str, bytes], value: Union[str, bytes], start: int, backward: bool) -> int: return memory_search(mem, value, start, backward) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemorySearchDefault.py b/boa3_test/test_sc/interop_test/stdlib/MemorySearchDefault.py index dd859cd51..b11705562 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemorySearchDefault.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemorySearchDefault.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.interop.stdlib import memory_search -from boa3.builtin.type import ByteString @public -def main(mem: ByteString, value: ByteString) -> int: +def main(mem: Union[str, bytes], value: Union[str, bytes]) -> int: return memory_search(mem, value) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemorySearchStart.py b/boa3_test/test_sc/interop_test/stdlib/MemorySearchStart.py index dc3e26da5..03654f608 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemorySearchStart.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemorySearchStart.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.interop.stdlib import memory_search -from boa3.builtin.type import ByteString @public -def main(mem: ByteString, value: ByteString, start: int) -> int: +def main(mem: Union[str, bytes], value: Union[str, bytes], start: int) -> int: return memory_search(mem, value, start) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooFewArguments.py b/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooFewArguments.py index a8b2d9e96..35fdd5c18 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooFewArguments.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooFewArguments.py @@ -1,6 +1,5 @@ from boa3.builtin.interop.stdlib import memory_search -from boa3.builtin.type import ByteString -def main(mem: ByteString) -> int: +def main(mem: bytes) -> int: return memory_search(mem) diff --git a/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooManyArguments.py b/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooManyArguments.py index 4eb8cde8c..0b0f2bf0c 100644 --- a/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooManyArguments.py +++ b/boa3_test/test_sc/interop_test/stdlib/MemorySearchTooManyArguments.py @@ -1,8 +1,7 @@ from typing import Any from boa3.builtin.interop.stdlib import memory_search -from boa3.builtin.type import ByteString -def main(mem: ByteString, value: ByteString, start: int, backward: bool, arg: Any) -> int: +def main(mem: bytes, value: bytes, start: int, backward: bool, arg: Any) -> int: return memory_search(mem, value, start, backward, arg) diff --git a/boa3_test/test_sc/interop_test/stdlib/SerializationBoa2Test.py b/boa3_test/test_sc/interop_test/stdlib/SerializationBoa2Test.py index 686c24ff1..3e492088e 100644 --- a/boa3_test/test_sc/interop_test/stdlib/SerializationBoa2Test.py +++ b/boa3_test/test_sc/interop_test/stdlib/SerializationBoa2Test.py @@ -13,24 +13,24 @@ def main(operation: int) -> Any: # serialize it to_save = serialize(stuff) - put('serialized', to_save) + put(b'serialized', to_save) if operation == 1: return to_save elif operation == 2: - to_retrieve = get('serialized') + to_retrieve = get(b'serialized') return to_retrieve elif operation == 3: - to_retrieve = get('serialized') + to_retrieve = get(b'serialized') deserialized = deserialize(to_retrieve) return deserialized elif operation == 4: - to_retrieve = get('serialized') + to_retrieve = get(b'serialized') deserialized = deserialize(to_retrieve) return cast(list, deserialized)[2] diff --git a/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py b/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py index 93c2b5c57..fc5b08ecc 100644 --- a/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py +++ b/boa3_test/test_sc/interop_test/storage/ImportInteropStorage.py @@ -5,25 +5,25 @@ @public -def put_value(key: str, value: int): +def put_value(key: bytes, value: int): interop.storage.put(key, value) @public -def get_value(key: str) -> int: +def get_value(key: bytes) -> int: return to_int(interop.storage.get(key)) @public -def delete_value(key: str): +def delete_value(key: bytes): interop.storage.delete(key) @public -def find_by_prefix(prefix: str) -> Iterator: +def find_by_prefix(prefix: bytes) -> Iterator: return interop.storage.find(prefix) @public -def create_storage_map(prefix: str) -> interop.storage.StorageMap: +def create_storage_map(prefix: bytes) -> interop.storage.StorageMap: return interop.storage.get_context().create_map(prefix) diff --git a/boa3_test/test_sc/interop_test/storage/ImportStorage.py b/boa3_test/test_sc/interop_test/storage/ImportStorage.py index 95410443d..9e6864539 100644 --- a/boa3_test/test_sc/interop_test/storage/ImportStorage.py +++ b/boa3_test/test_sc/interop_test/storage/ImportStorage.py @@ -5,20 +5,20 @@ @public -def put_value(key: str, value: int): +def put_value(key: bytes, value: int): storage.put(key, value) @public -def get_value(key: str) -> int: +def get_value(key: bytes) -> int: return to_int(storage.get(key)) @public -def delete_value(key: str): +def delete_value(key: bytes): storage.delete(key) @public -def find_by_prefix(prefix: str) -> Iterator: +def find_by_prefix(prefix: bytes) -> Iterator: return storage.find(prefix) diff --git a/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py b/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py index 2c9eceb8a..6fcdeccfe 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py +++ b/boa3_test/test_sc/interop_test/storage/StorageAsReadOnly.py @@ -4,20 +4,20 @@ @public -def put_value_in_storage(key: str, value: str): +def put_value_in_storage(key: bytes, value: str): put(key, value) @public -def get_value_in_storage(key: str) -> str: +def get_value_in_storage(key: bytes) -> str: return to_str(get(key)) @public -def put_value_in_storage_read_only(key: str, value: str): +def put_value_in_storage_read_only(key: bytes, value: str): put(key, value, get_context().as_read_only()) @public -def get_value_in_storage_read_only(key: str) -> str: +def get_value_in_storage_read_only(key: bytes) -> str: return to_str(get(key, get_context().as_read_only())) diff --git a/boa3_test/test_sc/interop_test/storage/StorageBoa2Test.py b/boa3_test/test_sc/interop_test/storage/StorageBoa2Test.py index 51c822598..6c8e20f82 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageBoa2Test.py +++ b/boa3_test/test_sc/interop_test/storage/StorageBoa2Test.py @@ -5,7 +5,7 @@ @public -def main(operation: str, arg: str, val: str) -> Any: +def main(operation: str, arg: bytes, val: str) -> Any: storage_context = get_context() print("context") diff --git a/boa3_test/test_sc/interop_test/storage/StorageCreateMap.py b/boa3_test/test_sc/interop_test/storage/StorageCreateMap.py index 6170ee985..9f60e5f8c 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageCreateMap.py +++ b/boa3_test/test_sc/interop_test/storage/StorageCreateMap.py @@ -3,22 +3,22 @@ @public -def get_from_map(key: str) -> bytes: +def get_from_map(key: bytes) -> bytes: context = create_map() return context.get(key) @public -def insert_to_map(key: str, value: str): +def insert_to_map(key: bytes, value: str): context = create_map() context.put(key, value) @public -def delete_from_map(key: str): +def delete_from_map(key: bytes): context = create_map() context.delete(key) def create_map() -> StorageMap: - return get_context().create_map('example_') + return get_context().create_map(b'example_') diff --git a/boa3_test/test_sc/interop_test/storage/StorageDeleteBytesKey.py b/boa3_test/test_sc/interop_test/storage/StorageDeleteBytesKey.py index 0e8aba464..adc06d772 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageDeleteBytesKey.py +++ b/boa3_test/test_sc/interop_test/storage/StorageDeleteBytesKey.py @@ -18,4 +18,4 @@ def has_key(key: bytes) -> bool: @public def _deploy(data: Any, update: bool): # test data to test in unit tests - storage.put('example', 23) + storage.put(b'example', 23) diff --git a/boa3_test/test_sc/interop_test/storage/StorageDeleteStrKey.py b/boa3_test/test_sc/interop_test/storage/StorageDeleteStrKey.py index cbe43e8e0..21f3ba1d2 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageDeleteStrKey.py +++ b/boa3_test/test_sc/interop_test/storage/StorageDeleteStrKey.py @@ -1,21 +1,5 @@ -from typing import Any - -from boa3.builtin.compile_time import public -from boa3.builtin.interop import storage from boa3.builtin.interop.storage import delete -@public def Main(key: str): delete(key) - - -@public -def has_key(key: bytes) -> bool: - return len(storage.get(key)) > 0 - - -@public -def _deploy(data: Any, update: bool): - # test data to test in unit tests - storage.put('example', 23) diff --git a/boa3_test/test_sc/interop_test/storage/StorageDeleteWithContext.py b/boa3_test/test_sc/interop_test/storage/StorageDeleteWithContext.py index ad5822f31..90dd13b2b 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageDeleteWithContext.py +++ b/boa3_test/test_sc/interop_test/storage/StorageDeleteWithContext.py @@ -3,11 +3,10 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop import storage from boa3.builtin.interop.storage import delete, get_context -from boa3.builtin.type import ByteString @public -def Main(key: ByteString): +def Main(key: bytes): context = get_context() delete(key, context) @@ -22,4 +21,4 @@ def has_key(key: bytes) -> bool: def _deploy(data: Any, update: bool): # test data to test in unit tests context = get_context() - storage.put('example', 23, context) + storage.put(b'example', 23, context) diff --git a/boa3_test/test_sc/interop_test/storage/StorageFindBytesPrefix.py b/boa3_test/test_sc/interop_test/storage/StorageFindBytesPrefix.py index e2a065d14..1bb52e4af 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageFindBytesPrefix.py +++ b/boa3_test/test_sc/interop_test/storage/StorageFindBytesPrefix.py @@ -3,7 +3,6 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.iterator import Iterator from boa3.builtin.interop.storage import find, put -from boa3.builtin.type import ByteString @public @@ -12,5 +11,5 @@ def find_by_prefix(prefix: bytes) -> Iterator: @public -def put_on_storage(key: ByteString, value: Union[int, ByteString]): +def put_on_storage(key: bytes, value: Union[bytes, int, str]): put(key, value) diff --git a/boa3_test/test_sc/interop_test/storage/StorageFindStrPrefix.py b/boa3_test/test_sc/interop_test/storage/StorageFindStrPrefix.py index 2b2778e88..df2a56a0c 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageFindStrPrefix.py +++ b/boa3_test/test_sc/interop_test/storage/StorageFindStrPrefix.py @@ -1,16 +1,12 @@ from typing import Union -from boa3.builtin.compile_time import public from boa3.builtin.interop.iterator import Iterator from boa3.builtin.interop.storage import find, put -from boa3.builtin.type import ByteString -@public def find_by_prefix(prefix: str) -> Iterator: return find(prefix) -@public -def put_on_storage(key: ByteString, value: Union[int, ByteString]): +def put_on_storage(key: bytes, value: Union[bytes, int, str]): put(key, value) diff --git a/boa3_test/test_sc/interop_test/storage/StorageFindWithContext.py b/boa3_test/test_sc/interop_test/storage/StorageFindWithContext.py index 206d9f8ab..3403fdb8b 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageFindWithContext.py +++ b/boa3_test/test_sc/interop_test/storage/StorageFindWithContext.py @@ -3,15 +3,14 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop.iterator import Iterator from boa3.builtin.interop.storage import find, get_context, put -from boa3.builtin.type import ByteString @public -def find_by_prefix(prefix: ByteString) -> Iterator: +def find_by_prefix(prefix: bytes) -> Iterator: context = get_context() return find(prefix, context) @public -def put_on_storage(key: ByteString, value: Union[int, ByteString]): +def put_on_storage(key: bytes, value: Union[bytes, int, str]): put(key, value) diff --git a/boa3_test/test_sc/interop_test/storage/StorageFindWithOptions.py b/boa3_test/test_sc/interop_test/storage/StorageFindWithOptions.py index f46708d05..94c1523db 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageFindWithOptions.py +++ b/boa3_test/test_sc/interop_test/storage/StorageFindWithOptions.py @@ -4,15 +4,14 @@ from boa3.builtin.interop.iterator import Iterator from boa3.builtin.interop.storage import find, get_context, put from boa3.builtin.interop.storage.findoptions import FindOptions -from boa3.builtin.type import ByteString @public -def find_by_prefix(prefix: ByteString) -> Iterator: +def find_by_prefix(prefix: bytes) -> Iterator: context = get_context() return find(prefix, context, FindOptions.REMOVE_PREFIX) @public -def put_on_storage(key: ByteString, value: Union[int, ByteString]): +def put_on_storage(key: bytes, value: Union[bytes, int, str]): put(key, value) diff --git a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py index c72b2dd0d..c57d5c239 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py +++ b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut1.py @@ -4,10 +4,10 @@ @public -def put_value(key: str, value: int): +def put_value(key: bytes, value: int): put(key, value) @public -def get_value(key: str) -> int: +def get_value(key: bytes) -> int: return to_int(get(key)) diff --git a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py index 8c7bbd388..c85e6cfe3 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py +++ b/boa3_test/test_sc/interop_test/storage/StorageGetAndPut2.py @@ -4,10 +4,10 @@ @public -def get_value(key: str) -> int: +def get_value(key: bytes) -> int: return to_int(get(key)) @public -def put_value(key: str, value: int): +def put_value(key: bytes, value: int): put(key, value) diff --git a/boa3_test/test_sc/interop_test/storage/StorageGetStrKey.py b/boa3_test/test_sc/interop_test/storage/StorageGetStrKey.py index fe6d85ee3..bede58494 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageGetStrKey.py +++ b/boa3_test/test_sc/interop_test/storage/StorageGetStrKey.py @@ -1,17 +1,5 @@ -from typing import Any - -from boa3.builtin.compile_time import public -from boa3.builtin.interop import storage from boa3.builtin.interop.storage import get -@public def Main(key: str) -> bytes: return get(key) - - -@public -def _deploy(data: Any, update: bool): - # test data to test in unit tests - storage.put('example', 23) - storage.put('test', 42) diff --git a/boa3_test/test_sc/interop_test/storage/StorageGetWithContext.py b/boa3_test/test_sc/interop_test/storage/StorageGetWithContext.py index 062495bd9..8f986f1a9 100644 --- a/boa3_test/test_sc/interop_test/storage/StorageGetWithContext.py +++ b/boa3_test/test_sc/interop_test/storage/StorageGetWithContext.py @@ -3,11 +3,10 @@ from boa3.builtin.compile_time import public from boa3.builtin.interop import storage from boa3.builtin.interop.storage import get, get_context -from boa3.builtin.type import ByteString @public -def Main(key: ByteString) -> bytes: +def Main(key: bytes) -> bytes: context = get_context() return get(key, context) @@ -16,5 +15,5 @@ def Main(key: ByteString) -> bytes: def _deploy(data: Any, update: bool): # test data to test in unit tests context = get_context() - storage.put('example', 23, context) - storage.put('test', 42, context) + storage.put(b'example', 23, context) + storage.put(b'test', 42, context) diff --git a/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyBytesValue.py b/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyBytesValue.py index ed6105540..498c67f27 100644 --- a/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyBytesValue.py +++ b/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyBytesValue.py @@ -1,8 +1,6 @@ -from boa3.builtin.compile_time import public from boa3.builtin.interop.storage import put -@public def Main(key: str): value: bytes = b'\x01\x02\x03' put(key, value) diff --git a/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyIntValue.py b/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyIntValue.py index 27e553a50..8c2026784 100644 --- a/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyIntValue.py +++ b/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyIntValue.py @@ -1,8 +1,6 @@ -from boa3.builtin.compile_time import public from boa3.builtin.interop.storage import put -@public def Main(key: str): value: int = 123 put(key, value) diff --git a/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyStrValue.py b/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyStrValue.py index c93518d45..566459862 100644 --- a/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyStrValue.py +++ b/boa3_test/test_sc/interop_test/storage/StoragePutStrKeyStrValue.py @@ -1,8 +1,6 @@ -from boa3.builtin.compile_time import public from boa3.builtin.interop.storage import put -@public def Main(key: str): value: str = '123' put(key, value) diff --git a/boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsMissingImplementationNEP11OptionalMethods.py b/boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsMissingImplementationNEP11OptionalMethods.py index 0c8e58c2d..d42856a13 100644 --- a/boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsMissingImplementationNEP11OptionalMethods.py +++ b/boa3_test/test_sc/metadata_test/MetadataInfoSupportedStandardsMissingImplementationNEP11OptionalMethods.py @@ -3,7 +3,7 @@ from boa3.builtin.compile_time import NeoMetadata, metadata, public from boa3.builtin.contract import Nep11TransferEvent from boa3.builtin.interop.iterator import Iterator -from boa3.builtin.type import ByteString, UInt160 +from boa3.builtin.type import UInt160 on_transfer = Nep11TransferEvent @@ -47,10 +47,10 @@ def tokens_of(owner: UInt160) -> Iterator: @public(name='ownerOf', safe=True) -def owner_of(token_id: ByteString) -> UInt160: +def owner_of(token_id: bytes) -> UInt160: pass @public -def transfer(to_address: UInt160, token_id: ByteString, data: Any) -> bool: +def transfer(to_address: UInt160, token_id: bytes, data: Any) -> bool: pass diff --git a/boa3_test/test_sc/native_test/cryptolib/Murmur32.py b/boa3_test/test_sc/native_test/cryptolib/Murmur32.py index 28c2bddfa..65ca05364 100644 --- a/boa3_test/test_sc/native_test/cryptolib/Murmur32.py +++ b/boa3_test/test_sc/native_test/cryptolib/Murmur32.py @@ -1,8 +1,7 @@ from boa3.builtin.compile_time import public from boa3.builtin.nativecontract.cryptolib import CryptoLib -from boa3.builtin.type import ByteString @public -def main(data: ByteString, seed: int) -> ByteString: +def main(data: bytes, seed: int) -> bytes: return CryptoLib.murmur32(data, seed) diff --git a/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsa.py b/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsa.py index 61081961c..3941f0b8e 100644 --- a/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsa.py +++ b/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsa.py @@ -1,11 +1,9 @@ -from typing import Any - from boa3.builtin.compile_time import public from boa3.builtin.interop.crypto import NamedCurve from boa3.builtin.nativecontract.cryptolib import CryptoLib -from boa3.builtin.type import ByteString, ECPoint +from boa3.builtin.type import ECPoint @public -def Main(message: Any, pubkey: ECPoint, signature: ByteString, curve: NamedCurve) -> bool: +def Main(message: bytes, pubkey: ECPoint, signature: bytes, curve: NamedCurve) -> bool: return CryptoLib.verify_with_ecdsa(message, pubkey, signature, curve) diff --git a/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256k1Str.py b/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256k1Str.py index 6d0bc4ec9..24f400ec5 100644 --- a/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256k1Str.py +++ b/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256k1Str.py @@ -1,9 +1,7 @@ -from boa3.builtin.compile_time import public from boa3.builtin.interop.crypto import NamedCurve from boa3.builtin.nativecontract.cryptolib import CryptoLib from boa3.builtin.type import ECPoint -@public def Main(): CryptoLib.verify_with_ecdsa('unit test', ECPoint(b'0123456789ABCDEFGHIJKLMNOPQRSTUVW'), b'signature', NamedCurve.SECP256K1) diff --git a/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256r1Str.py b/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256r1Str.py index 8bfae4abd..383e8fced 100644 --- a/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256r1Str.py +++ b/boa3_test/test_sc/native_test/cryptolib/VerifyWithECDsaSecp256r1Str.py @@ -1,9 +1,7 @@ -from boa3.builtin.compile_time import public from boa3.builtin.interop.crypto import NamedCurve from boa3.builtin.nativecontract.cryptolib import CryptoLib from boa3.builtin.type import ECPoint -@public def Main(): CryptoLib.verify_with_ecdsa('unit test', ECPoint(b'0123456789ABCDEFGHIJKLMNOPQRSTUVW'), b'signature', NamedCurve.SECP256R1) diff --git a/boa3_test/test_sc/native_test/stdlib/MemoryCompare.py b/boa3_test/test_sc/native_test/stdlib/MemoryCompare.py index 6921e59c7..4dd99f8fd 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemoryCompare.py +++ b/boa3_test/test_sc/native_test/stdlib/MemoryCompare.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString @public -def main(mem1: ByteString, mem2: ByteString) -> int: +def main(mem1: Union[bytes, str], mem2: Union[bytes, str]) -> int: return StdLib.memory_compare(mem1, mem2) diff --git a/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooFewArguments.py b/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooFewArguments.py index 2d8fe4c62..db42c8626 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooFewArguments.py +++ b/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooFewArguments.py @@ -1,6 +1,5 @@ from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString -def main(mem1: ByteString) -> int: +def main(mem1: bytes) -> int: return StdLib.memory_compare(mem1) diff --git a/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooManyArguments.py b/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooManyArguments.py index b8747952f..684a742f6 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooManyArguments.py +++ b/boa3_test/test_sc/native_test/stdlib/MemoryCompareTooManyArguments.py @@ -1,8 +1,7 @@ from typing import Any from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString -def main(mem1: ByteString, mem2: ByteString, arg: Any) -> int: +def main(mem1: bytes, mem2: bytes, arg: Any) -> int: return StdLib.memory_compare(mem1, mem2, arg) diff --git a/boa3_test/test_sc/native_test/stdlib/MemorySearch.py b/boa3_test/test_sc/native_test/stdlib/MemorySearch.py index 8baf266d9..c1ef02da9 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemorySearch.py +++ b/boa3_test/test_sc/native_test/stdlib/MemorySearch.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString @public -def main(mem: ByteString, value: ByteString, start: int, backward: bool) -> int: +def main(mem: Union[bytes, str], value: Union[bytes, str], start: int, backward: bool) -> int: return StdLib.memory_search(mem, value, start, backward) diff --git a/boa3_test/test_sc/native_test/stdlib/MemorySearchDefault.py b/boa3_test/test_sc/native_test/stdlib/MemorySearchDefault.py index a7b7d157d..902c85479 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemorySearchDefault.py +++ b/boa3_test/test_sc/native_test/stdlib/MemorySearchDefault.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString @public -def main(mem: ByteString, value: ByteString) -> int: +def main(mem: Union[bytes, str], value: Union[bytes, str]) -> int: return StdLib.memory_search(mem, value) diff --git a/boa3_test/test_sc/native_test/stdlib/MemorySearchStart.py b/boa3_test/test_sc/native_test/stdlib/MemorySearchStart.py index 1c7acb8df..cfdcce899 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemorySearchStart.py +++ b/boa3_test/test_sc/native_test/stdlib/MemorySearchStart.py @@ -1,8 +1,9 @@ +from typing import Union + from boa3.builtin.compile_time import public from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString @public -def main(mem: ByteString, value: ByteString, start: int) -> int: +def main(mem: Union[bytes, str], value: Union[bytes, str], start: int) -> int: return StdLib.memory_search(mem, value, start) diff --git a/boa3_test/test_sc/native_test/stdlib/MemorySearchTooFewArguments.py b/boa3_test/test_sc/native_test/stdlib/MemorySearchTooFewArguments.py index 2d612f3d9..ef5f059c3 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemorySearchTooFewArguments.py +++ b/boa3_test/test_sc/native_test/stdlib/MemorySearchTooFewArguments.py @@ -1,6 +1,5 @@ from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString -def main(mem: ByteString) -> int: +def main(mem: bytes) -> int: return StdLib.memory_search(mem) diff --git a/boa3_test/test_sc/native_test/stdlib/MemorySearchTooManyArguments.py b/boa3_test/test_sc/native_test/stdlib/MemorySearchTooManyArguments.py index 135f19d1f..da106f6ef 100644 --- a/boa3_test/test_sc/native_test/stdlib/MemorySearchTooManyArguments.py +++ b/boa3_test/test_sc/native_test/stdlib/MemorySearchTooManyArguments.py @@ -1,8 +1,7 @@ from typing import Any from boa3.builtin.nativecontract.stdlib import StdLib -from boa3.builtin.type import ByteString -def main(mem: ByteString, value: ByteString, start: int, backward: bool, arg: Any) -> int: +def main(mem: bytes, value: bytes, start: int, backward: bool, arg: Any) -> int: return StdLib.memory_search(mem, value, start, backward, arg) diff --git a/boa3_test/test_sc/native_test/stdlib/SerializationBoa2Test.py b/boa3_test/test_sc/native_test/stdlib/SerializationBoa2Test.py index 5025372fe..b09752003 100644 --- a/boa3_test/test_sc/native_test/stdlib/SerializationBoa2Test.py +++ b/boa3_test/test_sc/native_test/stdlib/SerializationBoa2Test.py @@ -13,24 +13,24 @@ def main(operation: int) -> Any: # serialize it to_save = StdLib.serialize(stuff) - put('serialized', to_save) + put(b'serialized', to_save) if operation == 1: return to_save elif operation == 2: - to_retrieve = get('serialized') + to_retrieve = get(b'serialized') return to_retrieve elif operation == 3: - to_retrieve = get('serialized') + to_retrieve = get(b'serialized') deserialized = StdLib.deserialize(to_retrieve) return deserialized elif operation == 4: - to_retrieve = get('serialized') + to_retrieve = get(b'serialized') deserialized = StdLib.deserialize(to_retrieve) return cast(list, deserialized)[2] diff --git a/boa3_test/test_sc/neo_type_test/IsInstanceIterator.py b/boa3_test/test_sc/neo_type_test/IsInstanceIterator.py index b5b6676a5..497485fd1 100644 --- a/boa3_test/test_sc/neo_type_test/IsInstanceIterator.py +++ b/boa3_test/test_sc/neo_type_test/IsInstanceIterator.py @@ -12,5 +12,5 @@ def is_iterator(value: Any) -> bool: @public def storage_find_is_context() -> bool: - storage_find_iterator = find('unit_test') + storage_find_iterator = find(b'unit_test') return is_iterator(storage_find_iterator) diff --git a/boa3_test/test_sc/neo_type_test/IsInstanceStorageMap.py b/boa3_test/test_sc/neo_type_test/IsInstanceStorageMap.py index 08dca0f4c..73edd57e5 100644 --- a/boa3_test/test_sc/neo_type_test/IsInstanceStorageMap.py +++ b/boa3_test/test_sc/neo_type_test/IsInstanceStorageMap.py @@ -11,5 +11,5 @@ def is_storage_map(value: Any) -> bool: @public def create_map_is_storage_map() -> Any: - storage_map = get_context().create_map('example_') + storage_map = get_context().create_map(b'example_') return is_storage_map(storage_map) diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringMultiplication.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringMultiplication.py deleted file mode 100644 index c14d05f75..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringMultiplication.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def bytestring_mult(a: ByteString, b: int) -> ByteString: - return a * b diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py deleted file mode 100644 index 5d0492dc7..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBool.py +++ /dev/null @@ -1,5 +0,0 @@ -from boa3.builtin.type import ByteString - - -def to_bool(arg: ByteString) -> bool: - return arg.to_bool() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py deleted file mode 100644 index 9079c1279..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToBytes.py +++ /dev/null @@ -1,5 +0,0 @@ -from boa3.builtin.type import ByteString - - -def to_bytes(arg: ByteString) -> bytes: - return arg.to_bytes() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py deleted file mode 100644 index 66b2a2a72..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToInt.py +++ /dev/null @@ -1,5 +0,0 @@ -from boa3.builtin.type import ByteString - - -def to_int(arg: ByteString) -> int: - return arg.to_int() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py b/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py deleted file mode 100644 index 444360dae..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ByteStringToStr.py +++ /dev/null @@ -1,5 +0,0 @@ -from boa3.builtin.type import ByteString - - -def to_str(arg: ByteString) -> str: - return arg.to_str() diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithByteString.py b/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithByteString.py deleted file mode 100644 index 50838c269..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithByteString.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def concat(arg1: ByteString, arg2: ByteString) -> ByteString: - return arg1 + arg2 diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithBytes.py b/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithBytes.py deleted file mode 100644 index 513a4d4c1..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithBytes.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def concat(arg: ByteString) -> bytes: - return b'12345' + arg diff --git a/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithStr.py b/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithStr.py deleted file mode 100644 index e0afbee88..000000000 --- a/boa3_test/test_sc/neo_type_test/bytestring/ConcatWithStr.py +++ /dev/null @@ -1,7 +0,0 @@ -from boa3.builtin.compile_time import public -from boa3.builtin.type import ByteString - - -@public -def concat(arg: ByteString) -> str: - return '12345' + arg diff --git a/boa3_test/test_sc/while_test/WhileWithInteropCondition.py b/boa3_test/test_sc/while_test/WhileWithInteropCondition.py index 6bcc323f1..2f8d8e2dc 100644 --- a/boa3_test/test_sc/while_test/WhileWithInteropCondition.py +++ b/boa3_test/test_sc/while_test/WhileWithInteropCondition.py @@ -8,7 +8,7 @@ FEE_RECEIVER_KEY = b'FEE_RECEIVER' -feesMap = get_context().create_map('feesMap') +feesMap = get_context().create_map(b'feesMap') @public diff --git a/boa3_test/tests/compiler_tests/test_interop/test_contract.py b/boa3_test/tests/compiler_tests/test_interop/test_contract.py index 091c97aa0..c6d0db9ce 100644 --- a/boa3_test/tests/compiler_tests/test_interop/test_contract.py +++ b/boa3_test/tests/compiler_tests/test_interop/test_contract.py @@ -119,19 +119,19 @@ def test_call_contract_with_flags(self): from boa3.internal.neo3.contracts import CallFlags - invokes.append(runner.call_contract(path, 'Main', call_hash, 'get_value', ['num'], CallFlags.READ_ONLY)) + invokes.append(runner.call_contract(path, 'Main', call_hash, 'get_value', [b'num'], CallFlags.READ_ONLY)) expected_results.append(0) - invokes.append(runner.call_contract(path, 'Main', call_hash, 'put_value', ['num', 10], CallFlags.STATES)) + invokes.append(runner.call_contract(path, 'Main', call_hash, 'put_value', [b'num', 10], CallFlags.STATES)) expected_results.append(None) - invokes.append(runner.call_contract(path, 'Main', call_hash, 'get_value', ['num'], CallFlags.READ_ONLY)) + invokes.append(runner.call_contract(path, 'Main', call_hash, 'get_value', [b'num'], CallFlags.READ_ONLY)) expected_results.append(10) - invokes.append(runner.call_contract(path, 'Main', call_hash, 'put_value', ['num', 99], CallFlags.ALL)) + invokes.append(runner.call_contract(path, 'Main', call_hash, 'put_value', [b'num', 99], CallFlags.ALL)) expected_results.append(None) - invokes.append(runner.call_contract(path, 'Main', call_hash, 'get_value', ['num'], CallFlags.READ_ONLY)) + invokes.append(runner.call_contract(path, 'Main', call_hash, 'get_value', [b'num'], CallFlags.READ_ONLY)) expected_results.append(99) invokes.append(runner.call_contract(path, 'Main', call_hash, 'notify_user', [], CallFlags.ALL)) @@ -153,13 +153,13 @@ def test_call_contract_with_flags(self): self.assertEqual(1, len(notify)) self.assertEqual('Notify was called', notify[0].arguments[0]) - runner.call_contract(path, 'Main', call_hash, 'get_value', ['num'], CallFlags.NONE) + runner.call_contract(path, 'Main', call_hash, 'get_value', [b'num'], CallFlags.NONE) runner.execute() self.assertEqual(VMState.FAULT, runner.vm_state, msg=runner.cli_log) self.assertRegex(runner.error, f'^{self.CANT_CALL_SYSCALL_WITH_FLAG_MSG_PREFIX}') - runner.call_contract(path, 'Main', call_hash, 'put_value', ['num', 10], CallFlags.READ_ONLY) - runner.call_contract(path, 'Main', call_hash, 'put_value', ['num', 10], CallFlags.NONE) + runner.call_contract(path, 'Main', call_hash, 'put_value', [b'num', 10], CallFlags.READ_ONLY) + runner.call_contract(path, 'Main', call_hash, 'put_value', [b'num', 10], CallFlags.NONE) runner.execute() self.assertEqual(VMState.FAULT, runner.vm_state, msg=runner.cli_log) self.assertRegex(runner.error, f'^{self.CANT_CALL_SYSCALL_WITH_FLAG_MSG_PREFIX}') diff --git a/boa3_test/tests/compiler_tests/test_interop/test_crypto.py b/boa3_test/tests/compiler_tests/test_interop/test_crypto.py index 9e51a118f..3044d0d06 100644 --- a/boa3_test/tests/compiler_tests/test_interop/test_crypto.py +++ b/boa3_test/tests/compiler_tests/test_interop/test_crypto.py @@ -430,207 +430,42 @@ def test_verify_with_ecdsa(self): self.compile(path) def test_verify_with_ecdsa_secp256r1_str(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - string = b'unit test' - named_curve = Integer(NamedCurve.SECP256R1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHDATA1 - + Integer(len(string)).to_byte_array(min_length=1) - + string - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256r1Str.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_bool(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256R1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHF - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256r1Bool.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_int(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256R1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSH10 - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256r1Int.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_bytes(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - string = b'unit test' - named_curve = Integer(NamedCurve.SECP256R1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHDATA1 - + Integer(len(string)).to_byte_array(min_length=1) - + string - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - - path = self.get_contract_path('VerifyWithECDsaSecp256r1Bytes.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + path = self.get_contract_path('VerifyWithECDsaSecp256k1Bool.py') + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_mismatched_type(self): path = self.get_contract_path('VerifyWithECDsaSecp256r1MismatchedType.py') self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_str(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - string = b'unit test' - named_curve = Integer(NamedCurve.SECP256K1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHDATA1 - + Integer(len(string)).to_byte_array(min_length=1) - + string - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256k1Str.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_bool(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256K1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHF - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256k1Bool.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_int(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256K1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSH10 - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256k1Int.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_bytes(self): byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' byte_input2 = b'signature' string = b'unit test' named_curve = Integer(NamedCurve.SECP256K1).to_byte_array(signed=True, min_length=1) - function_id = String(Interop.VerifyWithECDsa._sys_call).to_bytes() - call_flag = Integer(CallFlags.ALL).to_byte_array(signed=True, min_length=1) expected_output = ( Opcode.PUSHINT8 + named_curve diff --git a/boa3_test/tests/compiler_tests/test_interop/test_iterator.py b/boa3_test/tests/compiler_tests/test_interop/test_iterator.py index e3c20354e..44ed10173 100644 --- a/boa3_test/tests/compiler_tests/test_interop/test_iterator.py +++ b/boa3_test/tests/compiler_tests/test_interop/test_iterator.py @@ -1,3 +1,4 @@ +from boa3.internal.neo.vm.type.String import String from boa3_test.tests.boa_test import BoaTest # needs to be the first import to avoid circular imports from boa3.internal.exception import CompilerError @@ -19,11 +20,11 @@ def test_iterator_next(self): invokes = [] expected_results = [] - prefix = 'test_iterator_next' + prefix = b'test_iterator_next' invokes.append(runner.call_contract(path, 'has_next', prefix)) expected_results.append(False) - key = prefix + 'example1' + key = prefix + b'example1' runner.call_contract(path, 'store_data', key, 1) invokes.append(runner.call_contract(path, 'has_next', prefix)) expected_results.append(True) @@ -41,14 +42,15 @@ def test_iterator_value(self): invokes = [] expected_results = [] - prefix = 'test_iterator_value' + prefix = b'test_iterator_value' invokes.append(runner.call_contract(path, 'test_iterator', prefix)) expected_results.append(None) - key = prefix + 'example1' + key = prefix + b'example1' + key_str = String.from_bytes(key) runner.call_contract(path, 'store_data', key, 1) invokes.append(runner.call_contract(path, 'test_iterator', prefix)) - expected_results.append([key, '\x01']) + expected_results.append([key_str, '\x01']) runner.execute() self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) @@ -99,18 +101,19 @@ def test_iterator_implicit_typing(self): invokes = [] expected_results = [] - prefix = 'test_iterator_' + prefix = b'test_iterator_' + prefix_str = String.from_bytes(prefix) invokes.append(runner.call_contract(path, 'search_storage', prefix)) expected_results.append({}) - invokes.append(runner.call_contract(path, 'store', f'{prefix}1', 1)) + invokes.append(runner.call_contract(path, 'store', prefix + b'1', 1)) expected_results.append(None) - invokes.append(runner.call_contract(path, 'store', f'{prefix}2', 2)) + invokes.append(runner.call_contract(path, 'store', prefix + b'2', 2)) expected_results.append(None) invokes.append(runner.call_contract(path, 'search_storage', prefix)) - expected_results.append({f'{prefix}1': 1, f'{prefix}2': 2}) + expected_results.append({f'{prefix_str}1': 1, f'{prefix_str}2': 2}) runner.execute() self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) @@ -125,18 +128,19 @@ def test_iterator_value_access(self): invokes = [] expected_results = [] - prefix = 'test_iterator_' + prefix = b'test_iterator_' + prefix_str = String.from_bytes(prefix) invokes.append(runner.call_contract(path, 'search_storage', prefix)) expected_results.append({}) - invokes.append(runner.call_contract(path, 'store', f'{prefix}1', 1)) + invokes.append(runner.call_contract(path, 'store', prefix + b'1', 1)) expected_results.append(None) - invokes.append(runner.call_contract(path, 'store', f'{prefix}2', 2)) + invokes.append(runner.call_contract(path, 'store', prefix + b'2', 2)) expected_results.append(None) invokes.append(runner.call_contract(path, 'search_storage', prefix)) - expected_results.append({f'{prefix}1': 1, f'{prefix}2': 2}) + expected_results.append({f'{prefix_str}1': 1, f'{prefix_str}2': 2}) runner.execute() self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) diff --git a/boa3_test/tests/compiler_tests/test_interop/test_storage.py b/boa3_test/tests/compiler_tests/test_interop/test_storage.py index 44d58b494..11bc1b81e 100644 --- a/boa3_test/tests/compiler_tests/test_interop/test_storage.py +++ b/boa3_test/tests/compiler_tests/test_interop/test_storage.py @@ -2,7 +2,6 @@ from boa3.internal.exception import CompilerError from boa3.internal.model.builtin.interop.interop import Interop -from boa3.internal.model.type.type import Type from boa3.internal.neo.core.types.InteropInterface import InteropInterface from boa3.internal.neo.vm.opcode.Opcode import Opcode from boa3.internal.neo.vm.type.Integer import Integer @@ -27,12 +26,10 @@ def test_storage_get_bytes_key(self): + Opcode.DUP + Opcode.ISNULL + Opcode.JMPIFNOT - + Integer(7).to_byte_array(signed=True, min_length=1) + + Integer(5).to_byte_array(signed=True, min_length=1) + Opcode.DROP + Opcode.PUSHDATA1 + Integer(0).to_byte_array(signed=False, min_length=1) - + Opcode.CONVERT - + Type.bytes.stack_item + Opcode.RET ) @@ -41,66 +38,8 @@ def test_storage_get_bytes_key(self): self.assertEqual(expected_output, output) def test_storage_get_str_key(self): - expected_output = ( - Opcode.INITSLOT - + b'\x00' - + b'\x01' - + Opcode.LDARG0 - + Opcode.SYSCALL - + Interop.StorageGetContext.interop_method_hash - + Opcode.SYSCALL - + Interop.StorageGet.interop_method_hash - + Opcode.DUP - + Opcode.ISNULL - + Opcode.JMPIFNOT - + Integer(7).to_byte_array(signed=True, min_length=1) - + Opcode.DROP - + Opcode.PUSHDATA1 - + Integer(0).to_byte_array(signed=False, min_length=1) - + Opcode.CONVERT - + Type.bytes.stack_item - + Opcode.RET - ) - path = self.get_contract_path('StorageGetStrKey.py') - output = self.compile(path) - self.assertStartsWith(output, expected_output) - - path, _ = self.get_deploy_file_paths(path) - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - not_existing_key = 'unknown_key' - invokes.append(runner.call_contract(path, 'Main', not_existing_key, - expected_result_type=bytes)) - expected_results.append(b'') - - storage_key_1 = 'example' - storage_key_2 = 'test' - invokes.append(runner.call_contract(path, 'Main', storage_key_1, - expected_result_type=bytes)) - expected_results.append(Integer(23).to_byte_array()) - - invokes.append(runner.call_contract(path, 'Main', storage_key_2, - expected_result_type=bytes)) - expected_results.append(Integer(42).to_byte_array()) - - storage_contract = invokes[0].invoke.contract - runner.execute(get_storage_from=storage_contract) - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - self.assertIsNone(runner.storages.get(storage_contract, not_existing_key)) - - storage_result_1 = runner.storages.get(storage_contract, storage_key_1) - self.assertEqual(expected_results[1], storage_result_1.as_bytes()) - - storage_result_2 = runner.storages.get(storage_contract, storage_key_2) - self.assertEqual(expected_results[2], storage_result_2.as_bytes()) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_storage_get_mismatched_type(self): path = self.get_contract_path('StorageGetMismatchedType.py') @@ -250,147 +189,16 @@ def test_storage_put_bytes_key_str_value(self): self.assertEqual(stored_value, storage_result_2.as_str()) def test_storage_put_str_key_bytes_value(self): - path, _ = self.get_deploy_file_paths('StoragePutStrKeyBytesValue.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - storage_key_1 = 'test1' - storage_key_2 = 'test2' - stored_value = b'\x01\x02\x03' - - invokes.append(runner.call_contract(path, 'Main', storage_key_1)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'Main', storage_key_2)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'Main', storage_key_2)) - expected_results.append(None) - - storage_contract = invokes[0].invoke.contract - runner.execute(get_storage_from=storage_contract) - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - storage_result_1 = runner.storages.get(storage_contract, storage_key_1) - self.assertEqual(stored_value, storage_result_1.as_bytes()) - - storage_result_2 = runner.storages.get(storage_contract, storage_key_2) - self.assertEqual(stored_value, storage_result_2.as_bytes()) + path = self.get_contract_path('StoragePutStrKeyBytesValue.py') + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_storage_put_str_key_int_value(self): - value = Integer(123).to_byte_array() - expected_output = ( - Opcode.INITSLOT - + b'\x01' - + b'\x01' - + Opcode.PUSHINT8 + value - + Opcode.STLOC0 - + Opcode.PUSHINT8 + value - + Opcode.LDARG0 - + Opcode.SYSCALL - + Interop.StorageGetContext.interop_method_hash - + Opcode.SYSCALL - + Interop.StoragePut.interop_method_hash - + Opcode.RET - ) - path = self.get_contract_path('StoragePutStrKeyIntValue.py') - output = self.compile(path) - self.assertEqual(expected_output, output) - - path, _ = self.get_deploy_file_paths(path) - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - storage_key_1 = 'test1' - storage_key_2 = 'test2' - stored_value = 123 - - invokes.append(runner.call_contract(path, 'Main', storage_key_1)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'Main', storage_key_2)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'Main', storage_key_2)) - expected_results.append(None) - - storage_contract = invokes[0].invoke.contract - runner.execute(get_storage_from=storage_contract) - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - storage_result_1 = runner.storages.get(storage_contract, storage_key_1) - self.assertEqual(stored_value, storage_result_1.as_int()) - - storage_result_2 = runner.storages.get(storage_contract, storage_key_2) - self.assertEqual(stored_value, storage_result_2.as_int()) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_storage_put_str_key_str_value(self): - value = String('123').to_bytes() - expected_output = ( - Opcode.INITSLOT - + b'\x01' - + b'\x01' - + Opcode.PUSHDATA1 - + Integer(len(value)).to_byte_array(min_length=1, signed=True) - + value - + Opcode.STLOC0 - + Opcode.PUSHDATA1 - + Integer(len(value)).to_byte_array(min_length=1, signed=True) - + value - + Opcode.LDARG0 - + Opcode.SYSCALL - + Interop.StorageGetContext.interop_method_hash - + Opcode.SYSCALL - + Interop.StoragePut.interop_method_hash - + Opcode.RET - ) - path = self.get_contract_path('StoragePutStrKeyStrValue.py') - output = self.compile(path) - self.assertEqual(expected_output, output) - - path, _ = self.get_deploy_file_paths(path) - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - storage_key_1 = 'test1' - storage_key_2 = 'test2' - stored_value = '123' - - invokes.append(runner.call_contract(path, 'Main', storage_key_1)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'Main', storage_key_2)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'Main', storage_key_2)) - expected_results.append(None) - - storage_contract = invokes[0].invoke.contract - runner.execute(get_storage_from=storage_contract) - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - storage_result_1 = runner.storages.get(storage_contract, storage_key_1) - self.assertEqual(stored_value, storage_result_1.as_str()) - - storage_result_2 = runner.storages.get(storage_contract, storage_key_2) - self.assertEqual(stored_value, storage_result_2.as_str()) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_storage_put_mismatched_type_key(self): path = self.get_contract_path('StoragePutMismatchedTypeKey.py') @@ -452,55 +260,8 @@ def test_storage_delete_bytes_key(self): self.assertIsNone(runner.storages.get(storage_contract, storage_key)) def test_storage_delete_str_key(self): - expected_output = ( - Opcode.INITSLOT - + b'\x00' - + b'\x01' - + Opcode.LDARG0 - + Opcode.SYSCALL - + Interop.StorageGetContext.interop_method_hash - + Opcode.SYSCALL - + Interop.StorageDelete.interop_method_hash - + Opcode.RET - ) - path = self.get_contract_path('StorageDeleteStrKey.py') - output = self.compile(path) - self.assertStartsWith(output, expected_output) - - path, _ = self.get_deploy_file_paths(path) - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - not_existing_key = 'unknown_key' - storage_key = 'example' - - invokes.append(runner.call_contract(path, 'has_key', not_existing_key)) - expected_results.append(False) - - invokes.append(runner.call_contract(path, 'has_key', storage_key)) - expected_results.append(True) - - invokes.append(runner.call_contract(path, 'Main', not_existing_key)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'Main', storage_key)) - expected_results.append(None) - - invokes.append(runner.call_contract(path, 'has_key', storage_key)) - expected_results.append(False) - - storage_contract = invokes[0].invoke.contract - runner.execute(get_storage_from=storage_contract) - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - self.assertIsNone(runner.storages.get(storage_contract, not_existing_key)) - self.assertIsNone(runner.storages.get(storage_contract, storage_key)) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_storage_delete_mismatched_type(self): path = self.get_contract_path('StorageDeleteMismatchedType.py') @@ -537,34 +298,8 @@ def test_storage_find_bytes_prefix(self): self.assertEqual(expected_results[x], invokes[x].result) def test_storage_find_str_prefix(self): - path, _ = self.get_deploy_file_paths('StorageFindStrPrefix.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'find_by_prefix', 'example')) - expected_results.append([]) - - runner.execute() # getting result of multiple iterators is failing - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - storage = {'example_0': '0', - 'example_1': '1', - 'example_2': '3'} - expected_result = [[key, value] for key, value in storage.items()] - - for (key, value) in expected_result: - runner.call_contract(path, 'put_on_storage', key, value) - - invokes.append(runner.call_contract(path, 'find_by_prefix', 'example')) - expected_results.append(expected_result) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) + path = self.get_contract_path('StorageFindStrPrefix.py') + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_storage_find_mismatched_type(self): path = self.get_contract_path('StorageFindMismatchedType.py') @@ -811,7 +546,7 @@ def test_boa2_storage_test(self): invokes = [] expected_results = [] - storage_key = 'something' + storage_key = b'something' invokes.append(runner.call_contract(path, 'main', 'sget', storage_key, 'blah', expected_result_type=bytes)) expected_results.append(b'') @@ -882,7 +617,7 @@ def test_storage_between_contracts(self): invokes = [] expected_results = [] - key = 'example_key' + key = b'example_key' value = 42 invokes.append(runner.call_contract(path1, 'put_value', key, value)) @@ -923,7 +658,7 @@ def test_create_map(self): invokes.append(runner.call_contract(path, 'insert_to_map', storage_key, stored_value)) expected_results.append(None) - invokes.append(runner.call_contract(path, 'get_from_map', 'test1', + invokes.append(runner.call_contract(path, 'get_from_map', b'test1', expected_result_type=bytes)) expected_results.append(stored_value) @@ -934,10 +669,10 @@ def test_create_map(self): storage_result = runner.storages.get(storage_contract, map_key + storage_key) self.assertEqual(stored_value, storage_result.as_bytes()) - invokes.append(runner.call_contract(path, 'delete_from_map', 'test1')) + invokes.append(runner.call_contract(path, 'delete_from_map', b'test1')) expected_results.append(None) - invokes.append(runner.call_contract(path, 'get_from_map', 'test1', + invokes.append(runner.call_contract(path, 'get_from_map', b'test1', expected_result_type=bytes)) expected_results.append(b'') @@ -954,8 +689,9 @@ def test_import_storage(self): invokes = [] expected_results = [] - prefix = 'unit' - key = f'{prefix}_test' + prefix = b'unit' + key = prefix + b'_test' + key_str = String.from_bytes(key) value = 1234 invokes.append(runner.call_contract(path, 'get_value', key)) @@ -974,7 +710,7 @@ def test_import_storage(self): expected_results.append(value) invokes.append(runner.call_contract(path, 'find_by_prefix', prefix)) - expected_results.append([[key, Integer(value).to_byte_array()]]) + expected_results.append([[key_str, Integer(value).to_byte_array()]]) runner.execute() # getting result of multiple iterators is failing self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) @@ -1004,8 +740,9 @@ def test_import_interop_storage(self): invokes = [] expected_results = [] - prefix = 'unit' - key = f'{prefix}_test' + prefix = b'unit' + key = prefix + b'_test' + key_str = String.from_bytes(key) value = 1234 invokes.append(runner.call_contract(path, 'get_value', key)) @@ -1024,7 +761,7 @@ def test_import_interop_storage(self): expected_results.append(value) invokes.append(runner.call_contract(path, 'find_by_prefix', prefix)) - expected_results.append([[key, Integer(value).to_byte_array()]]) + expected_results.append([[key_str, Integer(value).to_byte_array()]]) runner.execute() # getting result of multiple iterators is failing self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) @@ -1054,7 +791,7 @@ def test_as_read_only(self): invokes = [] expected_results = [] - key = 'key' + key = b'key' value_old = 'old value' value_new = 'new value' diff --git a/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py b/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py index 1f7060b08..9fd5aa1f0 100644 --- a/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py +++ b/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py @@ -207,31 +207,8 @@ def test_verify_with_ecdsa(self): self.compile(path) def test_verify_with_ecdsa_secp256r1_str(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - string = b'unit test' - named_curve = Integer(NamedCurve.SECP256R1).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHDATA1 - + Integer(len(string)).to_byte_array(min_length=1) - + string - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256r1Str.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_bool(self): byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' @@ -313,31 +290,8 @@ def test_verify_with_ecdsa_secp256r1_mismatched_type(self): self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_str(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - string = b'unit test' - named_curve = Integer(NamedCurve.SECP256K1).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHDATA1 - + Integer(len(string)).to_byte_array(min_length=1) - + string - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256k1Str.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_bool(self): byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' diff --git a/boa3_test/tests/compiler_tests/test_neo_types.py b/boa3_test/tests/compiler_tests/test_neo_types.py index 3e9072bbc..e24d21af0 100644 --- a/boa3_test/tests/compiler_tests/test_neo_types.py +++ b/boa3_test/tests/compiler_tests/test_neo_types.py @@ -2,7 +2,6 @@ from boa3.internal.exception import CompilerError, CompilerWarning from boa3.internal.neo.vm.type.Integer import Integer -from boa3.internal.neo.vm.type.String import String from boa3.internal.neo3.vm import VMState from boa3_test.test_drive.testrunner.neo_test_runner import NeoTestRunner @@ -459,148 +458,6 @@ def test_ecpoint_script_hash_from_builtin(self): # endregion - # region ByteString - - def test_byte_string_manifest_generation(self): - path = self.get_contract_path('bytestring', 'ConcatWithByteString.py') - _, expected_manifest_output = self.get_deploy_file_paths(path) - output, manifest = self.get_output(path) - - import os - from boa3.internal.neo.vm.type.AbiType import AbiType - - self.assertTrue(os.path.exists(expected_manifest_output)) - self.assertIn('abi', manifest) - abi = manifest['abi'] - - self.assertIn('methods', abi) - self.assertEqual(1, len(abi['methods'])) - - method = abi['methods'][0] - - self.assertIn('parameters', method) - self.assertEqual(2, len(method['parameters'])) - self.assertIn('type', method['parameters'][0]) - self.assertEqual(AbiType.ByteArray, method['parameters'][0]['type']) - self.assertIn('type', method['parameters'][1]) - self.assertEqual(AbiType.ByteArray, method['parameters'][1]['type']) - - def test_byte_string_to_bool(self): - path = self.get_contract_path('bytestring', 'ByteStringToBool.py') - self.assertCompilerLogs(CompilerError.UnresolvedReference, path) - - def test_byte_string_to_int(self): - path = self.get_contract_path('bytestring', 'ByteStringToInt.py') - self.assertCompilerLogs(CompilerError.UnresolvedReference, path) - - def test_byte_string_to_str(self): - path = self.get_contract_path('bytestring', 'ByteStringToStr.py') - self.assertCompilerLogs(CompilerError.UnresolvedReference, path) - - def test_byte_string_to_bytes(self): - path = self.get_contract_path('bytestring', 'ByteStringToBytes.py') - self.assertCompilerLogs(CompilerError.UnresolvedReference, path) - - def test_concat_with_bytes(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ConcatWithBytes.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - prefix = b'12345' - arg = b'a' - invokes.append(runner.call_contract(path, 'concat', arg, - expected_result_type=bytes)) - expected_results.append(prefix + arg) - - arg = '6789' - invokes.append(runner.call_contract(path, 'concat', arg, - expected_result_type=bytes)) - expected_results.append(prefix + String(arg).to_bytes()) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_concat_with_str(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ConcatWithStr.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - prefix = '12345' - arg = 'a' - invokes.append(runner.call_contract(path, 'concat', arg)) - expected_results.append(prefix + arg) - - arg = b'6789' - invokes.append(runner.call_contract(path, 'concat', arg)) - expected_results.append(prefix + String.from_bytes(arg)) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_concat_with_bytestring(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ConcatWithByteString.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - prefix = '12345' - arg = 'a' - invokes.append(runner.call_contract(path, 'concat', prefix, arg)) - expected_results.append(prefix + arg) - - arg = b'a' - invokes.append(runner.call_contract(path, 'concat', prefix, arg)) - expected_results.append(prefix + String.from_bytes(arg)) - - prefix = b'12345' - arg = b'6789' - invokes.append(runner.call_contract(path, 'concat', prefix, arg, - expected_result_type=bytes)) - expected_results.append(prefix + arg) - - arg = '6789' - invokes.append(runner.call_contract(path, 'concat', prefix, arg, - expected_result_type=bytes)) - expected_results.append(prefix + String(arg).to_bytes()) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - def test_bytestring_multiplication(self): - path, _ = self.get_deploy_file_paths('bytestring', 'ByteStringMultiplication.py') - runner = NeoTestRunner(runner_id=self.method_name()) - - invokes = [] - expected_results = [] - - invokes.append(runner.call_contract(path, 'bytestring_mult', b'a', 4, - expected_result_type=bytes)) - expected_results.append(b'aaaa') - invokes.append(runner.call_contract(path, 'bytestring_mult', 'unit', 50)) - expected_results.append('unit' * 50) - - runner.execute() - self.assertEqual(VMState.HALT, runner.vm_state, msg=runner.error) - - for x in range(len(invokes)): - self.assertEqual(expected_results[x], invokes[x].result) - - # endregion - # region Opcode def test_opcode_manifest_generation(self): diff --git a/docs/source/tutorials.rst b/docs/source/tutorials.rst index 6db9e7e3b..0c2b0483b 100644 --- a/docs/source/tutorials.rst +++ b/docs/source/tutorials.rst @@ -22,7 +22,7 @@ All of the examples presented here can be found in the `examples folder of the N @public def Main(): - storage.put('hello', 'world') + storage.put(b'hello', b'world') @metadata From dde659d2190081f0de9be23d4dc1ca3ec756eab4 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 6 Jun 2023 12:19:36 -0300 Subject: [PATCH 13/17] #861mv1dju - Fix nep11 mismatched signature --- boa3_test/examples/nep11_non_divisible.py | 23 ++++++++++++----------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/boa3_test/examples/nep11_non_divisible.py b/boa3_test/examples/nep11_non_divisible.py index be9e661ac..37485bca0 100644 --- a/boa3_test/examples/nep11_non_divisible.py +++ b/boa3_test/examples/nep11_non_divisible.py @@ -83,7 +83,7 @@ def gm_manifest() -> NeoMetadata: ('from_addr', Union[UInt160, None]), ('to_addr', Union[UInt160, None]), ('amount', int), - ('tokenId', bytes) + ('tokenId', Union[bytes, str]) ], 'Transfer' ) @@ -210,7 +210,7 @@ def tokensOf(owner: UInt160) -> Iterator: @public -def transfer(to: UInt160, tokenId: bytes, data: Any) -> bool: +def transfer(to: UInt160, tokenId: Union[bytes, str], data: Any) -> bool: """ Transfers the token with id tokenId to address to @@ -236,20 +236,21 @@ def transfer(to: UInt160, tokenId: bytes, data: Any) -> bool: """ expect(validateAddress(to), "Not a valid address") expect(not isPaused(), "Contract is currently paused") - token_owner = get_owner_of(tokenId) + token_id: bytes = tokenId + token_owner = get_owner_of(token_id) if not check_witness(token_owner): return False if (token_owner != to): set_balance(token_owner, -1) - remove_token_account(token_owner, tokenId) + remove_token_account(token_owner, token_id) set_balance(to, 1) - set_owner_of(tokenId, to) - add_token_account(to, tokenId) - post_transfer(token_owner, to, tokenId, data) + set_owner_of(token_id, to) + add_token_account(to, token_id) + post_transfer(token_owner, to, token_id, data) return True @@ -275,7 +276,7 @@ def post_transfer(token_owner: Union[UInt160, None], to: Union[UInt160, None], t @public(safe=True) -def ownerOf(tokenId: bytes) -> UInt160: +def ownerOf(tokenId: Union[bytes, str]) -> UInt160: """ Get the owner of the specified token. @@ -286,7 +287,7 @@ def ownerOf(tokenId: bytes) -> UInt160: :return: the owner of the specified token. :raise AssertionError: raised if `tokenId` is not a valid NFT. """ - owner = get_owner_of(tokenId) + owner = get_owner_of(cast(bytes, tokenId)) debug(['ownerOf: ', owner]) return owner @@ -304,7 +305,7 @@ def tokens() -> Iterator: @public(safe=True) -def properties(tokenId: bytes) -> Dict[Any, Any]: +def properties(tokenId: Union[bytes, str]) -> Dict[Any, Any]: """ Get the properties of a token. @@ -315,7 +316,7 @@ def properties(tokenId: bytes) -> Dict[Any, Any]: :return: a serialized NVM object containing the properties for the given NFT. :raise AssertionError: raised if `tokenId` is not a valid NFT, or if no metadata available. """ - metaBytes = cast(str, get_meta(tokenId)) + metaBytes = cast(str, get_meta(cast(bytes, tokenId))) expect(len(metaBytes) != 0, 'No metadata available for token') metaObject = cast(Dict[str, str], json_deserialize(metaBytes)) From 7716a763280765a3906a9a64f97e0fdd0054b466 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Mon, 19 Jun 2023 13:13:07 -0300 Subject: [PATCH 14/17] #864ev3ef6 - Write a migration guide with how to migrate contracts that use ByteString class --- docs/migration-guide.md | 43 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 docs/migration-guide.md diff --git a/docs/migration-guide.md b/docs/migration-guide.md new file mode 100644 index 000000000..0606f0a50 --- /dev/null +++ b/docs/migration-guide.md @@ -0,0 +1,43 @@ +Welcome to the migration guide for the new version of Neo3Boa. + +This guide will assist you in migrating your code from the previous version to the latest version, which includes several improvements with debugger integration to enhance the smart contract debugging experience. + +## System Requirements: + +Ensure that your system meets the following requirements for the new compiler version: + +Compiler Version: v0.14.0 + +Python 3.7 or later + +## Pre-migration Preparation: + +Before migrating your code, we recommend following these steps: + +1. Backup your code and related files to ensure you have a copy of the previous version. + +2. Familiarize yourself with the changes and improvements introduced in the new version by referring to the release notes and documentation. + +## Migration Process: + +* In the new version, the `ByteString` type has been removed. Update any contracts that use this type with either `bytes` or `str`, depending on the code logic and requirements. +* Most of the interop methods that previously used `ByteString` have been modified to use `bytes` instead. + * Special attention to `storage` methods, which accepted both `bytes` and `str` as valid keys. In the news version, only `bytes` values are accepted as storage keys. +* Locate all instances where `ByteString` is used and replace it with the appropriate type (`bytes` or `str`). +* Review your codebase and make the necessary changes to ensure compatibility with the new version. + +## Known Issues and Troubleshooting: + +* ### NEP-11 Standard Validation: + + If your contracts implement the `NEP-11` standard, be aware that Neo3Boa verifies if the methods that used to have `ByteString` type now are implemented as `Union[bytes, str]`. + + Using either `bytes` or `str` in these methods won't pass the compiler validation. + +## Testing and Feedback: + +We encourage you to thoroughly test your migrated contracts in the new version and provide feedback on any issues or challenges you encounter. Your feedback will help us improve the migration process and address any inconsistent behaviors. + +Remember to consult the updated documentation and resources provided by the new version to familiarize yourself with any additional changes, features, or improvements. + +Thank you for choosing Neo3Boa, and we appreciate your cooperation in migrating to the new version. \ No newline at end of file From cebc9ed10f74971d4999d1a965b345cdeb7fdc06 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 20 Jun 2023 11:57:28 -0300 Subject: [PATCH 15/17] #864ev3ef6 - Review --- README.md | 2 ++ ...ration-guide.md => migration-guide-v0.14.0.md} | 15 +++++++++++---- .../boa3/builtin/type/boa3-builtin-type.rst | 8 ++++++++ 3 files changed, 21 insertions(+), 4 deletions(-) rename docs/{migration-guide.md => migration-guide-v0.14.0.md} (74%) diff --git a/README.md b/README.md index 83159329b..28615023d 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,8 @@
+> Note: The latest release (v0.14.0) has breaking changes with contracts written using previous versions. Please refer to our [migration guide](/docs/migration-guide-v0.14.0.md) to update your smart contracts. + ## Table of Contents - [Overview](#overview) - [Quickstart](#quickstart) diff --git a/docs/migration-guide.md b/docs/migration-guide-v0.14.0.md similarity index 74% rename from docs/migration-guide.md rename to docs/migration-guide-v0.14.0.md index 0606f0a50..ad9846180 100644 --- a/docs/migration-guide.md +++ b/docs/migration-guide-v0.14.0.md @@ -1,4 +1,6 @@ -Welcome to the migration guide for the new version of Neo3Boa. +# Neo3-Boa v0.14.0 Migration Guide + +Welcome to the migration guide for the new version of Neo3-Boa. This guide will assist you in migrating your code from the previous version to the latest version, which includes several improvements with debugger integration to enhance the smart contract debugging experience. @@ -21,16 +23,21 @@ Before migrating your code, we recommend following these steps: ## Migration Process: * In the new version, the `ByteString` type has been removed. Update any contracts that use this type with either `bytes` or `str`, depending on the code logic and requirements. + * Most of the interop methods that previously used `ByteString` have been modified to use `bytes` instead. - * Special attention to `storage` methods, which accepted both `bytes` and `str` as valid keys. In the news version, only `bytes` values are accepted as storage keys. + * Special attention to `storage` methods, which accepted both `bytes` and `str` as valid keys. In the new version, only `bytes` values are accepted as storage keys. + + Neo3-boa v0.14.0 has new methods to convert between types, like from `str` to `bytes`. Refer to [our docs](https://dojo.coz.io/neo3/boa/boa3/builtin/type/boa3-builtin-type.html#module-boa3.builtin.type.helper) for more details. + * Locate all instances where `ByteString` is used and replace it with the appropriate type (`bytes` or `str`). + * Review your codebase and make the necessary changes to ensure compatibility with the new version. ## Known Issues and Troubleshooting: * ### NEP-11 Standard Validation: - If your contracts implement the `NEP-11` standard, be aware that Neo3Boa verifies if the methods that used to have `ByteString` type now are implemented as `Union[bytes, str]`. + If your contracts implement the `NEP-11` standard, be aware that Neo3-Boa verifies if the methods that used to have `ByteString` type now are implemented as `Union[bytes, str]`. Using either `bytes` or `str` in these methods won't pass the compiler validation. @@ -40,4 +47,4 @@ We encourage you to thoroughly test your migrated contracts in the new version a Remember to consult the updated documentation and resources provided by the new version to familiarize yourself with any additional changes, features, or improvements. -Thank you for choosing Neo3Boa, and we appreciate your cooperation in migrating to the new version. \ No newline at end of file +Thank you for choosing Neo3-Boa, and we appreciate your cooperation in migrating to the new version. diff --git a/docs/source/boa3/builtin/type/boa3-builtin-type.rst b/docs/source/boa3/builtin/type/boa3-builtin-type.rst index b23695912..f6471ee93 100644 --- a/docs/source/boa3/builtin/type/boa3-builtin-type.rst +++ b/docs/source/boa3/builtin/type/boa3-builtin-type.rst @@ -2,3 +2,11 @@ type ==== .. automodule:: boa3.builtin.type + :ignore-module-all: + +Subpackages +----------- + +helper +~~~~~~ +.. automodule:: boa3.builtin.type.helper From 250fe95dd458a74f5620fb1e80671adcd323dbed Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 20 Jun 2023 14:13:14 -0300 Subject: [PATCH 16/17] #864er4r52 - Release Minor - ByteString refactoring, debug updates and bugfixes --- CHANGELOG.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5c2405bc..b29c21b5e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.14.0] - 2023-06-20 +> This version has breaking changes. Please refer to our [migration guide](/docs/migration-guide-v0.14.0.md) to update your smart contracts. + +### Changed +- Moved `ByteString` class methods `to_int`, `to_str`, `to_bytes` and `to_bool` to the module `boa3.builtin.type.helper` + +### Removed +- Removed `ByteString` type. +- Removed `to_int` implementation from `str` and `bytes` types. +- Removed `to_bytes` implementation from `int` and `bytes` types. +- Removed `to_str` implementation from `bytes` types. +- Removed `to_bool` implementation from `bytes` type. + +### Fixed +- Fixed debugging information for symbols of imported modules. +- Fixed incorrect import error caused by root folder path. +- Fixed generation of static variables that were duplicated. +- Fixed code generation for method calls on `return` statements in void methods. +- Fixed compilation failure caused by imports in the file where `NeoMetadata` is defined. +- Fixed standard validations when using imported symbols. + + ## [0.13.1] - 2023-05-29 ### Changed - Imported contract interfaces are included on metadata permissions to ensure the expected executing behaviour @@ -454,7 +476,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [0.0.2] - 2020-06-13 -[Unreleased]: https://github.com/CityOfZion/neo3-boa/tree/development +[Unreleased]: https://github.com/CityOfZion/neo3-boa/compare/master...staging +[0.14.0]: https://github.com/CityOfZion/neo3-boa/releases/tag/v0.14.0 [0.13.1]: https://github.com/CityOfZion/neo3-boa/releases/tag/v0.13.1 [0.13.0]: https://github.com/CityOfZion/neo3-boa/releases/tag/v0.13.0 [0.12.3]: https://github.com/CityOfZion/neo3-boa/releases/tag/v0.12.3 From 27d46f6939586c917242095505af1e47d8cdfae6 Mon Sep 17 00:00:00 2001 From: Mirella de Medeiros Date: Tue, 20 Jun 2023 16:37:12 -0300 Subject: [PATCH 17/17] lint --- .../compiler/codegenerator/codegenerator.py | 2 +- .../interop/storage/storagegetmethod.py | 1 - .../model/builtin/native/nativecontract.py | 1 - .../ContractInterfaceCodeOptimization.py | 2 +- ...ContractManualInterfaceCodeOptimization.py | 2 +- .../contract_interface_test/Nep17Interface.py | 2 +- .../Nep17InterfaceWithDisplayName.py | 2 +- .../aux_package/internal_package/__init__.py | 4 +- .../test_native/test_cryptolib.py | 88 +------------------ 9 files changed, 11 insertions(+), 93 deletions(-) diff --git a/boa3/internal/compiler/codegenerator/codegenerator.py b/boa3/internal/compiler/codegenerator/codegenerator.py index b1b541bba..c5297cb3f 100644 --- a/boa3/internal/compiler/codegenerator/codegenerator.py +++ b/boa3/internal/compiler/codegenerator/codegenerator.py @@ -434,7 +434,7 @@ def get_symbol(self, identifier: str, scope: Optional[ISymbol] = None, is_intern attribute, symbol_id = constants.ATTRIBUTE_NAME_SEPARATOR.join(split[:-1]), split[-1] another_attr_id, attr = self.get_symbol(attribute, is_internal=is_internal) if hasattr(attr, 'symbols') and symbol_id in attr.symbols: - found_id, found_symbol = symbol_id, attr.symbols[symbol_id] + found_id, found_symbol = symbol_id, attr.symbols[symbol_id] elif isinstance(attr, Package) and symbol_id in attr.inner_packages: found_id, found_symbol = symbol_id, attr.inner_packages[symbol_id] diff --git a/boa3/internal/model/builtin/interop/storage/storagegetmethod.py b/boa3/internal/model/builtin/interop/storage/storagegetmethod.py index 5997ada42..c182e3997 100644 --- a/boa3/internal/model/builtin/interop/storage/storagegetmethod.py +++ b/boa3/internal/model/builtin/interop/storage/storagegetmethod.py @@ -31,7 +31,6 @@ def __init__(self): @property def _opcode(self) -> List[Tuple[Opcode, bytes]]: - from boa3.internal.model.type.type import Type from boa3.internal.neo.vm.type.Integer import Integer opcodes = super()._opcode diff --git a/boa3/internal/model/builtin/native/nativecontract.py b/boa3/internal/model/builtin/native/nativecontract.py index 7a891a312..d4eefdcaf 100644 --- a/boa3/internal/model/builtin/native/nativecontract.py +++ b/boa3/internal/model/builtin/native/nativecontract.py @@ -1,6 +1,5 @@ from typing import List -from boa3.internal.model.builtin.builtin import Builtin from boa3.internal.model.builtin.interop.interop import Interop from boa3.internal.model.builtin.native import * from boa3.internal.model.builtin.native.oracleclass import OracleClass diff --git a/boa3_test/test_sc/contract_interface_test/ContractInterfaceCodeOptimization.py b/boa3_test/test_sc/contract_interface_test/ContractInterfaceCodeOptimization.py index 03416bec6..0ed3b860b 100644 --- a/boa3_test/test_sc/contract_interface_test/ContractInterfaceCodeOptimization.py +++ b/boa3_test/test_sc/contract_interface_test/ContractInterfaceCodeOptimization.py @@ -4,7 +4,7 @@ from boa3.builtin.type import UInt160 -@contract('0x409eb4868a2c43611b9c0f9df98de3846ada4fcb') +@contract('0x2b061955be33023e641bbd495c6887f6c0ba867f') class Nep17: @staticmethod diff --git a/boa3_test/test_sc/contract_interface_test/ContractManualInterfaceCodeOptimization.py b/boa3_test/test_sc/contract_interface_test/ContractManualInterfaceCodeOptimization.py index 7478619e4..919981349 100644 --- a/boa3_test/test_sc/contract_interface_test/ContractManualInterfaceCodeOptimization.py +++ b/boa3_test/test_sc/contract_interface_test/ContractManualInterfaceCodeOptimization.py @@ -6,7 +6,7 @@ class Nep17: - _hash = UInt160(b'\xcb\x4f\xda\x6a\x84\xe3\x8d\xf9\x9d\x0f\x9c\x1b\x61\x43\x2c\x8a\x86\xb4\x9e\x40') + _hash = UInt160(b'\x7f\x86\xba\xc0\xf6\x87\x68\x5c\x49\xbd\x1b\x64\x3e\x02\x33\xbe\x55\x19\x06\x2b') @classmethod def symbol(cls) -> str: diff --git a/boa3_test/test_sc/contract_interface_test/Nep17Interface.py b/boa3_test/test_sc/contract_interface_test/Nep17Interface.py index d6c1d58de..8dec73734 100644 --- a/boa3_test/test_sc/contract_interface_test/Nep17Interface.py +++ b/boa3_test/test_sc/contract_interface_test/Nep17Interface.py @@ -4,7 +4,7 @@ from boa3.builtin.type import UInt160 -@contract('0x409eb4868a2c43611b9c0f9df98de3846ada4fcb') +@contract('0x2b061955be33023e641bbd495c6887f6c0ba867f') class Nep17: @staticmethod diff --git a/boa3_test/test_sc/contract_interface_test/Nep17InterfaceWithDisplayName.py b/boa3_test/test_sc/contract_interface_test/Nep17InterfaceWithDisplayName.py index d6c1d58de..8dec73734 100644 --- a/boa3_test/test_sc/contract_interface_test/Nep17InterfaceWithDisplayName.py +++ b/boa3_test/test_sc/contract_interface_test/Nep17InterfaceWithDisplayName.py @@ -4,7 +4,7 @@ from boa3.builtin.type import UInt160 -@contract('0x409eb4868a2c43611b9c0f9df98de3846ada4fcb') +@contract('0x2b061955be33023e641bbd495c6887f6c0ba867f') class Nep17: @staticmethod diff --git a/boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py b/boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py index cd496243d..b7c2c2495 100644 --- a/boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py +++ b/boa3_test/test_sc/metadata_test/aux_package/internal_package/__init__.py @@ -1,6 +1,6 @@ -from boa3.builtin.compile_time import CreateNewEvent - from typing import Union + +from boa3.builtin.compile_time import CreateNewEvent from boa3.builtin.type import UInt160 on_transfer = CreateNewEvent( diff --git a/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py b/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py index 9fd5aa1f0..0c4460d3e 100644 --- a/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py +++ b/boa3_test/tests/compiler_tests/test_native/test_cryptolib.py @@ -211,52 +211,12 @@ def test_verify_with_ecdsa_secp256r1_str(self): self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_bool(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256R1).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHF - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256r1Bool.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_int(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256R1).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSH10 - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256r1Int.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256r1_bytes(self): byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' @@ -294,52 +254,12 @@ def test_verify_with_ecdsa_secp256k1_str(self): self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_bool(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256K1).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSHF - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256k1Bool.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_int(self): - byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW' - byte_input2 = b'signature' - named_curve = Integer(NamedCurve.SECP256K1).to_byte_array(signed=True, min_length=1) - - expected_output = ( - Opcode.PUSHINT8 + named_curve - + Opcode.PUSHDATA1 - + Integer(len(byte_input2)).to_byte_array(min_length=1) - + byte_input2 - + Opcode.PUSHDATA1 - + Integer(len(byte_input1)).to_byte_array(min_length=1) - + byte_input1 - + self.ecpoint_init - + Opcode.PUSH10 - + Opcode.CALLT + b'\x00\x00' - + Opcode.DROP - + Opcode.RET - ) - path = self.get_contract_path('VerifyWithECDsaSecp256k1Int.py') - output = self.compile(path) - self.assertEqual(expected_output, output) + self.assertCompilerLogs(CompilerError.MismatchedTypes, path) def test_verify_with_ecdsa_secp256k1_bytes(self): byte_input1 = b'0123456789ABCDEFGHIJKLMNOPQRSTUVW'