Skip to main content

Python

Javascript is not the only language that gives you the ability to interact with your deployed smart contract. Python also offers this capability through the web3 pypi package.

NOTE

Before starting this tutorial it is recommended to go through the EVM Javascript documentation to see how to deploy the HelloWorld.sol contract that we will be interacting with. If you already know how to deploy an EVM smart contract on the peaq/krest/agung network you can skip this step.

  • Contract deployment network: agung
  • EVM development environment: Hardhat
  • Contract language: Solidity
  • Contract interaction language: Python

Getting Started

We will be using the same previously deployed smart contract from the EVM Javascript doc to streamline the process. If you have already completed those sequences of steps, then you are ready to write an interaction script in Python, rather than the previously shown Javascript.

1. Download Python

Ensure that you have python installed. Some common ways to check for installation is by running the cmds: python --version or python3 --version in your cmd line. Download python if is not previously installed.

2. Install Dependencies

Web3: Allows the interaction with EVM deployed contracts in python.

pip install web3

Dotenv: Provides basic protection for secret variables.

pip install python-dotenv
INFORMATION

Your cmds may be different based on how you installed python.

3. Create Python File

Add a new file in the scripts directory called interact.py from the previously referenced Javascript tutorial. Doing so will allow us to connect to the contract's abi found in the artifacts directory that was created during contract compilation. Also, we will have access to the same environmental variables. evm-python-1

4. Writing the Contract

Below is a sample interact.py script you can copy and paste to see basic smart contract interaction.

import json
import os

from web3 import Web3
from dotenv import load_dotenv

# Load environment variables from .env file
load_dotenv()

# Access environment variables
agung_url = os.getenv('AGUNG_RPC_URL')
private_key = os.getenv('PRIVATE_KEY')

CONTRACT_ADDRESS = "" # Your deployed contract address
ABI = './artifacts/contracts/HelloWorld.sol/HelloWorld.json' # Path to Hardhat artifact JSON file

def write(web3, contract, new_string):
# Account & 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.setHello(new_string)
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(agung_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)

# Perform a simple read
greeting = contract.functions.hello().call()
print(greeting)

new_string = "Goodbye World"
# Write function is more complex as we have to build the transaction.
# Put into a separate function
write(web3, contract, new_string)

# Observe how the greeting has been changed
print(contract.functions.hello().call())

# change it back
new_string = "Hello World"
write(web3, contract, new_string)

# Observe how the greeting has been changed
print(contract.functions.hello().call())


main()

NOTE

Do not hardcode transaction values. Use your web3 instance to obtain the chainId, gas, gasPrice, and nonce to optimize your transaction. See code comments above for clarity.

Hurray! You have now used python to interact with your smart contract on the peaq/krest/agung network.