Calling Smart Contracts From Python

Ethereum brought the advancement of a smart contract, and which is publicily verifiable code. If we change the state of a contract, it will…

Photo by Zoltan Tasi on Unsplash

Calling Smart Contracts From Python

Ethereum brought the advancement of a smart contract, and which is publicily verifiable code. If we change the state of a contract, it will cost of us some gas. Now, let’s create a Python program which can call up a smart contract on Ethereum. As we don’t want it to cost us anything, we will run Ganche, and which is a local Ethereum instance.

We first go to Remix.ethereum.org and add our code:

The code we will add includes the functions of add(), sub(), mul(), sqr() and sqrt():

Now we compile our smart contract, and which produces ABI (Application Binary Interface). With ABI we can create an abstraction of all of the data elements and functions in the smart contract. This is normally defined in a JSON format. In our case the ABI is (and which can be copied from the ABI copy button in Remix):

Next, we run up Ganache:

After this we can select Ganache as our environment:

And then deploy our smart contract:

We can see that the contract has been deployed to Block 2. The contract has been deployed to the following address:

0x1aC3CD1b37898ed4D3005f3C12b4425A6eFFDc30

For Ganache, we run it at Port 8545, and can connect to it with web.Web(). The ABI data can then be compressed into a string. We can then call the contract with we3.eth.contract():

We can then simply call the functions in the smart contract with the form of:

rtn= c.caller().add(a,b)
print(f"{a}+{b}={rtn}")

A sample run of the code verifies the call to the smart contract:

% python web.py
5+4=9
5*4=20
5-4=1
sqr(5)=25
sqrt(5)=2

And, that it! All we need to do, is to compile our smart contract, and deploy it. We then need to record the address of the smart contract and the ABI. After that, it’s a matter to calling up the functions in the smart contract.

If you are interested in Ethereum, try here:

https://asecuritysite.com/ethereum