def contract(self, *args, **kwargs): ContractFactoryClass = kwargs.pop('ContractFactoryClass', Contract) contract_name = kwargs.pop('contract_name', None) has_address = any(( 'address' in kwargs, len(args) >= 1 and is_address(args[0]), len(args) >= 2 and is_address(args[1]), )) for potential_address in args: validate_address_checksum(potential_address) if has_address: if 'address' in kwargs: address = kwargs.pop('address') elif is_address(args[0]): address = args[0] elif is_address(args[1]): address = args[1] kwargs['abi'] = args[0] validate_address(address) return ContractFactoryClass.factory(self.web3, contract_name, **kwargs)(address) else: try: kwargs['abi'] = args[0] except IndexError: pass return ContractFactoryClass.factory(self.web3, contract_name, **kwargs)
def mint_tokens(instance: web3.eth.Contract, owner: str, recipient: str, amount: float, bucket: int, **kwargs) -> str: """ Call `mint` function on target contract. Args: instance: A ViewTokenMintage live and initialized contract instance. owner: An authorized Ethereum account to call the minting contract from. recipient: Address of VIEW Token Recipient. amount: Amount of VIEW Tokens to mint. bucket: A bucket number of the funding source (Team, Supporters...) Returns: txid: Transaction ID of the function call """ assert bucket in buckets.values(), "Invalid bucket id" assert type(amount) == float, "Invalid amount type" validate_address(recipient) tx_props = { 'value': 0, 'from': owner, } # if gas limit is not provided, # w3.eth.estimateGas() is usded if 'gas' in kwargs: tx_props['gas'] = kwargs['gas'] txid = instance.transact(tx_props).mint(recipient, to_wei(amount, 'ether'), bucket) return txid
def normalize_address(ens, address): if address: if is_ens_name(address): validate_name_has_address(ens, address) else: validate_address(address) return address
def normalize_address(ens, address): if address: if is_ens_name(address): validate_name_has_address(ens, address) else: validate_address(address) return address
def send_tokens(self, address, amount): """Send tokens from my wallet to address. :param str address: the address to send tokens to. :param Decimal amount: the amount of tokens to transfer. :returns: transaction id (hash) :rtype: str :raises: :class:`~erc20token.exceptions.SdkConfigurationError`: if the SDK was not configured with a private key. :raises: ValueError: if the amount is not positive. :raises: ValueError: if the address has a wrong format. :raises: ValueError: if the nonce is incorrect. :raises: ValueError: if insufficient funds for for gas * gas_price. """ if not self.address: raise SdkNotConfiguredError('private key not configured') validate_address(address) if amount <= 0: raise ValueError('amount must be positive') hex_data = self.token_contract._encode_transaction_data( 'transfer', args=(address, self.web3.toWei(amount, 'ether'))) data = hexstr_if_str(to_bytes, hex_data) return self._tx_manager.send_transaction(self.token_contract.address, 0, data)
def verify_fact(self, member_address, fact_uuid): validate_address(member_address) self.unlockAccount() txn_hash = self.contract.transact({ 'from': self.account }).verify_fact(member_address, fact_uuid) self.lockAccount() return txn_hash
def new_candidate(self, address): validate_address(address) self.unlockAccount() txn_hash = self.contract.transact({ 'from': self.account }).new_candidate(address) self.lockAccount() return txn_hash
def level_up(self, company_address, vac_uuid, member_address): validate_address(company_address) validate_address(member_address) self.unlockAccount() txn_hash = self.contract.transact({ 'from': self.account }).level_up(company_address, vac_uuid, member_address) self.lockAccount() return txn_hash
def new_fact(self, member_about_address, fact, fact_uuid): validate_address(member_about_address) self.unlockAccount() txn_hash = self.contract.transact({ 'from': self.account }).new_fact(member_about_address, json.dumps(fact, cls=DjangoJSONEncoder), fact_uuid) self.lockAccount() return txn_hash
def new_company_owner(self, company_address, member_address): validate_address(company_address) validate_address(member_address) self.unlockAccount() txn_hash = self.contract.transact({ 'from': self.account }).new_owner_member(company_address, member_address) self.lockAccount() return txn_hash
def approve_company_tokens(self, company_address, amount): validate_address(company_address) self.unlockAccount() self.contract.transact({ 'from': self.account }).approve_company_tokens(company_address, 0) txn_hash = self.contract.transact({ 'from': self.account }).approve_company_tokens(company_address, amount) self.lockAccount() return txn_hash
def _get_filter_args(from_address, to_address): if not from_address and not to_address: raise ValueError('either from_address or to_address or both must be provided') filter_args = {} if from_address: validate_address(from_address) filter_args['from'] = from_address if to_address: validate_address(to_address) filter_args['to'] = to_address return filter_args
def _get_filter_args(from_address, to_address): if not from_address and not to_address: raise ValueError('either from_address or to_address or both must be provided') filter_args = {} if from_address: validate_address(from_address) filter_args['from'] = from_address if to_address: validate_address(to_address) filter_args['to'] = to_address return filter_args
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
def construct_event_filter_params(event_abi, contract_address=None, argument_filters=None, topics=None, fromBlock=None, toBlock=None, address=None): filter_params = {} topic_set = construct_event_topic_set(event_abi, argument_filters) if topics is not None: if len(topic_set) > 1: raise TypeError( "Merging the topics argument with topics generated " "from argument_filters is not supported.") topic_set = topics if len(topic_set) == 1 and is_list_like(topic_set[0]): filter_params['topics'] = topic_set[0] else: filter_params['topics'] = topic_set if address and contract_address: if is_list_like(address): filter_params['address'] = address + [contract_address] elif is_string(address): filter_params['address'] = [address, contract_address] else: raise ValueError( "Unsupported type for `address` parameter: {0}".format( type(address))) elif address: filter_params['address'] = address elif contract_address: filter_params['address'] = contract_address if 'address' not in filter_params: pass elif is_list_like(filter_params['address']): for addr in filter_params['address']: validate_address(addr) else: validate_address(filter_params['address']) if fromBlock is not None: filter_params['fromBlock'] = fromBlock if toBlock is not None: filter_params['toBlock'] = toBlock data_filters_set = construct_event_data_set(event_abi, argument_filters) return data_filters_set, filter_params
def get_address_ether_balance(self, address): """Get Ether balance of a public address. :param: str address: a public address to query. :returns: the balance in Ether of the provided address. :rtype: Decimal :raises: ValueError: if the supplied address has a wrong format. """ validate_address(address) return self.web3.fromWei(self.web3.eth.getBalance(address), 'ether')
def get_address_token_balance(self, address): """Get token balance of a public address. :param: str address: a public address to query. :returns: : the balance in tokens of the provided address. :rtype: Decimal :raises: ValueError: if the supplied address has a wrong format. """ validate_address(address) return self.web3.fromWei(self.token_contract.call().balanceOf(address), 'ether')
def get_address_ether_balance(self, address): """Get Ether balance of a public address. :param: str address: a public address to query. :returns: the balance in Ether of the provided address. :rtype: Decimal :raises: ValueError: if the supplied address has a wrong format. """ validate_address(address) return self.web3.fromWei(self.web3.eth.getBalance(address), 'ether')
def contract(self, address=None, **kwargs): ContractFactoryClass = kwargs.pop('ContractFactoryClass', self.defaultContractFactory) ContractFactory = ContractFactoryClass.factory(self.web3, **kwargs) if address: validate_address(address) return ContractFactory(address) else: return ContractFactory
def __init__(self, wallet_impl, account_info): self.wallet_impl = wallet_impl self.web3 = wallet_impl.wallet_op.web3 self.private_hash = account_info['private_hash'] self.destination_tag = account_info['destination_tag'] self.pub_address = account_info['pub_address'] self.password = account_info['password'] validate_address(self.web3.toChecksumAddress(self.pub_address)) self.transfer_op = TransactionManager(self.web3, private_key=self.private_hash, address=self.pub_address, password=self.password)
def get_address_token_balance(self, address): """Get token balance of a public address. :param: str address: a public address to query. :returns: : the balance in tokens of the provided address. :rtype: Decimal :raises: ValueError: if the supplied address has a wrong format. """ validate_address(address) return self.web3.fromWei(self.token_contract.call().balanceOf(address), 'ether')
def construct_event_filter_params(event_abi, contract_address=None, argument_filters=None, topics=None, fromBlock=None, toBlock=None, address=None): filter_params = {} if topics is None: topic_set = construct_event_topic_set(event_abi, argument_filters) else: topic_set = [topics] + construct_event_topic_set(event_abi, argument_filters) if len(topic_set) == 1 and is_list_like(topic_set[0]): filter_params['topics'] = topic_set[0] else: filter_params['topics'] = topic_set if address and contract_address: if is_list_like(address): filter_params['address'] = address + [contract_address] elif is_string(address): filter_params['address'] = [address, contract_address] else: raise ValueError( "Unsupported type for `address` parameter: {0}".format(type(address)) ) elif address: filter_params['address'] = address elif contract_address: filter_params['address'] = contract_address if 'address' not in filter_params: pass elif is_list_like(filter_params['address']): for addr in filter_params['address']: validate_address(addr) else: validate_address(filter_params['address']) if fromBlock is not None: filter_params['fromBlock'] = fromBlock if toBlock is not None: filter_params['toBlock'] = toBlock data_filters_set = construct_event_data_set(event_abi, argument_filters) return data_filters_set, filter_params
def fromAddress(address): """ This method should be used to create an iban object from ethereum address @method fromAddress @param {String} address @return {Iban} the IBAN object """ validate_address(address) address_as_integer = int(address, 16) address_as_base36 = baseN(address_as_integer, 36) padded = pad_left_hex(address_as_base36, 15) return Iban.fromBban(padded.upper())
def fromAddress(address): """ This method should be used to create an iban object from ethereum address @method fromAddress @param {String} address @return {Iban} the IBAN object """ validate_address(address) address_as_integer = int(address, 16) address_as_base36 = baseN(address_as_integer, 36) padded = pad_left_hex(address_as_base36, 15) return Iban.fromBban(padded.upper())
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
def validated_payouts(payouts_in): """ This method validates json transactions. It ensures `recipient` addresses are valid ETH addresses, and expands `bucket` aliases into proper bucket_id's. """ # swap bucket name with matching ID payouts = [{ **x, 'bucket': buckets[x['bucket']], 'amount': float(x['amount'].replace(',', '')), } for x in (keymap(rename_field, y) for y in payouts_in)] # validate addresses for payout in payouts: validate_address(payout['recipient']) return payouts
def post(self, request, *args, **kwargs): address = request.POST.get('address') amount = request.POST.get('amount') try: validate_address(address) except ValueError: messages.warning(request, 'Invalid address') else: coin_h = CoinHandler() user_balance = coin_h.balanceOf(request.user.contract_address) if int(float(amount) * 10**18) > user_balance: return messages.warning(request, 'You do not have so many tokens') from jobboard.tasks import withdraw_tokens withdraw_tokens.delay(request.user.id, request.user.contract_address, address, amount) return super().get(request, *args, **kwargs)
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
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
def send_ether(self, address, amount): """Send Ether from my wallet to address. :param str address: the address to send Ether to. :param float amount: the amount of Ether to transfer. :return: transaction id :rtype: str :raises: :class:`~kin.exceptions.SdkConfigurationError`: if the SDK was not configured with a private key. :raises: ValueError: if the amount is not positive. :raises: ValueError: if the nonce is incorrect. :raises: ValueError if insufficient funds for for gas * price + value. """ if not self.address: raise SdkNotConfiguredError('address not configured') validate_address(address) if amount <= 0: raise ValueError('amount must be positive') return self._send_raw_transaction(address, amount)
def send_ether(self, address, amount): """Send Ether from my wallet to address. :param str address: the address to send Ether to. :param Decimal amount: the amount of Ether to transfer. :return: transaction id (hash) :rtype: str :raises: :class:`~erc20token.exceptions.SdkConfigurationError`: if the SDK was not configured with a private key. :raises: ValueError: if the amount is not positive. :raises: ValueError: if the address has a wrong format. :raises: ValueError: if the nonce is incorrect. :raises: ValueError: if insufficient funds for for gas * gas_price + value. """ if not self.address: raise SdkNotConfiguredError('private key not configured') validate_address(address) if amount <= 0: raise ValueError('amount must be positive') return self._tx_manager.send_transaction(address, amount)
def send_ether(self, address, amount): """Send Ether from my wallet to address. :param str address: the address to send Ether to. :param Decimal amount: the amount of Ether to transfer. :return: transaction id (hash) :rtype: str :raises: :class:`~erc20tokensdk.exceptions.SdkConfigurationError`: if the SDK was not configured with a private key. :raises: ValueError: if the amount is not positive. :raises: ValueError: if the address has a wrong format. :raises: ValueError: if the nonce is incorrect. :raises: ValueError: if insufficient funds for for gas * gas_price + value. """ if not self.address: raise SdkNotConfiguredError('private key not configured') validate_address(address) if amount <= 0: raise ValueError('amount must be positive') return self._tx_manager.send_transaction(address, amount)
def send_tokens(self, address, amount): """Send tokens from my wallet to address. :param str address: the address to send tokens to. :param Decimal amount: the amount of tokens to transfer. :returns: transaction id (hash) :rtype: str :raises: :class:`~erc20token.exceptions.SdkConfigurationError`: if the SDK was not configured with a private key. :raises: ValueError: if the amount is not positive. :raises: ValueError: if the address has a wrong format. :raises: ValueError: if the nonce is incorrect. :raises: ValueError: if insufficient funds for for gas * gas_price. """ if not self.address: raise SdkNotConfiguredError('private key not configured') validate_address(address) if amount <= 0: raise ValueError('amount must be positive') hex_data = self.token_contract._encode_transaction_data('transfer', args=(address, self.web3.toWei(amount, 'ether'))) data = hexstr_if_str(to_bytes, hex_data) return self._tx_manager.send_transaction(self.token_contract.address, 0, data)
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)
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" ))
def abi_address_to_hex(abi_type, data): if abi_type == 'address': validate_address(data)
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)
def balanceOf(self, address): validate_address(address) return self.contract.call().balanceOf(address)
def allowance(self, owner, spender): validate_address(owner) validate_address(spender) return self.contract.call().allowance(owner, spender)
def transfer(self, address, amount): validate_address(address) return self.contract.transact({ 'from': settings.WEB_ETH_COINBASE }).transfer(address, amount)