Python web3.Web3.toChecksumAddress() Examples

The following are 30 code examples of web3.Web3.toChecksumAddress(). 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: download_token_addresses.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def download_bamboo_relay_token_addresses(token_dict: Dict[str, str]):
    page_count = 1
    while True:
        url = f"{BAMBOO_RELAY_ENDPOINT}?perPage=1000&page={page_count}"
        async with aiohttp.ClientSession() as client:
            async with client.get(url, timeout=API_CALL_TIMEOUT) as response:
                page_count += 1
                try:
                    if response.status == 200:
                        markets = await response.json()
                        if len(markets) == 0:
                            break
                        for market in markets:
                            market_id = market.get("id")
                            base, quote = market_id.split("-")
                            if base not in token_dict:
                                token_dict[base] = Web3.toChecksumAddress(market.get("baseTokenAddress"))
                            if quote not in token_dict:
                                token_dict[quote] = Web3.toChecksumAddress(market.get("quoteTokenAddress"))
                    else:
                        raise Exception(f"Call to {url} failed with status {response.status}")
                except Exception as err:
                    logging.getLogger().error(err)
                    break 
Example #2
Source File: __init__.py    From py-etherdelta with MIT License 6 votes vote down vote up
def get_token_balance(self, account, token_addr):
        """
        Returns the token balance of an account

        :param account: account
        :type account: str
        :param token_addr: token address
        :type token_addr: str
        :return: balance
        :rtype: int
        """
        token_addr = Web3.toChecksumAddress(token_addr)
        contractToken = w3.eth.contract(address=token_addr, abi=self.token_abi)
        account = Web3.toChecksumAddress(account)
        balance = contractToken.call().balanceOf(account)
        return w3.fromWei(balance, 'ether') 
Example #3
Source File: marketplace.py    From catalyst with Apache License 2.0 6 votes vote down vote up
def choose_pubaddr(self):
        if len(self.addresses) == 1:
            address = self.addresses[0]['pubAddr']
            address_i = 0
            print('Using {} for this transaction.'.format(address))
        else:
            while True:
                for i in range(0, len(self.addresses)):
                    print('{}\t{}\t{}\t{}'.format(
                        i,
                        self.addresses[i]['pubAddr'],
                        self.addresses[i]['wallet'].ljust(10),
                        self.addresses[i]['desc'])
                    )
                address_i = int(input('Choose your address associated with '
                                      'this transaction: [default: 0] ') or 0)
                if not (0 <= address_i < len(self.addresses)):
                    print('Please choose a number between 0 and {}\n'.format(
                        len(self.addresses) - 1))
                else:
                    address = Web3.toChecksumAddress(
                        self.addresses[address_i]['pubAddr'])
                    break

        return address, address_i 
Example #4
Source File: __init__.py    From py-etherdelta with MIT License 6 votes vote down vote up
def get_etherdelta_token_balance(self, account, token_addr):
        """
        Returns the token balance in EtherDelta of an account

        :param account: account
        :type account: str
        :param token_addr: token address
        :type token_addr: str
        :return: balance
        :rtype: int
        """
        account = Web3.toChecksumAddress(account)
        balance = 0
        if token_addr:
            balance = self.contractEtherDelta.call().balanceOf(token=token_addr, user=account)
        return w3.fromWei(balance, 'ether') 
Example #5
Source File: twitter_dapp.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 6 votes vote down vote up
def run(self):
        try:
            account = w3.eth.account.privateKeyToAccount('0x'+self.private_key)
        except ValueError:
            QtWidgets.QMessageBox.warning(self, 'Error', 'Private key is invalid.')
            return
        nonce = w3.eth.getTransactionCount(Web3.toChecksumAddress(account.address))
        txn = TwitterOnBlockchain.functions.write_a_tweet(self.tweet.encode('utf-8')).buildTransaction({
                  'from': account.address,
                  'gas': 70000,
                  'gasPrice': w3.toWei('1', 'gwei'),
                  'nonce': nonce
              })
        signed = w3.eth.account.signTransaction(txn, private_key=self.private_key)
        txhash = w3.eth.sendRawTransaction(signed.rawTransaction)
        wait_for_transaction_receipt(w3, txhash)
        self.write_a_tweet.emit() 
