示例#1
0
    def __init__(self):
        from boa3.model.type.collection.sequence.uint160type import UInt160Type
        from boa3.model.builtin.interop.contract.callflagstype import CallFlagsType
        from boa3.model.type.type import Type
        identifier = 'call_contract'
        syscall = 'System.Contract.Call'

        call_flags = CallFlagsType.build()
        args: Dict[str, Variable] = {
            'script_hash': Variable(UInt160Type.build()),
            'method': Variable(Type.str),
            'args':
            Variable(Type.sequence),  # TODO: change when *args is implemented
            'call_flags': Variable(call_flags)
        }
        args_default = ast.parse("{0}".format(
            Type.sequence.default_value)).body[0].value
        call_flags_default = set_internal_call(
            ast.parse(
                "{0}.{1}".format(call_flags.identifier,
                                 call_flags.default_value.name)).body[0].value)

        super().__init__(identifier,
                         syscall,
                         args,
                         defaults=[args_default, call_flags_default],
                         return_type=Type.any)
示例#2
0
    def __init__(self):
        type_uint160 = UInt160Type.build()

        methods = [
            StandardMethod('symbol', safe=True, args={}, return_type=Type.str),
            StandardMethod('decimals',
                           safe=True,
                           args={},
                           return_type=Type.int),
            StandardMethod('totalSupply',
                           safe=True,
                           args={},
                           return_type=Type.int),
            StandardMethod('balanceOf',
                           safe=True,
                           args={'account': type_uint160},
                           return_type=Type.int),
            StandardMethod('transfer',
                           args={
                               'from': type_uint160,
                               'to': type_uint160,
                               'amount': Type.int,
                               'data': Type.any
                           },
                           return_type=Type.bool)
        ]
        events = [Builtin.Nep17Transfer]

        super().__init__(methods, events)
示例#3
0
 def __init__(self):
     from boa3.model.type.type import Type
     from boa3.model.type.collection.sequence.uint160type import UInt160Type
     identifier = 'Nep11TransferEvent'
     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()),
     }
     super().__init__(identifier, args)
     self.name = 'Transfer'
 def __init__(self):
     from boa3.model.type.collection.sequence.uint160type import UInt160Type
     identifier = '-get_calling_script_hash'
     syscall = 'System.Runtime.GetCallingScriptHash'
     args: Dict[str, Variable] = {}
     super().__init__(identifier,
                      syscall,
                      args,
                      return_type=UInt160Type.build())
示例#5
0
    def __init__(self):
        super().__init__('Notification')

        from boa3.model.type.type import Type
        self._variables: Dict[str, Variable] = {
            'script_hash': Variable(UInt160Type.build()),
            'event_name': Variable(Type.str),
            'state': Variable(Type.tuple)
        }
        self._constructor: Method = None
    def __init__(self):
        from boa3.model.type.collection.sequence.uint160type import UInt160Type
        from boa3.model.type.collection.sequence.ecpointtype import ECPointType

        identifier = 'create_standard_account'
        syscall = 'System.Contract.CreateStandardAccount'
        args: Dict[str, Variable] = {
            'pub_key': Variable(ECPointType.build())
        }
        super().__init__(identifier, syscall, args, return_type=UInt160Type.build())
    def __init__(self, neo_account_state: NeoAccountStateType):
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        identifier = 'get_account_state'
        native_identifier = 'getAccountState'
        args: Dict[str, Variable] = {'account': Variable(UInt160Type.build())}
        super().__init__(identifier,
                         native_identifier,
                         args,
                         return_type=neo_account_state)
示例#8
0
    def __init__(self):
        super().__init__('ContractPermissionDescriptor')
        from boa3.model.type.collection.sequence.uint160type import UInt160Type
        from boa3.model.type.collection.sequence.ecpointtype import ECPointType
        from boa3.model.type.type import Type

        self._variables: Dict[str, Variable] = {
            'hash': Variable(Type.optional.build(UInt160Type.build())),
            'group': Variable(Type.optional.build(ECPointType.build()))
        }
        self._constructor: Method = None
