我正在尝试将合同连接到我的私有RPC服务器。我希望能够更新我的html页面上的计数器参数,该参数反过来引用我的可靠性合同文件和浏览器上的更新。但是,我继续遇到下面的html文件的跟随错误。 index.html和contract.sol也包含在下面。 TY!
<!doctype html>
<html>
<head>
<title>myDapp</title>
<script src="web3.js/dist/web3.min.js"></script>
<script type="text/javascript">
var contract_address = "0x68FDbd58D28BeD866E07906f6129bAC86161e243";
var contract_abi = [ { "constant": true, "inputs": [], "name": "getCreator", "outputs": [ { "name": "", "type": "address", "value": "0xc0f0fb70a63e7b345932da8eb427463f586be95d" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [], "name": "kill", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "myNewNumber", "type": "uint256" } ], "name": "setMyNumber", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [], "name": "getMyNumber", "outputs": [ { "name": "", "type": "uint256", "value": "3" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" } ];
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// set the provider you want from Web3.providers
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
}
var contract_instance = web3.eth.contract(contract_abi).at(contract_address);
console.log(contract_instance);
function getCounter() {
document.getElementById("myCounter").innerText = contract_instance.getMyNumber().toNumber().call;
}
</script>
</head>
<body>
<h1>Interact with a contract</h1>
<button onclick="getCounter()">Update Counter</button>
<button onclick="increaseCounter()">Increase Counter</button>
<span id="myCounter"></span> Counter
</body>
</html>
contract.sol
pragma solidity ^0.4.15;
contract MyContract {
address creator;
uint256 myNumber;
function MyContract() public {
creator = msg.sender;
myNumber = 3;
}
function getCreator() public constant returns(address) {
return creator;
}
function getMyNumber() public constant returns(uint256) {
return myNumber;
}
function setMyNumber(uint256 myNewNumber) public {
myNumber = myNewNumber;
}
function kill() public {
if(msg.sender == creator) {
selfdestruct(creator);
}
}
}
答案 0 :(得分:0)
问题是您尝试将Metamask
直接与web3.js
联系起来,而不是您应该如何做到这一点。
Metamask基于provider Engine,提供者eninge不支持同步函数或操作,例如:
你做不到
web3.eth.accounts
但您可以web3.eth.getAcounts()
。
为了最好地利用提供程序引擎注入你的web3并从那里获取它,你会注意到为了让事情运行,你将把所有内容切换为异步格式。
但是在所有情况下都使用web3.js异步函数,你会得到你想要的东西。