Web3js
使用 web3js 和 infura 部署合約
const Web3 = require('web3'); const fs = require('fs'); const solc = require('solc'); let web3; if (typeof web3 !== 'undefined') { web3 = new Web3(web3.currentProvider); } else { web3 = new Web3(new Web3.providers.HttpProvider('https://ropsten.infura.io/my key')); } const source = fs.readFileSync('./contract/coin.sol', 'utf8'); const compile = solc.compile(source, 1); const contractCompile = Object.values(compile.contracts)[0]; const deployAddr = '0x.....'; const contractByteCode = '0x' + contractCompile.bytecode; const contractAbi = JSON.parse(contractCompile.interface); const gasEstimate = web3.eth.estimateGas({data: contractByteCode}); const gasPrice = '20000000000'; const myContract = new web3.eth.Contract(contractAbi, { from: deployAddr, gas: '15000000', gasPrice: gasPrice, }); const initialSupply = 10000000000; const tokenName = 'LLT'; const tokenSymbol = 'LLT'; myContract.deploy({ data: contractByteCode, arguments: [initialSupply, tokenName, tokenSymbol] }).send({ from: deployAddr, gas: '15000000', gasPrice: gasPrice }, function (error) { console.log(error); }) .on('transactionHash', function (transactionHash) {console.log(transactionHash)}) .on('receipt', function (receipt) { console.log(receipt.contractAddress) // contains the new contract address }).on('confirmation', function (confirmationNumber, receipt) { }).then(function (newContractInstance) { console.log(newContractInstance.options.address) // instance with the new contract address }).catch(err => { console.log("Error: failed to deploy, detail:", err) });
Error: Invalid JSON RPC response: ""
當我使用節點執行此程式碼時,我得到了。我該如何解決這個問題?謝謝
嘗試使用
.sendRawTransaction()
代替.send()
,所以:myContract.deploy({ data: contractByteCode, arguments: [initialSupply, tokenName, tokenSymbol] }).sendRawTransaction({ from: deployAddr, gas: '15000000', gasPrice: gasPrice }, function (error) { console.log(error); }) .on('transactionHash', function (transactionHash) {console.log(transactionHash)}) .on('receipt', function (receipt) { console.log(receipt.contractAddress) // contains the new contract address }).on('confirmation', function (confirmationNumber, receipt) { }).then(function (newContractInstance) { console.log(newContractInstance.options.address) // instance with the new contract address }).catch(err => { console.log("Error: failed to deploy, detail:", err) });
我不確定它是否有效,可能您必須在使用 Infura 發送之前準備並簽署交易。
我猜你正在使用 Metamask 並實際使用他們的提供者,因此進入這種情況的真實情況:
if (typeof web3 !== ‘undefined’) {
web3 = new Web3(web3.currentProvider);
}
else {
web3 = new Web3(new Web3.providers.HttpProvider(’ https://ropsten.infura.io/my key’));
}
所以這可能是由於元遮罩的同步問題而發生的(我在使用自定義 RPC 節點時遇到了幾次)
我的建議是嘗試去 MM 設置並重置帳戶(它只會刪除交易),如果沒有工作,嘗試解除安裝並重新安裝元遮罩