Solidity Smart Contract – How to Call a Function from Different Addresses Using web3.py

blockchainganachepythonweb3.py

I am a beginner with Blockchain development using python. I have a solidity smart contract with 3 functions, the first one can be called only by a ganache account A and the other functions can be called by other accounts (4 accounts in ganache: B,C,D and E).
My question is how to specify the caller of the function and how to change it?

import json
from web3 import Web3

# Set up web3 connection with Ganache
ganache_url = "http://127.0.0.1:7545"
web3 = Web3(Web3.HTTPProvider(ganache_url))

abi = json.loads('[{"constant":false,"inputs":[{"name":"_greeting","type":"string"}],"name":"setGreeting","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"greet","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"greeting","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]')
bytecode = "6060604052341561000f57600080fd5b6040805190810160405280600581526020017f48656c6c6f000000000000000000000000000000000..."

Best Answer

So, first I believe you want to deploy the contract. This works:

tx_hash = web3.eth.contract(
              abi = abi, bytecode = "0x"+bytecode
          ).constructor().transact({'from': web3.eth.accounts[0]})

contractAddress = web3.eth.get_transaction_receipt(tx_hash)['contractAddress']
contract = web3.eth.contract(address=contractAddress, abi=abi)

Notice the from argument above: we can specify who is making the transaction this way. web3.eth.accounts[0] is a wallet that ganache creates for us automatically (there are 10 total I believe).

To make a transaction using another wallet:

contract.functions.setGreeting("Hola").transact({'from': web3.eth.accounts[1]})
Related Topic