Interact with your Smart Contract on Polygon Mumbai with AMB Access

4 minute read
Content level: Foundational
3

Learn how to interact with a smart contract on Polygon Mumbai using Amazon Managed Blockchain (AMB) Access

Introduction

In this tutorial, you will learn how to interact with the smart contract that you deployed in Part 1 with Amazon Managed Blockchain (AMB) Access Polygon. This section will show you how to retrieve data from the blockchain and execute transactions to modify its state.

Prerequisites

Warning: Never share or expose your account’s private key or Accessor token publicly. It is important to note that the writeContract.js file is utilizing a locally stored private key and should not be used in production environments, as it poses a security risk.

Step 1: Read data from your contract

  1. In the root of your HelloWorldContract directory, create a file new named readContract.js and copy the following code:
const { Web3 } = require('web3');
const fs = require('fs');
require('dotenv').config();

// Set up web3 connection
const web3 = new Web3(process.env.AMB_ACCESS_POLYGON_MAINNET);

// Path to the ABI file
const abiPath = 'ignition/deployments/chain-137/artifacts/DeployHelloWorld#HelloWorld.json';

// Contract ABI and Address
const contractABI = JSON.parse(fs.readFileSync(abiPath, 'utf8')).abi;
const contractAddress = process.env.CONTRACT_ADDRESS

// Create Contract Instance
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Function to Read Data from the Contract
async function readGreeting() {
    try {
        const greeting = await contract.methods.getGreeting().call();
        console.log('Greeting from contract:', greeting);
    } catch (error) {
        console.error('Error reading greeting:', error);
    }
}

readGreeting();
  1. Read data from the contract by running:
node readContract.js

This outputs the current greeting stored in the smart contract.

Step 2: Write data to your contract

Create a new file in the root of the HelloWorldContract directory named writeContract.js and copy the following code:

const { Web3 } = require('web3');
const fs = require('fs');
require('dotenv').config();

// Set up the connection to AMB Access
const web3 = new Web3(process.env.AMB_ACCESS_POLYGON_MAINNET);

// Path to the ABI file
const abiPath = 'ignition/deployments/chain-137/artifacts/DeployHelloWorld#HelloWorld.json';

// Contract ABI and Address
const contractABI = JSON.parse(fs.readFileSync(abiPath, 'utf8')).abi;
const contractAddress = process.env.CONTRACT_ADDRESS

// Create Contract Instance
const contract = new web3.eth.Contract(contractABI, contractAddress);

// Function to Write Data to the Contract
async function writeGreeting(newGreeting) {
    try {
        // DO NOT USE AN ACCOUNT YOU USE ON MAINNET OR AN ACCOUNT THAT HAS ACTUAL FUNDS
        const wallet = web3.eth.accounts.wallet.add(process.env.PRIVATE_KEY);

        // Estimate the gas limit required for the transaction
        const gasEstimate = await contract.methods.setGreeting(newGreeting).estimateGas({ from: wallet[0].address });

        // Retrieve the current gas price from the network
        const gasPrice = await web3.eth.getGasPrice();

        // Send the transaction with the estimated gas limit and price
        await contract.methods.setGreeting(newGreeting).send({
            from: wallet[0].address,
            gas: gasEstimate,
            gasPrice: gasPrice
        });

        console.log('Greeting updated to:', newGreeting);
    } catch (error) {
        console.error('Error updating greeting:', error);
    }
}

writeGreeting("Hello, I am a Web3 Developer!"); // Call with the new greeting

Write data to the contract by running:

node writeContract.js

This script sets a new greeting message. If you would like to write a custom message, you can modify the message being passed into the writeGreeting function.

Step 3: Verifying the update

To confirm that the greeting in your contract has been updated, make another read call to your contract:

node readContract.js

This outputs the new greeting message.

Conclusion

By following these steps, you've successfully interacted with your smart contract on Polygon Mainnet using AMB Access and web3.js. This section covered performing read and write operations on the blockchain.

Please leave a comment below if you have any questions. If you would like to learn more about AMB Access Polygon, you can refer to the documentation.

profile pictureAWS
EXPERT
published 4 months ago1215 views