# Infura tutorials

> Complete documentation for infura tutorials

This file contains all documentation content in a single document following the llmstxt.org standard.

## Authenticate with JWT


This tutorial demonstrates how to create and apply a JSON Web Token (JWT) to authenticate an
[`eth_blockNumber`](../../reference/ethereum/json-rpc-methods/eth_blocknumber.mdx) API request
with Node.js.

## Prerequisites

- [Node](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) version 20+
- A text editor (for example, [VS Code](https://code.visualstudio.com/))
- An [Infura account](https://app.infura.io/register)

## Steps

### 1. Initiate your project

Create a new directory for your project:

```bash
mkdir infura-jwt-demo
```

Next, change into the `infura-jwt-demo` directory:

```bash
cd infura-jwt-demo
```

Initialize a new Node.js project:

```bash
npm init -y
```

Install the required dependencies:

```bash
npm install axios jsonwebtoken dotenv
```

### 2. Create a key pair

#### 2.1. Generate your private key

Generate your private key using the RSA (PKCS #8) or ES256 algorithm:

<Tabs>
  <TabItem value="RSA" default>

```bash
openssl genpkey                 \
  -algorithm RSA                \
  -out private_key.pem          \
  -pkeyopt rsa_keygen_bits:2048 \
  -outform PEM
```

  </TabItem>
  <TabItem value="ES256">

```bash
openssl ecparam    \
  -genkey          \
  -name prime256v1 \
  -noout           \
  -out private_key.pem
```

  </TabItem>
</Tabs>

#### 2.2. Generate your public key

Generate your public key from your RSA or ES256 private key:

<Tabs>
  <TabItem value="RSA" default>

```bash
openssl rsa           \
  -in private_key.pem \
  -pubout             \
  -out public_key.pem
```

  </TabItem>
  <TabItem value="ES256">

```bash
openssl ec            \
  -in private_key.pem \
  -pubout             \
  -out public_key.pem
```

  </TabItem>
</Tabs>

### 3. Set up your `.env` file

#### 3.1. Update the Infura dashboard

In the [Infura dashboard](https://app.infura.io/login), under **API Keys**, select the key you want to use for authentication. Go to its **Settings** tab. Under **Requirements**, fill out these fields:

- **JWT PUBLIC KEY NAME** - Provide a unique name for your JWT public key, which can help you manage multiple keys.
- **JWT PUBLIC KEY** - Paste the entire contents of the `public_key.pem` file.

:::note

Optionally, you can check **REQUIRE JWT FOR ALL REQUESTS**. If this option is not checked, you can make calls using your key without a JWT in the request header, however, invalid or expired tokens will result in the call being rejected.

:::

#### 3.2. Create your `.env` file

At the root of your Node.js project, create an environment file:

```bash
touch .env
```

Add the following details to `.env`:

<Tabs>
  <TabItem value="Syntax" default>

```text title=".env"
INFURA_API_KEY=<YOUR-API-KEY>
JWT_KEY_ID=<YOUR-JWT-KEY-ID>
INFURA_NETWORK_URL=<NETWORK-URL>
```

  </TabItem>
  <TabItem value="Example">

```text title=".env"
INFURA_API_KEY=8c101...6b26c77d8
JWT_KEY_ID=777e2caf...826bc4303f
INFURA_NETWORK_URL=https://sepolia.infura.io/v3/
```

  </TabItem>
</Tabs>

Replace the following values in the `.env` file:

- `<YOUR-API-KEY>` with your API key from the Infura dashboard.
- `<YOUR-JWT-KEY-ID>` with the JWT's key ID. This is generated by Infura, and you can find it in the Infura dashboard. The code in [Step 4](#4-create-and-apply-your-jwt) applies this ID to the JWT header to allow Infura to identify which key was used to sign the JWT.
- `<NETWORK-URL>` with the URL of an Infura network for which your key has access rights, and that supports the method [`eth_blockNumber`](../../reference/ethereum/json-rpc-methods/eth_blocknumber.mdx).

:::warning Important

Before pushing code to a public repository, add `.env` to your `.gitignore` file. This reduces the likelihood that keys are exposed in public repositories.

Note that `.gitignore` ignores only untracked files. If your `.env` file was committed in the past, it's tracked by Git. Untrack the file by deleting it and running `git rm --cached .env`, then include it in `.gitignore`.

:::

### 4. Create and apply your JWT

Create a new file named `call.js`:

```bash
touch call.js
```

Add the following to `call.js`:

```javascript title="call.js"
require('dotenv').config()
const axios = require('axios')
const jwt = require('jsonwebtoken')
const fs = require('fs')

function getAlgorithm(privateKey) {
  if (privateKey.includes('BEGIN RSA PRIVATE KEY') || privateKey.includes('BEGIN PRIVATE KEY')) {
    return 'RS256'
  } else if (privateKey.includes('BEGIN EC PRIVATE KEY')) {
    return 'ES256'
  } else {
    throw new Error('Unsupported key type')
  }
}

// Function to generate the JWT
function generateJWT() {
  const privateKey = fs.readFileSync('private_key.pem', 'utf8')
  const algorithm = getAlgorithm(privateKey)
  const token = jwt.sign({}, privateKey, {
    algorithm: algorithm, // Dynamically set the algorithm based on the key type
    keyid: process.env.JWT_KEY_ID,
    audience: 'infura.io',
    expiresIn: '1h',
    header: {
      typ: 'JWT',
    },
  })

  return token
}

// Function to authenticate with Infura and get the latest block number
async function getBlockNumber() {
  const jwtToken = generateJWT()
  const url = `${process.env.INFURA_NETWORK_URL}${process.env.INFURA_API_KEY}`
  const data = {
    jsonrpc: '2.0',
    method: 'eth_blockNumber',
    params: [],
    id: 1,
  }

  try {
    const response = await axios.post(url, data, {
      headers: {
        Authorization: 'Bearer ' + jwtToken,
        'Content-Type': 'application/json',
      },
    })
    console.log('Block number:', response.data.result)
  } catch (error) {
    console.error(
      'Error fetching block number:',
      error.response ? error.response.data : error.message
    )
  }
}

// Call the function to get latest block
getBlockNumber()
```

Next, run the code:

```bash
node call.js
```

Your console outputs the response, for example:

```bash
Block number: 0x61fc48
```

:::tip

This script:

1. Generates a JWT with a 1-hour expiry that is only valid on `infura.io`.
2. Applies this JWT to form the header of a `getBlockNumber` call.
3. Submits the API call.

:::

### (Optional) Examine the curl equivalent

If you want to better understand the code applied in [Step 4](#4-create-and-apply-your-jwt), you can examine the equivalent curl request.

Create a new file named `curl.js`:

```bash
touch curl.js
```

Add the following to `curl.js`:

```javascript title="curl.js"
require('dotenv').config()
const jwt = require('jsonwebtoken')
const fs = require('fs')

function getAlgorithm(privateKey) {
  if (privateKey.includes('BEGIN RSA PRIVATE KEY') || privateKey.includes('BEGIN PRIVATE KEY')) {
    return 'RS256'
  } else if (privateKey.includes('BEGIN EC PRIVATE KEY')) {
    return 'ES256'
  } else {
    throw new Error('Unsupported key type')
  }
}

// Function to generate the JWT
function generateJWT() {
  const privateKey = fs.readFileSync('private_key.pem', 'utf8')
  const algorithm = getAlgorithm(privateKey)
  const token = jwt.sign({}, privateKey, {
    algorithm: algorithm, // Dynamically set the algorithm based on the key type
    keyid: process.env.JWT_KEY_ID,
    audience: 'infura.io',
    expiresIn: '1h',
    header: {
      typ: 'JWT',
    },
  })
  return token
}

// Generate the JWT and print the curl command
async function printCurlRequest() {
  const jwtToken = generateJWT()
  console.log('Generated JWT:', jwtToken)
  const curlRequest = `
    curl -X POST ${process.env.INFURA_NETWORK_URL}${process.env.INFURA_API_KEY} \\
      -H "Authorization: Bearer ${jwtToken}" \\
      -H "Content-Type: application/json" \\
      -d '{
        "jsonrpc": "2.0",
        "method": "eth_blockNumber",
        "params": [],
        "id": 1
      }'
      `
  console.log('Equivalent curl request:')
  console.log(curlRequest)
}

// Call the function to print the curl request
printCurlRequest()
```

Next, run the code:

```bash
node curl.js
```

Your console outputs the curl request, for example:

```bash
curl -X POST https://sepolia.infura.io/v3/<YOUR-API-KEY> \
  -H "Authorization: Bearer pqJhbG**JWT-token**2Ud5o2Q" \
  -H "Content-Type: application/json" \
  -d '{
    "jsonrpc": "2.0",
    "method": "eth_blockNumber",
    "params": [],
    "id": 1
  }'
```

You can run this request yourself to make the call. Your console outputs the response, for example:

```bash
{"jsonrpc":"2.0","id":1,"result":"0x61fc48"}
```

## Next steps

Consider following these next steps:

- [Configure your JWT](../../how-to/json-web-token-jwt.md) to control its scope.
- Decode your JWT: Copy the JWT provided in the console by the [optional curl equivalent step](#optional-examine-the-curl-equivalent), and paste it into the **Encoded** field in [jwt.io](https://jwt.io/).
- Add a layer of verification to your call by applying the JWT's **FINGERPRINT** provided in the Infura dashboard.

  :::note

  The JWT's fingerprint is a hash of the public key, used to ensure the key's integrity and authenticity.

  :::

---

## Call a contract


This tutorial uses Web3.js to execute a function in a smart contract. Calling the contract function is a type of transaction that requires paying gas.

## Prerequisites

Before attempting this tutorial, ensure you completed the tutorial to [deploy a contract](deploy-a-contract-using-web3.js.md) and [updated the `.env` file with the smart contract address](deploy-a-contract-using-web3.js.md#10-update-the-env-file).

## Steps

### 1. Create a script to execute the contract

In the `deployContract` folder created [earlier](deploy-a-contract-using-web3.js.md#2-create-a-project-directory), create the JavaScript file that executes a contract function and signs the transaction.

In this example we'll create the `call.js` file with the following contents:

```javascript
const { Web3 } = require('web3')

// Loading the contract ABI
// (the results of a previous compilation step)
const fs = require('fs')
const { abi } = JSON.parse(fs.readFileSync('Demo.json'))

async function main() {
  // Configuring the connection to an Ethereum node
  const network = process.env.ETHEREUM_NETWORK
  const web3 = new Web3(
    new Web3.providers.HttpProvider(`https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`)
  )
  // Creating a signing account from a private key
  const signer = web3.eth.accounts.privateKeyToAccount('0x' + process.env.SIGNER_PRIVATE_KEY)
  web3.eth.accounts.wallet.add(signer)
  // Creating a Contract instance
  const contract = new web3.eth.Contract(
    abi,
    // Replace this with the address of your deployed contract
    process.env.DEMO_CONTRACT
  )
  // Issuing a transaction that calls the `echo` method
  const method_abi = contract.methods.echo('Hello, world!').encodeABI()
  const tx = {
    from: signer.address,
    to: contract.options.address,
    data: method_abi,
    value: '0',
    gasPrice: '100000000000',
  }
  const gas_estimate = await web3.eth.estimateGas(tx)
  tx.gas = gas_estimate
  const signedTx = await web3.eth.accounts.signTransaction(tx, signer.privateKey)
  console.log('Raw transaction data: ' + signedTx.rawTransaction)
  // Sending the transaction to the network
  const receipt = await web3.eth
    .sendSignedTransaction(signedTx.rawTransaction)
    .once('transactionHash', txhash => {
      console.log(`Mining transaction ...`)
      console.log(`https://${network}.etherscan.io/tx/${txhash}`)
    })
  // The transaction is now on chain!
  console.log(`Mined in block ${receipt.blockNumber}`)
}

require('dotenv').config()
main()
```

### 2. Call the contract

Run the script to call the smart contract:

```
node call.js
```

:::info

If you receive an `insufficient funds for gas` error, then you may need to top up your signer account with some testnet ETH.

:::

The script will display the details of the transaction in the output. View the transaction in a block explorer such as Etherscan.

---

## Deploy a contract using web3.js


In this tutorial, you'll create a simple smart contract and use the Web3 JavaScript library to compile and then deploy the smart contract.

## Prerequisites

- An [Ethereum project](../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)
- An Ethereum account for testing purposes

:::info

You can use [MetaMask](https://metamask.io) or similar to create an Ethereum account for testing purposes.

:::

## Steps

### 1. Fund your Ethereum account

[Use the MetaMask faucet to load testnet ETH](https://docs.metamask.io/developer-tools/faucet/) on your Ethereum account for the Sepolia network.

If using a network other than Sepolia, ensure you [update your environment file](deploy-a-contract-using-web3.js.md#10-update-the-env-file) with the network name.

### 2. Create a project directory

Create a new directory for your project. You can do this from the command line:

```bash
mkdir deployContract
```

Change into the new directory:

```bash
cd deployContract
```

### 3. Install required packages

Install the `web3`, `solc`, and `dotenv` packages in the project directory.

:::info

The [`dotenv`](../../how-to/javascript-dotenv.md) package allows you to use a `.env` file to securely store private environment variables on your local machine.

:::

Install the `web3` package:

```
npm install web3
```

:::info

This example has been written for web3js v4.x. It may not work for earlier versions.

:::

Install the solidity compiler (`solc` package):

```
npm install solc
```

Install the `dotenv` package:

```
npm install dotenv
```

### 4. Create the `.env` file

Create a `.env` file in your project directory to store the project and Ethereum account details.

```
ETHEREUM_NETWORK = "sepolia"
INFURA_API_KEY = "<YOUR-API-KEY>"
SIGNER_PRIVATE_KEY = "<YOUR-PRIVATE-KEY>"
```

Ensure you replace the following values in the `.env` file:

- `<YOUR-API-KEY>` with the API key of the Ethereum project.
- `<Private-Key>` with the [private key of your Ethereum account](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key).
- If using a network other than Sepolia, ensure you update `ETHEREUM_NETWORK` with the network name.

:::danger

Never disclose your private key. Anyone with your private keys can steal any assets held in your account.

:::

### 5. Create a smart contract

Using an editor, create a smart contract. In this example, we'll create a basic contract called `Demo.sol`.

```javascript
pragma solidity >=0.5.8;

contract Demo {
    event Echo(string message);

    function echo(string calldata message) external {
        emit Echo(message);
    }
}
```

### 6. Create the compile script

We need to compile the contract to ensure the code is correct.

:::info

You can compile the smart contract using the [`solc` command line options](https://docs.soliditylang.org/en/develop/using-the-compiler.html). In this example, we'll create a compile script using JavaScript.

:::

Create a file called `compile.js` with the following content:

```javascript
const fs = require('fs').promises
const solc = require('solc')

async function main() {
  // Load the contract source code
  const sourceCode = await fs.readFile('Demo.sol', 'utf8')
  // Compile the source code and retrieve the ABI and Bytecode
  const { abi, bytecode } = compile(sourceCode, 'Demo')
  // Store the ABI and Bytecode into a JSON file
  const artifact = JSON.stringify({ abi, bytecode }, null, 2)
  await fs.writeFile('Demo.json', artifact)
}

function compile(sourceCode, contractName) {
  // Create the Solidity Compiler Standard Input and Output JSON
  const input = {
    language: 'Solidity',
    sources: { main: { content: sourceCode } },
    settings: { outputSelection: { '*': { '*': ['abi', 'evm.bytecode'] } } },
  }
  // Parse the compiler output to retrieve the ABI and Bytecode
  const output = solc.compile(JSON.stringify(input))
  const artifact = JSON.parse(output).contracts.main[contractName]
  return {
    abi: artifact.abi,
    bytecode: artifact.evm.bytecode.object,
  }
}

main()
```

### 7. Run the compile script

In the [compile script](deploy-a-contract-using-web3.js.md#6-create-the-compile-script) we'll also copy the generated [Application Binary Interface (ABI)](https://docs.soliditylang.org/en/develop/abi-spec.html) and binary to a file called `Demo.json`.

To compile the contract run the following command:

```
node compile.js
```

A file called `Demo.json` should be created in the directory.

### 8. Create the deployment script

Next, we'll create a deployment script called `deploy.js`. The script uses the Web3 methods to sign the transaction and deploy the smart contract to the network.

```javascript
const { Web3 } = require('web3')

// Loading the contract ABI and Bytecode
// (the results of a previous compilation step)
const fs = require('fs')
const { abi, bytecode } = JSON.parse(fs.readFileSync('Demo.json'))

async function main() {
  // Configuring the connection to an Ethereum node
  const network = process.env.ETHEREUM_NETWORK
  const web3 = new Web3(
    new Web3.providers.HttpProvider(`https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`)
  )
  // Creating a signing account from a private key
  const signer = web3.eth.accounts.privateKeyToAccount('0x' + process.env.SIGNER_PRIVATE_KEY)
  web3.eth.accounts.wallet.add(signer)

  // Using the signing account to deploy the contract
  const contract = new web3.eth.Contract(abi)
  contract.options.data = bytecode
  const deployTx = contract.deploy()
  const deployedContract = await deployTx
    .send({
      from: signer.address,
      gas: await deployTx.estimateGas(),
    })
    .once('transactionHash', txhash => {
      console.log(`Mining deployment transaction ...`)
      console.log(`https://${network}.etherscan.io/tx/${txhash}`)
    })
  // The contract is now deployed on chain!
  console.log(`Contract deployed at ${deployedContract.options.address}`)
  console.log(
    `Add DEMO_CONTRACT to the .env file to store the contract address: ${deployedContract.options.address}`
  )
}

require('dotenv').config()
main()
```

### 9. Deploy the contract

Run the deployment script to deploy the contract to the blockchain:

```
node deploy.js
```

The contract deploys to the blockchain and the script displays the contract address.

To make calls to the contract in the future we'll need the contract address. Next we'll update the `.env` file to store the contract address.

### 10. Update the .env file

Update the .`env` file in the working directory to include the contract address. In this example, we'll add the `DEMO_CONTRACT` variable:

```
ETHEREUM_NETWORK = "sepolia"
INFURA_API_KEY = "<YOUR-API-KEY>"
SIGNER_PRIVATE_KEY = "<YOUR-PRIVATE-KEY>"
DEMO_CONTRACT = "<Contract_Address>"
```

## Next steps

You can now make [calls to the deployed contract](call-a-contract.md). A contract call is a transaction that will consume gas on the public Ethereum network.

---

## Monitor transfers using Python


In this tutorial, you'll monitor transfers to an Ethereum account using the Web3 Python library.

## Prerequisites

- [Pip](https://pip.pypa.io/en/stable/installation/) installed

## Steps

### 1. Create a project directory

Create a new directory for your project. This can be done from the command line:

```bash
mkdir monitorTransfer
```

Change into the new directory:

```bash
cd monitorTransfer
```

### 2. Install required packages

Install the `web3.py` package:

```bash
pip install web3
```

### 3. Create a script file

Create a file called `monitorTransactions.py`. At the top of file, add the following lines to import the `web3.py` library:

```python
from web3 import Web3

```

### 4. Connect to Infura

Connect to the Infura endpoint and the address of the account:

```python
infura_url = "https://mainnet.infura.io/v3/<YOUR-API-KEY>"
account = "<YOUR-PUBLIC-ADDRESS>"
web3 = Web3(Web3.HTTPProvider(infura_url))
```

:::warning

Replace `<YOUR-API-KEY>` with your Infura API key and `<YOUR-PUBLIC-ADDRESS>` with the Ethereum account you want to monitor.

:::

### 5. Set the function

Create a function to check new transactions for the account defined in [step 3](#3-create-a-script-file) and retrieves the details for the transaction:

```python
def watch():
  while True:
    block = web3.eth.get_block("latest")
    print("Searching in block " + str(block.number))

    if block and block.transactions:
      for transaction in block.transactions:
        tx_hash = transaction.hex()  # the hashes are stored in a hexBytes format
        tx = web3.eth.get_transaction(tx_hash)
        if tx.to is not None:
          if tx.to == account:
            print("Transaction found in block {} :".format(block.number))
            print({
              "hash": tx_hash,
              "from": tx["from"],
              "value": web3.from_wei(tx["value"], "ether")
            })
    time.sleep(5)

watch()
```

### 6. Check for confirmations

Exchanges often wait until a deposit has reached a certain number of confirmations before processing the new transaction. The number of confirmations is the number of blocks that have passed since the transaction was included onchain. By checking that a transaction has reached the specified number of confirmations, the exchange can be confident that this transaction is final and they can process the deposit.

Create a function to determine the number of confirmations for the transaction:

```python
def confirmations(tx_hash):
  tx = web3.eth.get_transaction(tx_hash)
  return web3.eth.block_number - tx.blockNumber
```

You can then call the function using something similar to:

```python
print(confirmations(tx_hash))
```

### 7. Run the script

Run the script using the following command:

<Tabs>
  <TabItem value="Command" label="Command" default>

```python
python3 monitorTransactions.py
```

  </TabItem>
  <TabItem value="Example output" label="Example output" >

```python
Searching in block 15019035
Transaction found in block 15019035 :
{"hash": "0x0f878eb882dfd069c482740df533e0ddef63504d795dcc3c934c3f9a6c159362", "from": "0x95B564F3B3BaE3f206aa418667bA000AFAFAcc8a", "value": 0}
Transaction found in block 15019035 :
{"hash": "0xee75ed766e17fef1cae917686b5b73e7c72b2fcf51e1558629b8fe96a7e5a1bd", "from": "0x9696f59E4d72E237BE84fFD425DCaD154Bf96976", "value": 0}
Transaction found in block 15019035 :
{"hash": "0x1cddbeff3ac97651f5d7e49e98f4289aeef728e08b05180c75bc04cdc970895d", "from": "0x21a31Ee1afC51d94C2eFcCAa2092aD1028285549", "value": 0}
...
67341
```

  </TabItem>
</Tabs>

### Complete code overview

```python
from web3 import Web3

infura_url = "https://mainnet.infura.io/v3/<YOUR-API-KEY>"
account = "<YOUR-PUBLIC-ADDRESS>"
web3 = Web3(Web3.HTTPProvider(infura_url))

def confirmations(tx_hash):
  tx = web3.eth.get_transaction(tx_hash)
  return web3.eth.block_number - tx.blockNumber

def watch():
  while True:
    block = web3.eth.get_block("latest")
    print("Searching in block " + str(block.number))

    if block and block.transactions:
      for transaction in block.transactions:
        tx_hash = transaction.hex()  # the hashes are stored in a hexBytes format
        tx = web3.eth.get_transaction(tx_hash)
        if tx.to is not None:
          if tx.to == account:
            print("Transaction found in block {} :".format(block.number))
            print({
              "hash": tx_hash,
              "from": tx["from"],
              "value": web3.from_wei(tx["value"], "ether")
            })
    time.sleep(5)

watch()
# print(confirmations("0x0d40d60e118e9e1f61c2baa2252cc5f8b8ed491c885ec35db6fd6cfc8589c1a7"))
```

---

## Retrieve and display ERC-721 and ERC-1155 tokens


In this tutorial, you'll retrieve and display ERC-721 and ERC-1155 tokens using the Web3 JavaScript library.

## Prerequisites

- An [Ethereum project](../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)

## Steps

### 1. Create a project directory

Create a new directory for your project. This can be done from the command line:

```bash
mkdir retrieveBalance
```

Change into the new directory:

```bash
cd retrieveBalance
```

### 2. Install required packages

Install the `web3` package in the project directory:

```bash
npm install web3
```

:::info

This example has been written for web3js v4.x. It may not work for earlier versions.

:::

### 3. Set up the script

Create a file called `retrieveBalance.js`. At the top of the file, add the following lines to import the web3.js library and connect to the Infura HTTPS endpoint:

```javascript
const { Web3 } = require('web3')

const web3 = new Web3(
  new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/<YOUR-API-KEY>')
)
```

Replace `<YOUR-API-KEY>` with your Infura API key.

### 4. Set the ABI

For ERC-721 NFTs, use the `tokenURI` function, which is part of the ERC-721 standard. This function retrieves a token's metadata so you can view it. For ERC-1155, use the `uri` method.

Note the `tokenURI` and `uri` methods are optional for contracts. However, these methods are the only standardized onchain way of seeing NFT metadata without using a third-party API.

Define the ABI for the respective method by adding the following to the script:

<Tabs>
  <TabItem value="ERC-721" label="ERC-721" default>

```javascript
const tokenURIABI = [
  {
    inputs: [
      {
        internalType: 'uint256',
        name: 'tokenId',
        type: 'uint256',
      },
    ],
    name: 'tokenURI',
    outputs: [
      {
        internalType: 'string',
        name: '',
        type: 'string',
      },
    ],
    stateMutability: 'view',
    type: 'function',
  },
]
```

  </TabItem>
  <TabItem value="ERC-1155" label="ERC-1155" >

```javascript
const uriABI = [
  {
    constant: true,
    inputs: [
      {
        internalType: 'uint256',
        name: '_id',
        type: 'uint256',
      },
    ],
    name: 'uri',
    outputs: [
      {
        internalType: 'string',
        name: '',
        type: 'string',
      },
    ],
    payable: false,
    stateMutability: 'view',
    type: 'function',
  },
]
```

  </TabItem>
</Tabs>

### 5. Request the metadata

Define the ABI for the respective method by adding the following to the script:

<Tabs>
  <TabItem value="ERC-721" label="ERC-721" default>

```javascript
const tokenContract = '0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d'
const tokenId = 101
```

  </TabItem>
  <TabItem value="ERC-1155" label="ERC-1155" >

```javascript
const tokenContract = '0x76be3b62873462d2142405439777e971754e8e77'
const tokenId = 10570
```

  </TabItem>
</Tabs>

`tokenContract` is the address of the token contract, and `tokenId` is the ID of the specific token to display.

Define the contract using `web3.eth.Contract()`, passing the ABI and contract address as parameters:

<Tabs>
  <TabItem value="ERC-721" label="ERC-721" default>

```javascript
const contract = new web3.eth.Contract(tokenURIABI, tokenContract)
```

  </TabItem>
  <TabItem value="ERC-1155" label="ERC-1155" >

```javascript
const contract = new web3.eth.Contract(uriABI, tokenContract)
```

  </TabItem>
</Tabs>

Next, create an `async` function that interacts with the smart contract.

This calls the ABI function defined in [step 4](retrieve-and-display-erc-721-and-erc-1155-tokens.md#4-set-the-abi).

<Tabs>
  <TabItem value="ERC-721" label="ERC-721" default>

```javascript
async function getNFTMetadata() {
  const result = await contract.methods.tokenURI(tokenId).call()

  console.log(result) // ipfs://QmeSjSinHpPnmXmspMjwiXyN6zS4E9zccariGR3jxcaWtq/101
}

getNFTMetadata()
```

  </TabItem>
  <TabItem value="ERC-1155" label="ERC-1155" >

```javascript
async function getNFTMetadata() {
  const result = await contract.methods.uri(tokenId).call()

  console.log(result) // https://nftdata.parallelnft.com/api/parallel-alpha/ipfs/QmSwnqTmpwvZH51Uv47opPUxGYx2nknYmGoKoRJQRMDcLL
}

getNFTMetadata()
```

  </TabItem>
</Tabs>

### 6. Run the script

Run the script using the following command:

```bash
node retrieveBalance.js
```

### Complete code overview

<Tabs>
  <TabItem value="ERC-721" label="ERC-721" default>

```js
const { Web3 } = require('web3')

const web3 = new Web3(
  new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/<YOUR-API-KEY>')
)

const tokenURIABI = [
  {
    inputs: [
      {
        internalType: 'uint256',
        name: 'tokenId',
        type: 'uint256',
      },
    ],
    name: 'tokenURI',
    outputs: [
      {
        internalType: 'string',
        name: '',
        type: 'string',
      },
    ],
    stateMutability: 'view',
    type: 'function',
  },
]

const tokenContract = '0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d' // BAYC contract address
const tokenId = 101 // A token we'd like to retrieve its metadata of

const contract = new web3.eth.Contract(tokenURIABI, tokenContract)

async function getNFTMetadata() {
  const result = await contract.methods.tokenURI(tokenId).call()
  console.log(result)
}

getNFTMetadata()
```

  </TabItem>
  <TabItem value="ERC-1155" label="ERC-1155">

```javascript
const { Web3 } = require('web3')

const web3 = new Web3(
  new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/<YOUR-API-KEY>')
)

const uriABI = [
  {
    constant: true,
    inputs: [
      {
        internalType: 'uint256',
        name: '_id',
        type: 'uint256',
      },
    ],
    name: 'uri',
    outputs: [
      {
        internalType: 'string',
        name: '',
        type: 'string',
      },
    ],
    payable: false,
    stateMutability: 'view',
    type: 'function',
  },
]

const tokenContract = '0x76be3b62873462d2142405439777e971754e8e77' // Parallel contract address
const tokenId = 10570 // A token we'd like to retrieve its metadata of

const contract = new web3.eth.Contract(uriABI, tokenContract)

async function getNFTMetadata() {
  const result = await contract.methods.uri(tokenId).call()

  console.log(result) // https://nftdata.parallelnft.com/api/parallel-alpha/ipfs/QmSwnqTmpwvZH51Uv47opPUxGYx2nknYmGoKoRJQRMDcLL
}

getNFTMetadata()
```

  </TabItem>
</Tabs>

---

## Retrieve the balance of an ERC-20 token


In this tutorial, using Web3.js, you'll retrieve the balance of an [ERC-20 token](../../how-to/interact-with-erc-20-tokens.md) in an account, using the account address and the token contract.

## Prerequisites

- An [Ethereum project](../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)

## Steps

### 1. Create a project directory

Create a new directory for your project. This can be done from the command line:

```bash
mkdir retrieveBalance
```

Change into the new directory:

```bash
cd retrieveBalance
```

### 2. Install required packages

Install the `web3` package in the project directory:

```bash
npm install web3
```

### 3. Set up the script

Create a file called `retrieveBalance.js`. At the top of the file, add the following lines to import the web3.js library and connect to the Infura HTTPS endpoint:

```javascript
const { Web3 } = require('web3')
const web3 = new Web3(
  new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/<YOUR-API-KEY>')
)
```

Make sure to replace `<YOUR-API-KEY>` with your Infura API key.

### 4. Set the ABI

You'll only use the `balanceOf` method, so you don't need the entire ABI for ERC-20 smart contracts. In the `retrieveBalance.js` file, define the ABI for the `balanceOf` method by adding the following to the script:

```javascript
const balanceOfABI = [
  {
    constant: true,
    inputs: [
      {
        name: '_owner',
        type: 'address',
      },
    ],
    name: 'balanceOf',
    outputs: [
      {
        name: 'balance',
        type: 'uint256',
      },
    ],
    payable: false,
    stateMutability: 'view',
    type: 'function',
  },
]
```

### 5. Select a token address

To retrieve the balance of a token, you need the contract address of the token. You can find this in the tokens section of a block explorer such as [Etherscan](https://etherscan.io/).

This example uses a DAI token contract. However, you can use any ERC-20 token contract address. Copy the token contract address you wish to use.

![](../../images/contract_address.jpeg)

### 6. Request the token balance

Define the addresses to use in the `retrieveBalance.js` script:

```javascript
const tokenContract = '0x6b175474e89094c44da98b954eedeac495271d0f'
const tokenHolder = '0xf326e4de8f66a0bdc0970b79e0924e33c79f1915'
```

Define `contract` using `web3.eth.Contract()`, passing the `balanceOfABI` and the token contract address `tokenContract` as parameters:

```javascript
const contract = new web3.eth.Contract(balanceOfABI, tokenContract)
```

Next, call `methods.balanceOf()` on the `contract` and pass the `tokenHolder` address. This call sends a request to your Infura endpoint to request the token balance in the `tokenHolder` account address.

Create the below `async` function `getTokenBalance` that accomplishes this by interacting with the `tokenContract`.

```javascript
async function getTokenBalance() {
  const result = await contract.methods.balanceOf(tokenHolder).call()
  console.log(result)
}

getTokenBalance()
```

### 7. Convert the token units

By default, calling `balanceOf` returns the balance value in wei, which is the smallest unit in Ethereum, equal to 0.000000000000000001 Ether.

Use `web3.utils.fromWei(result, "ether")` to get the actual number of DAI tokens, by adding the following line to the `async` function:

```javascript
const formattedResult = web3.utils.fromWei(result, 'ether')
```

Also, update your `console.log(format)`:

```javascript
console.log(formattedResult)
```

### 8. Run the script

#### Complete code

Here is the complete code for `retrieveBalance.js`. Before running it make sure you replace `<YOUR-API-KEY>` with your Infura API key.

```javascript
const { Web3 } = require('web3')
const web3 = new Web3(
  new Web3.providers.HttpProvider('https://mainnet.infura.io/v3/<YOUR-API-KEY>')
)

const balanceOfABI = [
  {
    constant: true,
    inputs: [
      {
        name: '_owner',
        type: 'address',
      },
    ],
    name: 'balanceOf',
    outputs: [
      {
        name: 'balance',
        type: 'uint256',
      },
    ],
    payable: false,
    stateMutability: 'view',
    type: 'function',
  },
]

// DAI token contract
const tokenContract = '0x6B175474E89094C44Da98b954EedeAC495271d0F'
// A DAI token holder
const tokenHolder = '0x075e72a5eDf65F0A5f44699c7654C1a76941Ddc8'
const contract = new web3.eth.Contract(balanceOfABI, tokenContract)

async function getTokenBalance() {
  const result = await contract.methods.balanceOf(tokenHolder).call()
  const formattedResult = web3.utils.fromWei(result, 'ether')
  console.log(formattedResult)
}

getTokenBalance()
```

Run the script using the following command:

<Tabs>
  <TabItem value="Command" label="Command" default>

```bash
node retrieveBalance.js
```

  </TabItem>
  <TabItem value="Example" label="Example" >

# Example output

```bash
278916727.186877714909963561
```

  </TabItem>
</Tabs>

---

## Use ethers.js


In this tutorial, you'll send a transaction of 0.001 ETH from one account to another using the [`ethers.js`](https://docs.ethers.io/v5/) JavaScript library.

## Prerequisites

- [Node.js](https://nodejs.org/en/download/)
- An Ethereum account

:::info

Use [MetaMask](https://metamask.io) or similar to create an Ethereum account for testing.

:::

## Steps

### 1. Select your network and verify funds

- **Sepolia** - To use the Sepolia testnet, ensure that your account has Sepolia ETH.
  You can use the [MetaMask faucet](https://docs.metamask.io/developer-tools/faucet/) to add more funds.
- **Alternative network** - To use an alternative network, ensure that your account has testnet ETH for that network.
  :::info note
  When using an alternative network, you'll update your `.env` file in
  [Step 4](#4-create-a-env-file) with the alternative network name.
  :::

### 2. Create a project directory

Create a new directory for your project using the command line:

```bash
mkdir infura
```

Change into the new directory:

```bash
cd infura
```

### 3. Install required packages

Install the `ethers` and `dotenv` packages in the project directory.

:::info

The [`dotenv`](../../../how-to/javascript-dotenv.md) package allows you to use a `.env` file to securely store private environment variables on your local machine.

:::

Install the `ethers` package:

```bash
npm install --save ethers
```

Install the `dotenv` package:

```
npm install dotenv --save
```

### 4. Create a `.env` file

Create a `.env` file in your project directory to store the project and Ethereum account details:

<Tabs>
  <TabItem value="Syntax" label="Syntax" default>

```text title=".env"
ETHEREUM_NETWORK = "<NETWORK>"
INFURA_API_KEY = "<YOUR-API-KEY>"
SIGNER_PRIVATE_KEY = "<PRIVATE-KEY>"
```

</TabItem>
<TabItem value="Example" label="Example" default>

```text title=".env"
ETHEREUM_NETWORK = "sepolia"
INFURA_API_KEY = "d23...x...6e"
SIGNER_PRIVATE_KEY = "0x561...x...61df"
```

</TabItem>
</Tabs>

Replace the following values in the `.env` file:

- `<NETWORK>` with `sepolia` or the alternative network you are using.
- `<YOUR-API-KEY>` with your API key of the web3 project.
- `<PRIVATE-KEY>` with the [private key of your Ethereum account](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key/). A transaction must be signed with the sender's private key. Make sure that you prefix the `SIGNER_PRIVATE_KEY` value with `0x`. The private key you export from MetaMask isn't prefixed with `0x`.

:::danger

Never disclose your private key. Anyone with your private keys can steal the assets controlled by those keys.

:::

### 5. Create an `eip1559_tx.js` file

In the project directory, create an `eip1559_tx.js` file, which configures and sends the transaction. For example:

:::warning Important

To send test ETH to an account of your choice, update line 15 with your selected account.

:::

```javascript title="eip1559_tx.js" showLineNumbers {15}
const { ethers, parseUnits } = require('ethers')

async function main() {
  // Configuring the connection to an Ethereum node
  const network = process.env.ETHEREUM_NETWORK
  const provider = new ethers.InfuraProvider(network, process.env.INFURA_API_KEY)
  // Creating a signing account from a private key
  const signer = new ethers.Wallet(process.env.SIGNER_PRIVATE_KEY).connect(provider)

  // Creating and sending the transaction object
  const tx = await signer.sendTransaction({
    to: '0x618917c657e9F5b346c0141CB14F5D3CED65D449', // Replace with your selected account
    value: parseUnits('0.001', 'ether'),
  })
  console.log('Mining transaction...')
  console.log(`https://${network}.etherscan.io/tx/${tx.hash}`)
  // Waiting for the transaction to be mined
  const receipt = await tx.wait()
  // The transaction is now on chain!
  console.log(`Mined in block ${receipt.blockNumber}`)
}

main()
```

### 6. Execute the transaction

To execute the transaction, run:

```bash
node eip1559_tx.js
```

Example output:

```bash
Mining transaction...
https://sepolia.etherscan.io/tx/0x7c5c0061fbda9e01c1bb1269ffc7323107e2116d8f7327ee945aecc7c33d21c8
Mined in block 7587728
```

You can search for the transaction on a block explorer such as [Sepolia Etherscan](https://www.infura.io/faucet).

### (Optional) Fine tune the transaction details

To change default values, update the `signer.sendTransaction` method to include an `estimateGas` result:

```javascript title="eip1559_tx.js"
const { ethers, parseUnits } = require('ethers')

const limit = await provider.estimateGas({
  from: signer.address,
  to: '<to_address_goes_here>',
  value: parseUnits('0.001', 'ether'),
})

// Creating and sending the transaction object
const tx = await signer.sendTransaction({
  to: '<to_address_goes_here>',
  value: parseUnits('0.001', 'ether'),
  gasLimit: limit,
  nonce: await signer.getTransactionCount(),
  maxPriorityFeePerGas: parseUnits('2', 'gwei'),
  chainId: 11155111, // Sepolia
})
```

---

## Use Go


Send a regular transaction from one account to another with [Go](https://go.dev/).

## Prerequisites

- [Go](https://go.dev/doc/install) installed.
- An Ethereum account containing some [Sepolia test ETH](https://www.infura.io/faucet).

:::info

Use [MetaMask](https://metamask.io) or similar to create an Ethereum account for testing.

:::

## Steps

### 1. Create a project directory

Create a new directory:

```bash
mkdir infura
```

`cd` into the directory:

```bash
cd infura
```

### 2. Initialize the directory and install the dependencies

```bash
go mod init infura
go get github.com/ethereum/go-ethereum/common
go get github.com/ethereum/go-ethereum/core/types
go get github.com/ethereum/go-ethereum/crypto
go get github.com/ethereum/go-ethereum/rpc@v1.10.17
```

### 3. Create `eip1559_tx.go` file

```go
package main

  "context"
  "crypto/ecdsa"
  "fmt"
  "log"
  "math/big"

  "github.com/ethereum/go-ethereum/common"
  "github.com/ethereum/go-ethereum/core/types"
  "github.com/ethereum/go-ethereum/crypto"
  "github.com/ethereum/go-ethereum/ethclient"
)

func main() {
  client, err := ethclient.Dial("https://sepolia.infura.io/v3/API_KEY")
  if err != nil {
    log.Fatal(err)
  }

  privateKey, err := crypto.HexToECDSA("PRIVATE_KEY")
  if err != nil {
    log.Fatal(err)
  }

  publicKey := privateKey.Public()
  publicKeyECDSA, ok := publicKey.(*ecdsa.PublicKey)
  if !ok {
    log.Fatal("error casting public key to ECDSA")
  }

  fromAddress := crypto.PubkeyToAddress(*publicKeyECDSA)

  nonce, err := client.PendingNonceAt(context.Background(), fromAddress)
  if err != nil {
    log.Fatal(err)
  }

  value := big.NewInt(10000000000000000) // in wei (0.01 eth)
  gasLimit := uint64(21000)              // in units
  tip := big.NewInt(2000000000)          // maxPriorityFeePerGas = 2 Gwei
  feeCap := big.NewInt(20000000000)      // maxFeePerGas = 20 Gwei
  if err != nil {
    log.Fatal(err)
  }

  toAddress := common.HexToAddress("ADDRESS_TO")
  var data []byte

  chainID, err := client.NetworkID(context.Background())
  if err != nil {
    log.Fatal(err)
  }

  tx := types.NewTx(&types.DynamicFeeTx{
    ChainID:   chainID,
    Nonce:     nonce,
    GasFeeCap: feeCap,
    GasTipCap: tip,
    Gas:       gasLimit,
    To:        &toAddress,
    Value:     value,
    Data:      data,
  })

  signedTx, err := types.SignTx(tx, types.LatestSignerForChainID(chainID), privateKey)
  if err != nil {
    log.Fatal(err)
  }

  err = client.SendTransaction(context.Background(), signedTx)
  if err != nil {
    log.Fatal(err)
  }

  fmt.Printf("Transaction hash: %s", signedTx.Hash().Hex())
}
```

Replace the following values in the script:

- `<YOUR-API-KEY>` with the Infura API key.
- `<PRIVATE-KEY>` with the [private key of your Ethereum account](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key/).
- `<ADDRESS-TO>` with the address of the recipient of funds.

If using a different Ethereum network, update the URL in the script.

:::danger

Never disclose your private key.

A malicious actor who has access to your private key can steal your assets.

:::

### 4. Execute the transaction

Run the script:

```bash
go run eip1559_tx.go
```

Example output:

```
Transaction hash: 0x47ed277bdfee88902f971510a7cd7b4c55722ea06488e697fb05dc99454e51ab
```

You can search for the transaction on a block explorer like [Sepolia Etherscan](https://sepolia.etherscan.io/).

---

## Use Python


Send a regular transaction from one account to another with [Python](https://www.python.org/).

## Prerequisites

- [Node.js](https://nodejs.org/en/download/).
- An Ethereum account containing some [Sepolia test ETH](https://www.infura.io/faucet).

:::info

Use [MetaMask](https://metamask.io) or similar to create an Ethereum account for testing.

:::

## Steps

### 1. Create a project directory

Create a new directory:

```bash
mkdir infura
```

`cd` into the directory:

```bash
cd infura
```

### 2. Install the dependencies

```bash
pip install web3
```

```bash
pip install python-dotenv
```

### 3. Create `.env` file

Create a `.env` file in your project directory to store the private key of your Ethereum account.

```bash
PRIVATE_KEY = <PRIVATE-KEY>
```

Find out how to access the [private key of your Ethereum account](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key/). Make sure that you prefix the `<PRIVATE_KEY>` value with `0x`. The
private key you export from MetaMask will not be prefixed with `0x`.

:::danger

Never disclose your private key.

A malicious actor who has access to your private key can steal your assets.

:::

### 4. Create `eip1559_tx.py` file

Create a file named `eip1559_tx.py` and add the following lines of code.

```python

from dotenv import load_dotenv
from web3 import Web3, exceptions

load_dotenv()

infura_url = "https://sepolia.infura.io/v3/<YOUR-API-KEY>"
private_key = os.getenv("PRIVATE_KEY")
from_account = "<PUBLIC-KEY>"
to_account = "<RECIPIENT-PUBLIC-KEY>"
web3 = Web3(Web3.HTTPProvider(infura_url))

try:
  from_account = web3.to_checksum_address(from_account)
except exceptions.InvalidAddress:
  print(f"Invalid 'from_account' address: {from_account}")

try:
  to_account = web3.to_checksum_address(to_account)
except exceptions.InvalidAddress:
  print(f"Invalid 'to_account' address: {to_account}")

nonce = web3.eth.get_transaction_count(from_account)
tx = {
  "type": "0x2",
  "nonce": nonce,
  "from": from_account,
  "to": to_account,
  "value": web3.to_wei(0.01, "ether"),
  "maxFeePerGas": web3.to_wei("250", "gwei"),
  "maxPriorityFeePerGas": web3.to_wei("3", "gwei"),
  "chainId": 11155111
}
gas = web3.eth.estimate_gas(tx)
tx["gas"] = gas
signed_tx = web3.eth.account.sign_transaction(tx, private_key)
tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)
print("Transaction hash: " + str(web3.to_hex(tx_hash)))
```

Ensure you replace the following values in the code:

- `<YOUR-API-KEY>` with the API key of the Web3 project.
- `<PUBLIC-KEY>` with the public key associated with the private key you added in the `.env` file.
- `<RECIPIENT-PUBLIC-KEY>` With the public key of the recipient of the transfer.

If using a different Ethereum network, update the URL in the code.

### 4. Execute the transaction

Run the script:

```bash
python eip1559_tx.py
```

Example output:

```
Transaction hash: 0x30c0ef29111ca7aecc78a99149649b5076d104afa7ed2f603ff2d2ec1aa27a8c
```

You can search for the transaction on a block explorer like [Sepolia Etherscan](https://sepolia.etherscan.io/tx/0x28e414889b47ba43b00086bc3ae42ea4ea521739f77b78afcaefb1b7fe42e955).

---

## Use Viem


In this tutorial, you'll send a transaction of 0.001 ETH from one account to another using the [Viem](https://viem.sh/)
TypeScript library.

## Prerequisites

- [Node.js](https://nodejs.org/en/download/)
- [Install TypeScript](https://www.typescriptlang.org/download/)
- [Install `ts-node`](https://www.npmjs.com/package/ts-node)
- An Ethereum account

:::info
Use [MetaMask](https://metamask.io/) or similar to create an Ethereum account for testing.
:::

## Steps

### 1. Select your network and verify funds

- **Sepolia** - To use the Sepolia testnet, ensure that your account has Sepolia ETH.
  You can use the [MetaMask faucet](https://docs.metamask.io/developer-tools/faucet/) to add more funds.
- **Alternative network** - To use an alternative network, ensure that your account has testnet ETH
  for that network.

  :::note
  When using an alternative network, update the chain name in the script (in Step 6) with the
  alternative network name from the [Viem supported chains list](https://github.com/wevm/viem/blob/main/src/chains/index.ts).
  :::

### 2. Create a project directory

Create a new directory for your project using the command line:

```bash
mkdir infura
```

Change into the new directory:

```bash
cd infura
```

### 3. Initialize the project

Create a `package.json` file with default values:

```bash
npm init -y
```

Generate a `tsconfig.json` file, which is used to configure TypeScript compiler options:

```bash
tsc --init --resolveJsonModule true
```

### 4. Install the required packages

Install the required packages in the project directory.

```bash
npm i viem
```

```bash
npm install -D tslib @types/node
```

### 5. Create a `config.ts` file

Create a `config.ts` file in your project directory to store the private key of the sending account:

<Tabs>
  <TabItem value="Syntax" label="Syntax" default>

```tsx title="config.ts"

export const account = privateKeyToAccount('<PRIVATE-KEY>')
```

  </TabItem>
  <TabItem value="Example" label="Example" default>

```tsx title="config.ts"

export const account = privateKeyToAccount('0x561...x...61df')
```

  </TabItem>
</Tabs>

In the `config.ts` file, replace `<PRIVATE-KEY>` with the [private key of your Ethereum account](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key/).
A transaction must be signed with the sender's private key. Make sure that you prefix the private key
value with `0x`. The private key you export from MetaMask isn't prefixed with `0x`.

:::danger
Never disclose your private key. Anyone with your private keys can steal the assets controlled by those keys.
:::

### 6. Create a `sendTransaction.ts` file

In the project directory, create a `sendTransaction.ts` file, which configures and sends the transaction. For example:

```tsx

// Create a wallet client to interact with Ethereum accounts.
const walletClient = createWalletClient({
  chain: sepolia,
  transport: http('https://sepolia.infura.io/v3/<YOUR-API-KEY>'),
})

async function sendTx() {
  // Create and send the transaction object.
  const hash = await walletClient.sendTransaction({
    account,
    to: '0xc2CB3fb3924b8DE3A63C1da570a8dBaf2a533eA7',
    value: parseEther('0.001'),
  })

  console.log('Mining transaction... ')
  console.log(`Tx mined in https://sepolia.etherscan.io/tx/${hash}`)
}

sendTx()
```

In the `sendTransaction.ts` file:

- Update the `chain` name if you're using an alternative network.
- Replace `<YOUR-API-KEY>` with your Infura API key.
- Update the `to` account in the code if you wish to send test ETH to an account of your choice.

### 7. Execute the transaction

To execute the transaction, run:

```bash
ts-node sendTransaction.ts
```

:::note
`ts-node` is a TypeScript execution engine for Node.js. It allows you to run TypeScript files without
manually compiling them into JavaScript first.
:::

An alternative way to execute your transaction using Node.js is to compile your `sendTransaction.ts` file to JavaScript
first, and then run the compiled JavaScript file:

```jsx
tsc sendTransaction.ts
node sendTransaction.js
```

You can also run the TypeScript file, `sendTransaction.ts`, directly from your code development environment (such as
VS Code) without using `ts-node` or pre-compiling to JavaScript.
The following is an example output:

```bash
Mining transaction...
Tx mined https://sepolia.etherscan.io/tx/0x310588719e733118f50c0a1608e13b4e8bd5eb5891d546d89795c2041833abb6
```

You can search for the transaction on a block explorer such as [Sepolia Etherscan](https://sepolia.etherscan.io/).

### 8. (Optional) Fine tune the transaction details

Viem automatically determines the gas limit and fees. If you want to change the default values, update
the `sendTransaction` method to include an `estimateGas` result (`gasLimit`) and the `maxFeePerGas` and
`maxPriorityFeePerGas` parameters.

To do this you will also need to declare an `httpClient` to interface with JSON-RPC methods like `eth_estimateGas`.

The following is a full code overview:

```tsx

// Create a wallet client to interact with Ethereum accounts.
const walletClient = createWalletClient({
  chain: sepolia,
  transport: http('https://sepolia.infura.io/v3/<YOUR-API-KEY>'),
})

// Create a public client to interact with JSON-RPC API methods.
const httpClient = createPublicClient({
  chain: sepolia,
  transport: http('https://sepolia.infura.io/v3/<YOUR-API-KEY>'),
})

async function sendTx() {
  // Estimate gas limit.
  const limit = await httpClient.estimateGas({
    account,
    to: '0xc2CB3fb3924b8DE3A63C1da570a8dBaf2a533eA7',
    value: parseEther('0.001'),
  })

  // Create and send the transaction object.
  const hash = await walletClient.sendTransaction({
    account,
    to: '0xc2CB3fb3924b8DE3A63C1da570a8dBaf2a533eA7',
    value: parseEther('0.001'),
    maxFeePerGas: parseGwei('20'),
    maxPriorityFeePerGas: parseGwei('2'),
    gas: limit,
  })

  console.log('Mining transaction... ')
  console.log(`Tx: https://sepolia.etherscan.io/tx/${hash}`)
}

sendTx()
```

---

## Use Ethers.js `InfuraProvider` or `Web3Provider`


In this tutorial, you'll create a simple React app to show the differences between using the
Ethers.js library's `InfuraProvider` and `Web3Provider` methods to send a transaction.

The key difference is that with `Web3Provider`, you can load the private key from a web3 wallet
(for example, MetaMask), while `InfuraProvider` needs a wallet created locally with a stored private key.

This tutorial uses the Sepolia testnet.

## Prerequisites

- Install [MetaMask](https://metamask.io) and create an Ethereum account for testing purposes.
- Load Sepolia ETH into your wallet from the [MetaMask faucet](https://docs.metamask.io/developer-tools/faucet/).
- [Node.js and npm installed](https://nodejs.org/en/download/).

You can run the following to confirm that Node and npm are installed:

```bash
node -v && npm -v
```

:::info

This tutorial was tested using ethers v5.7.2 and Node.js v16.17.0.

:::

## Steps

### 1. Create the React app

In the terminal, run the following command to create an app called `my-app`:

```bash
npx create-react-app my-app
```

Change into the project directory:

```bash
cd my-app
```

### 2. Install ethers.js

Install `ethers.js` in the project directory.

```
npm install --save ethers
```

### 3. Create the environment variables

Create a `.env` file in your project directory to store the project and Ethereum account details.

```
REACT_APP_API_KEY="<YOUR-API-KEY>"
REACT_APP_PRIVATE_KEY="<PRIVATE-KEY>"
```

Ensure you replace the following values in the `.env` file:

- `<YOUR-API-KEY>` with the API key of the Ethereum project.
- `<PRIVATE-KEY>` with the [private key of your Ethereum account](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key/).

:::danger

Never disclose your private key. Anyone with your private keys can steal any assets held in your account.

:::

### 4. Build the app

:::info

You can [copy the complete code sample from the final section](use-ethers.js-infuraprovider-or-web3provider.md#complete-code-sample).

:::

#### Import dependencies and create providers

Import the required dependencies and create the providers for communicating with the blockchain.

In the `src` directory open the `App.js` file. Remove the existing code and add the following code:

```javascript title="App.js"

function App() {
  const ethers = require('ethers')
  const API_KEY = process.env.REACT_APP_API_KEY
  const PRIVATE_KEY = process.env.REACT_APP_PRIVATE_KEY
  const provider_Metamask = new ethers.providers.Web3Provider(window.ethereum)
  const infuraProvider = new ethers.providers.InfuraProvider('sepolia', API_KEY)
}
export default App
```

#### Maintain the app state

Next, use the `useState` hook function to maintain the state of the app. Add the following code below the `const` declarations (inside the `App()` declaration):

```javascript title="App.js"
// Use the useState hook function to add state variables to a functional component.
const [blockNumber, setBlockNumber] = useState(null)
const [txSent, setTxSent] = useState(null)
const [txSentInfura, setTxSentInfura] = useState(null)
```

#### Create the app frontend

Next, create the app front-end that includes two forms for sending the transactions, and buttons for each provider to fetch the latest block number.

```javascript title="App.js"
// Configure the app frontend
return (
  
    <header className="App-header">
       Press one of the buttons to find out the latest block number: 
      
        <button onClick={handleButton1}>InfuraProvider</button>
        <button onClick={handleButton2}>Web3Provider</button>
        {blockNumber}
      
       Fill out the form to send a transaction via Web3Provider: 
      
        <form onSubmit={handleSubmitWeb3}>
          <input type="text" name="address" placeholder="Recipient Address" />
          <input type="text" name="amount" placeholder="Amount (ETH)" />
          <input type="submit" value="Send w/ Web3Provider" />
        </form>
        {txSent}
      
       Fill out the form to send a transaction via InfuraProvider: 
      
        <form onSubmit={handleSubmitInfura}>
          <input type="text" name="address" placeholder="Recipient Address" />
          <input type="text" name="amount" placeholder="Amount (ETH)" />
          <input type="submit" value="Send w/ InfuraProvider" />
        </form>
        {txSentInfura}
      
    </header>
  
)
```

#### Retrieve the latest block number

Create the code to retrieve the latest block number. Add the following code above the `return` statement.

```javascript
// Get the latest block using the InfuraProvider or wallet
const handleButton1 = async () => {
  const latest_block = await infuraProvider.getBlockNumber('latest')
  setBlockNumber(latest_block)
}

const handleButton2 = async () => {
  const latest_block = await provider_Metamask.getBlockNumber('latest')
  setBlockNumber(latest_block)
}
```

#### Send the transaction

To send the transaction, you need the target address and the amount to send. Add the following code below the code that retrieves the latest block number.

```javascript
// Handle the form submissions to send the transactions
const handleSubmitWeb3 = async e => {
  e.preventDefault()
  const data = new FormData(e.target)
  const address = data.get('address')
  const amount = data.get('amount')
  sendTransaction(address, amount)
}

const handleSubmitInfura = async e => {
  e.preventDefault()
  const data = new FormData(e.target)
  const address = data.get('address')
  const amount = data.get('amount')
  const signer = new ethers.Wallet(PRIVATE_KEY, infuraProvider)
  sendTransaction(address, amount, signer)
}
```

Next, create the `sendTransaction()` function that sends the transaction. Place the following code below the two `handleSubmit` methods.

```javascript
// Send the transaction using either the Web3Provider or InfuraProvider
const sendTransaction = async (address, amount, signer = null) => {
  if (signer == null) {
    // Web3 Provider
    if (!window.ethereum) console.error('No wallet found!')
    else {
      await window.ethereum.send('eth_requestAccounts')
      const provider = new ethers.providers.Web3Provider(window.ethereum)
      const signer = provider.getSigner()
      const tx = await signer.sendTransaction({
        to: address,
        value: ethers.utils.parseEther(amount),
      })
      console.log('tx', tx)
      setTxSent('Transaction initiated! Tx hash: ' + tx.hash)
    }
  } // InfuraProvider
  else {
    const tx = await signer.sendTransaction({
      to: address,
      value: ethers.utils.parseEther(amount),
    })
    console.log('tx', tx)
    setTxSentInfura('Transaction initiated! Tx hash: ' + tx.hash)
  }
}
```

### 5. Run the app

Run the app from the root of the directory:

```
npm start
```

:::warning

If you are using Create React App version >=5 you may run into issues building, such as:

```
Module not found: Error: Can't resolve 'crypto' in 'C:\Users\Username\Projects\testProject\client\node_modules\eth-lib\lib'

BREAKING CHANGE: webpack < 5 used to include polyfills for node.js core modules by default.
This is no longer the case. Verify if you need this module and configure a polyfill for it.
```

This is because Node.js polyfills are not included in the latest version of Create React App.

[Follow these instructions to resolve the issue](https://github.com/ChainSafe/web3.js#web3-and-create-react-app).

:::

In the app, notice that when you try and send a transaction using Web3Provider, the app opens a MetaMask instance to transfer your funds.

  

If you transfer funds using the InfuraProvider, then the funds are transferred directly from your app.

  

## Complete code sample

The complete code sample looks like this:

```javascript

function App() {
  const ethers = require('ethers')
  const API_KEY = process.env.REACT_APP_API_KEY
  const PRIVATE_KEY = process.env.REACT_APP_PRIVATE_KEY
  const provider_Metamask = new ethers.providers.Web3Provider(window.ethereum)
  const infuraProvider = new ethers.providers.InfuraProvider('mainnet', API_KEY)

  // Use the useState hook function to add state variables to a functional component.
  const [blockNumber, setBlockNumber] = useState(null)
  const [txSent, setTxSent] = useState(null)
  const [txSentInfura, setTxSentInfura] = useState(null)

  // Get the latest block using the InfuraProvider or wallet
  const handleButton1 = async () => {
    const latest_block = await infuraProvider.getBlockNumber('latest')
    setBlockNumber(latest_block)
  }

  const handleButton2 = async () => {
    const latest_block = await provider_Metamask.getBlockNumber('latest')
    setBlockNumber(latest_block)
  }

  // Handle the form submissions to send the transactions
  const handleSubmitWeb3 = async e => {
    e.preventDefault()
    const data = new FormData(e.target)
    const address = data.get('address')
    const amount = data.get('amount')
    sendTransaction(address, amount)
  }

  const handleSubmitInfura = async e => {
    e.preventDefault()
    const data = new FormData(e.target)
    const address = data.get('address')
    const amount = data.get('amount')
    const signer = new ethers.Wallet(PRIVATE_KEY, infuraProvider)
    sendTransaction(address, amount, signer)
  }

  // Send the transaction using either the Web3Provider or InfuraProvider
  const sendTransaction = async (address, amount, signer = null) => {
    if (signer == null) {
      // Web3 Provider
      if (!window.ethereum) console.error('No wallet found!')
      else {
        await window.ethereum.send('eth_requestAccounts')
        const provider = new ethers.providers.Web3Provider(window.ethereum)
        const signer = provider.getSigner()
        const tx = await signer.sendTransaction({
          to: address,
          value: ethers.utils.parseEther(amount),
        })
        console.log('tx', tx)
        setTxSent('Transaction initiated! Tx hash: ' + tx.hash)
      }
    } // InfuraProvider
    else {
      const tx = await signer.sendTransaction({
        to: address,
        value: ethers.utils.parseEther(amount),
      })
      console.log('tx', tx)
      setTxSentInfura('Transaction initiated! Tx hash: ' + tx.hash)
    }
  }

  // Configure the app frontend
  return (
    
      <header className="App-header">
         Press one of the buttons to find out the latest block number: 
        
          <button onClick={handleButton1}>InfuraProvider</button>
          <button onClick={handleButton2}>Web3Provider</button>
          {blockNumber}
        
         Fill out the form to send a transaction via Web3Provider: 
        
          <form onSubmit={handleSubmitWeb3}>
            <input type="text" name="address" placeholder="Recipient Address" />
            <input type="text" name="amount" placeholder="Amount (ETH)" />
            <input type="submit" value="Send w/ Web3Provider" />
          </form>
          {txSent}
        
         Fill out the form to send a transaction via InfuraProvider: 
        
          <form onSubmit={handleSubmitInfura}>
            <input type="text" name="address" placeholder="Recipient Address" />
            <input type="text" name="amount" placeholder="Amount (ETH)" />
            <input type="submit" value="Send w/ InfuraProvider" />
          </form>
          {txSentInfura}
        
      </header>
    
  )
}

export default App
```

---

## Use Rust


In this two-part tutorial we'll use Rust and the [ethers-rs library](https://docs.rs/ethers/latest/ethers/) to:

- Send a legacy transaction `("type":"0x0")`
- Send an EIP-1559 transaction `("type":"0x2")`

This tutorial uses the Sepolia testnet. Also see [Transaction types](../../../concepts/transaction-types.md).

## Prerequisites

- Make sure that you have test ETH in your MetaMask wallet. You can obtain test ETH for the Sepolia network using the
  [Infura Sepolia faucet](https://www.infura.io/faucet/sepolia).
- [Install Rust from The Cargo Book](https://doc.rust-lang.org/cargo/getting-started/installation.html).

## Send a legacy transaction

### 1. Create a new project

Open a terminal and create a new project:

```Rust
cargo new infura_rs
```

This creates the `infura_rs` directory with the following structure:

```text
infura_rs
├── Cargo.toml
└── src
    └── main.rs
```

:::info

Refer to the [Cargo documentation](https://doc.rust-lang.org/cargo/getting-started/first-steps.html) for more information about getting started with Cargo.

:::

### 2. Edit the dependencies

Open `Cargo.toml` with your preferred editor and add the following dependencies to it:

```toml
[dependencies]
ethers = "2.0"
eyre = "0.6.8"
hex = "0.4.3"
tokio = { version = "1.28.2", features = ["full"] }
serde_json = "1.0.96"
```

### 3. Update the main code

Open the Rust source `src/main.rs` and replace its contents with the following code:

```rust showLineNumbers
use ethers::{
  core::{types::TransactionRequest},
  middleware::SignerMiddleware,
  providers::{Http, Middleware, Provider},
  signers::{LocalWallet, Signer},
  utils,
  prelude::*
};
use eyre::Result;
use std::convert::TryFrom;

#[tokio::main]
async fn main() -> Result<()> {
  // Connect to the network
  let provider = Provider::<Http>::try_from("https://sepolia.infura.io/v3/INFURA_API_KEY")?;

  let chain_id = provider.get_chainid().await?;

  // Define the signer.
  // Replace the SIGNER_PRIVATE_KEY with
  // the private key of your Ethereum account (without the 0x prefix).
  // However, we recommend that you load it from
  // an .env file or external vault.
  let wallet: LocalWallet = "SIGNER_PRIVATE_KEY"
    .parse::<LocalWallet>()?
    .with_chain_id(chain_id.as_u64());

  let to_address = "0xAED01C776d98303eE080D25A21f0a42D94a86D9c";

  // Connect the wallet to the provider
  let client = SignerMiddleware::new(provider, wallet);

  // Craft the transaction
  // The below code knows how to figure out the
  // default gas value and determine the next nonce
  // so you do not need to explicitly add them.
  let tx = TransactionRequest::new()
    .to(to_address)
    .value(U256::from(utils::parse_ether(0.01)?));

  // Send it!
  let pending_tx = client.send_transaction(tx, None).await?;

  // Get the mined tx
  let receipt = pending_tx.await?.ok_or_else(|| eyre::format_err!("tx dropped from mempool"))?;
  let tx = client.get_transaction(receipt.transaction_hash).await?;

  println!("Sent tx: {}\n", serde_json::to_string(&tx)?);
  println!("Tx receipt: {}", serde_json::to_string(&receipt)?);

  Ok(())
}
```

Next, make the following updates to the above code:

- On line 16 replace the `INFURA_API_KEY` with you API key from the
  [Infura dashboard](/dashboard/get-started/create-api).
- On line 26 replace the `SIGNER_PRIVATE_KEY` with the private key of your Ethereum account.
- On line 29, use a test address, such as [`0xAED01C776d98303eE080D25A21f0a42D94a86D9c`](https://sepolia.etherscan.io/address/0xaed01c776d98303ee080d25a21f0a42d94a86d9c).

:::tip Secure your keys

To better secure your keys, follow the recommended approach described in the section [Create the .env file](use-web3.js.md#4-create-a-env-file).

:::

### 4. Run the code

From the `infura_rs` directory, run the code.

```rust
cargo run
```

You will see an output similar to the following:

:::note Use the wrap button
Use the wrap button on the top right of the below code block window for wrapped display.
:::

```log
Compiling infura_rs v0.1.0 (/Users/rajkaramchedu/onboarding/traian-tutorials/infura_rs)
Finished dev [unoptimized + debuginfo] target(s) in 2.14s
Running `target/debug/infura_rs`

Sent tx:
{
  "hash": "0x3cb5a5fac18e889457905351c9950108873a8f0789fe83e8a733b8367f49a67a",
  "nonce": "0x1",
  "blockHash": "0xa2787f5ec22d491588a8ffc6e7cec3ed97fccac4845e448650d02fce672a657c",
  "blockNumber": "0x3a7608",
  "transactionIndex": "0x3d",
  "from": "0xe33fef60722ba79989aeaa1b6e6daf7f351c0fbb",
  "to": "0xaed01c776d98303ee080d25a21f0a42d94a86d9c",
  "value": "0x2386f26fc10000",
  "gasPrice": "0x3cc",
  "gas": "0x5208",
  "input": "0x",
  "v": "0x1546d71",
  "r": "0x92aa9fe6039946db5ea291a245529a5d67f5531e95d74c483fe8283cca9ec666",
  "s": "0x4a5c0de8e64c79659965fb36f2b0ea1d295ae868f5f65809ef4cf1ef55239e09",
  "type": "0x0",
  "chainId": "0xaa36a7"
}

Tx receipt:
{
  "transactionHash": "0x3cb5a5fac18e889457905351c9950108873a8f0789fe83e8a733b8367f49a67a",
  "transactionIndex": "0x3d",
  "blockHash": "0xa2787f5ec22d491588a8ffc6e7cec3ed97fccac4845e448650d02fce672a657c",
  "blockNumber": "0x3a7608",
  "from": "0xe33fef60722ba79989aeaa1b6e6daf7f351c0fbb",
  "to": "0xaed01c776d98303ee080d25a21f0a42d94a86d9c",
  "cumulativeGasUsed": "0x406e87",
  "gasUsed": "0x5208",
  "contractAddress": null,
  "logs": [],
  "status": "0x1",
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "type": "0x0",
  "effectiveGasPrice": "0x3cc"
}
```

In the above transaction receipt, the transaction type shows `"type":"0x0"` indicating that this was a legacy transaction. Next, we will send an EIP-1559 transaction, which is of the type `"type":"0x2"`.

## Send an EIP-1559 transaction

### 1. Modify the main code

To send an EIP-1559 transaction, use `Eip1559TransactionRequest` instead of `TransactionRequest` in the `main.rs` code. Replace the code in `main.rs` with the following code.

```rust showLineNumbers
use ethers::{
  core::{types::TransactionRequest},
  middleware::SignerMiddleware,
  providers::{Http, Middleware, Provider},
  signers::{LocalWallet, Signer},
  utils,
  prelude::*
};
use eyre::Result;
use std::convert::TryFrom;
use types::Eip1559TransactionRequest;

#[tokio::main]
async fn main() -> Result<()> {
  // Connect to the network
  let provider = Provider::<Http>::try_from("https://sepolia.infura.io/v3/INFURA_API_KEY")?;

  let chain_id = provider.get_chainid().await?;

  // Define the signer.
  // Replace the SIGNER_PRIVATE_KEY with
  // the private key of your Ethereum account (without the 0x prefix).
  // However, we recommend that you load it from
  // an .env file or external vault.
  let wallet: LocalWallet = "SIGNER_PRIVATE_KEY"
    .parse::<LocalWallet>()?
    .with_chain_id(chain_id.as_u64());

  let to_address = "0xAED01C776d98303eE080D25A21f0a42D94a86D9c";

  // Connect the wallet to the provider
  let client = SignerMiddleware::new(provider, wallet);

  // Craft the transaction
  // This also knows to estimate the `max_priority_fee_per_gas`
  // but added it manually just to see how it would look
  let tx = Eip1559TransactionRequest::new()
    .to(to_address)
    .value(U256::from(utils::parse_ether(0.01)?))
    .max_priority_fee_per_gas(U256::from(2000000000_u128)); // 2 Gwei

  // Send it!
  let pending_tx = client.send_transaction(tx, None).await?;

  // Get the mined tx
  let receipt = pending_tx.await?.ok_or_else(|| eyre::format_err!("tx dropped from mempool"))?;
  let tx = client.get_transaction(receipt.transaction_hash).await?;

  println!("Sent tx: {}\n", serde_json::to_string(&tx)?);
  println!("Tx receipt: {}", serde_json::to_string(&receipt)?);

  Ok(())
}
```

### 2. Run the modified code

From the `infura_rs` directory, run the code:

```rust
cargo run
```

An output similar to the following is displayed:

```log
Compiling infura_rs v0.1.0 (/Users/rajkaramchedu/onboarding/traian-tutorials/infura_rs)
warning: unused import: `types::TransactionRequest`
 --> src/main.rs:2:12
  |
2 |     core::{types::TransactionRequest},
  |            ^^^^^^^^^^^^^^^^^^^^^^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

warning: `infura_rs` (bin "infura_rs") generated 1 warning (run `cargo fix --bin "infura_rs"` to apply 1 suggestion)
Finished dev [unoptimized + debuginfo] target(s) in 2.42s
Running `target/debug/infura_rs`

Sent tx:
{
  "hash": "0xbbc036f4dfe00b590c3693b8a2516316dec5748b3e4085ec92dfc040d8b8492b",
  "nonce": "0x4",
  "blockHash": "0xe64a029af23b18738a69c6eab19b85d99dc2844e8ce54a4bedcc1a75fe18dc08",
  "blockNumber": "0x3a7a42",
  "transactionIndex": "0xf",
  "from": "0xe33fef60722ba79989aeaa1b6e6daf7f351c0fbb",
  "to": "0xaed01c776d98303ee080d25a21f0a42d94a86d9c",
  "value": "0x2386f26fc10000",
  "gasPrice": "0x7735940c",
  "gas": "0x5208",
  "input": "0x",
  "v": "0x1",
  "r": "0xa0e4125501b3146910750408adaa255cd3e3a06461e311e1146a0983fcd9b0e0",
  "s": "0x35c5c6cf6650dcff0ed1e25689d0ce17f7f5986342276f11651976c7048172d1",
  "type": "0x2",
  "accessList": [],
  "maxPriorityFeePerGas": "0x77359400",
  "maxFeePerGas": "0xb2d05e16",
  "chainId": "0xaa36a7"
}

Tx receipt:
{
  "transactionHash": "0xbbc036f4dfe00b590c3693b8a2516316dec5748b3e4085ec92dfc040d8b8492b",
  "transactionIndex": "0xf",
  "blockHash": "0xe64a029af23b18738a69c6eab19b85d99dc2844e8ce54a4bedcc1a75fe18dc08",
  "blockNumber": "0x3a7a42",
  "from": "0xe33fef60722ba79989aeaa1b6e6daf7f351c0fbb",
  "to": "0xaed01c776d98303ee080d25a21f0a42d94a86d9c",
  "cumulativeGasUsed": "0x6a7187",
  "gasUsed": "0x5208",
  "contractAddress": null,
  "logs": [],
  "status": "0x1",
  "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
  "type": "0x2",
  "effectiveGasPrice": "0x7735940c"
}
```

Ignore the `"warning: unused import: types::TransactionRequest"`.
In the above transaction receipt, the transaction type shows `"type":"0x2"` indicating that this was an EIP-1559 transaction.

---

## Use web3.js


In this tutorial, you'll send a regular transaction of 0.001 ETH from one account to another using the Web3 JavaScript library.

## Prerequisites

- A [Web3 project](../../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)
- An Ethereum account

:::info

Use [MetaMask](https://metamask.io) or similar to create an Ethereum account for testing.

:::

## Steps

### 1. Select your network and verify funds

- **Sepolia** - To use the Sepolia testnet, ensure that your account has Sepolia ETH.
  You can use the [MetaMask faucet](https://docs.metamask.io/developer-tools/faucet/) to add more funds.
- **Alternative network** - To use an alternative network, ensure that your account has testnet ETH for that network.
  :::info note
  When using an alternative network, you'll:
  - Update your `.env` file in [Step 4](#4-create-a-env-file) with the alternative network name.
  - Update the `chaindId` in [Step 5](#5-create-a-sendjs-file) with the alternative network chain ID.
    :::

### 2. Create a project directory

Create a new directory for your project. This can be done from the command line:

```bash
mkdir sendTransaction
```

Change into the new directory:

```bash
cd sendTransaction
```

### 3. Install required packages

Install the `web3` and `dotenv` packages in the project directory.

:::info

The [`dotenv`](../../../how-to/javascript-dotenv.md) package allows you to use a `.env` file to securely store private environment variables on your local machine.

:::

Install the `web3` package:

```
npm install web3
```

Install the `dotenv` package:

```
npm install dotenv --save
```

### 4. Create a `.env` file

Create a `.env` file in your project directory to store the project and Ethereum account details.

<Tabs>
  <TabItem value="Syntax" label="Syntax" default>

```text title=".env"
ETHEREUM_NETWORK = "<NETWORK>"
INFURA_API_KEY = "<YOUR-API-KEY>"
SIGNER_PRIVATE_KEY = "<PRIVATE-KEY>"
```

</TabItem>
<TabItem value="Example" label="Example" default>

```text title=".env"
ETHEREUM_NETWORK = "sepolia"
INFURA_API_KEY = "d23...x...6e"
SIGNER_PRIVATE_KEY = "0x561...x...61df"
```

</TabItem>
</Tabs>

Replace the following values in the `.env` file:

- `<NETWORK>` with `sepolia` or the alternative network you are using.
- `<YOUR-API-KEY>` with your API key of the web3 project.
- `<PRIVATE-KEY>` with the [private key of your Ethereum account](https://support.metamask.io/configure/accounts/how-to-export-an-accounts-private-key/). A transaction must be signed with the sender's private key. Make sure that you prefix the `SIGNER_PRIVATE_KEY` value with `0x`. The private key you export from MetaMask isn't prefixed with `0x`.

:::danger

Never disclose your private key. Anyone with your private keys can steal the assets controlled by those keys.

:::

### 5. Create a `send.js` file

In the project directory, create a `send.js` file, which configures and sends the transaction.
For example:

:::warning Important

- To send test ETH to an account of your choice, update line 20 with your selected account.
- If you are using an alternative network to Sepolia, update the `chainId` in line 39 with your
  network chain ID.

:::

```javascript title="send.js" showLineNumbers {20,39}
const { Web3 } = require('web3')
const { ETH_DATA_FORMAT, DEFAULT_RETURN_FORMAT } = require('web3')
async function main() {
  // Configuring the connection to an Ethereum node
  const network = process.env.ETHEREUM_NETWORK
  const web3 = new Web3(
    new Web3.providers.HttpProvider(`https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`)
  )
  // Creating a signing account from a private key
  const signer = web3.eth.accounts.privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY)
  web3.eth.accounts.wallet.add(signer)
  await web3.eth
    .estimateGas(
      {
        from: signer.address,
        to: '0xAED01C776d98303eE080D25A21f0a42D94a86D9c', // Replace with your selected account
        value: web3.utils.toWei('0.0001', 'ether'),
      },
      'latest',
      ETH_DATA_FORMAT
    )
    .then(value => {
      limit = value
    })

  // Creating the transaction object
  const tx = {
    from: signer.address,
    to: '0xAED01C776d98303eE080D25A21f0a42D94a86D9c',
    value: web3.utils.toWei('0.0001', 'ether'),
    gas: limit,
    nonce: await web3.eth.getTransactionCount(signer.address),
    maxPriorityFeePerGas: web3.utils.toWei('3', 'gwei'),
    maxFeePerGas: web3.utils.toWei('90', 'gwei'),
    chainId: 11155111, // If you're not using Sepolia, replace with your network chain ID
    type: 0x2,
  }
  signedTx = await web3.eth.accounts.signTransaction(tx, signer.privateKey)
  console.log('Raw transaction data: ' + signedTx.rawTransaction)
  // Sending the transaction to the network
  const receipt = await web3.eth
    .sendSignedTransaction(signedTx.rawTransaction)
    .once('transactionHash', txhash => {
      console.log(`Mining transaction ...`)
      console.log(`https://${network}.etherscan.io/tx/${txhash}`)
    })
  // The transaction is now on chain!
  console.log(`Mined in block ${receipt.blockNumber}`)
}
require('dotenv').config()
main()
```

### 6. Execute the transaction

To execute the transaction, run:

```bash
node send.js
```

The terminal displays a log similar to the following. Select the URL to view the transaction details.

```bash
Raw transaction data:
0x02f87383aa36a78084b2d05e0084b2d05e0082520894aed01c776d98303ee080d25a21f0a42d94a86d9c865af3107a400080c080a058b88e1e01517ecaab0349f838aa07cbc90297679b2bbf2f48fa6f53b02ae358a00564373fe50e923d87f1da8d7805533c71cf81af32d66b3b2f45e972e4896fde
Mining transaction ...
https://sepolia.etherscan.io/tx/0x31581c7ac2020de48d48363171fb3406f19fd14e67575695dafba51295959049
Mined in block 3773903
```

---

## Send an ERC-20 token


In this tutorial we'll use Rust and the [ethers-rs library](https://docs.rs/ethers/latest/ethers/) to send an ERC-20 token from one address to another. This tutorial uses the Sepolia testnet and sends the [Chainlink token (LINK)](https://sepolia.etherscan.io/token/0x779877a7b0d9e8603169ddbd7836e478b4624789#code).

## Prerequisites

- Make sure that you have test LINK in your MetaMask wallet. You can obtain test LINK for the Sepolia network using the [Chainlink faucet](https://faucets.chain.link/). Make sure that the `Ethereum Sepolia` network is selected on the top right of the faucet page when you connect your MetaMask wallet.
- [Install Rust from The Cargo Book](https://doc.rust-lang.org/cargo/getting-started/installation.html).

## Send the token

### 1. Create a new project

Open a terminal and create a new project.

```Rust
cargo new infura_rs
```

This creates the `infura_rs` directory with the following structure:

```text
infura_rs
├── Cargo.toml
└── src
    └── main.rs
```

:::info

Refer to the [Cargo documentation](https://doc.rust-lang.org/cargo/getting-started/first-steps.html) for more information about getting started with Cargo.

:::

### 2. Edit the dependencies

Open `Cargo.toml` with your preferred editor and add the following dependencies to it:

```toml
[dependencies]
ethers = "2.0"
eyre = "0.6.8"
hex = "0.4.3"
tokio = { version = "1.28.2", features = ["full"] }
serde_json = "1.0.96"
```

### 3. Copy the contract ABI

- Create a text file with the name `ct.json` in the `infura-rs` project directory. Visit the [ChainLink Token site on Etherscan](https://sepolia.etherscan.io/token/0x779877a7b0d9e8603169ddbd7836e478b4624789#code) and copy the `Contract ABI` (you will see it in a bottom section of the page) into the `ct.json` file.

### 4. Update the main code

Open the Rust source `src/main.rs` and replace its contents with the following code:

```rust showLineNumbers
use ethers::{
  middleware::SignerMiddleware,
  providers::{Http, Middleware, Provider},
  signers::{LocalWallet, Signer},
  types::{Address, U256},
  contract::abigen
};
use eyre::Result;
use std::convert::TryFrom;
use std::sync::Arc;
use serde_json::Value;

#[tokio::main]
async fn main() -> Result<()> {
  // connect to the network, don't forget to replace your INFURA_API_KEY
  let provider = Provider::<Http>::try_from("https://sepolia.infura.io/v3/INFURA_API_KEY")?;

  let chain_id = provider.get_chainid().await?;

  let contract_address = "0x779877A7B0D9E8603169DdbD7836e478b4624789".parse::<Address>()?;

  // define a `ERC20Contract` struct from the ABI
  abigen!(ERC20Contract, "./ct.json",);

  let to_address = "0xF1B792820b52e6503208CAb98ec0B7b89ac64D6A".parse::<Address>()?;

  // Create the contract instance to let us call methods of the contract and let it sign transactions with the sender wallet.
  // for simplicity replace the private key (without 0x), ofc it always recommended to load it from an .env file or external vault
  let wallet: LocalWallet = "SIGNER_PRIVATE_KEY"
    .parse::<LocalWallet>()?
    .with_chain_id(chain_id.as_u64());

  let signer = Arc::new(SignerMiddleware::new(provider, wallet.with_chain_id(chain_id.as_u64())));
  let contract = ERC20Contract::new(contract_address, signer);

  // Fetch the decimals used by the contract so we can compute the decimal amount to send.
  let whole_amount: u64 = 1;
  let decimals = contract.decimals().call().await?;
  let decimal_amount = U256::from(whole_amount) * U256::exp10(decimals as usize);

  // Transfer the desired amount of tokens to the `to_address`
  let tx = contract.transfer(to_address, decimal_amount);
  let pending_tx = tx.send().await?;
  let _mined_tx = pending_tx.await?;

  println!("Transaction Receipt: {}", serde_json::to_string(&_mined_tx)?);

  // Extract the tx hash for printing
  let json_str = serde_json::to_string(&_mined_tx)?;
  let json: Value = serde_json::from_str(&json_str)?;

  if let Some(transaction_hash) = json["transactionHash"].as_str() {
    println!("\n URL: https://sepolia.etherscan.io/tx/{}", transaction_hash);
  } else {
    println!("Transaction Hash not found");
  }

  Ok(())
}
```

Next, make the following updates to the above code:

- On line 17 replace the `INFURA_API_KEY` with the API key of your API project from the
  [Infura dashboard](https://app.infura.io/login).
- On line 30 replace the `SIGNER_PRIVATE_KEY` with the private key of your Ethereum account.

:::tip Secure your keys
To better secure your keys, follow the recommended approach described in the section [Create the .env file](send-a-transaction/use-web3.js.md#4-create-a-env-file).
:::

### 4. Run the code

From the `infura_rs` directory, run the code.

```rust
cargo run
```

You will see an output similar to the following.
:::note Use the wrap button
Use the wrap button on the top right of the below code block window for wrapped display.
:::

```log
Finished dev [unoptimized + debuginfo] target(s) in 0.31s
     Running `target/debug/infura_rs`
Transaction Receipt: {"transactionHash":"0x301ae601943c5a1822886bf36e58c289ef942ca4bb08226ea3090b685aef9c7e","transactionIndex":"0x4","blockHash":"0xba6c880b14a7927ed2b6a5ac4e434d13d051dc770fe5f68666bb4d9b9ee1faed","blockNumber":"0x3a91b7","from":"0xe33fef60722ba79989aeaa1b6e6daf7f351c0fbb","to":"0x779877a7b0d9e8603169ddbd7836e478b4624789","cumulativeGasUsed":"0xd4673","gasUsed":"0x86fe","contractAddress":null,"logs":[{"address":"0x779877a7b0d9e8603169ddbd7836e478b4624789","topics":["0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef","0x000000000000000000000000e33fef60722ba79989aeaa1b6e6daf7f351c0fbb","0x000000000000000000000000f1b792820b52e6503208cab98ec0b7b89ac64d6a"],"data":"0x0000000000000000000000000000000000000000000000000de0b6b3a7640000","blockHash":"0xba6c880b14a7927ed2b6a5ac4e434d13d051dc770fe5f68666bb4d9b9ee1faed","blockNumber":"0x3a91b7","transactionHash":"0x301ae601943c5a1822886bf36e58c289ef942ca4bb08226ea3090b685aef9c7e","transactionIndex":"0x4","logIndex":"0x7","removed":false}],"status":"0x1","logsBloom":"0x00000004000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000008000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000010000000000000000000000040000001000000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000082000000000000000000000000000000008000000100000000000000000000000000008000000000000000000000000000000000000000000000000000","type":"0x2","effectiveGasPrice":"0xb2d05e09"}

 URL: https://sepolia.etherscan.io/tx/0x301ae601943c5a1822886bf36e58c289ef942ca4bb08226ea3090b685aef9c7e
```

Visit the URL displayed at the bottom of the above terminal log to confirm the transfer of the LINK token.

---

## Subscribe to pending transactions


This tutorial shows you how to use Ethereum subscriptions to listen for new transactions on the blockchain as they get submitted.

The tutorial uses the Python `websockets` library and Infura's WebSocket endpoint to subscribe to transactions and events on the blockchain.

## Prerequisites

- An [Ethereum project](../../get-started/infura.md) on Infura
- [Python installed](https://www.python.org/downloads/)

## Steps

### 1. Create your project directory

Create a new directory:

```bash
mkdir subscribe
```

`cd` into the directory:

```bash
cd subscribe
```

### 2. Install dependencies

Install `web3.py` and the `websockets` library:

```
pip install web3 websockets
```

### 3. Import project libraries

Create your file (for example `subscribe.py`) and import the libraries needed for the project:

```python

from web3 import Web3
from websockets import connect
```

### 4. Connect to Infura

Connect to Infura's WebSockets endpoint to subscribe to new pending transactions, and Infura's HTTP Ethereum endpoint so we can make JSON-RPC calls such as `eth_get_transaction` to get more information about a specific transaction.

Define the following endpoints in your file:

```python
infura_ws_url = "wss://mainnet.infura.io/ws/v3/<YOUR-API-KEY>"
infura_http_url = "https://mainnet.infura.io/v3/<YOUR-API-KEY>"
web3 = Web3(Web3.HTTPProvider(infura_http_url))
```

:::warning

Replace `<YOUR-API-KEY>` with your Infura API key, you can use the same for both endpoints.

:::

### 5. Subscribe to pending transactions

Create an `async` method that connects to Infura's WebSocket endpoint:

```python
async def get_event():
  async with connect(infura_ws_url) as ws:
    await ws.send('{"jsonrpc": "2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}')
    subscription_response = await ws.recv()
    print(subscription_response)  # {"jsonrpc": "2.0", "id": 1, "result": "0xd67da23f62a01f58042bc73d3f1c8936"}
```

In the method we use `ws.send()` to start a new subscription for new pending transactions, after which we get a confirmation back from the node with our subscription ID.

Next, we can await any new messages from the Infura node and print the transaction hash of every new transaction appearing on the Ethereum chain.

```python
while True:
  try:
    message = await asyncio.wait_for(ws.recv(), timeout=15)
    response = json.loads(message)
    txHash = response["params"]["result"]
    print(txHash)
  except Exception as e:
    print(f"An error occurred: {e}")
    pass
```

Finally, we'll add an `if __name__ == "__main__"` statement, so that our program runs when we execute it from a command line.

```python
if __name__ == "__main__":
  loop = asyncio.get_event_loop()
  while True:
    loop.run_until_complete(get_event())
```

The complete code sample should now look as follows:

```python

from web3 import Web3
from websockets import connect

infura_ws_url = "wss://mainnet.infura.io/ws/v3/<YOUR-API-KEY>"
infura_http_url = "https://mainnet.infura.io/v3/<YOUR-API-KEY>"
web3 = Web3(Web3.HTTPProvider(infura_http_url))

async def get_event():
  async with connect(infura_ws_url) as ws:
    await ws.send('{"jsonrpc": "2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}')
    subscription_response = await ws.recv()
    print(subscription_response)

    while True:
      try:
        message = await asyncio.wait_for(ws.recv(), timeout=15)
        response = json.loads(message)
        txHash = response["params"]["result"]
        print(txHash)
      except Exception as e:
        print(f"An error occurred: {e}")
        pass

if __name__ == "__main__":
  loop = asyncio.get_event_loop()
  while True:
    loop.run_until_complete(get_event())
```

### 6. Execute the program

Execute the program using the following:

```python
python3 subscribe.py
```

You should now see the terminal fill up with Ethereum transfers:

```
{"jsonrpc": "2.0", "id": 1, "result": "0xf1c8df0cb54ea89828976b86f2325930"}
0x9831d16f46bfe723514594e990cb3c66824a584fd849984f28adac8fb5523702
0x1c3837ceffdd48325e19754f7b84fda4effd32c0c141b7dafa90d741cdc2c8f9
0x4f8e5706c60be6482f810af9a5d9191447d55c7441f68f4019a124d04d2a40d4
0x0e90c6b1f286b6298f01f837ea8934229af680449a5e3761585cd79139fc6531
...
```

### 7. Monitor a specific address for transactions

You can update the program to monitor incoming transactions to a specific Ethereum address. Let's define an account we'd like to monitor first, outside of the `get_event()` function:

```python
account = "<YOUR_PUBLIC_ADDRESS>"
```

Then, inside the function and `try` block, append the following to check whether the recipient is the address we specified, after which it will print the transaction hash, sender address, and the value sent in Ether.

```python
tx = web3.eth.get_transaction(txHash)
if tx.to == account:
  print("Pending transaction found with the following details:")
  print({
    "hash": txHash,
    "from": tx["from"],
    "value": web3.fromWei(tx["value"], "ether")
  })
```

The full program code should now look as follows:

```python

from web3 import Web3
from websockets import connect

infura_ws_url = "wss://mainnet.infura.io/ws/v3/<YOUR-API-KEY>"
infura_http_url = "https://mainnet.infura.io/v3/<YOUR-API-KEY>"
web3 = Web3(Web3.HTTPProvider(infura_http_url))

# Used if you want to monitor ETH transactions to a specific address
account = "<YOUR_PUBLIC_ADDRESS>"

async def get_event():
  async with connect(infura_ws_url) as ws:
    await ws.send('{"jsonrpc": "2.0", "id": 1, "method": "eth_subscribe", "params": ["newPendingTransactions"]}')
    subscription_response = await ws.recv()
    print(subscription_response)

    while True:
      try:
        message = await asyncio.wait_for(ws.recv(), timeout=15)
        response = json.loads(message)
        txHash = response["params"]["result"]
        print(txHash)
        # Monitor transactions to a specific address
        tx = web3.eth.get_transaction(txHash)
        if tx.to == account:
          print("Pending transaction found with the following details:")
          print({
            "hash": txHash,
            "from": tx["from"],
            "value": web3.fromWei(tx["value"], "ether")
          })
      except Exception as e:
        print(f"An error occurred: {e}")
        pass

if __name__ == "__main__":
  loop = asyncio.get_event_loop()
  while True:
    loop.run_until_complete(get_event())
```

---

## Track ERC-20 token transfers


In this tutorial, you'll track [ERC-20 token](../../how-to/interact-with-erc-20-tokens.md) transfers from a specific address using the Web3 JavaScript library.

## Prerequisites

- An [Ethereum project](../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)

## Steps

### 1. Create a project directory

Create a new directory for your project. This can be done from the command line:

```bash
mkdir trackERC20
```

Change into the new directory:

```bash
cd trackERC20
```

### 2. Install required packages

Install the `web3` package in the project directory:

```bash
npm install web3
```

:::info

This example has been written for web3js v4.x. It may not work for earlier versions.

:::

### 3. Set up the script

Create a file called `trackERC20.js`. At the top of the file, add the following lines to import the web3.js library and connect to the Infura WebSocket endpoint:

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

async function main(){
  const web3 = new Web3("wss://mainnet.infura.io/ws/v3/<YOUR-API-KEY>");
  ...
}
main();
```

Make sure to replace `<YOUR-API-KEY>` with your Infura API key.

### 4. Set the ABI

Define the ERC-20 ABI by adding the following to the script:

```json
const abi = [
  {
    constant: true,
    inputs: [],
    name: "symbol",
    outputs: [
      {
        name: "",
        type: "string",
      },
    ],
    payable: false,
    stateMutability: "view",
    type: "function",
  },
  {
    constant: true,
    inputs: [],
    name: "decimals",
    outputs: [
      {
        name: "",
        type: "uint8",
      },
    ],
    payable: false,
    stateMutability: "view",
    type: "function",
  },
];
```

### 5. Subscribe to contract events

You can subscribe to the events that token contracts emit, allowing you to track every new token transfer as it occurs.

Add the following filter to the script, which tells the `web3.eth.subscribe` function in web3.js which events to track:

```javascript
let options = {
  topics: [web3.utils.sha3('Transfer(address,address,uint256)')],
}
```

Then, initiate the subscription by passing along the filter:

```javascript
let subscription = await web3.eth.subscribe('logs', options)
```

:::info

In [step 3](#3-set-up-the-script), you wrap the whole script in an async function `main()`, because top level await is not allowed except in recent JavaScript versions.

:::

You can also add the following lines to the script to see whether the subscription started successfully or if any errors occurred:

```javascript
subscription.on('error', err => {
  throw err
})
subscription.on('connected', nr => console.log('Subscription on ERC-20 started with ID %s', nr))
```

### 6. Read ERC-20 transfers

You can set the listener for the `subscription` created in [step 5](track-erc-20-token-transfers.md#5-subscribe-to-contract-events) by adding the following lines to the script:

```javascript
subscription.on('data', event => {
  if (event.topics.length == 3) {
    // ...
  }
})
```

:::info

To verify that the `Transfer` event you catch is an ERC-20 transfer, these lines check to see whether the length of the `topics` array equals 3. This is because ERC-721 events also emit a `Transfer` event but contain four items instead.

:::

Because you can't read the event topics on their own, you must decode them using the ERC-20 ABI. Edit the listener as follows:

```javascript
subscription.on('data', event => {
  if (event.topics.length == 3) {
    let transaction = web3.eth.abi.decodeLog(
      [
        {
          type: 'address',
          name: 'from',
          indexed: true,
        },
        {
          type: 'address',
          name: 'to',
          indexed: true,
        },
        {
          type: 'uint256',
          name: 'value',
          indexed: false,
        },
      ],
      event.data,
      [event.topics[0], event.topics[1], event.topics[2]]
    )
  }
})
```

You can now retrieve the sender address (`from`), receiving address (`to`), and the number of tokens transferred (`value`, though yet to be converted, see [step 7](track-erc-20-token-transfers.md#7-read-contract-data)) from the `transaction` object.

### 7. Read contract data

Even though you retrieve a `value` from the contract, this isn't the actual number of tokens transferred. ERC-20 tokens contain a `decimal` value, which indicates the number of decimals a token should have. You can directly call the `decimals` method of the smart contract to retrieve the decimal value, after which you can calculate the correct number of tokens sent.

:::note
It is optional for ERC-20 contracts to implement these methods (see [EIP-20: ERC-20 Token Standard](https://eips.ethereum.org/EIPS/eip-20#methods)), so you check for errors and fall back to default values.
:::

Outside the `subscription.on()` listener created in [step 6](track-erc-20-token-transfers.md#6-read-erc-20-transfers), define a new method that allows you to collect more information from the smart contract:

```javascript
async function collectData(contract) {
  try {
    var decimals = await contract.methods.decimals().call()
  } catch {
    decimals = 18n
  }
  try {
    var symbol = await contract.methods.symbol().call()
  } catch {
    symbol = '???'
  }
  return { decimals, symbol }
}
```

:::info

Since you're already requesting the `decimals` value from the contract, you can also request the `symbol` value to display the ticker of the token.

:::

Inside the listener, call the `collectData` function every time a new ERC-20 transaction is found. You can also calculate the correct decimal value:

```javascript
subscription.on('data', event => {
  if (event.topics.length == 3) {
    let transaction = web3.eth.abi.decodeLog(
      [
        {
          type: 'address',
          name: 'from',
          indexed: true,
        },
        {
          type: 'address',
          name: 'to',
          indexed: true,
        },
        {
          type: 'uint256',
          name: 'value',
          indexed: false,
        },
      ],
      event.data,
      [event.topics[0], event.topics[1], event.topics[2]]
    )

    const contract = new web3.eth.Contract(abi, event.address)
    collectData(contract).then(contractData => {
      var unit = Object.keys(web3.utils.ethUnitMap).find(
        key => web3.utils.ethUnitMap[key] == BigInt(10) ** contractData.decimals
      )
      if (!unit) {
        // Simplification for contracts that use "non-standard" units, e.g. REDDIT contract returns decimals==8
        unit = 'wei'
      }
      const value = web3.utils.fromWei(transaction.value, unit)
      console.log(
        `Transfer of ${value + ' '.repeat(Math.max(0, 30 - value.length))} ${
          contractData.symbol + ' '.repeat(Math.max(0, 10 - contractData.symbol.length))
        } from ${transaction.from} to ${transaction.to}`
      )
    })
  }
})
```

### 8. Track a specific address

You can track a specific sender address by reading the `from` value of the decoded `transaction` object. Add the following line to the listener created in [step 6](track-erc-20-token-transfers.md#6-read-erc-20-transfers), replacing `<SENDER_ADDRESS>` with the Ethereum address to track:

```javascript
if (transaction.from == '<SENDER_ADDRESS>') {
  console.log('Specified address sent an ERC-20 token!')
}
```

You can also track a specific recipient address receiving any tokens by tracking the `transaction.to` value:

```javascript
if (transaction.to == '<RECEIVING_ADDRESS>') {
  console.log('Specified address received an ERC-20 token!')
}
```

### 9. Track a specific token

You can track a specific address sending a specific ERC-20 token, by checking for both `transaction.from` (the token sender) and `event.address` (the ERC-20 smart contract). Add the following line to the listener created in [step 6](track-erc-20-token-transfers.md#6-read-erc-20-transfers), replacing `<SENDER_ADDRESS>` with the Ethereum address to track, and `<CONTRACT_ADDRESS>` with the smart contract address to track:

```javascript
if (transaction.from == '<SENDER_ADDRESS>' && event.address == '<CONTRACT_ADDRESS>') {
  console.log('Specified address transferred specified token!')
}
```

You can also track any transactions for a specific ERC-20 token, regardless of the sender or recipient:

```javascript
if (event.address == '<CONTRACT_ADDRESS>') {
  console.log('Specified ERC-20 transfer!')
}
```

### 10. Run the script

Run the script using the following command:

<Tabs>
  <TabItem value="Command" label="Command" default>

```bash
node trackERC20.js
```

  </TabItem>
  <TabItem value="Example output" label="Example output" >

```bash
Transfer of 9417.663694821564607555        RIO        from 0x6b75d8AF000000e20B7a7DDf000Ba900b4009A80 to 0x5b7E3E37a1aa6369386e5939053779abd3597508
Transfer of 1.554276118336708787           WETH       from 0x60594a405d53811d3BC4766596EFD80fd545A270 to 0x3fC91A3afd70395Cd496C647d5a6CC9D4B2b7FAD
Transfer of 2685                           DAI        from 0x008CE5dcC3d66e6FD7D657Ea81B54d1afFFAba4b to 0x60594a405d53811d3BC4766596EFD80fd545A270
Specified ERC-20 transfer!
Transfer of 9964.083347473883463154        RIO        from 0x5b7E3E37a1aa6369386e5939053779abd3597508 to 0x008CE5dcC3d66e6FD7D657Ea81B54d1afFFAba4b
```

  </TabItem>
</Tabs>

### Complete code overview

```javascript
const { Web3 } = require('web3')

async function main() {
  const web3 = new Web3('wss://mainnet.infura.io/ws/v3/<YOUR-API-KEY>')

  let options = {
    topics: [web3.utils.sha3('Transfer(address,address,uint256)')],
  }

  const abi = [
    {
      constant: true,
      inputs: [],
      name: 'symbol',
      outputs: [
        {
          name: '',
          type: 'string',
        },
      ],
      payable: false,
      stateMutability: 'view',
      type: 'function',
    },
    {
      constant: true,
      inputs: [],
      name: 'decimals',
      outputs: [
        {
          name: '',
          type: 'uint8',
        },
      ],
      payable: false,
      stateMutability: 'view',
      type: 'function',
    },
  ]

  let subscription = await web3.eth.subscribe('logs', options)

  async function collectData(contract) {
    try {
      var decimals = await contract.methods.decimals().call()
    } catch {
      decimals = 18n
    }
    try {
      var symbol = await contract.methods.symbol().call()
    } catch {
      symbol = '???'
    }
    return { decimals, symbol }
  }

  subscription.on('data', event => {
    if (event.topics.length == 3) {
      let transaction = web3.eth.abi.decodeLog(
        [
          {
            type: 'address',
            name: 'from',
            indexed: true,
          },
          {
            type: 'address',
            name: 'to',
            indexed: true,
          },
          {
            type: 'uint256',
            name: 'value',
            indexed: false,
          },
        ],
        event.data,
        [event.topics[0], event.topics[1], event.topics[2]]
      )

      const contract = new web3.eth.Contract(abi, event.address)
      collectData(contract).then(contractData => {
        var unit = Object.keys(web3.utils.ethUnitMap).find(
          key => web3.utils.ethUnitMap[key] == BigInt(10) ** contractData.decimals
        )
        if (!unit) {
          // Simplification for contracts that use "non-standard" units, e.g. REDDIT contract returns decimals==8
          unit = 'wei'
        }
        // This is logging each transfer event found:
        const value = web3.utils.fromWei(transaction.value, unit)
        console.log(
          `Transfer of ${value + ' '.repeat(Math.max(0, 30 - value.length))} ${
            contractData.symbol + ' '.repeat(Math.max(0, 10 - contractData.symbol.length))
          } from ${transaction.from} to ${transaction.to}`
        )

        // Below are examples of testing for transactions involving particular EOA or contract addresses
        if (transaction.from == '0x495f947276749ce646f68ac8c248420045cb7b5e') {
          console.log('Specified address sent an ERC-20 token!')
        }
        if (transaction.to == '0x495f947276749ce646f68ac8c248420045cb7b5e') {
          console.log('Specified address received an ERC-20 token!')
        }
        if (
          transaction.from == '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D' &&
          event.address == '0x6b175474e89094c44da98b954eedeac495271d0f'
        ) {
          console.log('Specified address transferred specified token!')
        } // event.address contains the contract address
        if (event.address == '0x6b175474e89094c44da98b954eedeac495271d0f') {
          console.log('Specified ERC-20 transfer!')
        }
      })
    }
  })

  subscription.on('error', err => {
    throw err
  })
  subscription.on('connected', nr => console.log('Subscription on ERC-20 started with ID %s', nr))
}
main()
```

---

## Track ERC-721 and ERC-1155 token transfers


In this tutorial, you'll track ERC-721 and ERC-1155 token transfers and mints from a specific address using the Web3 JavaScript library.

## Prerequisites

- An [Ethereum project](../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)

## Steps

### 1. Create a project directory

Create a new directory for your project. This can be done from the command line:

```javascript
mkdir trackERC721
```

Change into the new directory:

```javascript
cd trackERC721
```

### 2. Install required packages

Install the `web3` package in the project directory:

```javascript
npm install web3
```

:::info

This example has been written for web3js v4.x. It may not work for earlier versions.

:::

### 3. Set up the script

Create a file called `trackERC721.js`. At the top of file, add the following lines to import the web3.js library and connect to the Infura WebSocket endpoint:

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

async function main(){
  const web3 = new Web3("wss://mainnet.infura.io/ws/v3/<YOUR-API-KEY>");
  ...
}
main();
```

Make sure to replace `<YOUR-API-KEY>` with your Infura API key.

### 4. Subscribe to contract events

You can subscribe to the events that token contracts emit, allowing you to track every new token transfer as it occurs.

Add the following filter to the script, which tells the `web3.eth.subscribe` function in web3.js which events to track:

```javascript
let options721 = {
  topics: [web3.utils.sha3('Transfer(address,address,uint256)')],
}

let options1155 = {
  topics: [web3.utils.sha3('TransferSingle(address,address,address,uint256,uint256)')],
}
```

Then, initiate the subscription by passing along the filter:

```javascript
let subscription721 = await web3.eth.subscribe('logs', options721)
let subscription1155 = await web3.eth.subscribe('logs', options1155)
```

:::info

In [step 3](#3-set-up-the-script), you wrap the whole script in an async function `main()`, because top level await is not allowed except in recent JavaScript versions.

:::

You can also add the following lines to the script to see whether the subscription started successfully or if any errors occurred:

```javascript
subscription721.on('error', err => {
  throw err
})
subscription1155.on('error', err => {
  throw err
})

subscription721.on('connected', nr => console.log('Subscription on ERC-721 started with ID %s', nr))
subscription1155.on('connected', nr =>
  console.log('Subscription on ERC-1155 started with ID %s', nr)
)
```

### 5. Read ERC-721 transfers

Set the listener for the `subscription721` created in [step 4](#4-subscribe-to-contract-events) by adding the following lines to the script:

```javascript
subscription721.on('data', event => {
  if (event.topics.length == 4) {
    // ...
  }
})
```

:::info

To verify that the `Transfer` event you catch is an ERC-721 transfer, these lines check to see whether the length of the `topics` array equals 4. This is because ERC-20 events also emit a `Transfer` event but contain three items instead.

:::

Because you can't read the event topics on their own, you must decode them using the ERC-721 ABI. Edit the listener as follows:

```javascript
let transaction = web3.eth.abi.decodeLog(
  [
    {
      type: 'address',
      name: 'from',
      indexed: true,
    },
    {
      type: 'address',
      name: 'to',
      indexed: true,
    },
    {
      type: 'uint256',
      name: 'tokenId',
      indexed: true,
    },
  ],
  event.data,
  [event.topics[1], event.topics[2], event.topics[3]]
)
```

In order to directly call `from`, `to`, and `tokenId` on `transaction`, add the following:

```javascript
console.log(
  `\n` +
    `New ERC-721 transaction found in block ${event.blockNumber} with hash ${event.transactionHash}\n` +
    `From: ${transaction.from === '0x0000000000000000000000000000000000000000' ? 'New mint!' : transaction.from}\n` +
    `To: ${transaction.to}\n` +
    `Token contract: ${event.address}\n` +
    `Token ID: ${transaction.tokenId}`
)
```

### 6. Read ERC-1155 transfers

You can set the listener for the `subscription1155` created in [step 4](#4-subscribe-to-contract-events) by adding the following lines to the script:

```javascript
subscription1155.on('data', event => {
  // ...
})
```

As with ERC-721 in [Step 5](#5-read-erc-721-transfers), add the ERC-1155 ABI to the listener:

```javascript
let transaction = web3.eth.abi.decodeLog(
  [
    {
      type: 'address',
      name: 'operator',
      indexed: true,
    },
    {
      type: 'address',
      name: 'from',
      indexed: true,
    },
    {
      type: 'address',
      name: 'to',
      indexed: true,
    },
    {
      type: 'uint256',
      name: 'id',
    },
    {
      type: 'uint256',
      name: 'value',
    },
  ],
  event.data,
  [event.topics[1], event.topics[2], event.topics[3]]
)
```

In order to directly call `from`, `to`, and `tokenId` on `transaction`, add the following:

```javascript
console.log(
  `\n` +
    `New ERC-1155 transaction found in block ${event.blockNumber} with hash ${event.transactionHash}\n` +
    `Operator: ${transaction.operator}\n` +
    `From: ${transaction.from === '0x0000000000000000000000000000000000000000' ? 'New mint!' : transaction.from}\n` +
    `To: ${transaction.to}\n` +
    `id: ${transaction.id}\n` +
    `value: ${transaction.value}`
)
```

### 7. Track a specific address

You can track a specific sender address by reading the `from` value of the decoded `transaction` object. For each of the listeners, add the following line, replacing `<SENDER_ADDRESS>` with the Ethereum address to track:

```javascript
if (transaction.from == '<SENDER_ADDRESS>') {
  console.log('Specified address sent an NFT!')
}
```

You can also track a specific recipient address receiving any tokens by tracking the `transaction.to` value:

```javascript
if (transaction.to == '<RECIPIENT_ADDRESS>') {
  console.log('Specified address received an NFT')
}
```

### 8. Track a specific token

You can track a specific address sending a specific token, by checking for both `event.address` and `transaction.tokenID`. For each of the listeners, add the following line, replacing `<CONTRACT_ADDRESS>` with the smart contract address to track and `<TOKEN_ID>` with specific transaction token ID:

<Tabs>
  <TabItem value="ERC-721" label="ERC-721" default>

```javascript
if (event.address == "<CONTRACT_ADDRESS>" && transaction.tokenId == <TOKEN_ID>) { console.log("Specified ERC-721 NFT was transferred!"); }
```

  </TabItem>
  <TabItem value="ERC-1155" label="ERC-1155" >

```javascript
if (event.address == '<CONTRACT_ADDRESS>') {
  console.log('Specified ERC-1155 NFT was transferred!')
}
```

  </TabItem>
</Tabs>

### 9. Run the script

Run the script using the following command:

<Tabs>
  <TabItem value="Command" label="Command" default>

```javascript
node trackERC721.js
```

  </TabItem>
  <TabItem value="Example ERC-721 output" label="Example ERC-721 output" >

```javascript
New ERC-721 transaction found in block 15102209 with hash 0x3b133c1ad2d138bee9a596d94da25892e12a2c95efd1f0916d6708a9b86745b0
From: 0xDd3c42eb2660c0C7745E48f25864ff743Fef9f33
To: 0x4c5Ca726584d9b171AE9D6ce67Ab8AFb706259CB
Token contract: 0x35f3b8f37e9341F289398b70Fa2c576Dd102DF75
Token ID: 950
```

  </TabItem>
  <TabItem value="Example ERC-1155 output" label="Example ERC-1155 output" >

```javascript
New ERC-1155 transaction found in block 15102209 with hash 0xa08afd7696ec7424f8b403ca3733ebbb916faf68442757e2e9349c2d1b90aa9a
Operator: 0x20251a0505Ead51fb2C6ce5c1f399924ea068322
From: New mint!
To: 0x20251a0505Ead51fb2C6ce5c1f399924ea068322
id: 2
value: 1
```

  </TabItem>
</Tabs>

### Complete code overview

```javascript
const { Web3 } = require('web3')

async function main() {
  const web3 = new Web3('wss://mainnet.infura.io/ws/v3/<YOUR-API-KEY>')

  let options721 = {
    topics: [web3.utils.sha3('Transfer(address,address,uint256)')],
  }

  let options1155 = {
    topics: [web3.utils.sha3('TransferSingle(address,address,address,uint256,uint256)')],
  }

  let subscription721 = await web3.eth.subscribe('logs', options721)
  let subscription1155 = await web3.eth.subscribe('logs', options1155)

  subscription721.on('data', event => {
    if (event.topics.length == 4) {
      let transaction = web3.eth.abi.decodeLog(
        [
          {
            type: 'address',
            name: 'from',
            indexed: true,
          },
          {
            type: 'address',
            name: 'to',
            indexed: true,
          },
          {
            type: 'uint256',
            name: 'tokenId',
            indexed: true,
          },
        ],
        event.data,
        [event.topics[1], event.topics[2], event.topics[3]]
      )

      if (transaction.from == '0x495f947276749ce646f68ac8c248420045cb7b5e') {
        console.log('Specified address sent an NFT!')
      }
      if (transaction.to == '0x495f947276749ce646f68ac8c248420045cb7b5e') {
        console.log('Specified address received an NFT!')
      }
      if (
        event.address == '0xBC4CA0EdA7647A8aB7C2061c2E118A18a936f13D' &&
        transaction.tokenId == 2500
      ) {
        console.log('Specified NFT was transferred!')
      }

      console.log(
        `\n` +
          `New ERC-712 transaction found in block ${event.blockNumber} with hash ${event.transactionHash}\n` +
          `From: ${transaction.from === '0x0000000000000000000000000000000000000000' ? 'New mint!' : transaction.from}\n` +
          `To: ${transaction.to}\n` +
          `Token contract: ${event.address}\n` +
          `Token ID: ${transaction.tokenId}`
      )
    }
  })

  subscription1155.on('data', event => {
    let transaction = web3.eth.abi.decodeLog(
      [
        {
          type: 'address',
          name: 'operator',
          indexed: true,
        },
        {
          type: 'address',
          name: 'from',
          indexed: true,
        },
        {
          type: 'address',
          name: 'to',
          indexed: true,
        },
        {
          type: 'uint256',
          name: 'id',
        },
        {
          type: 'uint256',
          name: 'value',
        },
      ],
      event.data,
      [event.topics[1], event.topics[2], event.topics[3]]
    )

    console.log(
      `\n` +
        `New ERC-1155 transaction found in block ${event.blockNumber} with hash ${event.transactionHash}\n` +
        `Operator: ${transaction.operator}\n` +
        `From: ${transaction.from === '0x0000000000000000000000000000000000000000' ? 'New mint!' : transaction.from}\n` +
        `To: ${transaction.to}\n` +
        `id: ${transaction.id}\n` +
        `value: ${transaction.value}`
    )
  })

  subscription721.on('error', err => {
    throw err
  })
  subscription1155.on('error', err => {
    throw err
  })

  subscription721.on('connected', nr =>
    console.log('Subscription on ERC-721 started with ID %s', nr)
  )
  subscription1155.on('connected', nr =>
    console.log('Subscription on ERC-1155 started with ID %s', nr)
  )
}

main()
```

---

## Set up a simple reverse proxy


In this tutorial, you'll use [Caddy](https://caddyserver.com/) to set up a reverse proxy to route data from Infura to your own node.

## Prerequisites

- An [Ethereum project](../../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)
- [Homebrew](https://brew.sh/) installed

## Steps

### 1. Create a project directory

Create a new directory for your project. You can do this from the command line:

```bash
mkdir reverseProxy
```

Change into the new directory:

```bash
cd reverseProxy
```

### 2. Install Caddy

Install Caddy in the project directory using Homebrew:

```bash
brew install caddy
```

### 3. Create the reverse proxy

To create the reverse proxy, create a text file named `Caddyfile` with the following content:

```
localhost

reverse_proxy https://mainnet.infura.io {
header_up Host
}
```

Ensure you replace `<YOUR-API-KEY>` with the API key for your Ethereum project.

In this example, the reverse proxy retrieves information from the Infura endpoint, and redirects it to `localhost`.
Using `header_up Host` allows you to include your API key to both the Sepolia and localhost endpoints.

### 4. Run the reverse proxy

In a new terminal window, from your project directory, run the reverse proxy using Caddy:

```bash
caddy run
```

### 5. Make a request

In a new terminal window, make a curl request to `localhost`. The following example executes a `web3_clientVersion` request:

<Tabs>
  <TabItem value="Example curl HTTPS request" label="Example curl HTTPS request" default>

```bash
curl https://localhost/v3/<YOUR-API-KEY> \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1}'
```

  </TabItem>
  <TabItem value="Example JS result" label="Example JS result" >

```javascript
{"jsonrpc": "2.0", "id": 1, "result": "Geth/v1.10.8-omnibus-aef5bfb3/linux-amd64/go1.16.7"}
```

  </TabItem>
</Tabs>

To ensure that the reverse proxy is working, execute the same request, replacing `localhost` with `sepolia.infura.io`. You should get the same result:

<Tabs>
  <TabItem value="Example curl HTTPS request" label="Example curl HTTPS request" default>

```bash
curl https://sepolia.infura.io/v3/<YOUR-API-KEY> \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1}'
```

  </TabItem>
  <TabItem value="Example JS result" label="Example JS result" >

```javascript
{"jsonrpc": "2.0", "id": 1, "result": "Geth/v1.10.8-omnibus-aef5bfb3/linux-amd64/go1.16.7"}
```

  </TabItem>
</Tabs>

---

## Use Infura as a backup for your node


In this tutorial, you'll use [Caddy](https://caddyserver.com/) to set up a reverse proxy with two upstreams, one from your own node, and one from Infura as a backup.

## Prerequisites

- An [Ethereum project](../../../get-started/infura.md) on Infura
- [Node.js installed](https://nodejs.org/en/download/)
- [Homebrew](https://brew.sh/) installed

## Steps

### 1. Create a project directory

Create a new directory for your project. You can do this from the command line:

```bash
mkdir reverseProxy
```

Change into the new directory:

```bash
cd reverseProxy
```

### 2. Install Caddy

Install Caddy in the project directory using Homebrew:

```bash
brew install caddy
```

### 3. Create a Node.js stub

You may be running your own Ethereum node, but for the sake of this tutorial, you can substitute a node with a Node.js stub. Create a file named `main.js` in the project directory with the following content:

```javascript
const https = require('https')
const fs = require('fs')
const options = {
  key: fs.readFileSync('<PATH_TO_CERTIFICATE_KEY_FILE>.pem'),
  cert: fs.readFileSync('<PATH_TO_CERTIFICATE_FILE>.pem'),
}

const hostname = '127.0.0.1'
const port = 9000

const server = https.createServer(options, function (req, res) {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  setTimeout(() => {
    res.end('Reverse proxy success!\n')
  }, 1000)
})

server.listen(port, hostname, () => {
  console.log(`Server running at https://${hostname}:${port}/`)
})
```

This sets up a backend HTTPS service running on `127.0.0.1:9000` (`localhost:9000`) and displays a success message if the proxy works.

:::warning

When creating a reverse proxy with multiple upstreams, Caddy requires _all_ upstream endpoints to be HTTP or HTTPS. In this tutorial, because the backup Infura endpoint is HTTPS, you must create a TLS certificate for your localhost (if you're not already using your own private HTTPS node).

:::

You can [install and use mkcert](https://web.dev/how-to-use-local-https/#setup) to generate a certificate key file and certificate file for your stub:

```bash
brew install mkcert
mkcert -install
mkcert localhost
```

Replace `<PATH_TO_CERTIFICATE_KEY_FILE>` and `<PATH_TO_CERTIFICATE_FILE>` in `main.js` with the generated files.

### 4. Run the Node.js stub

In a new terminal window, from your project directory, start the Node.js stub and leave that connection open:

```bash
node main.js
```

### 5. Create the reverse proxy

To create the reverse proxy, create a text file named `Caddyfile` with the following content:

```
localhost:3000

reverse_proxy https://localhost:9000 https://sepolia.infura.io {
  header_up Host {/v3/<YOUR-API-KEY>}
}
```

Ensure you replace `<YOUR-API-KEY>` with the API key for your Ethereum project.

In this example, the reverse proxy retrieves information from `localhost:9000`, and redirects it to `localhost:3000`.
If `localhost:9000` stops responding, Caddy will move on to retrieve information from the Sepolia endpoint.
Using `header_up Host` allows you to include your API key to both the Sepolia and localhost endpoints.

### 6. Run the reverse proxy

In a new terminal window, from your project directory, run the reverse proxy using Caddy:

```bash
caddy run
```

### 7. Make a request

In a new terminal window, make a curl request to `localhost`. The following example executes a `web3_clientVersion` request:

<Tabs>
  <TabItem value="Example CURL request" label="Example CURL request" default>

```bash
curl http://localhost:3000/v3/<YOUR-API-KEY> \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1}'
```

  </TabItem>
  <TabItem value="Example result" label="Example result" >

```
Reverse proxy success!
```

  </TabItem>
</Tabs>

The success message from `main.js` should display, because you've asked the reverse proxy to go to `localhost:9000` first.

If you close the Node.js server and send the request again, you should get the result from the Sepolia node:

<Tabs>
  <TabItem value="Example CURL request" label="Example CURL request" default>

```bash
curl http://localhost:3000/v3/<YOUR-API-KEY> \
  -X POST \
  -H "Content-Type: application/json" \
  -d '{"jsonrpc": "2.0", "method": "web3_clientVersion", "params": [], "id": 1}'
```

  </TabItem>
  <TabItem value="Example result" label="Example result" >

```javascript
{"jsonrpc": "2.0", "id":1, "result": "Geth/v1.10.8-omnibus-aef5bfb3/linux-amd64/go1.16.7"}
```

  </TabItem>
</Tabs>

The reverse proxy ignores the localhost node, since it's not functioning, and falls back to the Sepolia node.

---

## Send a transaction with Polygon


As with Ethereum, [transactions](https://ethereum.org/en/developers/docs/transactions/) are state-changing actions on the Polygon PoS blockchain. Examples of transactions are:

- Regular transactions from one account to another.
- Contract deployment transactions, or calling a function in a smart contract.

This tutorial uses the Ethereum Web3 JavaScript library to send a transaction between two accounts on the Polygon Amoy testnet.

## Prerequisites

- An Infura [API key](/dashboard/get-started/create-api)
- [Node.js installed](https://nodejs.org/en/download/)
- [MetaMask installed](https://metamask.io) and an account for testing purposes

:::info

You can use [MetaMask](https://metamask.io) or a similar Ethereum wallet to create an account for testing purposes on the Polygon blockchain.

:::

## Steps

### 1. Add Polygon network to MetaMask

Refer to the Polygon instructions to [add the Polygon networks to MetaMask](https://polygon.technology/blog/getting-started-with-metamask-on-polygon). This tutorial uses the Polygon Amoy network.

### 2. Fund your account

[Use the Polygon faucet](https://faucet.polygon.technology) to load testnet MATIC on your account for the Amoy network.

### 3. Create a project directory

Create a new directory for your project. This can be done from the command line:

```bash
mkdir sendTransaction
```

Change into the new directory:

```bash
cd sendTransaction
```

### 4. Install required packages

Install the `web3` and `dotenv` packages in the project directory.

:::info

The `dotenv` package allows you to use a `.env` file to securely store private environment variables on your local machine.

:::

Install the `web3` package:

```
npm install web3
```

Install the `dotenv` package:

```
npm install dotenv --save
```

### 5. Create the `.env` file

Create a `.env` file in your project directory to store the project and account details.

```
POLYGON_NETWORK = "polygon-amoy"
INFURA_API_KEY = "<YOUR-API-KEY>"
SIGNER_PRIVATE_KEY = "<Private-Key>"
```

Ensure you replace the following values in the `.env` file:

- `<YOUR-API-KEY>` with the API key from your [Infura dashboard](https://app.infura.io/).
- `<Private-Key>` with the [private key of your account](https://metamask.zendesk.com/hc/en-us/articles/360015289632-How-to-Export-an-Account-Private-Key).

:::danger

Never disclose your private key. Anyone with your private keys can steal any assets held in your account.

:::

### 6. Create `send.js` file

In this example we'll create a JavaScript file (`send.js`) in the project directory which configures and sends the transaction.

```javascript title="send.js"
const { Web3 } = require('web3')

async function main() {
  // Configuring the connection to the Polygon node
  const network = process.env.POLYGON_NETWORK
  const web3 = new Web3(
    new Web3.providers.HttpProvider(`https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`)
  )
  // Creating a signing account from a private key
  const signer = web3.eth.accounts.privateKeyToAccount(process.env.SIGNER_PRIVATE_KEY)
  web3.eth.accounts.wallet.add(signer)
  // Creating the transaction object
  const tx = {
    from: signer.address,
    to: '0xAED01C776d98303eE080D25A21f0a42D94a86D9c',
    value: web3.utils.toWei('0.001', 'ether'),
  }
  // Assigning the right amount of gas
  tx.gas = await web3.eth.estimateGas(tx)

  // Sending the transaction to the network
  const receipt = await web3.eth.sendTransaction(tx).once('transactionHash', txhash => {
    console.log(`Mining transaction ...`)
    console.log(`Transaction hash: ${txhash}`)
  })
  // The transaction is now on chain!
  console.log(`Mined in block ${receipt.blockNumber}`)
}

require('dotenv').config()
main()
```

### 7. Execute the transaction

To execute the transaction, run:

```bash
node send.js
```

The command line will display the block number containing the transaction details.

### 8. View the transaction details

Copy transaction hash and view the transaction in the [Polygon Amoy block explorer](https://amoy.polygonscan.com/).
