为以太坊交易分配 'Value' 参数
Assigning a 'Value' Parameter to an Ethereum Transaction
我正在尝试将 0.05 以太币的值分配给以太坊交易的值参数,如下面的代码所述。我不明白如何将 50000000000000000 Wei(0.05 Eth)转换为描述的格式“0x29a2241af62c0000”。请有人告诉我如何将 50000000000000000 wei 转换为这种格式,它到底是什么?
//Sending Ethereum to an address
sendEthButton.addEventListener('click', () => {
ethereum
.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: '0x2f318C334780961FB129D2a6c30D0763d9a5C970',
value: '0x29a2241af62c0000',
gasPrice: '0x09184e72a000',
gas: '0x2710',
},
],
})
.then((txHash) => console.log(txHash))
.catch((error) => console.error);
});
0x29a2241af62c000
是十进制数187500000000000000
的十六进制表示。
您可以使用本机 JS 方法 toString()
将十进制数转换为十六进制形式。
'0x' + (50000000000000000).toString(16)
returns
0xb1a2bc2ec50000
或者,如果您想使用 web3,可以使用 numberToHex() 方法。
"0x" + Number(Web3.utils.toWei("0.05", "ether")).toString(16)
我认为这是更准确的实现方式,它适用于我,首先将您的值转换为 wei,然后再转换为 hex
我正在尝试将 0.05 以太币的值分配给以太坊交易的值参数,如下面的代码所述。我不明白如何将 50000000000000000 Wei(0.05 Eth)转换为描述的格式“0x29a2241af62c0000”。请有人告诉我如何将 50000000000000000 wei 转换为这种格式,它到底是什么?
//Sending Ethereum to an address
sendEthButton.addEventListener('click', () => {
ethereum
.request({
method: 'eth_sendTransaction',
params: [
{
from: accounts[0],
to: '0x2f318C334780961FB129D2a6c30D0763d9a5C970',
value: '0x29a2241af62c0000',
gasPrice: '0x09184e72a000',
gas: '0x2710',
},
],
})
.then((txHash) => console.log(txHash))
.catch((error) => console.error);
});
0x29a2241af62c000
是十进制数187500000000000000
的十六进制表示。
您可以使用本机 JS 方法 toString()
将十进制数转换为十六进制形式。
'0x' + (50000000000000000).toString(16)
returns
0xb1a2bc2ec50000
或者,如果您想使用 web3,可以使用 numberToHex() 方法。
"0x" + Number(Web3.utils.toWei("0.05", "ether")).toString(16)
我认为这是更准确的实现方式,它适用于我,首先将您的值转换为 wei,然后再转换为 hex