900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > [区块链笔记10] remix部署合约并连接Ganache 前端web3与智能合约交互

[区块链笔记10] remix部署合约并连接Ganache 前端web3与智能合约交互

时间:2019-06-27 23:58:17

相关推荐

[区块链笔记10] remix部署合约并连接Ganache 前端web3与智能合约交互

开启Ganache,搭建好本地的测试链

ganache链接到metamask

要注意这个搭建过程是把ganache链接到metamask而不是连接到remix

具体来说就是ganache链接到metamask上,然后remix通过injected web3的方式又把metamask的账户链接remix上

remix里的run设置里改成injected web3,表示用metamask注入的web3

remix里编辑简单的智能合约并部署

pragma solidity ^0.4.23;contract InfoContract {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);}}

把编译后的abi复制一下到infocontract_abi.js文件里

文件内容var infoContractABI = 复制的json格式的abi

编辑index.css

body {background-color: #F0F0F0;}#info {padding: 20px;background-color: #FFF;}#button {width: 100px;}

前端代码

<!DOCTYPE html><html><head><meta charset="utf-8"><title>First Dapp demo</title><link rel="stylesheet" type="text/css" href="index.css"><script src="infocontract_abi.js"></script><script src="/gh/ethereum/web3.js/dist/web3.min.js"></script><script src="jquery.js"></script></head><body><div class="content"><h1>First Dapp demo</h1><h2 id="info"></h2><br /><label>姓名: </label><input id="name" type="text"><br /><label>年龄: </label><input id="age" type="text"><br /><br /><button id="button">更新</button></div><script type="text/javascript">这里还有一部分代码,因为这这部分代码卡了4天,猜猜是什么console.log(web3);var infoContract = web3.eth.contract(infoContractABI);var info = infoContract.at('0x4594bede91b5353c6ee1b1cd7f8179750fe7844b');info.getInfo(function(error, result) {if (!error) {$('#info').html(result[0] + '(' +result + ') years old');}})$('#button').click(function() {var name = $('#name').val();var age = $('#age').val();info.setInfo(name, age, function(error, result) {if (!error) {console.log('set ok');}})})</script></body></html>

然后运行apache服务器。

访问页面就会显示合约的状态,也可以通过表单来修改合约的状态,但是要付gas。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。