温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用智能合约开发以太坊DApp应用程序

发布时间:2022-01-15 15:01:03 来源:亿速云 阅读:198 作者:iii 栏目:互联网科技

本篇内容主要讲解“如何用智能合约开发以太坊DApp应用程序”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何用智能合约开发以太坊DApp应用程序”吧!

1. 设置开发环境

我们使用一个模拟的内存区块链(ganache)代替真实的区块链在进行开发。在本教程的2章,我们将与真实的区块链交互。下面是安装ganache、web3js的步骤,然后在linux上启动一个测试链。在macOS上安装过程也是一样的。

如何用智能合约开发以太坊DApp应用程序

你可以看到ganache-cli自动创建了10个测试账号,每个账号预分配了100(虚构的)ethers

如果需要更详细的开发环境安装教程,可以参考如下文章:

  • windows以太坊开发环境搭建

  • linux/ubuntu以太坊开发环境搭建

2.简单的投票合约

我们将使用solidity编程语言来编写我们的合约。如果您熟悉面向对象编程,学习编写solidity合约应该是轻而易举的事。我们将编写一个合约对象,含有一个构造函数初始化候选人数组。合约对象有2个方法:

  1. 返回候选人获得的总票数

  2. 增加候选人的投票数。

注意:构造函数只被调用一次,当您部署合约到区块链。不像在网络世界里的每一个部署你的代码覆盖旧的代码,部署后的代码在区块链上是不变的。例如,如果你更新你的合约并且再次部署,旧合约仍然会在区块链上, 它所存储的数据不受影响,新的部署将创建一个新实例的合约。

下面是投票合约的代码:

pragma solidity ^0.4.18;  
    // We have to specify what version of compiler this code will compile with  
      
    contract Voting {  
      /* mapping field below is equivalent to an associative array or hash.  
      The key of the mapping is candidate name stored as type bytes32 and value is  
      an unsigned integer to store the vote count  
      */  
        
      mapping (bytes32 => uint8) public votesReceived;  
        
      /* Solidity doesn't let you pass in an array of strings in the constructor (yet).  
      We will use an array of bytes32 instead to store the list of candidates  
      */  
        
      bytes32[] public candidateList;  
      
      /* This is the constructor which will be called once when you  
      deploy the contract to the blockchain. When we deploy the contract,  
      we will pass an array of candidates who will be contesting in the election  
      */  
      function Voting(bytes32[] candidateNames) public {  
        candidateList = candidateNames;  
      }  
      
      // This function returns the total votes a candidate has received so far  
      function totalVotesFor(bytes32 candidate) view public returns (uint8) {  
        require(validCandidate(candidate));  
        return votesReceived[candidate];  
      }  
      
      // This function increments the vote count for the specified candidate. This  
      // is equivalent to casting a vote  
      function voteForCandidate(bytes32 candidate) public {  
        require(validCandidate(candidate));  
        votesReceived[candidate] += 1;  
      }  
      
      function validCandidate(bytes32 candidate) view public returns (bool) {  
        for(uint i = 0; i < candidateList.length; i++) {  
          if (candidateList[i] == candidate) {  
            return true;  
          }  
        }  
        return false;  
      }  
    }

复制上面的代码,在hello_world_voting目录下创建一个Voting.sol文件。现在让我们来编译代码并将其部署到ganache的区块链上.

为了编译solidity代码,我们需要安装名字为solc的npm模块

~/hello_world_voting$ npm install solc

我们将在node控制台中使用这个库来编译我们的合约。在上一篇文章中我们提到,web3js是一个让我们可以通过rpc访问区块链的库。我们将使用该库来部署我们的应用程序并与之交互。

首先,在命令行中断运行node命令进入node控制台,初始化solc和文本对象。下面的所有代码片段都需要在node控制台中键入

~/hello_world_voting$ node  
> Web3 = require('web3')  
> web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

为了确保web3对象已经初始化、区块链能够访问,让我们试一下查询区块链上的所有账户。您应该看到如下的结果:

> web3.eth.accounts  
    ['0x9c02f5c68e02390a3ab81f63341edc1ba5dbb39e',  
    '0x7d920be073e92a590dc47e4ccea2f28db3f218cc',  
    '0xf8a9c7c65c4d1c0c21b06c06ee5da80bd8f074a9',  
    '0x9d8ee8c3d4f8b1e08803da274bdaff80c2204fc6',  
    '0x26bb5d139aa7bdb1380af0e1e8f98147ef4c406a',  
    '0x622e557aad13c36459fac83240f25ae91882127c',  
    '0xbf8b1630d5640e272f33653e83092ce33d302fd2',  
    '0xe37a3157cb3081ea7a96ba9f9e942c72cf7ad87b',  
    '0x175dae81345f36775db285d368f0b1d49f61b2f8',  
    '0xc26bda5f3370bdd46e7c84bdb909aead4d8f35f3']

从voting.sol加载代码,保存在一个字符串变量中,然后开始编译

> code = fs.readFileSync('Voting.sol').toString()  
> solc = require('solc')  
> compiledCode = solc.compile(code)

当你的代码编译成功并打印了合约对象的内容(在node控制台中输出的内容),有2个字段很重要,需要理解它们:

  • compiledCode.contracts[‘:Voting’].bytecode: Voting.sol源代码编译后得到的字节码。这是将被部署到blockchain的代码。

  • compiledCode.contracts[‘:Voting’].interface: 合约接口或模板(称为ABI)告诉用户合约含有哪些方法。您需要这些ABI的定义,因为将来你总是需要与合约交互的。

到此,相信大家对“如何用智能合约开发以太坊DApp应用程序”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI