区块链-web3与智能合约交互实例

        其它相关知识在如下连接博客。   css

             http://www.noobyard.com/article/p-kzfmshyi-hv.htmlhtml

搭建测试链

          咱们选择的Ganache(在此以前使用的是testrpc,Ganache属于它的升级版),一个图形化测试软件(也有命令行版本),能够一键在本地搭建以太坊区块链测试环境,而且将区块链的状态经过图形界面显示出来,Ganache的运行界面以下图所示.前端

 

建立智能合约

       以太坊官方在线编译器:node

                     https://remix.ethereum.orgjquery

pragma solidity ^0.4.21;

contract InfoContract {

   string fName;
   uint age;

   function setInfo(string _fName, uint _age) public {
       fName = _fName;
       age = _age;
   }

   function getInfo() public constant returns (string, uint) {
       return (fName, age);
   }
}

      编译器结构以下图,在没有错误的状况下,点击run,编译环境是web3  provider。会出现弹框,将其地址改成上图Ganache中的地址。git

 

安装Web3

建立项目github

使用 node.js 的包管理工具 npm 初始化项目,建立package.json 文件,其中保存了项目须要的相关依赖环境。web

一路按回车直到项目建立完成。最后,运行下面命令安装web.js:npm

注意: 在实际安装过程当中我发现web3在安装完成后并无 /node_modules/web3/dist/we3.min.js 文件,这个问题在 issue#1041中有体现,但官方好像一直没解决。不过能够在这里下载所需的文件,解压后将dist文件夹的内容拷贝到 /node_modules/web3路径下。json

建立 前端

建立index.html

     注意abi和合约地址。在代码中有相关备注

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>

    <link rel="stylesheet" type="text/css" href="main.css">

    <script src="./node_modules/web3/dist/web3.min.js"></script>

</head>
<body>
    <div class="container">

        <h1>Info Contract</h1>

        <h2 id="info"></h2>

        <label for="name" class="col-lg-2 control-label">Name</label>
        <input id="name" type="text">

        <label for="name" class="col-lg-2 control-label">Age</label>
        <input id="age" type="text">

        <button id="button">Update Info</button>


    </div>

    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>

    <script>

       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:7545"));
        }

        web3.eth.defaultAccount = web3.eth.accounts[0];
         //abi
        var infoContract = web3.eth.contract([
	{
		"constant": false,
		"inputs": [
			{
				"name": "_fName",
				"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"
	}
]);

        var info = infoContract.at('0xb42fd1b7fe64aad7a7b00696f7f93be37de1d92e');  //合约地址

        info.getInfo(function(error, result){
            if(!error)
                {
                    $("#info").html(result[0]+' ('+result[1]+' years old)');
                    console.log(result);
                }
            else
                console.error(error);
        });

        $("#button").click(function() {
            info.setInfo($("#name").val(), $("#age").val());
            console.log($("#name").val(),$("#age").val());
            console.info(typeof($("#name").val()));
            console.info(typeof($("#age").val()));
             location.reload();
            $("#info").html(result[0]+' ('+result[1]+' years old)');

        });

    </script>

</body>
</html>

建立main.css

body {
    background-color:#F0F0F0;
    padding: 2em;
    font-family: 'Raleway','Source Sans Pro', 'Arial';
}
.container {
    width: 50%;
    margin: 0 auto;
}
label {
    display:block;
    margin-bottom:10px;
}
input {
    padding:10px;
    width: 50%;
    margin-bottom: 1em;
}
button {
    margin: 2em 0;
    padding: 1em 4em;
    display:block;
}

#info {
    padding:1em;
    background-color:#fff;
    margin: 1em 0;
}

#loader {
    width: 100px;
    display:none;
}

运行成功: 

 

          完整文件:

                                   

       相关资料在网上查找。

       关于其余知识在上篇博客中已经写完,能够参照一下连接博客。

                 http://www.noobyard.com/article/p-kzfmshyi-hv.html