Example #1
0
 def normalize_property(cls, key, val):
     if key == 'abi':
         if isinstance(val, str):
             val = json.loads(val)
         validate_abi(val)
         return val
     elif key == 'address':
         validate_address(val)
         return to_normalized_address(val)
     else:
         return val
Example #2
0
 def normalize_property(cls, key, val):
     if key == 'abi':
         if isinstance(val, str):
             val = json.loads(val)
         validate_abi(val)
         return val
     elif key == 'address':
         validate_address(val)
         return to_normalized_address(val)
     elif key in {
             'bytecode_runtime',
             'bytecode',
     }:
         return HexBytes(val)
     else:
         return val
Example #3
0
 def normalize_property(cls, key, val):
     if key == 'abi':
         if isinstance(val, str):
             val = json.loads(val)
         validate_abi(val)
         return val
     elif key == 'address':
         if is_ens_name(val):
             validate_name_has_address(cls.web3.ens, val)
             return val
         else:
             validate_address(val)
             return to_checksum_address(val)
     elif key in {
         'bytecode_runtime',
         'bytecode',
     }:
         return HexBytes(val)
     else:
         return val
Example #4
0
 def normalize_property(cls, key, val):
     if key == 'abi':
         if isinstance(val, str):
             val = json.loads(val)
         validate_abi(val)
         return val
     elif key == 'address':
         if is_ens_name(val):
             validate_name_has_address(cls.web3.ens, val)
             return val
         else:
             validate_address(val)
             return to_checksum_address(val)
     elif key in {
         'bytecode_runtime',
         'bytecode',
     }:
         return HexBytes(val)
     else:
         return val
Example #5
0
    def __init__(self, *args, **kwargs):
        """Create a new smart contract proxy object.

        :param address: Contract address as 0x hex string
        """
        code = kwargs.pop('code', empty)
        code_runtime = kwargs.pop('code_runtime', empty)
        source = kwargs.pop('source', empty)
        abi = kwargs.pop('abi', empty)
        address = kwargs.pop('address', empty)

        if self.web3 is None:
            raise AttributeError(
                'The `Contract` class has not been initialized.  Please use the '
                '`web3.contract` interface to create your contract class.')

        arg_0, arg_1, arg_2, arg_3, arg_4 = tuple(
            itertools.chain(
                args,
                itertools.repeat(empty, 5),
            ))[:5]

        if is_list_like(arg_0):
            if abi:
                raise TypeError("The 'abi' argument was found twice")
            abi = arg_0
        elif is_address(arg_0):
            if address:
                raise TypeError("The 'address' argument was found twice")
            address = arg_0

        if arg_1 is not empty:
            if address:
                raise TypeError("The 'address' argument was found twice")
            address = arg_1

        if arg_2 is not empty:
            if code:
                raise TypeError("The 'code' argument was found twice")
            code = arg_2

        if arg_3 is not empty:
            if code_runtime:
                raise TypeError("The 'code_runtime' argument was found twice")
            code_runtime = arg_3

        if arg_4 is not empty:
            if source:
                raise TypeError("The 'source' argument was found twice")
            source = arg_4

        if any((abi, code, code_runtime, source)):
            warnings.warn(
                DeprecationWarning(
                    "The arguments abi, code, code_runtime, and source have been "
                    "deprecated and will be removed from the Contract class "
                    "constructor in future releases.  Update your code to use the "
                    "Contract.factory method."))

        if abi is not empty:
            validate_abi(abi)
            self.abi = abi
        if code is not empty:
            self.bytecode = code
        if code_runtime is not empty:
            self.bytecode_runtime = code_runtime
        if source is not empty:
            self._source = source

        if address is not empty:
            validate_address(address)
            self.address = to_normalized_address(address)
        else:
            warnings.warn(
                DeprecationWarning(
                    "The address argument is now required for contract class "
                    "instantiation.  Please update your code to reflect this change"
                ))
