If you're using web3.js
version 4.6.0 (i.e., the latest available version at this point in time), then when you prepend '0x'
to stringToHex("any string message")
, you might encounter this error when passing it as data
to the transaction:
Error: Cannot convert string to Uint8Array. only supports 0x-prefixed hex strings and this string was given: 0x0x...
Because stringToHex()
already includes the '0x'
prefix, so there's no need to prepend it explicitly.
Also, you might need to calculate the gasPrice
and gasLimit
, because passing these values as static, might result in the reverting of transaction. Since, you're passing data
along with the transaction, so the expected gasPrice
and gasLimit
for the transaction to be included in the block would change according to the data length and complexity (also depending on certain other factors like network/chain that you're using, network congestion, etc.).
Therefore, the right approach would be to calculate both of these values using the corresponding web3.eth
functions, i.e., web3.eth.getGasPrice()
and web3.eth.estimateGas
.
Here is a sample code to test the same end-to-end:
const { Web3 } = require('web3');
const { stringToHex } = require('web3-utils');
const providerUrl = 'JSON_RPC_PROVIDER_URL';
const web3 = new Web3(providerUrl);
// Example transaction parameters
const fromAddress = 'SENDER_ADDRESS';
const toAddress = 'RECIPIENT_ADDRESS';
const privateKey = 'SENDER_PRIVATE_KEY';
const amountToSend = web3.utils.toWei('0.1', 'ether'); // 0.1 ETH
const data = stringToHex('Hello, World!'); // Convert string to hexadecimal
// Get current gas price
web3.eth.getGasPrice()
.then(gasPrice => {
// Estimate gas limit
web3.eth.estimateGas({
from: fromAddress,
to: toAddress,
value: amountToSend,
data: data
})
.then(gasLimit => {
// Create the transaction object
const txObject = {
from: fromAddress,
to: toAddress,
value: amountToSend,
gas: gasLimit, // Gas limit
gasPrice: gasPrice, // Gas price
data: data // Include data in the transaction
};
// Sign the transaction
web3.eth.accounts.signTransaction(txObject, privateKey)
.then(signedTx => {
// Send the signed transaction
web3.eth.sendSignedTransaction(signedTx.rawTransaction)
.on('transactionHash', (hash) => {
console.log('Transaction hash:', hash);
})
.on('receipt', (receipt) => {
console.log('Transaction receipt:', receipt);
})
.on('error', (error) => {
console.error('Transaction error:', error);
});
})
.catch(error => {
console.error('Signing error:', error);
});
})
.catch(error => {
console.error('Error estimating gas limit:', error);
});
})
.catch(error => {
console.error('Error fetching gas price:', error);
});
qtmtransactionType
variable ?