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

        其它相关知识在以下链接博客。   

             https://blog.csdn.net/qq_40452317/article/details/87988463

搭建测试链

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

 

创建智能合约

       以太坊官方在线编译器:

                     https://remix.ethereum.org

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中的地址。

 

安装Web3

创建项目

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

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

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

创建 前端

创建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;
}

运行成功: 

 

          完整文件:

                                   

       相关资料在网上查找。

       关于其他知识在上篇博客中已经写完,可以参照一下链接博客。

                 https://blog.csdn.net/qq_40452317/article/details/87988463

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值