Reading Metadata from Transactions

In this example, we will be reading metadata from a transaction. To begin, we will be reading from a transaction that already exists. This transaction will contain around 100kb worth of "a" characters. Below we will read from the polygon network utilizing the "ethers" and "Web3.Js" library.

Ethers

import {ethers} from 'ethers' //version 6.12.1

// window.etheruem will connect to a wallet like metamask, while https://polygon-rpc.com is public connection to polygon network
const provider = new ethers.BrowserProvider(window.ethereum || 'https://polygon-rpc.com')
const transactionReceipt = await provider.getTransactionReceipt('0xbeab5823b60da4d003293a2594fc9503ee7c002af969ede94bf1ee57a0168ac2')
const data = transactionReceipt['logs'][2].data

Web3.js

import {Web3} from 'web3' //version 4.8.0

// window.etheruem will connect to a wallet like metamask, while https://polygon-rpc.com is public connection to polygon network
const provider = new Web3(window.ethereum || 'https://polygon-rpc.com')
const transactionReceipt = await provider.eth.getTransactionReceipt('0xbeab5823b60da4d003293a2594fc9503ee7c002af969ede94bf1ee57a0168ac2')
const data = transactionReceipt['logs'][2].data

When requesting a log from the chain, that log will contain a hex value. This hex value contains the JSON we are looking for, but it's surrounded by bytes that will make decoding challenging. Thus, we will install the following package to extract the json from the hex string with ease.

npm i hex2json

Ethers

import {ethers} from 'ethers' //version 6.12.1
import { decodeHexToJson } from 'hex2json';

// window.etheruem will connect to a wallet like metamask, while https://polygon-rpc.com is public connection to polygon network
const provider = new ethers.BrowserProvider(window.ethereum || 'https://polygon-rpc.com')
const transactionReceipt = await provider.getTransactionReceipt('0xbeab5823b60da4d003293a2594fc9503ee7c002af969ede94bf1ee57a0168ac2')
const data = transactionReceipt['logs'][2].data
const json = decodeHexToJson(data)
console.log(json)
//We extracted the meta data succesfully from the chain.

Web3.js

🎉 Whoop whoop, now if you haven't already given it a shot testing your own transaction with your custom metadata. Make sure to send it as a JSON as well.

Last updated