我正在web3.js库的帮助下与部署在本地以太坊节点上的智能合约进行交互。不幸的是,web3.eth.Contract(abi, address)
似乎未能启动合同实例。
【摘要】整个app.js
文件如下所示:
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
const abi = [{"anonymous": false,"inputs": [{"indexed": false,"name": "add","type": "int256"},{"indexed": false,"name": "name","type": "string"},{"indexed": true,"name": "id","type": "uint256"},{"indexed": true,"name": "checked","type": "bool"}],"name": "globalValueChanged","type": "event"},{"constant": false,"inputs": [{"name": "add","type": "int256"},{"name": "name","type": "string"},{"name": "id","type": "uint256"},{"name": "checked","type": "bool"}],"name": "modifyGlobalValue","outputs": [{"name": "","type": "int256"}],"payable": false,"stateMutability": "nonpayable","type": "function"},{"inputs": [],"payable": false,"stateMutability": "nonpayable","type": "constructor"},{"constant": true,"inputs": [],"name": "getGlobalValue","outputs": [{"name": "","type": "int256"}],"payable": false,"stateMutability": "view","type": "function"},{"constant": true,"inputs": [{"name": "times","type": "int256"}],"name": "testGlobalValue","outputs": [{"name": "","type": "int256"}],"payable": false,"stateMutability": "view","type": "function"}]
const address = '0x9f6c4e63cbca51dea852a579c907317a0eac138c';
const contractInstance = new web3.eth.Contract(abi, address);
// to test if initialized web3 works fine
web3.eth.getAccounts().then((results) => {
console.log("***web3.eth.getAccounts()***:")
console.log(results)
})
// to test if web3.eth.Contract works
console.log("***contractInstance.abi***:")
console.log(contractInstance.abi)
【输出】正在运行的node app.js
的输出。
**contractInstance.abi***:
undefined
***web3.eth.getAccounts()***:
[ '0x135B02baD443C1073C14F8a7f13cEc8661d3eC3d',
'0x69890d19B6eb060cA47e1ca41d93256E46bb7195' ]
web3.eth.getAccounts()
返回正确的值,而web3.eth.Contract(abi, address)
似乎无法启动合同实例。
【附加信息】
npm list web
输出web3@1.0.0-beta.52
。
其他诸如web3.eth.getAccounts()之类的web3功能也可以正常工作。
在geth控制台中,使用abi
和address
相同的值,eth.contract(abi).at(address)
可以正常工作。