我想用Node-js部署一份智能合同。我遵循了本指南,但是在实例化智能契约时会出现一个错误。
app.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="0x7c028611F45a40a0ef035416B6bFc405F190990c";
var contract_sol=fs.readFileSync('E:/Deploy/contracts/Deploy.sol','utf8');
var contract_compiled=solc.compile(contract_sol);
for (let contractName in contract_compiled.contracts) {
var contract_byteCode=contract_compiled.contracts[contractName].bytecode;
var contract_abi=JSON.parse(contract_compiled.contracts[contractName].interface);
}
var gasEstimate=web3.eth.estimateGas({data:contract_byteCode});
var gasResult;
var contract=new web3.eth.Contract(contract_abi);在最后一行中,会发生错误:
Error: You must provide the json interface of the contract when instantiating a contract object.发布于 2020-03-08 14:33:37
我使用我的合同的ABI和字节码作为一个值,并且所提到的错误从未发生。
var contractAbi=[
{
"constant": true,
"inputs": [],
"name": "notation",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
}
];现在,我的全部代码都在这里,没有提到的错误:
var Web3=require('web3');
var fs=require('fs');
var solc=require('solc');
var web3=new Web3('ws://127.0.0.1:8545');
var address="0x7c028611F45a40a0ef035416B6bFc405F190990c";
var contractAbi=[
{
"constant": true,
"inputs": [],
"name": "notation",
"outputs": [
{
"internalType": "string",
"name": "",
"type": "string"
}
],
"payable": false,
"stateMutability": "pure",
"type": "function"
}
];
var contract_sol=fs.readFileSync('E:/Deploy/contracts/Deploy.sol','utf8');
var contract_compiled=solc.compile(contract_sol);
for (let contractName in contract_compiled.contracts) {
var contract_byteCode=contract_compiled.contracts[contractName].bytecode;
}
var gasEstimate=web3.eth.estimateGas({data:contract_byteCode});
var contract_object=new web3.eth.Contract(contractAbi);也许有更好的方法,但这种方法消除了问题。
发布于 2020-03-08 09:50:23
可能contract_compiled.contracts[contractName]没有一个名为interface的字段。
这意味着contract_compiled.contracts[contractName].interface == undefined。
我相信你要寻找的领域叫做_jsonInterface。
但无论是哪种情况,帮你自己一个忙:
console.log(JSON.stringify(contract_compiled.contracts[contractName], null, 4));找出这个字段的真实名称,然后使用它。
还请注意,web3.eth.estimateGas返回一个Promise objcet,您需要解析它才能获得实际值(例如,在async函数中使用return await gasEstimate=web3.eth.estimateGas(...) )。
发布于 2020-03-08 09:54:36
我在您的代码中看到了几个错误:
fs.readFileSync('E:/Deploy/contracts/Deploy.sol','utf8'); ),而是开始使用相对路径,因为当您更改项目路径或从其他设备运行项目路径时,项目将无法工作。contract_compiled.contracts中的所有契约,在循环完成后,如何将哪个契约保存在变量contract_abi中?您只需要为所需的合同(如此contract_compiled.contracts[<NAME>] )使用abi定义。new web3.eth.Contract(contract_abi, <CONTRACT_ADDRESS>)时,您可能希望传递address参数。https://ethereum.stackexchange.com/questions/80416
复制相似问题