Once a transaction is sent to the Ethereum network, it can take some time to be processed and confirmed. MetaMask provides a way to check the status of a transaction using its API. Below is a detailed explanation of how to check the status of a transaction in MetaMask, along with sample code.

1. Getting the Transaction Hash

To check the status of a transaction, you need to get the transaction hash. This can be obtained from the eth_sendTransaction method or from the transaction receipt.


const getTransactionHash = async () => {
const txHash = await window.ethereum.request({
method: 'eth_sendTransaction',
params: [{
from: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
to: '0x55241586d50469745864804697458648046974',
value: '0x186a0',
gas: '0x5208',
gasPrice: '0x186a0'
}]
});
console.log(`Transaction hash: ${txHash}`);
};

getTransactionHash();

2. Checking the Transaction Status

To check the status of a transaction, you can use the eth_getTransactionReceipt method. This will return the transaction receipt, which includes the status of the transaction.


const getTransactionStatus = async (txHash) => {
const receipt = await window.ethereum.request({
method: 'eth_getTransactionReceipt',
params: [txHash]
});
if (receipt) {
console.log(`Transaction status: ${receipt.status}`);
} else {
console.log('Transaction not found');
}
};

// Example usage
const txHash = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
getTransactionStatus(txHash);

3. Polling for Transaction Status

Since the transaction status may not be available immediately, you can use a polling mechanism to check the status at regular intervals.


const pollTransactionStatus = async (txHash) => {
const intervalId = setInterval(async () => {
const receipt = await window.ethereum.request({
method: 'eth_getTransactionReceipt',
params: [txHash]
});
if (receipt) {
console.log(`Transaction status: ${receipt.status}`);
clearInterval(intervalId);
}
}, 1000); // Poll every 1 second
};

// Example usage
const txHash = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
pollTransactionStatus(txHash);

4. Using Etherscan API

Alternatively, you can use the Etherscan API to check the transaction status. This API provides a more reliable way to get the transaction status, especially for transactions that are not yet confirmed.


const getTransactionStatusEtherscan = async (txHash) => {
const response = await fetch(`https://api.etherscan.io/api?module=transaction&action=gettxreceiptstatus&txhash=${txHash}&apikey=YOUR_ETHERSCAN_API_KEY`);
const data = await response.json();
console.log(data.result);
};

// Example usage
const txHash = '0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef';
getTransactionStatusEtherscan(txHash);

Conclusion

By utilizing the MetaMask API and Etherscan API, developers can effectively check the status of a transaction and provide a better user experience.