Example #6
0
    def __init__(self, keyfile='', password='', private_key='', provider='', provider_endpoint_uri='',
                 contract_address='', contract_abi={}, gas_price=None, gas_limit=None):
        """Create a new instance of the Token SDK.

        The SDK needs a JSON-RPC provider, contract definitions and (optionally) a wallet private key.

        The user may pass either a provider or a provider endpoint URI, in which case a default
        :class:`web3:providers:HTTPProvider` will be created. If neither private_key nor keyfile+password
        are provided, the SDK can still be used in "anonymous" mode, with only the following functions available:
            - get_address_ether_balance
            - get_transaction_status
            - get_transaction_data
            - monitor_ether_transactions

        :param str private_key: a private key to initialize the wallet with. If either private key or keyfile
            are not provided, the wallet will not be initialized and methods needing the wallet will raise exception.

        :param str keyfile: the path to the keyfile to initialize the wallet with. You will also need to supply
            a password for this keyfile.

        :param str password: a password for the keyfile.

        :param provider: JSON-RPC provider to work with. If not given, a default `web3:providers:HTTPProvider`
            is used, inited with provider_endpoint_uri.
        :type provider: :class:`web3:providers:BaseProvider`

        :param str provider_endpoint_uri: a URI to use with a default HTTPProvider.

        :param str contract_address: the address of the token contract.

        :param list contract_abi: The contract ABI json.

        :param number gas_price: The price of gas in Gwei.

        :param number gas_limit: Transaction gas limit.

        :returns: An instance of the SDK.
        :rtype: :class:`~erc20tokensdk.SDK`

        :raises: :class:`~erc20tokensdk.exceptions.SdkConfigurationError` if some of the configuration
            parameters are invalid.
        """

        if not provider and not provider_endpoint_uri:
            raise SdkConfigurationError('either provider or provider endpoint must be provided')

        try:
            validate_address(contract_address)
        except ValueError as ve:
            raise SdkConfigurationError('invalid token contract address: ' + str(ve))

        try:
            validate_abi(contract_abi)
        except Exception as e:
            raise SdkConfigurationError('invalid token contract abi: ' + str(e))

        if gas_price and not (isinstance(gas_price, int) or isinstance(gas_price, float)):
            raise SdkConfigurationError('gas price must be either integer of float')

        if gas_limit and not isinstance(gas_limit, int):
            raise SdkConfigurationError('gas limit must be integer')

        if provider:
            self.web3 = Web3(provider)
        else:
            self.web3 = Web3(RetryHTTPProvider(provider_endpoint_uri))
        if not self.web3.isConnected():
            raise SdkConfigurationError('cannot connect to provider endpoint')

        self.token_contract = self.web3.eth.contract(contract_address, abi=contract_abi)
        self.private_key = None
        self.address = None

        if keyfile:
            try:
                self.private_key = load_keyfile(keyfile, password)
            except Exception as e:
                raise SdkConfigurationError('cannot load keyfile: ' + str(e))
        elif private_key:
            self.private_key = private_key

        if self.private_key:
            try:
                private_key_bytes = hexstr_if_str(to_bytes, self.private_key)
                pk = keys.PrivateKey(private_key_bytes)
                self.address = self.web3.eth.defaultAccount = pk.public_key.to_checksum_address()
            except ValidationError as e:
                raise SdkConfigurationError('cannot load private key: ' + str(e))

            # init transaction manager
            self._tx_manager = TransactionManager(self.web3, self.private_key, self.address, self.token_contract,
                                                  gas_price, gas_limit)

        # monitoring filter manager
        self._filter_mgr = FilterManager(self.web3)
Example #7
0
def normalize_abi(abi):
    if isinstance(abi, str):
        abi = json.loads(abi)
    validate_abi(abi)
    return abi
