import json
import os
from web3 import Web3
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv()
# Access environment variables
RPC_URL = os.getenv('RPC_URL')
PRIVATE_KEY = os.getenv('PRIVATE_KEY')
CONTRACT_ADDRESS = "" # Your deployed contract address
ABI = './artifacts/contracts/SimpleStorage.sol/SimpleStorage.json' # Path to Hardhat artifact JSON file
def write(web3, contract, my_number):
# Account and transaction details
from_account = web3.eth.account.from_key(PRIVATE_KEY) # object representation of your account to sign transactions
chain_id = web3.eth.chain_id # rpc_url chain id that is connected to web3
gas_price = web3.eth.gas_price # get current gas price from the connected network
nonce = web3.eth.get_transaction_count(from_account.address) # obtain nonce from your account address
# Obtain the estimated gas based on the expected transaction and your wallet address
tx = contract.functions.set(my_number)
estimated_gas = tx.estimate_gas({'from': from_account.address})
# Build transaction object
tx = tx.build_transaction({
'chainId': chain_id,
'gas': estimated_gas,
'gasPrice': gas_price,
'nonce': nonce
})
# Sign the transaction from your account
signed_tx = from_account.sign_transaction(tx)
# Send the transaction
tx_receipt = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
tx_hash = web3.to_hex(tx_receipt)
# Wait for it to be added on chain
receipt = web3.eth.wait_for_transaction_receipt(tx_hash)
# Uncomment below to see completed transaction receipt
# print("Receipt: ", receipt)
def main():
# Create a Web3 connection instance
web3 = Web3(Web3.HTTPProvider(RPC_URL))
# Load JSON to get ABI
with open(ABI) as file:
contract_json = json.load(file)
contract_abi = contract_json['abi']
# Use contract address and abi to obtain an instance of the network deployed contract
contract = web3.eth.contract(address=CONTRACT_ADDRESS, abi=contract_abi)
# Write function is more complex as we have to build the transaction.
# Put into a separate function
my_number = 10
write(web3, contract, my_number)
# Perform a simple read
greeting = contract.functions.set().call()
print(greeting)
# change it again
my_number2 = 20
write(web3, contract, my_number2)
# Observe how the number has been changed
print(contract.functions.set().call())
main()