示例#9
0
    def __init__(self):
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        identifier = 'is_blocked'
        native_identifier = 'isBlocked'
        args: Dict[str, Variable] = {'account': Variable(UInt160Type.build())}
        super().__init__(identifier,
                         native_identifier,
                         args,
                         return_type=Type.bool)
示例#10
0
    def __init__(self, contract_script_hash: bytes):
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        identifier = 'balanceOf'
        native_identifier = 'balanceOf'
        args: Dict[str, Variable] = {'account': Variable(UInt160Type.build())}
        super().__init__(identifier,
                         native_identifier,
                         args,
                         return_type=Type.int,
                         script_hash=contract_script_hash)
    def __init__(self):
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        identifier = 'check_witness'
        syscall = 'System.Runtime.CheckWitness'
        args: Dict[str, Variable] = {
            'hash_or_pubkey':
            Variable(Type.union.build([Type.bytes,
                                       UInt160Type.build()]))
        }
        super().__init__(identifier, syscall, args, return_type=Type.bool)
示例#12
0
    def __init__(self):
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.ecpointtype import ECPointType
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        identifier = 'vote'
        native_identifier = 'vote'
        args: Dict[str, Variable] = {
            'account': Variable(UInt160Type.build()),
            'vote_to': Variable(ECPointType.build())
        }
        super().__init__(identifier, native_identifier, args, return_type=Type.bool)
示例#13
0
    def __init__(self):
        type_uint160 = UInt160Type.build()
        type_iterator = IteratorType.build()
        type_bytestring = ByteStringType.build()

        methods = [
            StandardMethod('symbol', safe=True, args={}, return_type=Type.str),
            StandardMethod('decimals',
                           safe=True,
                           args={},
                           return_type=Type.int),
            StandardMethod('totalSupply',
                           safe=True,
                           args={},
                           return_type=Type.int),
            StandardMethod('balanceOf',
                           safe=True,
                           args={'owner': type_uint160},
                           return_type=Type.int),
            StandardMethod('tokensOf',
                           safe=True,
                           args={'owner': type_uint160},
                           return_type=type_iterator),
            StandardMethod('transfer',
                           args={
                               'to': type_uint160,
                               'tokenId': type_bytestring,
                               'data': Type.any
                           },
                           return_type=Type.bool),
            StandardMethod('ownerOf',
                           safe=True,
                           args={'tokenId': type_bytestring},
                           return_type=type_uint160),
        ]

        optionals = [
            StandardMethod('tokens',
                           safe=True,
                           args={},
                           return_type=type_iterator),
            StandardMethod('properties',
                           safe=True,
                           args={
                               'tokenId': type_bytestring,
                           },
                           return_type=Type.dict),
        ]

        events = [Builtin.Nep11Transfer]

        super().__init__(methods, events, optionals)
示例#14
0
    def __init__(self):
        super().__init__('Contract')
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        self._variables: Dict[str, Variable] = {
            'id': Variable(Type.int),
            'update_counter': Variable(Type.int),
            'hash': Variable(UInt160Type.build()),
            'nef': Variable(Type.bytes),
            'manifest': Variable(Type.dict)
        }
        self._constructor: Method = None
示例#15
0
    def __init__(self, contract_script_hash: bytes):
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        identifier = 'transfer'
        native_identifier = 'transfer'
        args: Dict[str, Variable] = {
            'from_address': Variable(UInt160Type.build()),
            'to_address': Variable(UInt160Type.build()),
            'amount': Variable(Type.int),
            'data': Variable(Type.any),
        }

        data_default = ast.parse("{0}".format(
            Type.any.default_value)).body[0].value

        super().__init__(identifier,
                         native_identifier,
                         args,
                         defaults=[data_default],
                         return_type=Type.bool,
                         script_hash=contract_script_hash)