def main(provider_endpoint_uri, private_key):
    contract_address = '0xB7E7AeD7a722ccb62cBE1C87b950D5792512589d'
    contract_abi = json.loads(
        '[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"tokens","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"from","type":"address"},{"name":"to","type":"address"},{"name":"tokens","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"_totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"tokenOwner","type":"address"}],"name":"balanceOf","outputs":[{"name":"balance","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"acceptOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"}],"name":"safeSub","outputs":[{"name":"c","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"to","type":"address"},{"name":"tokens","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"}],"name":"safeDiv","outputs":[{"name":"c","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"spender","type":"address"},{"name":"tokens","type":"uint256"},{"name":"data","type":"bytes"}],"name":"approveAndCall","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"}],"name":"safeMul","outputs":[{"name":"c","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":true,"inputs":[],"name":"newOwner","outputs":[{"name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"tokenAddress","type":"address"},{"name":"tokens","type":"uint256"}],"name":"transferAnyERC20Token","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"tokenOwner","type":"address"},{"name":"spender","type":"address"}],"name":"allowance","outputs":[{"name":"remaining","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"a","type":"uint256"},{"name":"b","type":"uint256"}],"name":"safeAdd","outputs":[{"name":"c","type":"uint256"}],"payable":false,"stateMutability":"pure","type":"function"},{"constant":false,"inputs":[{"name":"_newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"payable":true,"stateMutability":"payable","type":"fallback"},{"anonymous":false,"inputs":[{"indexed":true,"name":"_from","type":"address"},{"indexed":true,"name":"_to","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"tokens","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"tokenOwner","type":"address"},{"indexed":true,"name":"spender","type":"address"},{"indexed":false,"name":"tokens","type":"uint256"}],"name":"Approval","type":"event"}]'
    )
    # MIST Account
    to_address = '0x1441cF38f688C15Fb07741E390948CbA3C7B2590'
    to_amount = 1

    web3 = Web3(Web3.HTTPProvider(provider_endpoint_uri))

    # make sure connection is established
    isConnected = web3.isConnected()
    print('isConnected:{}'.format(isConnected))

    # validate contract address and abi
    print('validate_address:{}'.format(validate_address(contract_address)))
    print('validate_abi:{}'.format(validate_abi(contract_abi)))

    # init contract instance
    token_contract = web3.eth.contract(contract_address, abi=contract_abi)

    private_key_bytes = hexstr_if_str(to_bytes, private_key)
    print('private_key_bytes:{}'.format(private_key_bytes))
    pk = keys.PrivateKey(private_key_bytes)
    print('pk:{}'.format(pk))

    # get default account address
    address = web3.eth.defaultAccount = pk.public_key.to_checksum_address()
    print('address:{}'.format(address))

    # get Ether balance of the wallet
    balance = web3.fromWei(web3.eth.getBalance(address), 'ether')
    print('Ether balance:{}'.format(balance))

    # get JMToken balance of the wallet
    balance = web3.fromWei(token_contract.call().balanceOf(address), 'ether')
    print('JMToken balance:{}'.format(balance))

    # In order to transact with Infura nodes, you will need to create and sign
    # transactions offline before sending them, as Infura nodes have no visibility
    # of your encrypted Ethereum key files, which are required to unlock accounts
    # via the Personal Geth/Parity admin commands.

    nonce = web3.eth.getTransactionCount(address, 'pending')
    print('nonce:{}'.format(nonce))

    jmt_tx = token_contract.functions.transfer(
        to_address, to_amount).buildTransaction({
            # testnet
            'chainId': 3,
            # gas limit
            'gas': 100000,
            # gas price in Gwei = 10^-9 Eth
            'gasPrice': web3.eth.gasPrice,
            'nonce': nonce,
        })
    print('jmt_tx:{}'.format(jmt_tx))

    signed_txn = web3.eth.account.signTransaction(jmt_tx, private_key_bytes)
    print('signed_txn:{}'.format(signed_txn))

    tx_id = web3.toHex(web3.eth.sendRawTransaction(signed_txn.rawTransaction))
    print('tx_id:{}'.format(tx_id))
