'Is there anyway to way to use an input variable as a function call?
In my current situation, I am trying to build an application that utilizes the Web3.py Python module. The main issue that I am encountering when trying to turn my script into a full stack application is that the function calls in Web3 contracts are not all the same.
For Example:
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io'))
abi_endpoint = 'https://api.etherscan.io/api?module=contract&action=getabi&address='
project_address = '0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e'
url = ABI_ENDPOINT + project_address
response = requests.get(url)
response = response.json()
abi = json.loads(response['result'])
contract = w3.eth.contract(address=project_address, abi=abi)
total_supply = contract.functions.totalSupply().call()
I am wanting to be able to put an input variable when I call totalSupply(). The main reason I need to do this is since a lot of the contracts do not have the same function names. For instance, it could be totalApes(), MAX_SUPPLY(), or anything similar. I am just looking for a way to be able to change these things on the front-end rather than having to go change the code every time I am trying to use it.
Solution 1:[1]
I'm not really addressing your sample code but by the sounds of your question I think looking at this may help?
def func1():
print("foo")
def func2():
print("bar")
def func3(f):
f()
func3(func1)#prints foo
func3(func2)#prints bar
#A little more risky
def func4(s):
f = eval(s)
f()
func4("func1")#prints foo
func4("func2")#prints bar
Note that using eval is generally considered a security vulnerability and should only be used in select circumstances.
Solution 2:[2]
You need to use get_function_by_name() method together with the exec statement.
For example if you want to loop on the state function doFoo() doBar() doBaz() you would do:
for i in ['doFoo','doBar','doBaz']:
exec(f"var{i} = contract.get_function_by_name('{i}')")
You'll get your results in var_doFoo, var_doBar and var_doBaz
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | kpie |
| Solution 2 | Maxpm |
