Solidity

使用 Web3.js 部署智能合約會出錯?

  • May 18, 2017

我正在使用以下指南部署智能合約,但遇到一個奇怪的錯誤 -

指南:https ://tokenmarket.net/blog/creating-ethereum-smart-contract-transactions-in-client-side-javascript/

let fs = require("fs");
let Web3 = require('web3');
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

let source = fs.readFileSync("LMS.json");
let contracts = JSON.parse(source)["contracts"];
let abi = JSON.parse(contracts["LMS.sol:LMS"]["abi"]);
let code = contracts['LMS.sol:LMS'].bin
let LMS = web3.eth.contract(abi);

var lms = LMS.new("sanchit", "sanchit@sanchit.com", {
  from:web3.eth.coinbase,
  data:code,
  gas:600000}, function(err, myContract){
   console.log(err);
   if(!err) {
      if(!myContract.address) {
          console.log(myContract.transactionHash)
      } else {
          console.log(myContract.address) // the contract address
      }
   }
 });

這給了我以下錯誤-

Error: invalid argument 0: missing 0x prefix for hex data
at Object.InvalidResponse (/home/sanchitb/blockchain-workshop/lms/node_modules/web3/lib/web3/errors.js:35:16)
at /home/sanchitb/blockchain-workshop/lms/node_modules/web3/lib/web3/requestmanager.js:86:36
at XMLHttpRequest.request.onreadystatechange (/home/sanchitb/blockchain-workshop/lms/node_modules/web3/lib/web3/httpprovider.js:118:13)
at XMLHttpRequestEventTarget.dispatchEvent (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:64:18)
at XMLHttpRequest._setReadyState (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:354:12)
at XMLHttpRequest._onHttpResponseEnd (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:509:12)
at IncomingMessage.<anonymous> (/home/sanchitb/blockchain-workshop/lms/node_modules/xhr2/lib/xhr2.js:469:24)
at emitNone (events.js:91:20)
at IncomingMessage.emit (events.js:188:7)
at endReadableNT (_stream_readable.js:975:12)

有人可以告訴我我在這裡做錯了什麼嗎?

注意:預設帳戶已解鎖,console.log(abi) 顯示 abi 定義。

添加 ‘0x’ 作為字節碼的前綴解決了這個問題,下面是完美執行的程式碼 -

let fs = require("fs");
let Web3 = require('web3');
let web3 = new Web3();
web3.setProvider(new web3.providers.HttpProvider('http://localhost:8545'));

let source = fs.readFileSync("LMS.json");
let contracts = JSON.parse(source)["contracts"];

let abi = JSON.parse(contracts["LMS.sol:LMS"]["abi"]);
let code = '0x'+contracts['LMS.sol:LMS'].bin
let gasEstimate = web3.eth.estimateGas({data: code});
let LMS = web3.eth.contract(abi);

var lms = LMS.new("sanchit", "s@a.com", {
  from:web3.eth.coinbase,
  data:code,
  gas: gasEstimate
}, function(err, myContract){
   if(!err) {
      if(!myContract.address) {
          console.log(myContract.transactionHash) 
      } else {
          console.log(myContract.address) 
      }
   }
 });

引用自:https://ethereum.stackexchange.com/questions/16281