Example #9
0
    def __init__(self, keyfile='', password='', private_key='', provider='', provider_endpoint_uri='',
                 contract_address='', contract_abi={}, gas_price=None, gas_limit=None):
        """Create a new instance of the Token SDK.

        The SDK needs a JSON-RPC provider, contract definitions and (optionally) a wallet private key.

        The user may pass either a provider or a provider endpoint URI, in which case a default
        :class:`web3:providers:HTTPProvider` will be created. If neither private_key nor keyfile+password
        are provided, the SDK can still be used in "anonymous" mode, with only the following functions available:
            - get_address_ether_balance
            - get_transaction_status
            - get_transaction_data
            - monitor_ether_transactions

        :param str private_key: a private key to initialize the wallet with. If either private key or keyfile
            are not provided, the wallet will not be initialized and methods needing the wallet will raise exception.

        :param str keyfile: the path to the keyfile to initialize the wallet with. You will also need to supply
            a password for this keyfile.

        :param str password: a password for the keyfile.

        :param provider: JSON-RPC provider to work with. If not given, a default `web3:providers:HTTPProvider`
            is used, inited with provider_endpoint_uri.
        :type provider: :class:`web3:providers:BaseProvider`

        :param str provider_endpoint_uri: a URI to use with a default HTTPProvider.

        :param str contract_address: the address of the token contract.

        :param list contract_abi: The contract ABI json.

        :param number gas_price: The price of gas in Gwei.

        :param number gas_limit: Transaction gas limit.

        :returns: An instance of the SDK.
        :rtype: :class:`~erc20token.SDK`

        :raises: :class:`~erc20token.exceptions.SdkConfigurationError` if some of the configuration
            parameters are invalid.
        """

        if not provider and not provider_endpoint_uri:
            raise SdkConfigurationError('either provider or provider endpoint must be provided')

        try:
            validate_address(contract_address)
        except ValueError as ve:
            raise SdkConfigurationError('invalid token contract address: ' + str(ve))

        try:
            validate_abi(contract_abi)
        except Exception as e:
            raise SdkConfigurationError('invalid token contract abi: ' + str(e))

        if gas_price and not (isinstance(gas_price, int) or isinstance(gas_price, float)):
            raise SdkConfigurationError('gas price must be either integer of float')

        if gas_limit and not isinstance(gas_limit, int):
            raise SdkConfigurationError('gas limit must be integer')

        if provider:
            self.web3 = Web3(provider)
        else:
            self.web3 = Web3(RetryHTTPProvider(provider_endpoint_uri))
        if not self.web3.isConnected():
            raise SdkConfigurationError('cannot connect to provider endpoint')

        self.token_contract = self.web3.eth.contract(contract_address, abi=contract_abi)
        self.private_key = None
        self.address = None

        if keyfile:
            try:
                self.private_key = load_keyfile(keyfile, password)
            except Exception as e:
                raise SdkConfigurationError('cannot load keyfile: ' + str(e))
        elif private_key:
            self.private_key = private_key

        if self.private_key:
            try:
                private_key_bytes = hexstr_if_str(to_bytes, self.private_key)
                pk = keys.PrivateKey(private_key_bytes)
                self.address = self.web3.eth.defaultAccount = pk.public_key.to_checksum_address()
            except ValidationError as e:
                raise SdkConfigurationError('cannot load private key: ' + str(e))

            # init transaction manager
            self._tx_manager = TransactionManager(self.web3, self.private_key, self.address, self.token_contract,
                                                  gas_price, gas_limit)

        # monitoring filter manager
        self._filter_mgr = FilterManager(self.web3)
Example #10
0
def normalize_abi(abi):
    if isinstance(abi, str):
        abi = json.loads(abi)
    validate_abi(abi)
    return abi
