我试图执行一个事务,首先使用我的私钥使用ethereumjs-tx签名,然后使用sendSignedTransaction将事务发送到网络。但是不知怎么的,这些事务被困在了待定状态,我没有得到任何receipt。
下面是我正在使用的完整代码。
const Web3 = require('web3') // ^1.0.0-beta.55
const abi = [
{
"constant": false,
"inputs": [
{
"name": "name",
"type": "string"
}
],
"name": "addName",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "current_name",
"outputs": [
{
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]
const address = "0xffae257a6c0734ffbfb4c74fac865d95882d1153"
const network = {
ropsten: "https://ropsten.infura.io"
}
var web3 = new Web3(new Web3.providers.HttpProvider(network.ropsten))
//Test Keys
const keystore = {
ropsten: {
address: "0x232D1038Ca6d21DF85F2109E6155E3f7c0Eea808",
privateKey: "dd3853d79745bd65a3a2691052e9fe27c39a314e45780b389e5ceb236d615f6c"
}
}
const TestContract = new web3.eth.Contract(abi, address,{
from: keystore.ropsten.address,
gas: 3000000,
})
const sendTRX = async () => {
let data = TestContract.methods.addName("vasa").encodeABI()
const Tx = require('ethereumjs-tx')
const privateKey = new Buffer(keystore.ropsten.privateKey, 'hex')
let nonce = await web3.eth.getTransactionCount(keystore.ropsten.address);
console.log("nonce: ", nonce)
const rawTx = {
nonce: nonce,
gasPrice: '100',
gasLimit: '300',
to: address,
data: data
}
const tx = new Tx(rawTx);
tx.sign(privateKey);
const serializedTx = tx.serialize()
web3.eth.sendSignedTransaction('0x' +
serializedTx.toString('hex'))
.on('receipt', (receipt)=> {
console.log(receipt)
});
}
sendTRX()发布于 2019-05-13 17:17:13
问题可能在于您将gasPrice设置为100,gasLimit设置为300。如果有更高的价格和更高的利润,矿商不会把你的交易纳入一个区块。
汽油价格总是根据市场需求和用户愿意支付的价格波动,因此硬编码汽油价格有时并不理想。相反,您可以使用await web3.eth.getGasPrice()根据以前的区块获得平均汽油价格。
气体限制应该与您预期的事务消耗一样高,事务消耗的气体量取决于它所做的事情。要获得估计值,可以使用web3.eth.estimateGas执行消息调用或事务,该消息调用或事务在节点的VM中直接执行,但从未挖掘到块链中并返回使用的气体量。(见Javascript)
注意: estimateGas()方法设置的气体限制是基于区块链的当前状态,只是一个估计。如果您的事务经常失败,或者您希望完全控制应用程序的气体消耗量,则可能需要手动设置此值。(参考)
https://ethereum.stackexchange.com/questions/70626
复制相似问题