Python web3.Web3.toWei() Examples

The following are 19 code examples of web3.Web3.toWei(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module web3.Web3 , or try the search function .
Example #1
Source File: __init__.py    From py-etherdelta with MIT License 6 votes vote down vote up
def approve_deposit(self, tokenaddress, amount, user_private_key):
        global web3, addressEtherDelta
        maxGas = 250000
        gasPriceWei = 4000000000    # 1 Gwei

        amount_in_wei = Web3.toWei(amount, 'ether')
        kwargs = {
            '_spender' : Web3.toChecksumAddress(addressEtherDelta),
            '_value' : int(Decimal(amount_in_wei)),
        }

        userAccount = w3.eth.account.privateKeyToAccount(user_private_key).address
        # Bail if there's no private key
        if len(user_private_key) != 64: raise ValueError('WARNING: user_private_key must be a hexadecimal string of 64 characters long')
        # Build binary representation of the function call with arguments
        token_contract = w3.eth.contract(address=Web3.toChecksumAddress(tokenaddress), abi=self.token_abi)
        abidata = token_contract.encodeABI("approve", kwargs=kwargs)
        nonce = w3.eth.getTransactionCount(userAccount)
        transaction = { 'to': Web3.toChecksumAddress(tokenaddress), 'from': userAccount, 'gas': maxGas, 'gasPrice': gasPriceWei, 'data': abidata, 'nonce': nonce, 'chainId': 1}
        print(transaction)
        signed = w3.eth.account.signTransaction(transaction, user_private_key)
        result = w3.eth.sendRawTransaction(w3.toHex(signed.rawTransaction))
        print("Transaction returned: " + str(result))
        print("\nDone! You should see the transaction show up at https://etherscan.io/tx/" + w3.toHex(result))
        return result, nonce 
Example #2
Source File: test_models.py    From safe-relay-service with MIT License 6 votes vote down vote up
def test_token_calculate_payment(self):
        token = TokenFactory(fixed_eth_conversion=0.1)
        self.assertEqual(token.calculate_payment(Web3.toWei(1, 'ether')), Web3.toWei(10, 'ether'))

        token = TokenFactory(fixed_eth_conversion=1.0)
        self.assertEqual(token.calculate_payment(Web3.toWei(1, 'ether')), Web3.toWei(1, 'ether'))

        token = TokenFactory(fixed_eth_conversion=2.0)
        self.assertEqual(token.calculate_payment(Web3.toWei(1, 'ether')), Web3.toWei(0.5, 'ether'))

        token = TokenFactory(fixed_eth_conversion=10.0)
        self.assertEqual(token.calculate_payment(Web3.toWei(1, 'ether')), Web3.toWei(0.1, 'ether'))

        token = TokenFactory(fixed_eth_conversion=0.6512)
        self.assertEqual(token.calculate_payment(Web3.toWei(1.23, 'ether')), 1888820638820638720)

        token = TokenFactory(fixed_eth_conversion=1.0, decimals=17)
        self.assertEqual(token.calculate_payment(Web3.toWei(1, 'ether')), Web3.toWei(0.1, 'ether')) 
Example #3
Source File: __init__.py    From py-etherdelta with MIT License 6 votes vote down vote up
def withdraw(self, amount, user_private_key):
        """
        Invokes on-chain withdraw ether
        :param amount: withdraw ether amount
        :type amount: float
        :param user_private_key: user private key
        :type user_private_key: string
        :return: tx
        :rtype: object
        """

        amount_in_wei = Web3.toWei(amount, 'ether')
        kwargs = {
            'amount' : int(Decimal(amount_in_wei)),
        }
        return self.__send_transaction("withdraw", kwargs, user_private_key) 
Example #4
Source File: base.py    From clove with GNU General Public License v3.0 6 votes vote down vote up
def value_to_base_units(value: float) -> int:
        '''
        Converting value to base units.

        Args:
            value (int): value in main coins (Ethereum)

        Returns:
            float: value in base units (Wei)

        Example:
            >>> from clove.network import Ethereum
            >>> network = Ethereum()
            >>> network.value_to_base_units(0.00000001)
            10000000000
        '''
        return Web3.toWei(value, 'ether') 
Example #5
Source File: __init__.py    From py-etherdelta with MIT License 6 votes vote down vote up
def withdraw_token(self, tokenaddress, amount, user_private_key):
        """
        Invokes on-chain withdraw tokens. Only apply for 18 decimal tokens
        :param tokenaddress: withdraw contract address
        :type order: string
        :param amount: withdraw token amount
        :type amount: float
        :param user_private_key: user private key
        :type user_private_key: string
        :return: tx
        :rtype: object
        """

        amount_in_wei = Web3.toWei(amount, 'ether')
        kwargs = {
            'token' : Web3.toChecksumAddress(tokenaddress),
            'amount' : int(Decimal(amount_in_wei)),
        }
        self.__send_transaction(self, "withdrawToken", kwargs, user_private_key) 
Example #6
Source File: ethereum_processor.py    From SempoBlockchain with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,
                     contract_address,
                     contract_abi_string,
                     ethereum_chain_id,
                     http_provider,
                     websocket_provider,
                     gas_price_gwei,
                     gas_limit,):

            self.abi_dict = json.loads(contract_abi_string)
            self.contract_address = utils.checksum_encode(contract_address)
            self.ethereum_chain_id = int(ethereum_chain_id)

            self.w3 = Web3(HTTPProvider(http_provider))
            # self.wsw3 = Web3(WebsocketProvider(websocket_provider))

            self.contract = self.w3.eth.contract(address=self.contract_address, abi=self.abi_dict)
            self.decimals = self.get_decimals()

            self.gas_price = self.w3.toWei(gas_price_gwei, 'gwei')
            self.gas_limit = gas_limit
            self.transaction_max_value = self.gas_price * self.gas_limit 
