Web3js

使用 web3.js 和 Node.js 部署帶參數的合約

  • August 1, 2018

我嘗試部署 ERC721 合約。來自OpenZeppelin。

我的合約建構子需要兩個輸入字元串欄位。

constructor(string _name, string _symbol) public {
   name_ = _name;
   symbol_ = _symbol;

   // register the supported interfaces to conform to ERC721 via ERC165
   _registerInterface(InterfaceId_ERC721Enumerable);
   _registerInterface(InterfaceId_ERC721Metadata);
}

但是,當我部署合約時,它告訴我設置的參數必須是 HEX 編碼的數據。

這是我收到的錯誤消息: /Users/amos_mac/721_server/node_modules/solc/soljson.js:1 (function (exports, require, module, __filename, __dirname) { var Module;if(!Module)Module=(typeof Module!=="undefined"?Module:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=typeof window==="object";var ENVIRONMENT_IS_WORKER=typeof importScripts==="function";var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;var ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=function print(x){process["stdout"].write(x+"\n")};if(!Module["printErr"])Module["printErr"]=function printErr(x){process["stderr"].write(x+"\n")};var nodeFS=require("fs");var nodePath=require("path");Module["read"]=function read(filename,binary){filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"](filename);if(!

Error: The data field must be HEX encoded data.

所以我使用web3.utils.asciiToHex()了,但它沒有幫助。

這是我部署合約的程式碼:

MyToken.deploy({
   arguments: [[web3.utils.asciiToHex('Top 10 Students')],[web3.utils.asciiToHex('Top10')]]
}).send({
   from: address,
   gasPrice: gasPrice,
   gas: gas + 500000
}).then((instance) => {
   console.log("Contract mined at " + instance.options.address);
});

請幫忙!非常感謝!


檢查我的程式碼後,我意識到我在我的字節碼中添加了額外的“0x”。這就是導致錯誤的原因。

web3.eth.Contract.deploy 的文件指出,您必須提供已編譯智能合約的字節碼以及參數:

MyToken.deploy({
   data: '0x[INSERT THE BYTECODE HERE]',
   // You can omit the asciiToHex calls, as the contstructor takes strings. 
   // Web3 will do the conversion for you.
   arguments: ['Top 10 Students','Top10'] 
}).send({
   from: address,
   gasPrice: gasPrice,
   gas: gas + 500000
}).then((instance) => {
   console.log("Contract mined at " + instance.options.address);
});

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