示例#16
0
    def __init__(self):
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type

        identifier = 'unclaimed_gas'
        native_identifier = 'unclaimedGas'
        args: Dict[str, Variable] = {
            'account': Variable(UInt160Type.build()),
            'end': Variable(Type.int)
        }
        super().__init__(identifier,
                         native_identifier,
                         args,
                         return_type=Type.int)
示例#17
0
    def __init__(self):
        from boa3.model.type.collection.sequence.uint160type import UInt160Type
        from boa3.model.type.collection.sequence.ecpointtype import ECPointType
        from boa3.model.type.type import Type

        identifier = 'create_multisig_account'
        syscall = 'System.Contract.CreateMultisigAccount'
        args: Dict[str, Variable] = {
            'm': Variable(Type.int),
            'pub_keys':
            Variable(Type.list.build_collection([ECPointType.build()]))
        }
        super().__init__(identifier,
                         syscall,
                         args,
                         return_type=UInt160Type.build())
示例#18
0
    def __init__(self, notification_type: NotificationType):
        from boa3.model.type.collection.sequence.uint160type import UInt160Type
        from boa3.model.type.type import Type

        identifier = 'get_notifications'
        syscall = 'System.Runtime.GetNotifications'
        uint160 = UInt160Type.build()

        args: Dict[str, Variable] = {'script_hash': Variable(uint160)}
        args_default = set_internal_call(
            ast.parse("{0}()".format(uint160.raw_identifier)).body[0].value)

        super().__init__(identifier,
                         syscall,
                         args, [args_default],
                         return_type=Type.list.build([notification_type]))
示例#19
0
    def __init__(self):
        super().__init__('Transaction')
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type
        from boa3.model.type.collection.sequence.uint256type import UInt256Type

        self._variables: Dict[str, Variable] = {
            'hash': Variable(UInt256Type.build()),
            'version': Variable(Type.int),
            'nonce': Variable(Type.int),
            'sender': Variable(UInt160Type.build()),
            'system_fee': Variable(Type.int),
            'network_fee': Variable(Type.int),
            'valid_until_block': Variable(Type.int),
            'script': Variable(Type.bytes),
        }
        self._constructor: Method = None
示例#20
0
 def __init__(self):
     from boa3.model.type.collection.sequence.uint160type import UInt160Type
     from boa3.model.type.type import Type
     identifier = 'call_contract'
     syscall = 'System.Contract.Call'
     args: Dict[str, Variable] = {
         'script_hash': Variable(UInt160Type.build()),
         'method': Variable(Type.str),
         'args':
         Variable(Type.sequence)  # TODO: change when *args is implemented
     }
     args_default = ast.parse("{0}".format(
         Type.sequence.default_value)).body[0].value
     super().__init__(identifier,
                      syscall,
                      args,
                      defaults=[args_default],
                      return_type=Type.any)
示例#21
0
    def __init__(self):
        super().__init__('Block')
        from boa3.model.type.type import Type
        from boa3.model.type.collection.sequence.uint160type import UInt160Type
        from boa3.model.type.collection.sequence.uint256type import UInt256Type

        uint256 = UInt256Type.build()

        self._variables: Dict[str, Variable] = {
            'hash': Variable(uint256),
            'version': Variable(Type.int),
            'previous_hash': Variable(uint256),
            'merkle_root': Variable(uint256),
            'timestamp': Variable(Type.int),
            'index': Variable(Type.int),
            'primary_index': Variable(Type.int),
            'next_consensus': Variable(UInt160Type.build()),
            'transaction_count': Variable(Type.int)
        }
        self._constructor: Method = None
 def __init__(self, script_hash: bytes):
     from boa3.model.type.collection.sequence.uint160type import UInt160Type
     identifier = '-get_nep17_contract'
     self.script_hash = script_hash
     args: Dict[str, Variable] = {}
     super().__init__(identifier, args, return_type=UInt160Type.build())
示例#23
0
 def __init__(self):
     from boa3.model.type.collection.sequence.uint160type import UInt160Type
     identifier = '-get_ledger_contract'
     args: Dict[str, Variable] = {}
     super().__init__(identifier, args, return_type=UInt160Type.build())
示例#24
0
 def __init__(self, contract_type: ContractType):
     from boa3.model.type.collection.sequence.uint160type import UInt160Type
     identifier = 'get_contract'
     syscall = 'getContract'
     args: Dict[str, Variable] = {'hash': Variable(UInt160Type.build())}
     super().__init__(identifier, syscall, args, return_type=contract_type)
示例#25
0
class Builtin:
    @classmethod
    def get_symbol(cls, symbol_id: str) -> Optional[Callable]:
        for name, method in vars(cls).items():
            if isinstance(method,
                          IBuiltinCallable) and method.identifier == symbol_id:
                return method

    @classmethod
    def get_any_symbol(cls, symbol_id: str) -> Optional[ISymbol]:
        for name, method in vars(cls).items():
            if isinstance(method,
                          IdentifiedSymbol) and method.identifier == symbol_id:
                return method

    @classmethod
    def get_by_self(cls, symbol_id: str,
                    self_type: IType) -> Optional[Callable]:
        for name, method in vars(cls).items():
            if (isinstance(method, IBuiltinMethod)
                    and method.identifier == symbol_id
                    and method.validate_self(self_type)):
                return method

    # builtin method
    Abs = AbsMethod()
    Exit = ExitMethod()
    IsInstance = IsInstanceMethod()
    Len = LenMethod()
    NewEvent = CreateEventMethod()
    Max = MaxMethod()
    Min = MinMethod()
    Print = PrintMethod()
    ScriptHash = ScriptHashMethod()
    Sqrt = SqrtMethod()
    Sum = SumMethod()

    # python builtin class constructor
    ByteArray = ByteArrayMethod()
    Range = RangeMethod()
    Exception = ExceptionMethod()

    # python class method
    SequenceAppend = AppendMethod()
    SequenceClear = ClearMethod()
    SequenceExtend = ExtendMethod()
    SequenceInsert = InsertMethod()
    SequencePop = PopMethod()
    SequenceRemove = RemoveMethod()
    SequenceReverse = ReverseMethod()
    DictKeys = MapKeysMethod()
    DictValues = MapValuesMethod()

    # custom class methods
    ConvertToBytes = ToBytesMethod
    ConvertToInt = ToIntMethod
    ConvertToStr = ToStrMethod
    ConvertToBool = ToBoolMethod

    _python_builtins: List[IdentifiedSymbol] = [
        Abs, ByteArray, ConvertToBool, ConvertToBytes, ConvertToInt,
        ConvertToStr, DictKeys, DictValues, Exit, IsInstance, Len, Max, Min,
        Print, ScriptHash, SequenceAppend, SequenceClear, SequenceExtend,
        SequenceInsert, SequencePop, SequenceRemove, SequenceReverse, Sqrt, Sum
    ]

    @classmethod
    def interop_symbols(cls,
                        package: str = None) -> Dict[str, IdentifiedSymbol]:
        return {
            symbol.raw_identifier
            if hasattr(symbol, 'raw_identifier') else symbol.identifier: symbol
            for symbol in Interop.interop_symbols(package)
        }

    # builtin decorator
    Metadata = MetadataDecorator()
    Public = PublicDecorator()

    # boa builtin type
    Event = EventType
    UInt160 = UInt160Type.build()
    UInt256 = UInt256Type.build()

    # boa events
    Nep5Transfer = Nep5TransferEvent()
    Nep17Transfer = Nep17TransferEvent()

    # boa smart contract methods
    Abort = AbortMethod()

    _boa_builtins: List[IdentifiedSymbol] = [
        Public, NewEvent, Event, Metadata, NeoMetadataType, ScriptHash
    ]

    metadata_fields: Dict[str, Union[type, Tuple[type]]] = {
        'author': (str, type(None)),
        'email': (str, type(None)),
        'description': (str, type(None)),
        'extras': dict
    }

    @classmethod
    def boa_symbols(cls) -> Dict[str, IdentifiedSymbol]:
        return {symbol.identifier: symbol for symbol in cls._boa_builtins}

    @classmethod
    def package_symbols(cls,
                        package: str = None) -> Dict[str, IdentifiedSymbol]:
        if package in BoaPackage.__members__.values():
            return {
                symbol.identifier: symbol
                for symbol in cls._boa_symbols[package]
            }

        return cls.boa_symbols()

    _boa_symbols: Dict[BoaPackage, List[IdentifiedSymbol]] = {
        BoaPackage.Contract: [
            Abort,
            Nep17Transfer,
            Nep5Transfer,
        ],
        BoaPackage.Interop: Interop.package_symbols,
        BoaPackage.Type: [UInt160, UInt256]
    }
示例#26
0
class Builtin:
    @classmethod
    def get_symbol(cls, symbol_id: str) -> Optional[Callable]:
        for method in cls._python_builtins:
            if isinstance(method,
                          IBuiltinCallable) and method.identifier == symbol_id:
                return method

    @classmethod
    def get_by_self(cls, symbol_id: str,
                    self_type: IType) -> Optional[Callable]:
        for name, method in vars(cls).items():
            if (isinstance(method, IBuiltinMethod)
                    and method.identifier == symbol_id
                    and method.validate_self(self_type)):
                return method

    # builtin method
    Abs = AbsMethod()
    Exit = ExitMethod()
    IsInstance = IsInstanceMethod()
    Len = LenMethod()
    NewEvent = CreateEventMethod()
    Max = MaxIntMethod()
    Min = MinIntMethod()
    Print = PrintMethod()
    ScriptHash = ScriptHashMethod()
    StrSplit = StrSplitMethod()
    Sum = SumMethod()

    # python builtin class constructor
    Bool = BoolMethod()
    ByteArray = ByteArrayMethod()
    Exception = ExceptionMethod()
    IntByteString = IntByteStringMethod()
    IntInt = IntIntMethod()
    Range = RangeMethod()
    Reversed = ReversedMethod()
    Super = SuperMethod()

    # python class method
    BytesStringIsDigit = IsDigitMethod()
    BytesStringJoin = JoinMethod()
    BytesStringLower = LowerMethod()
    BytesStringStartswith = StartsWithMethod()
    BytesStringStrip = StripMethod()
    BytesStringUpper = UpperMethod()
    CountSequence = CountSequenceMethod()
    CountStr = CountStrMethod()
    Copy = CopyListMethod()
    SequenceAppend = AppendMethod()
    SequenceClear = ClearMethod()
    SequenceExtend = ExtendMethod()
    SequenceIndex = IndexSequenceMethod()
    SequenceInsert = InsertMethod()
    SequencePop = PopSequenceMethod()
    SequenceRemove = RemoveMethod()
    SequenceReverse = ReverseMethod()
    StrIndex = IndexStrMethod()
    DictKeys = MapKeysMethod()
    DictPop = PopDictMethod()
    DictValues = MapValuesMethod()

    # custom class methods
    ConvertToBytes = ToBytesMethod
    ConvertToInt = ToIntMethod
    ConvertToStr = ToStrMethod
    ConvertToBool = ToBoolMethod

    # builtin decorator
    ClassMethodDecorator = ClassMethodDecorator()
    InstanceMethodDecorator = InstanceMethodDecorator()
    PropertyDecorator = PropertyDecorator()
    StaticMethodDecorator = StaticMethodDecorator()

    _python_builtins: List[IdentifiedSymbol] = [
        Abs,
        ByteArray,
        BytesStringIsDigit,
        BytesStringJoin,
        BytesStringLower,
        BytesStringStartswith,
        BytesStringStrip,
        BytesStringUpper,
        ClassMethodDecorator,
        ConvertToBool,
        ConvertToBytes,
        ConvertToInt,
        ConvertToStr,
        Copy,
        CountSequence,
        CountStr,
        DictKeys,
        DictValues,
        Exception,
        Exit,
        IsInstance,
        Len,
        Max,
        Min,
        Print,
        PropertyDecorator,
        Range,
        Reversed,
        ScriptHash,
        SequenceAppend,
        SequenceClear,
        SequenceExtend,
        SequenceIndex,
        SequenceInsert,
        SequencePop,
        SequenceRemove,
        SequenceReverse,
        StaticMethodDecorator,
        StrIndex,
        StrSplit,
        Sum,
        Super,
    ]

    @classmethod
    def interop_symbols(cls,
                        package: str = None) -> Dict[str, IdentifiedSymbol]:
        return {
            symbol.raw_identifier
            if hasattr(symbol, 'raw_identifier') else symbol.identifier: symbol
            for symbol in Interop.interop_symbols(package)
        }

    # boa builtin decorator
    ContractInterface = ContractDecorator()
    ContractMethodDisplayName = DisplayNameDecorator()
    Metadata = MetadataDecorator()
    Public = PublicDecorator()

    # boa builtin type
    ByteString = ByteStringType.build()
    Event = EventType
    UInt160 = UInt160Type.build()
    UInt256 = UInt256Type.build()
    ECPoint = ECPointType.build()
    NeoAccountState = NeoAccountStateType.build()

    # boa events
    Nep5Transfer = Nep5TransferEvent()
    Nep11Transfer = Nep11TransferEvent()
    Nep17Transfer = Nep17TransferEvent()

    # boa smart contract methods
    Abort = AbortMethod()

    # region boa builtin modules

    BuiltinMathCeil = DecimalCeilingMethod()
    BuiltinMathFloor = DecimalFloorMethod()

    MathModule = Package(
        identifier='math',
        methods=[Math.Sqrt, BuiltinMathCeil, BuiltinMathFloor])

    _modules = [MathModule]

    # endregion

    boa_builtins: List[IdentifiedSymbol] = [
        ContractInterface, ContractMethodDisplayName, Event, Metadata,
        NeoMetadataType, NewEvent, Public, ScriptHash
    ] + _modules

    metadata_fields: Dict[str, Union[type, Tuple[type]]] = {
        'name': str,
        'supported_standards': list,
        'trusts': list,
        'author': (str, type(None)),
        'email': (str, type(None)),
        'description': (str, type(None)),
        'extras': dict
    }

    @classmethod
    def boa_symbols(cls) -> Dict[str, IdentifiedSymbol]:
        return {symbol.identifier: symbol for symbol in cls.boa_builtins}

    @classmethod
    def package_symbols(cls,
                        package: str = None) -> Dict[str, IdentifiedSymbol]:
        if package in BoaPackage.__members__.values():
            return {
                symbol.identifier: symbol
                for symbol in cls._boa_symbols[package]
            }

        return cls.boa_symbols()

    _boa_symbols: Dict[BoaPackage, List[IdentifiedSymbol]] = {
        BoaPackage.Contract: [
            Abort,
            NeoAccountState,
            Nep11Transfer,
            Nep17Transfer,
            Nep5Transfer,
        ],
        BoaPackage.Interop:
        Interop.package_symbols,
        BoaPackage.Type: [ByteString, ECPoint, UInt160, UInt256]
    }

    _internal_methods = [InnerDeployMethod.instance()]
    internal_methods = {
        method.raw_identifier: method
        for method in _internal_methods
    }