Here’s an article on how to retrieve the revert message
from a send method call in Web3.js:
Decoding the Revert Message in Web3.js
In Web3.js, when you use the send
method to execute a transaction, it returns a receipt object that contains various information about the transaction. One of the values you can access is the logs[0].data
, which is a string containing the hexadecimal value of the data stored in the transaction.
The revert message
is encoded in this hexadecimal value. To decode the revert message, you’ll need to use some Web3.js methods and functions.
Step 1: Accessing the Receipt Object
First, you need to access the receipt object from the send
method’s return value.
const receipt = await ethers.getReceipt();
Step 2: Extracting the Hexadecimal Value
Next, extract the hexadecimal value from the logs[0].data
property of the receipt object. You can do this using the toString(16)
method to convert the hexadecimal string to a number.
const revertMessage = receipt.logs[0].data.toString('hex');
Step 3: Decoding the Revert Message
Now, you need to decode the reverted message from the hexadecimal value. In Web3.js, this can be done using the from
method with an optional decode
function.
const revert = await ethers.utils.fromHex(revertMessage, { decode: true });
The decode
function is a callback that takes two arguments: the hex-encoded message and an object with various properties. In this case, we’re using it to decode the reverted message.
Putting it all together
Here’s the complete example:
async function getRevertMessage() {
try {
const receipt = await ethers.getReceipt();
const revertMessage = receipt.logs[0].data.toString('hex');
const revert = await ethers.utils.fromHex(revertMessage, { decode: true });
return revert;
} catch (error) {
console.error(error);
}
}
Sample Use Cases
In this example, we’re using the getRevertMessage
function to retrieve and print the revert message. The reverted message is stored in the revert
variable.
Note that the decode
function may throw an error if it’s unable to parse the hexadecimal value. You should handle this error accordingly.
Hope this helps! Let me know if you have any questions or need further assistance.