Example #7
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def test_send_back_if_possible_block(self):
        self.state.calls.append(
            self.get_call(
                claripy.If(
                    self.env.block_number < 100000000000,
                    self.env.value + Web3.toWei(1, "ether"),
                    0,
                )
            )
        )
        self.assertTrue(self.check_state(self.state)) 
Example #8
Source File: __init__.py    From py-etherdelta with MIT License 5 votes vote down vote up
def deposit_token(self, tokenaddress, amount, user_private_key):

        approved, nonce = self.approveDeposit(tokenaddress, amount, user_private_key)

        amount_in_wei = Web3.toWei(amount, 'ether')
        kwargs = {
            'token' : Web3.toChecksumAddress(tokenaddress),
            'amount' : int(Decimal(amount_in_wei)),
        }

        global web3, addressEtherDelta
        maxGas = 250000
        gasPriceWei = 4000000000    # 1 Gwei

        userAccount = w3.eth.account.privateKeyToAccount(user_private_key).address
        # Bail if there's no private key
        if len(user_private_key) != 64: raise ValueError('WARNING: user_private_key must be a hexadecimal string of 64 characters long')
        # Build binary representation of the function call with arguments
        abidata = self.contractEtherDelta.encodeABI("depositToken", kwargs=kwargs)
        transaction = { 'to': addressEtherDelta, 'from': userAccount, 'gas': maxGas, 'gasPrice': gasPriceWei, 'data': abidata, 'nonce': nonce + 1, 'chainId': 1}
        print(transaction)
        signed = w3.eth.account.signTransaction(transaction, user_private_key)
        depositresult = w3.eth.sendRawTransaction(w3.toHex(signed.rawTransaction))
        print("Transaction returned: " + str(depositresult))
        print("\nDone! You should see the transaction show up at https://etherscan.io/tx/" + w3.toHex(depositresult))

        result = {
            "approve": approved,
            "deposit": depositresult
        }
        return result 
Example #9
Source File: test_recursive_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def check_states(self, states, mock_storage=None):
        self.analyzer = RecursiveAnalyzer(
            max_wei_to_send=Web3.toWei(10, "ether"),
            min_wei_to_receive=Web3.toWei(1, "milliether"),
        )
        if mock_storage is not None:
            self.analyzer.actual_storage = mock_storage
        return self.analyzer.check_states(states, timeout=0, max_depth=4) 
