Create new instance of web3.py
Note: You need to have a RPC_URL to connect to the blockchain
from web3 import Web3
w3_instance = Web3(Web3.HTTPProvider("<RPC_URL>")
assert w3_instance.is_connected()
Get storage at address (usefull to get private variables):
Note: You need to have a web3 instance (see previous snippet)
storage = w3_instance.eth.get_storage_at("<ADDRESS>", <INT_INDEX>)
# Example:
storage = w3_instance.eth.get_storage_at("0xfce177A183CDff53910b5399Ee3ADcC982c1b5bE", 0)
w3_instance.eth.get_block(<INT_INDEX>, <BOOL_FULL_TRANSACTION>)
w3_instance.eth.get_block(0, True)
from solcx import compile_source
contract_code = open("MyContract.sol", "r").read()
compiled = compile_source(
contract_code,
output_values=['abi', 'bin']
)
contract_interface = compiled['<stdin>:MyContract']
bytecode = contract_interface['bin']
abi = contract_interface['abi']
contract = w3_instance.eth.contract(address=contract_address, abi=abi, bytecode=bytecode)
Get public variables or view/pure functions:
Note: You need to have a contract instance (see previous snippet)
contract.functions.solver().call()
Call transact function (my_awesome_function):
Transact function need to be called with a private key and a caller address
private_key = "<PRIVATE_KEY>"
caller = "<CALLER_ADDRESS>"
Chain_id = w3_instance.eth.chain_id
nonce = w3_instance.eth.get_transaction_count(caller)
tx_data = {"chainId": Chain_id, "from": caller, "nonce": nonce}
call_function = contract.functions.my_awesome_function().build_transaction(tx_data)
signed_tx = w3_instance.eth.account.sign_transaction(call_function, private_key=private_key)
send_tx = w3_instance.eth.send_raw_transaction(signed_tx.rawTransaction)
tx_receipt = w3_instance.eth.wait_for_transaction_receipt(send_tx)
print(tx_receipt)
You can also call payable function you just need to add the value, and gas in the tx_data:
Note: Gas and gasPrice need to be calculated before.
tx_data = {'nonce': nonce, 'to': contract_address, 'value': 500000000000000000, 'gas': <INT_GAS>, 'gasPrice': <INT_GAS_PRICE> }