Web3js

什麼是 .new()?

  • April 18, 2021

我正在使用以下程式碼使用 Node-js 將智能合約部署到專用網路。但是TypeError: contract_object.new is not a function會發生錯誤。什麼是.new()錯誤的解決方案?

應用程序.js:

var Web3=require('web3');
var fs=require('fs');
var solc=require('solc');
var web3=new Web3('ws://127.0.0.1:8545');
var address="0xB6EB958b199219Abf33462d6B348C9709C8E24f8";
var contract_sol=fs.readFileSync('E:/Deploy/contracts/Deploy.sol','utf8');
var contract_compiled=solc.compile(contract_sol);
var contract_json="E:/Deploy/build/contracts/Deploy.json";
var contract_js=JSON.parse(fs.readFileSync(contract_json));
var contract_abi=contract_js.abi;
var contract_byteCode="0x608060405234801561001057600080fd5b5061011d806100206000396000f3fe6080604052348015600f57600080fd5b506004361060285760003560e01c806318620ef014602d575b600080fd5b603360ab565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101560715780820151818401526020810190506058565b50505050905090810190601f168015609d5780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040518060400160405280601581526020017f436f6e7472616374206973206465706c6f79656421000000000000000000000081525090509056fea265627a7a723158206cddf11cab61deaceb98041f67bc88c98dfa84738b1c39323262ccd385732c7864736f6c634300050c0032";
var gasEstimate=web3.eth.estimateGas({data:contract_byteCode});
var contract_object=new web3.eth.Contract(contract_abi);
   web3.eth.personal.unlockAccount(address,"Alireza");
var theContract=contract_object.new({ from: address, data:contract_byteCode, gas: gasEstimate+10000})

您需要web3模組,但在不需要模組truffle-contract時使用了模組方法。因此,您可以使用web3提供給您的所有方法。命令:

var theContract=contract_object.new({ from: address, data:contract_byteCode, gas: gasEstimate+10000})

使用truffle-contract模組的方法。只需將其替換為以下web3模組命令即可:

contract_object.deploy().send({ from: <address>, data:contract_byteCode, gas: gasEstimate+10000});

new web3.eth.Contract呼叫類的建構子web3.eth.Contract

這個建構子(自然地)返回一個類的實例web3.eth.Contract

您的嘗試:

var contract_object=new web3.eth.Contract(...);
var theContract=contract_object.new(...);

失敗,因為類web3.eth.Contract沒有名為 的成員函式new

您很可能會將其與 Truffle 的artifacts.require('<ContractName>').new.

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