Example #10
Source File: cli.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def ethWeiAmount(arg):
    m = re.match(r"^([0-9.]+) ?(\w+)$", arg)
    if m is None:
        raise argparse.ArgumentError(
            "The argument must be in the form '1 ether' for example."
        )
    return Web3.toWei(float(m.group(1)), m.group(2)) 
Example #11
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def test_read_concrete(self):
        self.analyzer.actual_storage = {0: 0xBAD1DEA}

        self.state.storage_read[utils.bvv(0)] = claripy.BVS("storage[0]", 256)
        self.state.selfdestruct_to = self.state.storage_read[utils.bvv(0)]
        self.assertFalse(self.check_state(self.state))

        self.state.calls.append(
            self.get_call(
                Web3.toWei(1, "ether") * self.state.storage_read[utils.bvv(0)]
            )
        )
        self.assertTrue(self.check_state(self.state)) 
Example #12
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def test_send_back_fixed_amount(self):
        self.state.calls.append(self.get_call(Web3.toWei(1, "ether")))
        self.assertTrue(self.check_state(self.state)) 
Example #13
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def test_send_back_if_impossible_block(self):
        self.state.calls.append(
            self.get_call(
                claripy.If(
                    self.env.block_number > 100000000000,
                    self.env.value + Web3.toWei(1, "ether"),
                    0,
                )
            )
        )
        self.assertFalse(self.check_state(self.state)) 
Example #14
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def test_send_back_more(self):
        self.state.calls.append(self.get_call(self.env.value + Web3.toWei(1, "ether")))
        self.assertTrue(self.check_state(self.state)) 
Example #15
Source File: test_analyzer.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.env = Env(b"", caller=utils.DEFAULT_CALLER, address=utils.DEFAULT_ADDRESS)

        self.state = State(self.env)
        self.analyzer = Analyzer(
            address=self.env.address,
            caller=self.env.caller,
            max_wei_to_send=Web3.toWei(10, "ether"),
            min_wei_to_receive=Web3.toWei(1, "milliether"),
        ) 
Example #16
Source File: funding_service.py    From safe-relay-service with MIT License 5 votes vote down vote up
def send_eth_to(self, to: str, value: int, gas: int = 22000, gas_price=None,
                    retry: bool = False, block_identifier='pending'):
        if not gas_price:
            gas_price = self.gas_station.get_gas_prices().standard

        if self.max_eth_to_send and value > Web3.toWei(self.max_eth_to_send, 'ether'):
            raise EtherLimitExceeded('%d is bigger than %f' % (value, self.max_eth_to_send))

        with EthereumNonceLock(self.redis, self.ethereum_client, self.funder_account.address,
                               lock_timeout=60 * 2) as tx_nonce:
            return self.ethereum_client.send_eth_to(self.funder_account.key, to, gas_price, value,
                                                    gas=gas,
                                                    retry=retry,
                                                    block_identifier=block_identifier,
                                                    nonce=tx_nonce) 
Example #17
Source File: gas_station.py    From safe-relay-service with MIT License 5 votes vote down vote up
def __init__(self, gas_price: Optional[int] = None):
        if gas_price is None:
            self.lowest = Web3.toWei(1, 'gwei')
            self.safe_low = Web3.toWei(5, 'gwei')
            self.standard = Web3.toWei(10, 'gwei')
            self.fast = Web3.toWei(20, 'gwei')
            self.fastest = Web3.toWei(50, 'gwei')
        else:
            self.lowest = Web3.toWei(gas_price, 'gwei')
            self.safe_low = Web3.toWei(gas_price + 1, 'gwei')
            self.standard = Web3.toWei(gas_price + 2, 'gwei')
            self.fast = Web3.toWei(gas_price + 3, 'gwei')
            self.fastest = Web3.toWei(gas_price + 4, 'gwei') 