Example #11
0
    def __init__(self,
                 keyfile='',
                 password='',
                 private_key='',
                 provider='',
                 provider_endpoint_uri='http://159.89.240.147:8545',
                 contract_address=KIN_CONTRACT_ADDRESS,
                 contract_abi=KIN_ABI):
        """Create a new instance of the KIN SDK.

        The SDK needs a JSON-RPC provider, contract definitions and the wallet private key.
        The user may pass either a provider or a provider endpoint URI, in which case a default
        `web3:providers:HTTPProvider` will be created.

        If private_key is not provided, the SDK can still be used in "anonymous" mode with only the following
        functions available:
            - get_address_ether_balance
            - get_transaction_status
            - monitor_ether_transactions

        :param str private_key: a private key to initialize the wallet with. If either private key or keyfile
            are not provided, the wallet will not be initialized and methods needing the wallet will raise exception.

        :param str keyfile: the path to the keyfile to initialize to wallet with. Usually you will also need to supply
        a password for this keyfile.

        :param str password: a password for the keyfile.

        :param provider: JSON-RPC provider to work with. If not provided, a default `web3:providers:HTTPProvider`
            is used, inited with provider_endpoint_uri.
        :type provider: :class:`web3:providers:BaseProvider`

        :param str provider_endpoint_uri: a URI to use with a default HTTPProvider. If not provided, a
            default endpoint will be used.

        :param str contract_address: the address of the token contract. If not provided, a default KIN
            contract address will be used.

        :param dict contract_abi: The contract ABI. If not provided, a default KIN contract ABI will be used.

        :returns: An instance of the SDK.
        :rtype: :class:`~kin.TokenSDK`

        :raises: :class:`~kin.exceptions.SdkConfigurationError` if some of the configuration parameters are invalid.
        """

        if not provider and not provider_endpoint_uri:
            raise SdkConfigurationError(
                'either provider or provider endpoint must be provided')

        if not contract_address:
            raise SdkConfigurationError('token contract address not provided')

        try:
            validate_address(contract_address)
        except ValueError:
            raise SdkConfigurationError('invalid token contract address')

        if not contract_abi:
            raise SdkConfigurationError('token contract abi not provided')

        try:
            validate_abi(contract_abi)
        except Exception as e:
            raise SdkConfigurationError('invalid token contract abi: ' +
                                        str(e))

        if provider:
            self.web3 = Web3(provider)
        else:
            self.web3 = Web3(HTTPProvider(provider_endpoint_uri))
        if not self.web3.isConnected():
            raise SdkConfigurationError('cannot connect to provider endpoint')

        self.token_contract = self.web3.eth.contract(
            contract_address, abi=contract_abi, ContractFactoryClass=Contract)
        self.private_key = None
        self.address = None

        if keyfile:
            with open(keyfile, 'r') as f:
                try:
                    keystore = json.load(f)
                except Exception as e:
                    raise SdkConfigurationError(
                        'invalid json in keystore file')
            from ethereum.tools import keys as ekeys
            if not ekeys.check_keystore_json(keystore):
                raise SdkConfigurationError('invalid keystore file')
            try:
                self.private_key = ekeys.decode_keystore_json(
                    keystore, password)
            except ValueError as e:
                raise SdkConfigurationError('keyfile decode error: ' + str(e))
        elif private_key:
            self.private_key = private_key

        if self.private_key:
            try:
                private_key_bytes = hexstr_if_str(to_bytes, self.private_key)
                pk = keys.PrivateKey(private_key_bytes)
            except ValidationError as e:
                raise SdkConfigurationError('cannot load private key: ' +
                                            str(e))
            self.address = self.web3.eth.defaultAccount = pk.public_key.to_checksum_address(
            )

        # monitoring filters
        self._pending_tx_filter = None
        self._new_block_filter = None