Now that your contract is deployed on the blockchain, the next step is to interact with it. Interacting with a smart contract involves calling its functions to read or modify its state. In this guide you will learn how to interact with your contract using Remix, JavaScript, and Python.

Prerequisites

  • Successful smart contract deployment.
  • The ABI and contract address from the previous deployment are recorded. Generated after compilation and deployment.
  • Funded wallet connected to the appropriate network (peaq/agung).

Instructions

Interacting Using Remix

1. Access the Deployed Contract

  • In Remix, navigate to the Deployed Contracts section in the Deploy & Run Transactions sidebar.
  • You’ll see your deployed contract listed, with an interactive UI displaying the contract’s functions.

2. Perform Write Operations

  • In the Deployed Contracts interface, locate the set function.
  • Enter an integer as an input field (e.g. 10) and click the set button.
  • A MetaMask popup will be triggered to confirm the transaction. Confirm the transaction and wait for it to be appended on-chain.
  • After completion the new value will be stored on the blockchain.

3. Perform Read Operations

  • Locate the get function in the Deployed Contracts drop down in the Deploy & Run Transactions tab.
  • Click the get button to fetch the current value stored in the contract.
  • The result will appear below the function, showing the updated value (e.g., 10).

Interacting with the Contract Using JavaScript

1. Create an Interaction Script

  • Inside the scripts/ directory of your project, create a new file named interact.js
  • Add the following script to interact with your deployed contract:
const contractAddress = "YOUR_CONTRACT_ADDRESS"; // Replace with your contract address
const ContractArtifact = require('../artifacts/contracts/SimpleStorage.sol/SimpleStorage.json');

async function main() {
    const [deployer] = await ethers.getSigners();
    const contract = new ethers.Contract(contractAddress, ContractArtifact.abi, deployer);

    // Perform a read operation
    const storedValue = await contract.get();
    console.log('Stored Value:', storedValue.toString());

    // Perform a write operation
    const tx = await contract.set(10); // Setting value to 10
    await tx.wait(); // Wait for transaction to complete

    // Verify the new value
    const updatedValue = await contract.get();
    console.log('Updated Value:', updatedValue.toString());
}

main()
    .then(() => process.exit(0))
    .catch((error) => {
        console.error(error);
        process.exit(1);
    });

2. Execute the Interaction Script

  • In the root directory of your program run the cmd to execute the code written above. The code will deploy the contract on the agung network as defined in the hardhat.config.js file.
npx hardhat run scripts/interact.js --network agung

🎉 Congratulations! You have successfully written, deployed, and interacted with a smart contract! Now let’s interact with this same contract, but now using another language - Python.

Interacting with the Contract Using Python

1. Install Dependencies

  • web3 - Allows the interaction with EVM deployed contracts in Python.
  • python-dotenv - Provides basic protection for secret variables.
pip install web3
pip install python-dotenv

2. Create Python File

  • Inside the scripts/ directory of your project, create a new file named interact.py
  • Add the following script to interact with your deployed contract:
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()

3. Execute the Interaction Script

  • To execute the code above you can use the following script:
python scripts/interact.py

After doing so, the code inside the Python file interacts with the SimpleStorage contract you made earlier! Now you understand how to get a smart contract on chain and interact with it. However, there are ways to create upgradeable smart contracts which are talked about in the next section.