Example #6
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 #7
Source File: models.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 6 votes vote down vote up
def upload_video(self, video_user, password, video_file, title):
        video_path = MEDIA_ROOT + '/video.mp4'
        with open(video_path, 'wb+') as destination:
            for chunk in video_file.chunks():
                destination.write(chunk)
        ipfs_add = self.ipfs_con.add(video_path)
        ipfs_path = ipfs_add['Hash'].encode('utf-8')
        title = title[:20].encode('utf-8')
        nonce = self.w3.eth.getTransactionCount(Web3.toChecksumAddress(video_user))
        txn = self.SmartContract.functions.upload_video(ipfs_path, title).buildTransaction({
                    'from': video_user,
                    'gas': 200000,
                    'gasPrice': self.w3.toWei('30', 'gwei'),
                    'nonce': nonce
                  })
        txn_hash = self.w3.personal.sendTransaction(txn, password)
        wait_for_transaction_receipt(self.w3, txn_hash) 
Example #8
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 #9
Source File: zero_ex_coordinator_v3.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def hard_cancel_order(self, order: List[Order]) -> str:
        order_tuple: Tuple = convert_order_to_tuple(order)

        # Set gas to 1, so it avoids estimateGas call in Web3, which will revert
        hardCancelOrderData = self._exchange_contract.functions.cancelOrder(
            order_tuple
        ).buildTransaction({ 'gas': 1 })

        data = hardCancelOrderData['data']

        self._current_gas_price = self._wallet.gas_price + 10

        transaction = self._generate_signed_zero_ex_transaction(data, order['makerAddress'], self._chain_id)

        tx_hash = await self._submit_coordinator_transaction(
            transaction,
            Web3.toChecksumAddress(order['makerAddress']),
            transaction['signature'],
            [],
            0
        )

        return tx_hash 
Example #10
Source File: zero_ex_coordinator_v3.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def batch_hard_cancel_orders(self, orders: List[Order]) -> str:
        order_tuples: List[Tuple] = [convert_order_to_tuple(order) for order in orders]

        makerAddress = orders[0]['makerAddress']

        # Set gas to 1, so it avoids estimateGas call in Web3, which will revert
        batchHardCancelOrderData = self._exchange_contract.functions.batchCancelOrders(
            order_tuples
        ).buildTransaction({ 'gas': 1 })

        data = batchHardCancelOrderData['data']

        self._current_gas_price = self._wallet.gas_price + 10

        transaction = self._generate_signed_zero_ex_transaction(data, makerAddress, self._chain_id)

        tx_hash = await self._submit_coordinator_transaction(
            transaction,
            Web3.toChecksumAddress(makerAddress),
            transaction['signature'],
            [],
            0
        )

        return tx_hash 
Example #11
Source File: base.py    From clove with GNU General Public License v3.0 6 votes vote down vote up
def unify_address(address: str) -> str:
        '''
        Returns Ethereum address with checksum.

        Args:
            str: Ethereum address

        Returns:
            str: address with checksum

        Raises:
            AssertionError: if the address length is incorrect

        Example:
            >>> from clove.network import Ethereum
            >>> network = Ethereum()
            >>> network.unify_address('0x999f348959e611f1e9eab2927c21e88e48e6ef45')
            '0x999F348959E611F1E9eab2927c21E88E48e6Ef45'
        '''
        assert len(address) in (40, 42), 'Provided address is not properly formatted.'
        if len(address) == 40:
            address = '0x' + address
        int(address, 16)
        return Web3.toChecksumAddress(address) 
Example #12
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,
                 contract_owner_private_key):

        super(MintableERC20Processor, self).__init__(contract_address,
                                                     contract_abi_string,
                                                     ethereum_chain_id,
                                                     http_provider,
                                                     websocket_provider,
                                                     gas_price_gwei,
                                                     gas_limit)

        self.master_wallet_private_key = contract_owner_private_key
        self.master_wallet_address = Web3.toChecksumAddress(utils.privtoaddr(self.master_wallet_private_key)) 