Example #18
Source File: ethereum_processor.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def make_disbursement(self,
                          transfer_amount,
                          recipient_address,
                          account_to_approve_encoded_pk,
                          master_wallet_approval_status,
                          uncompleted_tasks,
                          is_retry,
                          credit_transfer_id=None):

        chain_list = []

        approval_required = self.determine_if_master_wallet_approval_required(
            master_wallet_approval_status,
            uncompleted_tasks,
            is_retry)

        if approval_required:
            chain_list.extend(
                self.construct_master_wallet_approval_tasks(
                    account_to_approve_encoded_pk,
                    credit_transfer_id)
            )

        if not is_retry or 'disbursement' in uncompleted_tasks:
            chain_list.extend([
                celery_tasks.disburse_funds.si(transfer_amount, recipient_address, credit_transfer_id),
                celery_tasks.create_transaction_response.s(credit_transfer_id)
            ])


        if not is_retry or 'ether load' in uncompleted_tasks:
            if float(self.force_eth_disbursement_amount or 0) > 0:

                forced_amount_wei = Web3.toWei(self.force_eth_disbursement_amount, 'ether')

                chain_list.extend([
                    celery_tasks.load_ether.si(recipient_address, forced_amount_wei, 1),
                    celery_tasks.create_transaction_response.s(credit_transfer_id)
                ])

        chain(chain_list).on_error(celery_tasks.log_error.s(credit_transfer_id)).delay() 
Example #19
Source File: __init__.py    From py-etherdelta with MIT License 4 votes vote down vote up
def trade(self, order, eth_amount, user_private_key):
        """
        Invokes on-chain trade

        :param order: order
        :type order: object
        :param eth_amount: ETH amount
        :type eth_amount: float
        :param user_private_key: user private key
        :type user_private_key: string
        :return: tx
        :rtype: object
        """
        global web3, addressEtherDelta
        userAccount = w3.eth.account.privateKeyToAccount(user_private_key).address
        # Transaction info
        maxGas = 250000
        gasPriceWei = 1000000000    # 1 Gwei
        if order['tokenGive'] == '0x0000000000000000000000000000000000000000':
            ordertype = 'buy'    # it's a buy order so we are selling tokens for ETH
            amount = eth_amount / float(order['price'])
        else:
            ordertype = 'sell'   # it's a sell order so we are buying tokens for ETH
            amount = eth_amount
        amount_in_wei = web3.toWei(amount, 'ether')
        print("\nTrading " + str(eth_amount) + " ETH of tokens (" + str(amount) + " tokens) against this " + ordertype + " order: %.10f tokens @ %.10f ETH/token" % (float(order['ethAvailableVolume']), float(order['price'])))
        print("Details about order: " + str(order))
        # trade function arguments
        kwargs = {
            'tokenGet' : Web3.toChecksumAddress(order['tokenGet']),
            'amountGet' : int(Decimal(order['amountGet'])),
            'tokenGive' : Web3.toChecksumAddress(order['tokenGive']),
            'amountGive' : int(Decimal(order['amountGive'])),
            'expires' : int(order['expires']),
            'nonce' : int(order['nonce']),
            'user' : Web3.toChecksumAddress(order['user']),
            'v' : order['v'],
            'r' : w3.toBytes(hexstr=order['r']),
            's' : w3.toBytes(hexstr=order['s']),
            'amount' : int(amount_in_wei),
        }
        # Bail if there's no private key
        if len(user_private_key) != 64: raise ValueError('WARNING: user_private_key must be a hexadecimal string of 64 characters long')
        # Build binary representation of the function call with arguments
        abidata = self.contractEtherDelta.encodeABI('trade', kwargs=kwargs)
        print("abidata: " + str(abidata))
        nonce = w3.eth.getTransactionCount(userAccount)
        # Override to have same as other transaction:
        #nonce = 53
        print("nonce: " + str(nonce))
        transaction = { 'to': addressEtherDelta, 'from': userAccount, 'gas': maxGas, 'gasPrice': gasPriceWei, 'data': abidata, 'nonce': nonce, 'chainId': 1}
        print(transaction)
        signed = w3.eth.account.signTransaction(transaction, user_private_key)
        print("signed: " + str(signed))
        result = w3.eth.sendRawTransaction(w3.toHex(signed.rawTransaction))
        print("Transaction returned: " + str(result))
        print("\nDone! You should see the transaction show up at https://etherscan.io/tx/" + w3.toHex(result))
        return result