Send transactions on Polygon Mainnet with AMB Access and web3.js

5 minute read
Content level: Foundational
2

Learn how to send transactions on Polygon Mainnet with Amazon Managed Blockchain (AMB) Access

Introduction

This tutorial walks you through sending a transaction on Polygon Mainnet using Amazon Managed Blockchain (AMB) Access and web3.js, a popular JavaScript library for interacting with Ethereum-compatible blockchains.

Note

In line with Polygon's deprecation of Mumbai announced on March 27 2024, we will cease support of AMB Access Mumbai on April 15 2024. AMB Access Polygon Mainnet will continue to be available as Public Preview. We will continue evaluating support for Amoy Testnet in AMB Access. Please contact us if you would like to learn more.

Prerequisites
  • Basic knowledge of JavaScript and Node.js.
  • Node.js installed on your machine.
  • A text editor (e.g., VSCode).
  • Installation of the AWS Command Line Interface (CLI).
    • Run the command aws configure to set the variables for your IAM User’s Access Key ID, Secret Access Key, and Region.
      • Ensure that this User has the appropriate IAM permissions for AMB Access Polygon. For this tutorial, you can use the AmazonManagedBlockchainFullAccess managed policy.

Step 1: Setting up the project

  1. Make a new folder for your project and change into it by running the following command in your terminal:
mkdir AMBPolygonTransaction && cd AMBPolygonTransaction
  1. Run the following command to install the necessary dependencies:
npm install web3 dotenv @aws-sdk/client-managedblockchain

Web3 enables blockchain interactions, dotenv handles environment variables, and the Managed Blockchain client is used to initialize your AMB Access Polygon Mainnet endpoint.

Step 2: Environment variable setup

The following script automates the following tasks:

  1. Retrieval or creation of an AMB Polygon Mainnet Accessor token.
    • The script first checks for any existing Polygon Mainnet Accessor tokens in your AWS account. If an available token is found, it will be reused. Otherwise, a new Accessor token will be created.
  2. Configuration of an AMB Access Polygon Mainnet endpoint with your Accessor token.
    • Your configured endpoint will allow you to make JSON-RPC calls to Polygon Mainnet with web3.js.

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

Create a new file (e.g init.js) in your directory and copy the following code:

const fs = require('fs').promises;
const { Web3 } = require('web3');
const { ManagedBlockchainClient, CreateAccessorCommand, ListAccessorsCommand, GetAccessorCommand } = require("@aws-sdk/client-managedblockchain");

const network = "POLYGON_MAINNET";

async function getExistingAccessor(client) {
    try {
        const response = await client.send(new ListAccessorsCommand({ NetworkType: network }));

        for (const accessor of response.Accessors) {
            if (accessor.Status === "AVAILABLE") {
                const accessorResponse = await client.send(new GetAccessorCommand({ AccessorId: accessor.Id }));
                return accessorResponse.Accessor;
            }
        }
    } catch (error) {
        console.error('Error retrieving existing Accessor. Please double check your AWS credentials.', error);
        throw error;
    }
    return null;
}

async function createAccessor() {
    const client = new ManagedBlockchainClient();
    const existingAccessor = await getExistingAccessor(client);

    if (existingAccessor) {
        console.log('Using existing Accessor token.');
        return {
            billingToken: existingAccessor.BillingToken
        };
    }
    else {
        console.log('Creating a new Accessor token.');
    }

    try {
        const input = {
            AccessorType: "BILLING_TOKEN",
            NetworkType: network,
        };
        const command = new CreateAccessorCommand(input);
        const response = await client.send(command);
        return {
            billingToken: response.BillingToken,
        };
    } catch (error) {
        console.error('Error creating Accessor token:', error);
        throw error;
    }
}

async function main() {
    try {
        console.log('Creating or retrieving AMB Access Polygon Accessor token...');
        const accessor = await createAccessor();
        const accessEndpoint = `https://mainnet.polygon.managedblockchain.us-east-1.amazonaws.com?billingtoken=${accessor.billingToken}`;
        const account = 'YOUR-PRIVATE-KEY';
        const dataToSave = `PRIVATE_KEY=${account}\nAMB_ACCESS_POLYGON_MAINNET=${accessEndpoint}`;
        await fs.writeFile('.env', dataToSave);
        console.log('Accessor token created or retrieved. Details saved to .env file.');
    } catch (error) {
        console.error('Setup failed:', error);
    }
}

main();

Execute the script by running:

node init.js

Your endpoint for AMB Access Polygon has been securely stored in a generated .env file.

Note: Modify the placeholder PRIVATE_KEY variable in the .env file. Make sure that your private key starts with the 0x prefix.

Step 3: Create the transaction script

Create a new file (e.g sendTransaction.js) and copy the following code:

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

async function main() {
    // Creating a connection to AMB Access Polygon Mainnet
    const web3 = new Web3(process.env.AMB_ACCESS_POLYGON_MAINNET)


    // Generate a signing account using a private key from environment variables
    // This account is used to securely sign transactions
    // ONLY USE AN ACCOUNT ON MAINNET THAT HAS A SMALL AMOUNT OF FUNDS
    const wallet = web3.eth.accounts.wallet.add(process.env.PRIVATE_KEY);

    // Defining a transaction object (specifying the sender, receiver, and amount to send)
    const tx = {
        from: wallet[0].address,
        to: "0x1E67B920828254C5cEBad802877060f1ae1e998F",
        value: web3.utils.toWei("0.001", "ether")
    };

    // Attempt to send the transaction
    try {
        // Estimate the gas limit required for the transaction.
        tx.gas = await web3.eth.estimateGas(tx);

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

        console.log(`Sending transaction ...`);
        // Send the transaction and wait for the receipt
        const receipt = await web3.eth.sendTransaction(tx);

        // Log successful transaction details
        console.log(`Transaction hash: ${receipt.transactionHash}`);
        console.log(`Transaction successful! Block: ${receipt.blockNumber.toLocaleString()}`);
    } catch (error) {
        // Log any errors encountered during the transaction
        console.error(`An error occurred: ${error.message}`);
    }
}
// Execute the main function
main();

Execute the transaction by running:

node sendTransaction.js

Step 4: Inspect the transaction details

Copy the transaction hash and examine the transaction by using the Polygon blockchain explorer.

Conclusion

You have successfully sent a transaction on Polygon Mainnet using AMB Access. This tutorial covered the basics of interacting with the blockchain by utilizing AMB Access Polygon and web3.js. Remember to prioritize security, especially with private keys and your Accessor token.

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 ago1513 views