Example #13
Source File: download_token_addresses.py    From hummingbot with Apache License 2.0 6 votes vote down vote up
def download_dolomite_token_addresses(token_dict: Dict[str, str]):
    async with aiohttp.ClientSession() as client:
        async with client.get(DOLOMITE_ENDPOINT, timeout=API_CALL_TIMEOUT) as response:
            if response.status == 200:
                try:
                    response = await response.json()
                    tokens = response.get("data")
                    for token in tokens:
                        asset = token["ticker"]
                        if asset not in token_dict:
                            token_dict[asset] = Web3.toChecksumAddress(token["identifier"])
                        elif asset == "LRC":
                            # Other integrations use the wrong address for LRC
                            token_dict[asset] = Web3.toChecksumAddress(token["identifier"])
                except Exception as err:
                    logging.getLogger().error(err) 
Example #14
Source File: serializers.py    From pm-trading-db with MIT License 5 votes vote down vote up
def validate_marketMaker(self, market_maker_address):
        # Convert settings.LMSR_MARKET_MAKER to list of checksum addresses
        lmsr_addresses = [Web3.toChecksumAddress(address) for address in settings.LMSR_MARKET_MAKER.split(',') if address]

        # If given market_marker_address is not among addresses in settings, we don't accept it
        if not Web3.toChecksumAddress(market_maker_address) in lmsr_addresses:
            raise serializers.ValidationError('Market Maker {} does not exist'.format(market_maker_address))
        return market_maker_address 
Example #15
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 #16
Source File: zero_ex_coordinator_v3.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _fetch_server_endpoint_or_throw(self, feeRecipient: str) -> str:
        coordinatorOperatorEndpoint: str = self._registry_contract.functions.getCoordinatorEndpoint(Web3.toChecksumAddress(feeRecipient)).call()

        if (coordinatorOperatorEndpoint == '') or (coordinatorOperatorEndpoint is None):
            raise Exception(
                'No Coordinator server endpoint found in Coordinator Registry for feeRecipientAddress: ' + feeRecipient + '. Registry contract address: ' + self._registry_address
            )
        
        return coordinatorOperatorEndpoint 
Example #17
Source File: __init__.py    From py-etherdelta with MIT License 5 votes vote down vote up
def get_available_volume(self, token_addr, order_id):
        """
        Returns available volume for an order give order ID

        :param token_addr: token address
        :type token_addr: str
        :param order_id: order ID
        :type order_id: str
        :return: available volume
        :rtype: int
        """
        order = self.get_order(token_addr, order_id)
        if order == None:
            return None
        amountGet = int('{:.0f}'.format(Decimal(order['amountGet'])))
        amountGive = int('{:.0f}'.format(Decimal(order['amountGive'])))
        tokenGet = Web3.toChecksumAddress(order['tokenGet'])
        tokenGive = Web3.toChecksumAddress(order['tokenGive'])
        expires = int(order['expires'])
        nonce = int(order['nonce'])
        user = Web3.toChecksumAddress(order['user'])
        v = int(order['v'])
        r = Web3.toBytes(hexstr=order['r'])
        s = Web3.toBytes(hexstr=order['s'])
        available_volume = self.contractEtherDelta.call().availableVolume(tokenGet, amountGet, tokenGive, amountGive, expires, nonce, user, v, r, s)
        return available_volume 
Example #18
Source File: zero_ex_coordinator_v3.py    From hummingbot with Apache License 2.0 5 votes vote down vote up
def _submit_coordinator_transaction(
        self,
        transaction,
        txOrigin: str,
        transactionSignature: str,
        approvalSignatures: List[str],
        protocolFeeMultiplier
    ) -> Tuple[str, Decimal]:
        transaction: Tuple[str, any] = (
            transaction["salt"],
            transaction["expirationTimeSeconds"],
            transaction["gasPrice"],
            Web3.toChecksumAddress(transaction["signerAddress"]),
            self._w3.toBytes(hexstr=transaction["data"])
        )
        transactionSignature: bytes = self._w3.toBytes(hexstr=transactionSignature)
        approvalSignatures: List[bytes] = [self._w3.toBytes(hexstr=signature) for signature in approvalSignatures]

        gas_price = self._current_gas_price
        protocol_fee = protocolFeeMultiplier * gas_price
        tx_hash: str = self._wallet.execute_transaction(
            self._coordinator_contract.functions.executeTransaction(
                transaction,
                txOrigin,
                transactionSignature,
                approvalSignatures
            ),
            gasPrice=int(gas_price),
            value=int(protocol_fee)
        )
        return tx_hash, Decimal(protocol_fee) 
