Send transactions on the Polygon Mumbai network with AMB Access and web3.js

6 minute read
Content level: Foundational

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


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

  • 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 Mumbai endpoint.

Step 2: Polygon account creation and environment variable setup

The following script automates the following tasks:

  1. Creation of a Polygon account (public/private key pair).
  2. Retrieval or creation of an AMB (Amazon Managed Blockchain) Mumbai Accessor token.
    • The script first checks for any existing Polygon Mumbai Accessor tokens in your AWS account. If an available token is found, it will be reused. Otherwise, a new Accessor token will be created.
  3. Configuration of an AMB Access Polygon Mumbai endpoint with your Accessor token.
    • Your configured endpoint will allow you to make JSON-RPC calls to the Polygon Mumbai testnet 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. You should only use accounts that do not have any actual funds and only conduct transactions on the Mumbai testnet to avoid the risk of losing actual funds.

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_MUMBAI";

async function createAccount(accessEndpoint) {
    const web3 = new Web3(accessEndpoint);
    const account = web3.eth.accounts.create();
    return account;

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 = `${accessor.billingToken}`;
        console.log('Creating account...');
        const account = await createAccount(accessEndpoint);
        const dataToSave = `PUBLIC_ADDRESS=${account.address}\nPRIVATE_KEY=${account.privateKey}\nAMB_ACCESS_POLYGON_MUMBAI=${accessEndpoint}`;
        await fs.writeFile('.env', dataToSave);
        console.log('Account and Accessor token created or retrieved. Details saved to .env file.');
        console.log(`Fund your newly created account (${account.address}) with testnet Polygon using a public faucet.`);
    } catch (error) {
        console.error('Setup failed:', error);


Execute the script by running:

node init.js

Your public address, private key, and endpoint for AMB Access Polygon Mumbai have been securely stored in a generated .env file.

Note: If you would like to use an existing account, modify the PUBLIC_ADDRESS and PRIVATE_KEY variables in the .env file.

Step 3: Fund your testnet Polygon account

Use a public faucet (such as Alchemy’s) to request a small amount of testnet Polygon to your newly created account's public address.

Step 4: Create the transaction script

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

const { Web3 } = require("web3");

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

    // Generate a signing account using a private key from environment variables
    // This account is used to securely sign transactions
    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 required for the transaction
        tx.gas = await web3.eth.estimateGas(tx);

        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

Execute the transaction by running:

node sendTransaction.js

Step 5: Inspect the transaction details

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


You have successfully sent a transaction on the Polygon Mumbai testnet 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
published 3 months ago1421 views