DEV Community

Muwawu Moses
Muwawu Moses

Posted on • Edited on

How to Interact with Smart Contracts locally using web3.py

Writing smart contracts is one thing but, interacting with them is another.Today we are going to dive into how we can interact with our deployed smart contracts locally using web3.py. I would recommend you to look out for my early post which is a beginner tutorial on how to write smart contracts using vyper, remix IDE and deploying them on bnb smart chain.

Step-by-step procedure:

We are going to go through the process in two major steps i.e;

a. Writing and compiling our smart contract on remix and then deploy it on binance smart chain.

b. Interacting with the deployed smart contract locally in vs code.

Well, let's start with writing the following smart contract in Remix IDE that must print Hello, World!.

# A simple Vyper contract
@external
def sayHello() -> String[13]:
    return "Hello, World!"

Enter fullscreen mode Exit fullscreen mode

I won't go deep into this process as i have already covered this in my first tutorial.. I would recommend you visit it so that we can move at the same pace.

So, after compiling, copy and save the ABI. We shall use this later with in our web3.py code.

Next, deploy the code and copy and save the contract address. This also, is going to be important in our web3.py code as we shall see later.

Copy contract addres

I am going to use vs code for development on wsl2(Ubuntu) on my local machine, and web3.py for interacting with the smart contracts.

  • First, we need to setup our development environment by setting up a development folder and environment.We shall do this by running the following commands in Ubuntu simultaneously as follows $ mkdir testing, $ cd testing, $ python3 -m venv .venv, and then open vs code using the command; code .

In vs code, open terminal and activate the virtual environment
by running $ source .venv/bin/activate

  • Next, we need to install a very important tool Ganache.This development tool allows you to simulate a blockchain environment locally on your machine.Let's run the following commands to install and activate it respectively.

$ npm install -g ganache-cli and ganache-cli.

  • Installing web3.py

This is a Python library for interacting with Ethereum-based blockchains. Let's install by running the following command:

$ pip install web3.

Good. Now, we are ready to go. Next, let's create a folder inside our root folder testing and name it vyper_project. Then, inside our newly created folder, we create a file named call_say_hello.py. This is where we are going to put our python code.

from web3 import Web3

# Connect to a remote bsc node
web3 = Web3(Web3.HTTPProvider('https://data-seed-prebsc-1-s1.binance.org:8545/'))

# ABI of the compiled Vyper contract
abi = [
    {
        "type": "function",
        "name": "sayHello",
        "stateMutability": "nonpayable",
        "inputs": [],
        "outputs": [
            {
                "name": "",
                "type": "string"
            }
        ]
    }
] # Replace this with your contact ABI


# Address of the deployed contract
contract_address = web3.to_checksum_address('0xae95803315d402afb1a24c48e4c3f7d67180747e')  # replace with your contract's address

# Create a contract instance
contract = web3.eth.contract(address=contract_address, abi=abi)

# Call the sayHello function
def call_say_hello():
    try:
        result = contract.functions.sayHello().call()
        print('Contract sayHello() output:', result)
    except Exception as e:
        print('Error calling sayHello():', e)

call_say_hello()

Enter fullscreen mode Exit fullscreen mode

Lastly, we have to run the code.

$ python3 path/to/your/file which in this case will be $ python3 vyper_project/call_say_hello.py

We should get this out-put:

Terminal Output

The out put of Contract sayHello output: Hello, World! confirms that we have successfully interacted with our smart contract.

Congratulations if you have made it up to this stage. Happy building.
You can also check on my article of how to interact with smart contracts using python and django.
If you found this article helpful, please leave a heart and interactions are welcome in the comment section.

Top comments (0)