参考之前大佬做的保存姓名、年龄的简单合约开发DAPP案例,在搭建好服务器跑的时候,一个是报错提示metamask不再支持inject web3了,还有一个报错是提示web3.eth.contract is not a function,后者大概率是更新换代后的web3语法问题,前面一个问题主要原因是什么呢?还有一堆警告。 合约源码:**pragma solidity ^0.4.24;
contract MeetingInfoContract{ string name; uint age; function setInfo(string _name,uint _age) public{ name = _name; age = _age; } function getInfo() public view returns(string,uint){ return(name,age); } }**
html源码:
<!DOCTYPE html>
<html lang="en">
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="main.css">
<!--引入web3-->
<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
</head>
<body>
<div class="container">
<h1>First Dapp Demo</h1>
<h2 id="info"></h2>
<label>姓名:</label>
<input type="text" id="name">
<label>年龄:</label>
<input type="text" id="age">
<button id="button">更新</button>
</div>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
<!--验证引入web3成功-->
console.log("web3"+web3);
<!--连接web3的provider或本地,其实本例中值得就是lite-server所创建的那个服务器环境-->
if (typeof web3 !== 'undefined') {
web3 = new Web3(web3.currentProvider);
} else {
// Set the provider you want from Web3.providers
let web3 = new Web3(Web3.givenProvider || "ws://localhost:8545");
}
<!--此处中括号[]中的内容直接从remix中compile后的ABI处复制-->
var infoContract = web3.eth.contract([
{
"constant": false,
"inputs": [
{
"name": "_name",
"type": "string"
},
{
"name": "_age",
"type": "uint256"
}
],
"name": "setInfo",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": true,
"inputs": [],
"name": "getInfo",
"outputs": [
{
"name": "",
"type": "string"
},
{
"name": "",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
]);
<!--此处的address单引号''中内容是从remix中deploy后的地址复制而来-->
var info = infoContract.at('0xd5aabfcaed0186b7e7e7b5a4b8636923ee0186d7');
<!--此处可以参考web3在github上的文档http://github.com/ethereum/web3.js-->
<!--也就是web3.js提供的对于智能合约方法的操作与交互-->
<!--getInfo方法是对上面的id="info"设置,result是从智能合约获得的结果-->
info.getInfo(function(error,result){
if(!error){
$("#info").html(result[0]+'('+result[1]+')years old');
}
});
<!--这里setInfo对应智能合约的set方法,此处将html中的name和age设置到智能合约-->
$("#button").click(function(){
var name = $("#name").val();
var age = $("#age").val();
info.setInfo(name,age,function(error,result){
if(!error){
console.log("ok");
}
});
});
</script>
</body>
</html>
现在使用 window.ethereum 作为prider
if (window.ethereum) {
let privider = window.ethereum;
try {
// Request account access
await window.ethereum.enable();
} catch (error) {
// User denied account access...
console.error("User denied account access")
}
}