Example #19
Source File: __init__.py    From py-etherdelta with MIT License 5 votes vote down vote up
def get_etherdelta_eth_balance(self, account):
        """
        Returns the ETH balance in EtherDelta of an account

        :param account: account
        :type account: str
        :return: balance
        :rtype: int
        """
        account = Web3.toChecksumAddress(account)
        balance = self.contractEtherDelta.call().balanceOf(token='0x0000000000000000000000000000000000000000', user=account)
        return w3.fromWei(balance, 'ether') 
Example #20
Source File: ethereum.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def get_address_from_public_key(cls, public_key: str) -> str:
        """
        Get the address from the public key.

        :param public_key: the public key
        :return: str
        """
        keccak_hash = Web3.keccak(hexstr=public_key)
        raw_address = keccak_hash[-20:].hex().upper()
        address = Web3.toChecksumAddress(raw_address)
        return address 
Example #21
Source File: __init__.py    From py-etherdelta with MIT License 5 votes vote down vote up
def get_eth_balance(self, account):
        """
        Returns the ETH balance of an account

        :param account: account
        :type account: str
        :return: balance
        :rtype: float
        """
        account = Web3.toChecksumAddress(account)
        balance = w3.eth.getBalance(account)
        return w3.fromWei(balance, 'ether') 
Example #22
Source File: ethereum.py    From agents-aea with Apache License 2.0 5 votes vote down vote up
def _try_get_transaction_count(self, address: Address) -> Optional[int]:
        """Try get the transaction count."""
        try:
            nonce = self._api.eth.getTransactionCount(  # pylint: disable=no-member
                self._api.toChecksumAddress(address)
            )
        except Exception as e:  # pragma: no cover
            logger.warning("Unable to retrieve transaction count: {}".format(str(e)))
            nonce = None
        return nonce 
Example #23
Source File: ethereum_processor.py    From SempoBlockchain with GNU General Public License v3.0 5 votes vote down vote up
def construct_master_wallet_approval_tasks(self, account_to_approve_encoded_pk, credit_transfer_id):

        private_key = self.decode_private_key(account_to_approve_encoded_pk)

        address = Web3.toChecksumAddress(utils.privtoaddr(private_key))

        gas_required, gas_price = self.estimate_load_ether_gas_and_price()

        return [
            celery_tasks.load_ether.si(address, gas_required, gas_price),
            celery_tasks.create_transaction_response.s(credit_transfer_id),
            celery_tasks.approve_master_for_transfers.si(account_to_approve_encoded_pk, gas_required, gas_price),
            celery_tasks.create_transaction_response.s(credit_transfer_id)
        ] 
Example #24
Source File: transaction.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def show_details(self) -> dict:
        '''Returns a dictionary with transaction details.'''
        details = super().show_details()
        details['token_address'] = Web3.toChecksumAddress(details.pop('to'))
        details['sender_address'] = self.sender_address
        return details 
Example #25
Source File: contract.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, network, tx_dict):

        self.network = network
        self.tx_dict = tx_dict
        self.abi = self.network.abi
        self.method_id = self.network.extract_method_id(tx_dict['input'])
        self.type = self.network.get_method_name(self.method_id)
        self.token = None

        if self.method_id != self.network.initiate:
            logger.warning('Not a contract transaction.')
            raise ValueError('Not a contract transaction.')

        input_types = get_abi_input_types(find_matching_fn_abi(self.abi, fn_identifier=self.type))
        input_names = get_abi_input_names(find_matching_fn_abi(self.abi, fn_identifier=self.type))
        input_values = decode_abi(input_types, Web3.toBytes(hexstr=self.tx_dict['input'][10:]))
        self.inputs = dict(zip(input_names, input_values))

        self.locktime = datetime.utcfromtimestamp(self.inputs['_expiration'])
        self.recipient_address = Web3.toChecksumAddress(self.inputs['_participant'])
        self.refund_address = self.tx_dict['from']
        self.secret_hash = self.inputs['_hash'].hex()
        self.contract_address = Web3.toChecksumAddress(self.tx_dict['to'])
        self.block_number = self.tx_dict['blockNumber']
        self.confirmations = self.network.get_latest_block - self.block_number
        self.balance = self.get_balance()

        if self.is_token_contract:
            self.value_base_units = self.inputs['_value']
            self.token_address = Web3.toChecksumAddress(self.inputs['_token'])
            self.token = self.network.get_token_by_address(self.token_address)
            self.value = self.token.value_from_base_units(self.value_base_units)
            self.symbol = self.token.symbol
        else:
            self.value_base_units = self.tx_dict['value']
            self.value = self.network.value_from_base_units(self.value_base_units)
            self.symbol = self.network.default_symbol 
Example #26
Source File: generate-ethereum-networks.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def extract_tokens(self):
        links = [l for l in self.html.find('#ContentPlaceHolder1_divresult tbody tr h5 a')]
        for l in links:
            address = l.attrib['href'].replace('/token/', '')
            try:
                name, symbol = l.text[:-1].split(' (')
            except ValueError:
                continue
            decimals = self.get_token_precision(address)
            if not decimals:
                print_error(f'Cannot define the number of decimal places for {name} ({symbol}). Ignoring.')
                self.ignored.append(name)
                continue
            if not symbol:
                print_error(f'Cannot get symbol for {name}. Ignoring.')
                self.ignored.append(name)
                continue
            token = Token(name, symbol, Web3.toChecksumAddress(address), decimals)
            if symbol in self.symbols:
                print_error(f'Duplicate symbol {symbol} for token {name}. Ignoring.')
                self.ignored.append(token)
                continue
            elif name in self.names:
                print_error(f'Duplicate name {name} for token {symbol}. Ignoring.')
                self.ignored.append(token)
                continue
            self.tokens.append(token)
            self.symbols.add(symbol)
            self.names.add(name)
        print_section(f'Tokens counter: {len(self.tokens)}.') 
Example #27
Source File: generate-ethereum-networks.py    From clove with GNU General Public License v3.0 5 votes vote down vote up
def get_token_precision(self, token_address):
        token_contract = ConciseContract(
            self.network.web3.eth.contract(
                address=Web3.toChecksumAddress(token_address),
                abi=ERC20_BASIC_ABI,
            )
        )
        time.sleep(0.5)  # we don't want to spam the API
        try:
            return token_contract.decimals()
        except (OverflowError, BadFunctionCallOutput):
            return 
Example #28
Source File: cli.py    From pakala with GNU General Public License v3.0 5 votes vote down vote up
def addressOrStdin(s):
    if s == "-":
        return s
    if not re.match(r"^0x([0-9a-fA-F]){40}$", s):
        raise argparse.ArgumentError("Invalid address.")
    return Web3.toChecksumAddress(s) 
Example #29
Source File: blockchain.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def create_send_transaction(self, tx):
        nonce = self.w3.eth.getTransactionCount(tx.sender)
        transaction = {
          'from': tx.sender,
          'to': Web3.toChecksumAddress(tx.destination),
          'value': self.w3.toWei(str(tx.amount), 'ether'),
          'gas': 21000,
          'gasPrice': self.w3.toWei(str(tx.fee), 'gwei'),
          'nonce': nonce
        }

        tx_hash = self.w3.personal.sendTransaction(transaction, tx.password)
        wait_for_transaction_receipt(self.w3, tx_hash) 
Example #30
Source File: models.py    From Hands-On-Blockchain-for-Python-Developers with MIT License 5 votes vote down vote up
def like_video(self, video_liker, password, video_user, index):
        if self.SmartContract.functions.video_has_been_liked(video_liker, video_user, index).call():
            return
        nonce = self.w3.eth.getTransactionCount(Web3.toChecksumAddress(video_liker))
        txn = self.SmartContract.functions.like_video(video_user, index).buildTransaction({
                    'from': video_liker,
                    'gas': 200000,
                    'gasPrice': self.w3.toWei('30', 'gwei'),
                    'nonce': nonce
                  })
        txn_hash = self.w3.personal.sendTransaction(txn, password)
        wait_for_transaction_receipt(self.w3, txn_hash)