Web3js

使用帶有建構子參數的 web3.eth.contract(abi) 進行合約部署

  • March 29, 2021

我正在嘗試部署以下智能合約:

pragma solidity ^0.5.00;

contract TestContract {

  address public owner;
  string public word;

  constructor(string memory _word) public{
     owner = msg.sender;
     word = _word;
  }

  modifier onlyOwner() {
     require(msg.sender == owner);
     _;
  }

  function getWord() public view returns (string memory) {
     return(word);
  }

  function updateWord(string memory _word) public onlyOwner {
     word = _word;
  }
}

但是我在使用建構子參數部署它時遇到了麻煩。我正在使用帶有以下測試程式碼的MetaMask 和 web3.js(我從這裡獲得:https ://github.com/ethereum/web3.js/blob/develop/dist/web3.js):

var Web3 = require('web3');
var web3 = new Web3(web3.currentProvider);

var code = '0x608060405234801561001057600080fd5b506040516106b...';

var abi = JSON.parse('[{"constant":true,"inputs":[],"name":"word","outputs":...');

var myContract;
function createExampleContract() {

   document.getElementById('create').style.visibility = 'hidden';
   document.getElementById('code').innerText = code;

   web3.eth.defaultAccount = web3.eth.coinbase;
   document.getElementById('status').innerText = "transaction sent, waiting for confirmation";

   web3.eth.contract(abi).new({data: code}, function (err, contract) {
       if(err) {
           console.error(err);
           return;
       } else if(contract.address){
           myContract = contract;
           console.log('address: ' + myContract.address);
           document.getElementById('status').innerText = 'Mined!';
           document.getElementById('call').style.visibility = 'visible';
       }
   });
}

function callExampleContract() {
   var param = parseInt(document.getElementById('value').value);

   myContract.getWord(param, function(err, result) {
     if (err) {
       console.log('e: ' + err);
     } else {
       console.log('r: ' + result);
     }
   });
}

我用這兩個終端命令得到了codeandabi``solc --bin contract.sol``solc --abi contract.sol

我正在嘗試並且契約部署通過但是當我呼叫該方法時,會arguments:['param']出現此錯誤並線上搜尋我發現這可能是由於從方法呼叫返回的值而導致的。那麼如何正確部署帶有建構子參數的合約呢?data:code``getWord``BigNumber Error: new BigNumber() not a base 16 number``null

謝謝你們!!=)

查看web3 v0.20.xx 文件,建構子參數就在{data:code}這樣的前面:

web3.eth.contract(abi).new(param1,param2,{data:code}, callback);

希望這對將來的參考有所幫助!

參考文件:web3.js v1.3.1

solc 版本:0.8.0

web3.js 版本:1.3.1

假設以下是您的智能合約:

contract myContract{
   constructor(int a, string memory str){
       // Some code using the arguments.
   }
}

以下是部署合約的方式:

var intObj = 10;
var strObj = 'Hello';
contract = await new web3.eth.Contract(compiledContract.abi)
   .deploy({ 
       data: compiledContract.bytecode, 
       arguments: [intObj, strObj] // Writing you arguments in the array
   })
   .send({ from: accounts[0], gas: minGas });
   

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