[Ethereum] Call Smart Contract Function in Python Script

contract-invocationpythonweb3.py

My situation is reverse to most. I am relatively experienced in coding in Solidity, but have absolutely no experience in using Python.

What I would ideally like to do is have a script that will, in predetermined time intervals, call a Smart Contract Function and give it the required input, then read and possibly store the output.

I need help figuring out the "calling the function" part. Please dont just point me to web3.py, I looked it over and while it seems very useful I dont know where to start and I dont have the time to take it from the top right now. If you could provide some help specifically on what I am asking for, please do.

Thank you.

Best Answer

Here is an example using Brownie that should help:

import time
from brownie import Contract, network, web3


abi = {}          # contract ABI as a dict
address = "0x00"  # contract address as a string


network.connect('mainnet')
my_contract = Contract("MyContractName", address, abi=abi)

height = web3.eth.blockNumber

while True:
    result = my_contract.myCallableFn(arg1, arg2) # change to call the desired method
    if result == desired_result:
        # do whatever you need to do

    while web3.eth.blockNumber == height:
        time.sleep(1)
    height = web3.eth.blockNumber

You will have to modify some configuration settings to point at your own node, or set an infura API key in your environment variables.

The documentation on accessing contract methods might also be useful if my example is unclear.

Hope this helps.

Related Topic